Programming

[Asp.net] Convert datatable to Json

This code is used to convert datatable to json format. It also handle double quote and backslash issue.

public static string Convert(DataTable dt)
        {
            string sb = "";
            sb += "[";
            foreach (DataRow dr in dt.Rows)
            {
                sb += "{";
                foreach (DataColumn dc in dt.Columns)
                {
                    //Column Name
                    sb += "\"";
                    sb += dc.ColumnName;
                    sb += "\":";
                    //Column Value
                    sb += "\"";
                    //Value contain " must be replace with \"
                    sb += dr[dc].ToString().Replace(@"\", @"\\").Replace("\"", "\\\"");
                    sb += "\",";
                }
                if (sb.EndsWith(","))
                {
                    sb = sb.Substring(0, sb.Length - 1);
                }
                sb += "},";
            }
            if (sb.EndsWith(","))
            {
                sb = sb.Substring(0, sb.Length - 1);
            }
            sb += "]";

            return sb;
        }

Read the rest of this entry »

  • Share/Bookmark

Collapsible Drag & Drop Panels like WordPress Dashboard using Jquery and ASP.NET

I found a great article that teach us how to create drag and drop panel like dashboard in wordpress panel.
In this sites: http://webdeveloperplus.com/jquery/saving-state-for-collapsible-drag-drop-panels/ shows us how to create the drag and drop panel and save the state in PHP and mysql. In this article, I will show the code in ASP.NET using SQL Server 2005.

4-25-2011 4-15-33 PM
Read the rest of this entry »

  • Share/Bookmark

VB.NET – ASP.NET communication between user control and web page using event handler

In this post, we want to show how button in user control communicate with web page in asp.net

First create user control called button.ascx.

Add 3 button, name it btnSave, btnEdit and btnCancel.

in button.ascx back code, add this code:

Public Partial Class button
    Inherits System.Web.UI.UserControl
    Public Event btnSaveHandler As System.EventHandler
    Public Event btnEditHandler As System.EventHandler
    Public Event btnCancelHandler As System.EventHandler

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
        RaiseEvent btnSaveHandler(Me, New EventArgs())
    End Sub

    Protected Sub btnEdit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEdit.Click
        RaiseEvent btnEditHandler(Me, New EventArgs())
    End Sub

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancel.Click
        RaiseEvent btnCancelHandler(Me, New EventArgs())
    End Sub
End Class

In Default.aspx, add 1 label called label1, then drag the button.ascx to the default.aspx.
Add code in default.aspx as below:

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Label1.Text = Request.QueryString("label")
        AddHandler button1.btnCancelHandler, AddressOf cancelClick
        AddHandler button1.btnEditHandler, AddressOf editClick
        AddHandler button1.btnSaveHandler, AddressOf saveClick
    End Sub

    Private Sub cancelClick(ByVal sender As Object, ByVal e As EventArgs)
        Response.Redirect("default.aspx?label=Cancel")
    End Sub

    Private Sub editClick(ByVal sender As Object, ByVal e As EventArgs)
        Response.Redirect("default.aspx?label=Edit")
    End Sub

    Private Sub saveClick(ByVal sender As Object, ByVal e As EventArgs)
        Response.Redirect("default.aspx?label=Save")
    End Sub
End Class

Run it, you will see that button that we create in user control can be manipulate and used in default.aspx
See other example for communication between user control and page in:

http://www.codeproject.com/KB/user-controls/Page_UserControl.aspx

  • Share/Bookmark

ASP.NET – GridView – Get Hidden Field Value in RowCommand

There is a problem when we set BoundField visibility to false, the column isn’t rendered to the client. A work around would be to use a HiddenField within a TemplateField instead.

<asp:TemplateField HeaderText="MemberID">
    <ItemTemplate>
        <asp:LinkButton ID="lbtn_memberid" runat="server" CommandName="GetMemberID" CommandArgument='<%# DataBinder.Eval(Container, "DataItem.memberid") %>'
            Text='<%# DataBinder.Eval(Container, "DataItem.memberid") %>'></asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField>

<asp:TemplateField>
    <ItemTemplate>
        <asp:HiddenField ID="fieldid" runat="server" Value='<%# Eval("fieldname") %>' />
    </ItemTemplate>
</asp:TemplateField>

