Today, I saw an article about Equals and ==, something confuses me. http://forums.asp.net/t/1511559.aspx
So I do it myself.
 
   1:  static void Main(string[] args)
   2:  {
   3:      DoEQ();
   4:      Console.ReadLine();
   5:  }
   6:   
   7:  private static void DoEQ()
   8:  {
   9:      Console.WriteLine("For value datatype:");
  10:      int i = 6;
  11:      int j = 6;
  12:      int h = 8;
  13:      Console.WriteLine("6==6 {0}",i==j);
  14:      Console.WriteLine("6.Equals(6) {0}", i.Equals(j));
  15:      Console.WriteLine("6==8 {0}", i == h);
  16:      Console.WriteLine("6.Equals(8) {0}", i.Equals(h));
  17:   
  18:      Console.WriteLine();
  19:      Console.WriteLine("For reference datatype:");
  20:      StringBuilder iC = new StringBuilder("My");
  21:      StringBuilder jC = new StringBuilder("My");
  22:      StringBuilder hC = new StringBuilder("My Test");
  23:      Console.WriteLine("StringBuilder('My')==StringBuilder('My') {0}", iC == jC);
  24:      Console.WriteLine("StringBuilder('My').Equals(StringBuilder('My')) {0}", iC.Equals(jC));
  25:      Console.WriteLine("StringBuilder('My')==StringBuilder('My Test') {0}", iC == hC);
  26:      Console.WriteLine("StringBuilder('My').Equals(StringBuilder('My Test')) {0}", iC.Equals(hC));
  27:   
  28:      Console.WriteLine();
  29:      Console.WriteLine("For special reference datatype(string):");
  30:      string iStr = "Test";
  31:      string jStr = "Test";
  32:      string hStr = "Just a Test";
  33:      Console.WriteLine("\"Test\"==\"Test\" {0}", iStr == jStr);
  34:      Console.WriteLine("\"Test\".Equals(\"Test\") {0}", iStr.Equals(jStr));
  35:      Console.WriteLine("\"Test\"==\"Just a Test\" {0}", iStr == hStr);
  36:      Console.WriteLine("\"Test\".Equals(\"Just a Test\") {0}", iStr.Equals(hStr));
  37:   
  38:      Console.WriteLine();
  39:      Console.WriteLine("For null and  reference datatype:");
  40:      string iN = null;
  41:      string jN = null;
  42:      string hN = "Test";
  43:      Console.WriteLine("Null==Null {0}", iN == jN);
  44:      //Console.WriteLine("Null.Equals(Null) {0}", iN.Equals(jN));
  45:      Console.WriteLine("Null==\"Test\" {0}", iN == hN);
  46:      //Console.WriteLine("Null.Equals(\"Test\") {0}", iN.Equals(hN));
  47:      Console.WriteLine("\"Test\".Equals(Null) {0}", hN.Equals(iN));
  48:   
  49:      Console.WriteLine();
  50:      Console.WriteLine("For special value datatype(zero):");
  51:      int iZ = 0;
  52:      short jZ =0;
  53:      Console.WriteLine("0i==0s {0}", iZ == jZ);
  54:      Console.WriteLine("0i.Equals(0s) {0}", iZ.Equals(jZ));
  55:  }

image

Conclusion:

  1. By value type, there’s no difference between Equals and ==
  2. By reference type, Equals compare the value of the two objects, the == compare whether the two objects point the same address.
  3. For different value type, Equals and == work the same way.

