Yonggang Meng's Weblog

<br><a href= "http://weblogs.asp.net/gonggangmeng" target="_self" >Try what I want, do what I can!</a>

  • Two ways to make CommandArgument have value in GridView

    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

  • Use UdpClient to send and receive message

    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.

  • Problem about SQLite and Linq to Entities

    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!

  • Export data to excel or word

    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

  • SQL 表信息问题

    若要查看表的列名,可以使用 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,内容是表的列名称

  • How to invoke PageMethods in MasterPage

    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.