Saturday, June 28, 2014

Update ASP.NET Label control value using continuous mouse down click

Starting today, I'm going to contribute source code in vbforums.com(Visual Basic Forum). The community helped me way back since VB 6.0 and VBA. And in turn, it's time to give back as an experienced member. :)

Here's a an ASP.NET application I posted in ASP.NET code bank on how to update label values continuously on mouse hold. Update Label Value using jQuery/Javascript in ASP.NET

Reference: Easily do a continuous action on mouse hold using javascript

Cheers! :)

Friday, June 27, 2014

Bind XML Node Value To GridView column in ASP.NET using XPath

Given in a datasource object where in you have a column which contains an XML string and you want to bind a certain node value instead of the entire XML string to GridView column, here's a solution using XPath. ASPX:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" BackColor="White"   
       Width="400px" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3">  
       <AlternatingRowStyle BackColor="#F7F7F7" />  
       <Columns>  
         <asp:BoundField DataField="ID" HeaderText="ID" >  
         <ItemStyle Width="50px" />  
         </asp:BoundField>  
         <asp:BoundField DataField="XMLData" HeaderText="Name" >  
         <ItemStyle Width="350px" />  
         </asp:BoundField>  
       </Columns>  
       <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />  
       <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />  
       <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />  
       <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />  
       <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />  
       <SortedAscendingCellStyle BackColor="#F4F4FD" />  
       <SortedAscendingHeaderStyle BackColor="#5A4C9D" />  
       <SortedDescendingCellStyle BackColor="#D8D8F0" />  
       <SortedDescendingHeaderStyle BackColor="#3E3277" />  
     </asp:GridView>  

C# Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
protected void BindToGridXPath()
        {
            XmlDocument xmlDoc;
            XmlNode xmlNode;
            String xpathExpr;

            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[]
                {
                    new DataColumn("ID",typeof(int)), 
                    new DataColumn("XMLData", typeof(string))
                });

            DataRow row = dt.NewRow();
            row["ID"] = 1;
            row["XMLData"] = "<Person><Name>James Minervo</Name><Age>33</Age></Person>";

            DataRow row1 = dt.NewRow();
            row1["ID"] = 2;
            row1["XMLData"] = "<Person><Name>Mike Phill</Name><Age>45</Age></Person>";

            //...codes to manipulate the datatable
            xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(row["XMLData"].ToString());
            xpathExpr = "/Person/Name";
            xmlNode = xmlDoc.SelectSingleNode(xpathExpr);
            row["XMLData"] = xmlNode.InnerText;

            xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(row1["XMLData"].ToString());
            xpathExpr = "/Person/Name";
            xmlNode = xmlDoc.SelectSingleNode(xpathExpr);
            row1["XMLData"] = xmlNode.InnerText;

            dt.Rows.Add(row);
            dt.Rows.Add(row1);

            gvPersons.DataSource = dt;
            gvPersons.DataBind();
        }

Output:

Monday, June 23, 2014

Retrieve last inserted record in MySQL Database using C#.NET

To get last inserted unique ID in MySQL, use LAST_INSERT_ID().
C# Code:
1
2
3
4
string insert_product_query = ("INSERT INTO PRODUCTS (Stock) VALUES (5); SELECT LAST_INSERT_ID()");
MySqlCommand cmd_query = new MySqlCommand(insert_product_query, objConn);
int idResult = Convert.ToInt32(cmd_query.ExecuteScalar());
txtID.Text = idResult.ToString();
MySQL Docs: Getting Last Unique ID in MySQL

Monday, June 9, 2014

ASP.NET Generic Handler Not Downloading .pptx and .pdf files properly

There was a question raised in the forums as to why the generic handler doesn't download properly .ppt/.pdf files using Firefox but works perfectly using chrome and IE. The solution is to add a content-disposition header and set the ContentType property of context.Response.
VB.NET Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
 
        Dim documentID As Int32
        If Not context.Request.QueryString("documentID") Is Nothing Then
            documentID = Convert.ToInt32(context.Request.QueryString("documentID"))
        Else
            Throw New ArgumentException("No parameter specified")
        End If
  
        Dim strm As Stream = ShowDocument(documentID)
        context.Response.AddHeader("content-disposition", "attachment; filename=" & fileName.Replace(" ", "_") & ".pptx")
        context.Response.ContentType = docType
  
        If ShowDocument(documentID) Is Nothing Then
        Else
            strm = ShowDocument(documentID)
            Dim buffer As Byte() = New Byte(4095) {}
            Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
 
            Do While byteSeq > 0
                context.Response.OutputStream.Write(buffer, 0, byteSeq)
                byteSeq = strm.Read(buffer, 0, 4096)
            Loop
        End If
 
    End Sub

Friday, June 6, 2014

ASP.NET MVC ActionResult with [HttpPost, HttpPut] filter not executing

Given the ActionResult method and View that executes the controller.
ActionResult:
Code:
       [HttpPost, HttpPut] 
       public ActionResult Update(EditModel input)
        {
            if (ModelState.IsValid)
            {
                var person = Database.People.Find(input.Id);
                input.ToPerson(person);

                Database.SaveChanges();

                return RedirectToAction("Edit", new { id = person.Id });
            }

            return View("Edit", input);
        }

View:
 @model PagedListTableMvcDemo.Models.EditModel  
 @{  
   ViewBag.Title = "Edit";  
 }  
 <h2>Update</h2>  
 @using (Html.BeginForm("Update", "People")) {  
   @Html.Partial("_Person")  
 }  
When the user clicks the submit button rendered by the BeginForm helper, the browser shows an error URL not found or The view does not navigate to the Action with the corresponding Controller supplied in the BeginForm's parameters. The solution is to replace %5BHttpPost, HttpPut%5D with AcceptVerbs attribute.
Code:
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
        public ActionResult Update(EditModel input)
        {
            if (ModelState.IsValid)
            {
                var person = Database.People.Find(input.Id);
                input.ToPerson(person);

                Database.SaveChanges();

                return RedirectToAction("Edit", new { id = person.Id });
            }

            return View("Edit", input);
        }