Functions disassembled by Reflector:

   1:  [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
   2:  public virtual bool Equals(object obj)
   3:  {
   4:      return RuntimeHelpers.Equals(this, obj);
   5:  }
   

 

   1:  [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
   2:  public static bool Equals(object objA, object objB)
   3:  {
   4:      return ((objA == objB) || (((objA != null) && (objB != null)) && objA.Equals(objB)));
   5:  }
 
   
   1:  [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
   2:  public static bool ReferenceEquals(object objA, object objB)
   3:  {
   4:      return (objA == objB);
   5:  }
 
 
We all know that CommandArgument Property can remember value or index, but sometimes, there's nothing in it, do you know why?
Today, i study for a while, and i find the following two ways.
  • Use <asp:ButtonField CommandName="CMD" />, the CommandArgument will memory the RowIndex of the GridView automatically.
  • Use <asp:TemplateField><ItemTemplate><asp:Button CommandName="MCMD" CommandArgument="Value"  /></ItemTemplate></asp:TemplateField>, the Argument value is Value

If you want to know what an assembly does, you can use Reflector to refactor the assembly and check the codes.

If you want to know why binding assembly failed, you can use Assembly Binding Log Viewer to check it. Also you should set HKLM\Software\Microsoft\Fusion\ForceLog registry value to 1.

When the assembly is used, you want to know what the assembly uses, you can use Process Explorer.

I have a function which returns the last day of a month. The function is like this:

In Javascript Editor, it works like the above picture.

But in VS2008, it's strange.

I am very strange for this, then I Bing,

http://www.w3schools.com/jsref/jsref_parseInt.asp

See the fuction parseInt(string, radix)

String: the value you want to convert to number.

Rules:

If the string begins with "0x", the radix is 16 (hexadecimal)

If the string begins with "0", the radix is 8 (octal). This feature is deprecated

If the string begins with any other value, the radix is 10 (decimal)

Then, I change my codes

var month = parseInt(strs[1]);

to

var month = parseInt(strs[1],10);

It functions.

Javascript Editor seems not function well.

====================================================================

The JS codes have something wrong. I change it to this:

var strs = p_InputMonth.split("/");
var year = parseInt(strs[0]);
var month = parseInt(strs[1], 10);
var date = new Date(year,month, 0 ); 0: the last day of the month. (Month Index: 0...11)
var lastDay = date.getDate();

When i use new Date(2009,9,iDay) or Date.setDate(iDay) in Javascript Editor, if iDay is not in (1...31) , it will pop an error message "It's a not valid parameter."

but in IE, the js codes work well.

====================================================================

date.setFullYear(year, month+1,1);
date = new Date(date/86400000);
var lastDay =date.getDate();

In Javascript Editor, i must use "/", but in IE i should use "-"

====================================================================

Why Javascript Editor is different with IE? is it just because my JS Editor is free version???

Client to receive message sent by server:
 
   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Data;
   5:  using System.Drawing;
   6:  using System.Linq;
   7:  using System.Text;
   8:  using System.Windows.Forms;
   9:  using System.Net.Sockets;
  10:  using System.Threading;
  11:  using System.Net;
  12:   
  13:  namespace NoticeSystemClient
  14:  {
  15:      public partial class MainForm : Form
  16:      {
  17:          public delegate void ShowMessage(string message);
  18:          public ShowMessage myDelegate;
  19:          Int32 port = 11000;
  20:          UdpClient udpClient = new UdpClient(11000);
  21:          Thread thread;
  22:          public MainForm()
  23:          {
  24:              //CheckForIllegalCrossThreadCalls = false;
  25:              InitializeComponent();
  26:          }
  27:   
  28:          private void MainForm_KeyDown(object sender, KeyEventArgs e)
  29:          {
  30:              if (e.KeyCode == Keys.Escape)
  31:              {
  32:                  thread.Abort();
  33:                  udpClient.Close();
  34:                  Close();
  35:              }
  36:          }
  37:   
  38:          private void ReceiveMessage()
  39:          {                      
  40:              while (true)
  41:              {
  42:                  IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, port);
  43:                  byte[] content = udpClient.Receive(ref remoteIPEndPoint);
  44:   
  45:                  if (content.Length > 0)
  46:                  {
  47:                      string message = Encoding.ASCII.GetString(content);
  48:                      
  49:                      this.Invoke(myDelegate, new object[] { message });
  50:                  }
  51:              }
  52:          }
  53:   
  54:   
  55:          private void ShowMessageMethod(string message)
  56:          {
  57:              richText.Text = message;
  58:          }
  59:   
  60:          private void MainForm_Load(object sender, EventArgs e)
  61:          {            
  62:              myDelegate = new ShowMessage(ShowMessageMethod);
  63:              thread = new Thread(new ThreadStart(ReceiveMessage));
  64:              thread.IsBackground = true;
  65:              thread.Start();
  66:          }
  67:      }
  68:  }

Server:

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel;
   4:  using System.Data;
   5:  using System.Drawing;
   6:  using System.Linq;
   7:  using System.Text;
   8:  using System.Windows.Forms;
   9:  using System.Net.Sockets;
  10:  using System.Net;
  11:   
  12:  namespace NoticeSystem
  13:  {
  14:      public partial class MainForm : Form
  15:      {
  16:          UdpClient udpClient = new UdpClient();
  17:          public MainForm()
  18:          {
  19:              InitializeComponent();
  20:          }
  21:   
  22:          private void btnClose_Click(object sender, EventArgs e)
  23:          {
  24:              udpClient.Close();
  25:              Close();
  26:          }
  27:   
  28:          private void btnSend_Click(object sender, EventArgs e)
  29:          {
  30:              Int32 port = 11000;
  31:              IPAddress ip = IPAddress.Parse(txtStartIP.Text.Trim());
  32:              IPEndPoint ipEndPoint = new IPEndPoint(ip,port);
  33:              byte[] content = Encoding.ASCII.GetBytes(richText.Text);
  34:              try
  35:              {
  36:                  int count = udpClient.Send(content, content.Length, ipEndPoint);
  37:                  if (count > 0)
  38:                  {
  39:                      MessageBox.Show("Message has been sent.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
  40:                  }
  41:              }
  42:              catch
  43:              {
  44:                  MessageBox.Show("Error occurs.", "Exclamation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  45:              }
  46:          }
  47:      }
  48:  }

There’s no more to say but the Client source code, red words.

We must indicate the port of the UdpClient, otherwise, it will pop errors.

code:

UdpClient udpClient = new UdpClient(11000);

At the outset, i don’t indicate the port, so when i debug the code, there’s nothing happen on client side.

Source code disassembled by Red Gate’s .Net Reflector of the UdpClient:

   1:  public UdpClient(int port) : this(port, AddressFamily.InterNetwork)
   2:  {
   3:  }

 

   1:  public UdpClient(int port, AddressFamily family)
   2:  {
   3:      IPEndPoint point;
   4:      this.m_Buffer = new byte[0x10000];
   5:      this.m_Family = AddressFamily.InterNetwork;
   6:      if (!ValidationHelper.ValidateTcpPort(port))
   7:      {
   8:          throw new ArgumentOutOfRangeException("port");
   9:      }
  10:      if ((family != AddressFamily.InterNetwork) && (family != AddressFamily.InterNetworkV6))
  11:      {
  12:          throw new ArgumentException(SR.GetString("net_protocol_invalid_family"), "family");
  13:      }
  14:      this.m_Family = family;
  15:      if (this.m_Family == AddressFamily.InterNetwork)
  16:      {
  17:          point = new IPEndPoint(IPAddress.Any, port);
  18:      }
  19:      else
  20:      {
  21:          point = new IPEndPoint(IPAddress.IPv6Any, port);
  22:      }
  23:      this.createClientSocket();
  24:      this.Client.Bind(point);
  25:  }
 
You will find that the UdpClient need a port to bind to to listen the IPENDPOINT.

Recently, we need import some data from excel to  Oracle database. A strange thing confused me.

The excel file has a column, for example PhoneNumber, the format is 999999,

here are some example data:

  • 123456
  • 234561
  • 345612
  • 456123
  • 561234
  • 612345
  • 000123
  • 000231
  • 000312

When i use the following code to select data, something is strange.

   1:  string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + ftpFile.PostedFile.FileName + ";" 
   2:                   + "Extended Properties=\"Excel 8.0;IMEX=1\"";
   3:  DataSet ds = new DataSet();
   4:  string strSql = "select * from [Sheet1$]";
   5:  using (OleDbDataAdapter adp = new OleDbDataAdapter(strSql, strConn))
   6:  {
   7:        adp.Fill(ds, "Phone");
   8:  }

view the ds data, you will find this:

  • 123456
  • 234561
  • 345612
  • 456123
  • 561234
  • 612345
  •             

if i change the number format to text, i still can not retrieve the number start with 000.

 

I don’t know why, finally i change every number to string in excel file. for example: 123456---> ‘123456 and 000123--->’000123. it works.

anyone who has a good solution for this?

I have a web project developed in VS2008, which use System.Data.SQLite for .Net 2.0 and Linq to Entities to access data.

Here is the source layout:

image

image

image

You can see that i have a SQLite database Test_DB.db3 in SQLite folder. In my develop machine, i use connectiongstring created by Linq to Entities named “Test_DBEntities”, and don’t have the DBProviderFactories section, it run well. The Default.aspx page display data and the pages in Admin folder manage the data.

I publish the website in my product machine, it can not run, the error is “Could not load the assembly System.Data.SQLite”,

I search a solution, which ask me add the DBProviderFactories to the web.config file and add new reference to System.Data.SQLite.Linq.ddl. After do this, i can view the Default.aspx which display data. But i can not manage my data through the pages in Admin folder. I get error “Can not open the database file”, some people said the database can not in App_Data, but my file is not in App_Data, i still get the error.

I feel strange when i view the default.aspx, Test.edmx get data successfully, but when i view pages in Admin, for example, Manage.aspx, it will get the error “Can not open the database file”, The Manage.aspx get data only, no else. Following is my code to access data:

using (Test_DBEntities osDataContext = new Test_DBEntities(Common.GetConnString()))
{                    
     OS_Module module = osDataContext.OS_Module.First<OS_Module>(m => m.Status == "Y" && m.ModuleValue == this.ModuleValue);
       this.modelTitle.InnerHtml = module.ModuleTitle;
       this.modelDetail.InnerHtml = Server.HtmlDecode(module.ModuleDetail);
}

I can use Default.aspx display different data, which get data successfully each time, but when display data use Manage.aspx in Admin folder, i will get the error “Can not open the database file”.

Any one who gets a solution, please comment here. Thanks very much!

In the actual develpment, we offen encounter such a problem about exporting data to excel or word, especially excel.

I can export data to excel from gridview, but i can not apply styles to the excel cell. Last week, i found how to set the style.

For example:

the following is from:http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook
   xmlns="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:o="urn:schemas-microsoft-com:office:office"
   xmlns:x="urn:schemas-microsoft-com:office:excel"
   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:html="http://www.w3.org/TR/REC-html40">
  <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
    <Author>Darl McBride</Author>
    <LastAuthor>Bill Gates</LastAuthor>
    <Created>2007-03-15T23:04:04Z</Created>
    <Company>SCO Group, Inc.</Company>
    <Version>11.8036</Version>
  </DocumentProperties>
  <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
    <WindowHeight>6795</WindowHeight>
    <WindowWidth>8460</WindowWidth>
    <WindowTopX>120</WindowTopX>
    <WindowTopY>15</WindowTopY>
    <ProtectStructure>False</ProtectStructure>
    <ProtectWindows>False</ProtectWindows>
  </ExcelWorkbook>
  <Styles>
    <Style ss:ID="Default" ss:Name="Normal">
      <Alignment ss:Vertical="Bottom" />
      <Borders />
      <Font />
      <Interior />
      <NumberFormat />
      <Protection />
    </Style>
    <Style ss:ID="s21">
      <Font x:Family="Swiss" ss:Bold="1" />
    </Style>
  </Styles>
  <Worksheet ss:Name="Sheet1">
    <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="5"
    x:FullColumns="1" x:FullRows="1">
      <Row>
        <Cell>
          <Data ss:Type="String">Text in cell A1</Data>
        </Cell>
      </Row>
      <Row>
        <Cell ss:StyleID="s21">
          <Data ss:Type="String">Bold text in A2</Data>
        </Cell>
      </Row>
      <Row ss:Index="4">
        <Cell ss:Index="2">
          <Data ss:Type="Number">43</Data>
        </Cell>
      </Row>
      <Row>
        <Cell ss:Index="2" ss:Formula="=R[-1]C/2">
          <Data ss:Type="Number">21.5</Data>
        </Cell>
      </Row>
    </Table>
    <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
      <Print>
        <ValidPrinterInfo />
        <HorizontalResolution>600</HorizontalResolution>
        <VerticalResolution>600</VerticalResolution>
      </Print>
      <Selected />
      <Panes>
        <Pane>
          <Number>3</Number>
          <ActiveRow>5</ActiveRow>
          <ActiveCol>1</ActiveCol>
        </Pane>
      </Panes>
      <ProtectObjects>False</ProtectObjects>
      <ProtectScenarios>False</ProtectScenarios>
    </WorksheetOptions>
  </Worksheet>
</Workbook>

And i found a open source project http://excelpackage.codeplex.com/ which can easily create ooxml.

The same as excel, we can export data to word:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument
   xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml"
   xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint"
   xmlns:o="urn:schemas-microsoft-com:office:office"
   w:macrosPresent="no"
   w:embeddedObjPresent="no"
   w:ocxPresent="no"
   xml:space="preserve">
  <o:DocumentProperties>
    <o:Title>This is the title</o:Title>
    <o:Author>Darl McBride</o:Author>
    <o:LastAuthor>Bill Gates</o:LastAuthor>
    <o:Revision>1</o:Revision>
    <o:TotalTime>0</o:TotalTime>
    <o:Created>2007-03-15T23:05:00Z</o:Created>
    <o:LastSaved>2007-03-15T23:05:00Z</o:LastSaved>
    <o:Pages>1</o:Pages>
    <o:Words>6</o:Words>
    <o:Characters>40</o:Characters>
    <o:Company>SCO Group, Inc.</o:Company>
    <o:Lines>1</o:Lines>
    <o:Paragraphs>1</o:Paragraphs>
    <o:CharactersWithSpaces>45</o:CharactersWithSpaces>
    <o:Version>11.6359</o:Version>
  </o:DocumentProperties>
  <w:fonts>
    <w:defaultFonts
       w:ascii="Times New Roman"
       w:fareast="Times New Roman"
       w:h-ansi="Times New Roman"
       w:cs="Times New Roman" />
  </w:fonts>
  <w:styles>
    <w:versionOfBuiltInStylenames w:val="4" />
    <w:latentStyles w:defLockedState="off" w:latentStyleCount="156" />
    <w:style w:type="paragraph" w:default="on" w:styleId="Normal">
      <w:name w:val="Normal" />
      <w:rPr>
        <wx:font wx:val="Times New Roman" />
        <w:sz w:val="24" />
        <w:sz-cs w:val="24" />
        <w:lang w:val="EN-US" w:fareast="EN-US" w:bidi="AR-SA" />
      </w:rPr>
    </w:style>
    <w:style w:type="paragraph" w:styleId="Heading1">
      <w:name w:val="heading 1" />
      <wx:uiName wx:val="Heading 1" />
      <w:basedOn w:val="Normal" />
      <w:next w:val="Normal" />
      <w:rsid w:val="00D93B94" />
      <w:pPr>
        <w:pStyle w:val="Heading1" />
        <w:keepNext />
        <w:spacing w:before="240" w:after="60" />
        <w:outlineLvl w:val="0" />
      </w:pPr>
      <w:rPr>
        <w:rFonts w:ascii="Arial" w:h-ansi="Arial" w:cs="Arial" />
        <wx:font wx:val="Arial" />
        <w:b />
        <w:b-cs />
        <w:kern w:val="32" />
        <w:sz w:val="32" />
        <w:sz-cs w:val="32" />
      </w:rPr>
    </w:style>
    <w:style w:type="character" w:default="on" w:styleId="DefaultParagraphFont">
      <w:name w:val="Default Paragraph Font" />
      <w:semiHidden />
    </w:style>
    <w:style w:type="table" w:default="on" w:styleId="TableNormal">
      <w:name w:val="Normal Table" />
      <wx:uiName wx:val="Table Normal" />
      <w:semiHidden />
      <w:rPr>
        <wx:font wx:val="Times New Roman" />
      </w:rPr>
      <w:tblPr>
        <w:tblInd w:w="0" w:type="dxa" />
        <w:tblCellMar>
          <w:top w:w="0" w:type="dxa" />
          <w:left w:w="108" w:type="dxa" />
          <w:bottom w:w="0" w:type="dxa" />
          <w:right w:w="108" w:type="dxa" />
        </w:tblCellMar>
      </w:tblPr>
    </w:style>
    <w:style w:type="list" w:default="on" w:styleId="NoList">
      <w:name w:val="No List" />
      <w:semiHidden />
    </w:style>
  </w:styles>
  <w:docPr>
    <w:view w:val="print" />
    <w:zoom w:percent="100" />
    <w:doNotEmbedSystemFonts />
    <w:proofState w:spelling="clean" w:grammar="clean" />
    <w:attachedTemplate w:val="" />
    <w:defaultTabStop w:val="720" />
    <w:punctuationKerning />
    <w:characterSpacingControl w:val="DontCompress" />
    <w:optimizeForBrowser />
    <w:validateAgainstSchema />
    <w:saveInvalidXML w:val="off" />
    <w:ignoreMixedContent w:val="off" />
    <w:alwaysShowPlaceholderText w:val="off" />
    <w:compat>
      <w:breakWrappedTables />
      <w:snapToGridInCell />
      <w:wrapTextWithPunct />
      <w:useAsianBreakRules />
      <w:dontGrowAutofit />
    </w:compat>
  </w:docPr>
  <w:body>
    <wx:sect>
      <w:p>
        <w:r>
          <w:t>This is the first paragraph</w:t>
        </w:r>
      </w:p>
      <wx:sub-section>
        <w:p>
          <w:pPr>
            <w:pStyle w:val="Heading1" />
          </w:pPr>
          <w:r>
            <w:t>This is a heading</w:t>
          </w:r>
        </w:p>
        <w:sectPr>
          <w:pgSz w:w="12240" w:h="15840" />
          <w:pgMar w:top="1440"
		   w:right="1800"
		   w:bottom="1440"
		   w:left="1800"
		   w:header="720"
		   w:footer="720"
		   w:gutter="0" />
          <w:cols w:space="720" />
          <w:docGrid w:line-pitch="360" />
        </w:sectPr>
      </wx:sub-section>
    </wx:sect>
  </w:body>
</w:wordDocument>

If we want to export some complex data to excel, we can create the xml manually, apply every style we like we want

若要查看表的列名,可以使用 sp_help 或下列查询之一:SELECT name FROM sys.columns WHERE OBJECT_ID IN (SELECT OBJECT_ID ('table_name')) 或 SELECT TOP 0 * FROM table_name。
1.   Execute sp_help tablename  如: Execute sp_help 'Schedule'
2.   Select Top 0 * From tablename 如:Select Top 0 * From 'Schedule'
3.   Select name From sys.columns where Object_Id In (Select Object_Id(tablename)) 如: Select name From sys.columns where Object_Id In (Select Object_Id('Schedule'))
三种的区别如下:
1.   可以得到table的详细信息,可以得到五个表
2.   一个无记录行的表结构
3.   一个单列表,列名name,内容是表的列名称

I have a web project, in the project, there is a MasterPage and some WebContentPages.
In the MasterPage, there is a function, when you click a button, show or hide the left content.When you refresh or navigate other WebContentPage, the left content keeps its display style.
Here is my first solution:
MasterPage.Master:

<div id="left" style='<%=string.Format("display:{0}",GetToolbarDisplayFlag())%>'>

</div>

<div id="buttons_left">
     <img alt="Move Left" onclick="switchView('left',this);" src='<%=GetImgSrc()%>' />

</div>

Remember to set the EnablePageMethods = "True"


MasterPage.Master.CS:

public string GetToolbarDisplayFlag()
{

       return HttpContext.Current.Session["ToolbarDisplay"] == null ? "block" : HttpContext.Current.Session["ToolbarDisplay"].ToString();

}
public string GetImgSrc()
{
   if(GetToolbarDisplayFlag() == string.Empty || GetToolbarDisplayFlag() == "block")
   {
       return "../App_Themes/images/s_left.gif";
   }
   return "../App_Themes/images/s_right.gif";

}

[WebMethod]public static void SetToolbarDisplayFlag(string flag)
{
    HttpContext.Current.Session["ToolbarDisplay"= flag;

}


JS:


function switchView(objname,current)
{
    var obj = $get(objname);
    if(obj.style.display=="block" || obj.style.display=="")
    {
        obj.style.display="none";
        current.src ='../App_Themes/images/s_right.gif';
        PageMethods.SetToolbarDisplayFlag("none",OnSucceeded,OnFailed);
    }
    else
    {
        obj.style.display="block";
        current.src ='../App_Themes/images/s_left.gif';
        PageMethods.SetToolbarDisplayFlag("block",OnSucceeded,OnFailed);
    }
}
function OnSucceeded(result, userContext, methodName)
{   
    return;
} 
function OnFailed(error, userContext, methodName)
{
    return;
}           

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


When you click the button, it will cause exception: PageMethods not defined.

This is because the method "SetToolbarDisplayFlag" Js invoke is in MasterPage, it seems PageMethods donot contain MasterPage methods.

 

So, my solution is move the method "SetToolbarDisplayFlag" from MasterPage to a base page called "PageBase" which inherited from System.Web.UI.Page, and each WebContentPage derived from PageBase.

PageBase.cs:


public class PageBase : Page

{

   [WebMethod]
   public static void SetToolbarDisplayFlag(string flag)
   {
       HttpContext.Current.Session["ToolbarDisplay"] = flag;

   }

}


Now, you can invoke methods in MasterPage.
More Posts Next page »