Back Code:

    Protected Sub gridview1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridview1.RowCommand

        If e.CommandName = "GetMemberID" Then

            Session("GetMemberID") = e.CommandArgument.ToString()

            Dim gv As GridViewRow = DirectCast(DirectCast(e.CommandSource, LinkButton).NamingContainer, GridViewRow)

            Dim i As Integer = gv.RowIndex

            Dim row As GridViewRow = gridview1.Rows(i)

            Dim hidden As HiddenField = DirectCast(row.Cells(0).FindControl("fieldid"), HiddenField)

            Dim fieldid As Integer = CInt(hidden.Value)

        End If

    End Sub
  • Share/Bookmark

Ask for username and password when calling reporting service

These code allow us to set username and password for reporting services to avoid popup request authentication.

This code tested in Visual Studio 2008 and Reporting Services from SQL Server 2005

First create a class called ReportServerCredentials.vb

Imports Microsoft.VisualBasic
Imports Microsoft.Reporting.WebForms
Imports System.Security.Principal

Public NotInheritable Class ReportServerCredentials
    Implements IReportServerCredentials

    Public ReadOnly Property ImpersonationUser() As WindowsIdentity _
            Implements IReportServerCredentials.ImpersonationUser
        Get

            'Use the default windows user.  Credentials will be
            'provided by the NetworkCredentials property.
            Return Nothing

        End Get
    End Property

    Public ReadOnly Property NetworkCredentials() As Net.ICredentials _
            Implements IReportServerCredentials.NetworkCredentials
        Get

            'Read the user information from the web.config file.
            'By reading the information on demand instead of storing
            'it, the credentials will not be stored in session,
            'reducing the vulnerable surface area to the web.config
            'file, which can be secured with an ACL.

            'User name
            Dim userName As String = _
                ConfigurationManager.AppSettings("UserName")

            If (String.IsNullOrEmpty(userName)) Then
                Throw New Exception("Missing user name from web.config file")
            End If

            'Password
            Dim password As String = _
                ConfigurationManager.AppSettings("Password")

            If (String.IsNullOrEmpty(password)) Then
                Throw New Exception("Missing password from web.config file")
            End If

            'Domain
            Dim domain As String = _
                ConfigurationManager.AppSettings("SERVERNAME")

            If (String.IsNullOrEmpty(domain)) Then
                Throw New Exception("Missing domain from web.config file")
            End If

            Return New Net.NetworkCredential(userName, password, domain)

        End Get
    End Property

    Public Function GetFormsCredentials(ByRef authCookie As System.Net.Cookie, _
                                        ByRef userName As String, _
                                        ByRef password As String, _
                                        ByRef authority As String) _
                                        As Boolean _
            Implements IReportServerCredentials.GetFormsCredentials

        authCookie = Nothing
        userName = Nothing
        password = Nothing
        authority = Nothing

        'Not using form credentials
        Return False

    End Function

End Class 

Second, add parameter key to your web.config

<appSettings>
<add key="UserName" value="UserName"/>
		<add key="Password" value="Password"/>
		<add key="SERVERNAME" value="SERVERNAME"/>
</appSettings>

And then add this line of code before calling reportserverURL in the report view page:

ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials()
  • Share/Bookmark

Send Email with multiple attachments from VB.NET

This code show how to send email multiple attachments from vb.net by using System.Net.Mail

1. This is how you use it

Dim fileAttch = New ArrayList
fileAttch.Add("C:\test.csv")
fileAttch.Add("C:\test2.csv")
fileAttch.Add("C:\test3.csv")

sendEmail.send(your_emailHost, "no-reply@company.com", your_EmailTo, your_EmailSubject, your_EmailBody, your_EmailccTo, fileAttch)


Read the rest of this entry »

  • Share/Bookmark

Get first day of the month and last day of the month in VB.NET

This code show how to get first date of the month and last day of the month date.

Private Function GetFirstDayOfMonth(ByVal dtDate As DateTime) As DateTime
        Dim dtFrom As DateTime = dtDate
        dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1))
        Return dtFrom
    End Function

    Private Function GetLastDayOfMonth(ByVal dtDate As DateTime) As DateTime
        Dim dtTo As New DateTime(dtDate.Year, dtDate.Month, 1)
        dtTo = dtTo.AddMonths(1)
        dtTo = dtTo.AddDays(-(dtTo.Day))
        Return dtTo
    End Function

'if you put code like:
GetFirstDayOfMonth("2010-05-05") ' It will return = 2010-05-01
GetLastDayOfMonth("2010-05-05") ' It will return = 2010-05-31
  • Share/Bookmark

VB.NET Set Data Table to CSV File

This function show how to Convert DataTable to CSV File

    Sub SetDataTable_To_CSV(ByVal dtable As DataTable, ByVal path_filename As String, ByVal sep_char As String)
        Dim writer As System.IO.StreamWriter
        Try
            writer = New System.IO.StreamWriter(path_filename)

            Dim _sep As String = ""
            Dim builder As New System.Text.StringBuilder
            For Each col As DataColumn In dtable.Columns
                builder.Append(_sep).Append(col.ColumnName)
                _sep = sep_char
            Next
            writer.WriteLine(builder.ToString())

            For Each row As DataRow In dtable.Rows
                _sep = ""
                builder = New System.Text.StringBuilder

                For Each col As DataColumn In dtable.Columns
                    builder.Append(_sep).Append(row(col.ColumnName))
                    _sep = sep_char
                Next
                writer.WriteLine(builder.ToString())
            Next
        Catch ex As Exception

        Finally
            If Not writer Is Nothing Then writer.Close()
        End Try
    End Sub

This is how you use it

Dim dt As New DataTable
SetDataTable_To_CSV(dt, "C:\test.csv", ",")
  • Share/Bookmark

How to set command Timeout for getData() in TableAdapter

One of the disadvantages when we using tableadapter to retrieve the data from database is they do not provide property to set command timeout (SHIT). This giving me a huge headache for my project which most of the entire project is using tableadapter instead of creating my own DAL or class.
After do some research on the internet, there is 1 ways to add command timeout in tableadapter dataset (.xsd file) which is

create new property inside partial class:
Double click on xxxTableAdaper and it will show you behind code in .vb file of xsd file. Add this code inside Partial Public Class xxxDataTableAdapter

Namespace xxxTableAdapters
    Partial Public Class yyyTableAdapter
        Public WriteOnly Property CommandTimeout() As Integer
            Set(ByVal value As Integer)
                Dim i As Integer = 0
                While (i < Me.CommandCollection.Length)
                    If (Me.CommandCollection(i) IsNot Nothing) Then
                        Me.CommandCollection(i).CommandTimeout = value
                    End If
                    i = (i + 1)
                End While
            End Set
        End Property
    End Class
End Namespace

And how you use it, you just add 1 line of code:

            Dim dt As New DataSet1TableAdapters.AddressTableAdapter
            dt.CommandTimeout = 120
            gridview1 = dt.GetData()

Notes:
xxxTableAdapters , xxx you replace with the name of .xsd file
yyyTableAdapter you replace with the name of table adapter

This code is tested in visual studio 2008

Plus500

  • Share/Bookmark

VB.NET Date Time Format Patterns

Plus500

Standard Format Example List:

Format Code Result
MM/dd/yyyy Date.Now().ToString(“d”) 1/15/2010
dddd, dd MMMM yyyy Date.Now().ToString(“D”) Friday, January 15, 2010
dddd, dd MMMM yyyy hh:mm tt Date.Now().ToString(“f”) Friday, January 15, 2010 11:06 AM
dddd, dd MMMM yyyy HH:mm:ss Date.Now().ToString(“F”) Friday, January 15, 2010 11:06:46 AM
MM/dd/yyyy h:mm tt Date.Now().ToString(“g”) 1/15/2010 11:06 AM
MM/dd/yyyy HH:mm:ss Date.Now().ToString(“G”) 1/15/2010 11:06:46 AM
MMMM dd Date.Now().ToString(“m”) January 15
dd MMM yyyy HH’:'mm’:'ss ‘GMT’ Date.Now().ToString(“r”) Fri, 15 Jan 2010 11:06:46 GMT
yyyy’-'MM’-'dd’T'HH’:'mm’:'ss Date.Now().ToString(“s”) 2010-01-15T11:06:46
yyyy’-'MM’-'dd HH’:'mm’:'ss’Z’ Date.Now().ToString(“u”) 2010-01-15 11:06:46Z
dddd, MMMM dd yyyy HH:mm:ss Date.Now().ToString(“U”) Friday, January 15, 2010 3:06:46 AM
yyyy MMMM Date.Now().ToString(“y”) January, 2010

Read the rest of this entry »

  • Share/Bookmark