Technical Insights: Azure, .NET, Dynamics 365 & EV Charging Architecture

Category: ASP.NET Page 5 of 7

Category for ASP.NET

AJAX Update Panel Timeout Issue

I have an asp.net page where the page will query the report from the database. To query the report itself might cause timeout exception on the page itself before the report result is being returned from database.

You need to do it in two steps, first you need to override the script timeout only for the pageitself. put this code in your code behind

    Dim pageTimeOut As Integer
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        pageTimeOut = Server.ScriptTimeout

        'this is in seconds
        Server.ScriptTimeout = 2500
End Sub

Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

Server.ScriptTimeout = pageTimeOut

End Sub

The next step is required only if you use AJAX Update panel. Put this script on the aspx page


   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
        function (sender, args)
        {
             if (args.get_error() && args.get_error().name == 'Sys.WebForms.PageRequestManagerTimeoutException')
            {
                  // remember to set errorHandled = true to keep from getting a popup from the AJAX library itself
                 args.set_errorHandled(true);
             }
        });

Simple LINQ Tutorial

I’ve started learning about LINQ because I need to keep up to date with the latest technology out there. I’ve created a simple Business Layer which interact directly with Linq to SQL(DBML). It includes Insert, Update, Delete, Select and paging with LINQ.

Hopefully this tutorial will be useful enough for someone who is going to learn about LINQ. With LINQ we can really simplify/integrate the stored procedure into our Code base but it doesn’t mean LINQ does not support Stored Procedure.

It supports Stored Procedure as well since we might use Stored Procedure for complex calculation. You don’t need to create a table adapter anymore since LINQ does everything the same as table adapter.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqCore.Factories
{
    public class GroupFactory
    {

        /// 
        /// this is used to get all the groups
        /// 
        /// 
        public IQueryable GetAllGroups()
        {
            GroupsDataContext db = new GroupsDataContext();
            var groups = from g in db.Groups
                         select g;

            return groups;
        }

        /// 
        /// this is used to get the group based on the group id
        /// 
        /// 
        /// 
        public Group GetGroup(int groupid)
        {
            GroupsDataContext db = new GroupsDataContext();

            var groups = from g in db.Groups
                         where (g.GroupID == groupid)
                         select g;

            return groups.SingleOrDefault();
        }

        /// 
        /// this is used to insert Or Update which determined by the nullable
        /// integer value of the groupID
        /// 
        /// 
        /// 
        /// 
        public void GroupUpdate(int? groupID, string groupName, bool valid)
        {
            GroupsDataContext db = new GroupsDataContext();
            Group group = new Group();

            if (groupID.HasValue)
            {
               group = db.Groups.Single(p => p.GroupID == groupID.Value);
            }

            group.GroupName = groupName;
            group.valid = valid;

            if (!groupID.HasValue)
            {
                db.Groups.InsertOnSubmit(group);
            }
            db.SubmitChanges();
        }

        /// 
        /// this is used to delete a group based on its ID
        /// 
        /// 
        public void GroupDelete(int groupID)
        {
            GroupsDataContext db = new GroupsDataContext();

            Group group = db.Groups.Single(p => p.GroupID == groupID);
            db.Groups.DeleteOnSubmit(group);
            db.SubmitChanges();
        }

        /// 
        /// this is used to do paging for the returned result
        /// 
        /// 
        /// 
        /// 
        public IQueryable GetAllGroups(int startIndex, int pageSize)
        {
            GroupsDataContext db = new GroupsDataContext();
            var groups = from g in db.Groups
                         select g;

            return groups.Skip(startIndex).Take(pageSize);
        }
    }
}

File Stream/Stream response in AJAX Update Panel

Last few months, I got a problem to place a button to generate a CSV file in the update panel. I was having a problem related with response error. So what i did was to place the button outside the Update Panel. Today, I found a simple solution to place this button inside the AJAX Update panel

1. You need to set the page mode on the page load event

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.Form.Enctype = "multipart/form-data";
}

2. set the update Panel Children as trigger to true


3. set the trigger to your button


   

Filtering Field/Column in DataTable

I was having a problem when I have the same datatable and one datagrid but I want to display different field on the grid for different report and I want to use AutoGenerateColumn = true in the datagrid. Remember, it is about filtering fields not Row(If you want to filter row then you can use dataview).

This is the way of filtering field in datatable

     public static DataTable FilterTableRemoveColumns(tdsReports.ReportSelectDataTable inputTable, List fields)
        {
            //create a new data table
            DataTable newTable = new DataTable();
            newTable.TableName = "newtable";

            //iterate through each column
            foreach (DataColumn col in inputTable.Columns)
            {
                //cross match and filter fields/column
                if (fields.Contains(col.ColumnName))
                {
                    //create a new datacolumn with the same column name and same datatype
                    DataColumn newCol = new DataColumn(col.ColumnName, col.DataType);
                    newTable.Columns.Add(newCol);
                }
            }

            //you ignore the schema because you don't want to throw the exception
            //you merge the data with the new schema
            newTable.Merge(inputTable, true, MissingSchemaAction.Ignore);
            return newTable;
        }

this is how you use it. You pass a string list into the function. The string list contains your desired column

Private Function FilterDataTableColumn(ByVal dtReport As tdsReports.ReportSelectDataTable) As DataTable

        Dim dt As DataTable = New DataTable()
        Try
            Dim list As List(Of String) = New List(Of String)

            If (ReportType = Enums.ReportType.DispatchedOrdersReport) Then
                list.Add("OrderID")
                list.Add("PaymentType")
                list.Add("ProductCode")
                list.Add("Qty")
                list.Add("Price")
                list.Add("Total")
                list.Add("IncGst")

            ElseIf (ReportType = Enums.ReportType.MonthySalesReport) Then
                list.Add("Qty")
                list.Add("ProductCode")
                list.Add("ProductName")

            ElseIf (ReportType = Enums.ReportType.OrderReport) Then
                list.Add("ProductCode")
                list.Add("Qty")
                list.Add("ProductName")

            End If

            dt = objReportService.FilterTableRemoveColumns(dtReport, list)

        Catch ex As Exception

        End Try

        Return dt
    End Function

Set Default value with clear text for input type=”password”

Normally we have two text boxes which is user name and password. On the first load of the page we want to set the default value of user name text box becoming ‘username’ and set the default value of password text box becoming ‘password’ not ‘*******’.

Well what most of us think that we can use javascript to change the type of the input box?well I’ve got this trick to have two textboxes in the same location and swap it with “OnFocus” event

  
            

    

Set the default value for username text box via code behind

      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            txtUserName.Attributes.Add("onfocus", "JavaScript:if(this.value=='username'){this.value=''};")
            txtUserName.Attributes.Add("onblur", "JavaScript:if(this.value==''){this.value='username'};")
            txtUserName.Attributes.Add("value", "username")

            txtPassword.Attributes.Add("onkeydown", _
                                            "javascript:if((event.which && event.which == 13) || " _
                                            + "(event.keyCode && event.keyCode == 13))" _
                                            + " {document.getElementById('" + btnLogin.ClientID + "').click(); " _
                                            + " return false; } else return true;")
        End Sub

Error System.NotSupportedException: The given path’s format is not supported

I got this exception when i tried to uploading a file to a web and try to save it as a different name

System.NotSupportedException: The given path’s format is not supported.
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at

By using code below it will make sure that you will get the real file name without any trailing path, fuCSV is a file upload control and there is a property file name but it doesn’t guarantee that you will get the actual file name. When i tried to debug it, it also give me the file path. The best way of doing this is to use GetFileName method from System.IO.Path

It was:

string filename = fuCSV.PostedFile.FileName;

Fix

string filename = System.IO.Path.GetFileName(fuCSV.PostedFile.FileName);

Record/Row Filter in DataTable

When I have a smaller rows return from my sql stored procedure, I tend to think of not recreating another stored procedure to do filtering or to use optional parameter. My idea is to do filtering from the code base and not recreating/adding the stored procedure.

The idea was to create a generic stored procedure without any filter and apply the filter from the code base. The example given is by applying filter to dataset and then after that add the datatable to dataset and then cast it back again to the datatable.

  public tdsEvent.EventSummaryDataTable TodayEventSummaryFilter(string filter)
        {
            tdsEvent.EventSummaryDataTable table = TodayEventSummaryCache();
            DataRow[] rows = table.Select(filter); //apply the filter first

            if (rows.Length != 0)
            {
                DataSet ds = new DataSet();

                tdsEvent.EventSummaryDataTable eventTable = new tdsEvent.EventSummaryDataTable();
                ds.Tables.Add(eventTable); // add to the filter
                ds.Merge(rows, false, MissingSchemaAction.Ignore);
                // cast it back to the data table
                table = ds.Tables[0] as tdsEvent.EventSummaryDataTable;
            }
            else
            {
                table = new tdsEvent.EventSummaryDataTable();
            }

            return table;
        }

This is the alternative code which doing the same thing as above

Dim table as tdsEvent.EventSummaryDataTable = TodayEventSummaryCache()
//create dataview instance based on datatable

dim dv as DataView = new DataView(table)

//create the filter to select the valid only
dv.RowFilter = "Valid = 1"

//bind to the grid or repeater
rptEvent.Datasource = dv
rptEvent.DataBind()

Casting DataItem in repeater to strongly typed dataset

Most of the time when you use repeater, you want to be able to cast the datasource/dataitem, you don’t really want to do DataBinder.Eval(e.Item.DataItem, “Description”) but you want to do row.Description. It’s not hard to do that, this is the snippet

Protected Sub rptEvents_Repeater(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rptEvents.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then

             'you need to cast eh dataitem into datarowview and cast them again to strongly type dataset

            Dim view As DataRowView = DirectCast(e.Item.DataItem, DataRowView)
            Dim row As tdsEvent.EventSummaryRow = DirectCast(view.Row, tdsEvent.EventSummaryRow)

            If Not (row Is Nothing) Then

                Dim lblVenue As Label = DirectCast(e.Item.FindControl("lblVenue"), Label)
                Dim lblEvent As HyperLink = DirectCast(e.Item.FindControl("lblEvent"), HyperLink)
                Dim lblState As Label = DirectCast(e.Item.FindControl("lblState"), Label)
                Dim lblTime As Label = DirectCast(e.Item.FindControl("lblTime"), Label)
                Dim lblType As Label = DirectCast(e.Item.FindControl("lblType"), Label)

                Dim eventClass As String = row.ColorCode ' don't set free

                ' if event is not normal, set it...
                If Not (row.IsVenueNull()) Then
                    lblVenue.Text = row.Venue
                End If

                If Not (row.IsEventNull()) Then
                    lblEvent.Text = Left(row.Event, 25) + "..."
                    lblEvent.NavigateUrl = String.Format("~/playpoker/view-event.aspx?EventID={0}&EventTypeID={1}", row.EventID.ToString(), row.EventTypeID.ToString())
                End If

                If Not (row.IsStateNull()) Then
                    lblState.Text = row.State
                End If

                If Not (row.IsEventTypeNull()) Then
                    lblType.Text = row.EventType
                End If

                If Not (row.IsRegistrationTimeNull()) Then
                    lblTime.Text = row.RegistrationTime.ToString("hh:mm tt")
                End If

                'bind all the data...

                'set class's
                If Not (String.IsNullOrEmpty(eventClass)) Then
                    lblVenue.CssClass = eventClass
                    lblEvent.CssClass = eventClass
                    lblState.CssClass = eventClass
                    lblTime.CssClass = eventClass
                    lblType.CssClass = eventClass
                End If

            End If
        ElseIf (e.Item.ItemType = ListItemType.Header) Then

            Dim lnk As LinkButton = DirectCast(e.Item.FindControl("lnkVenue"), LinkButton)

            If Not (lnk Is Nothing) Then
                lnk.CommandName = "SortCommand"
                lnk.CommandArgument = "Venue"
            End If

            lnk = DirectCast(e.Item.FindControl("lnkEvent"), LinkButton)

            If Not (lnk Is Nothing) Then
                lnk.CommandName = "SortCommand"
                lnk.CommandArgument = "Event"
            End If

            lnk = DirectCast(e.Item.FindControl("lnkState"), LinkButton)

            If Not (lnk Is Nothing) Then
                lnk.CommandName = "SortCommand"
                lnk.CommandArgument = "State"
            End If

            lnk = DirectCast(e.Item.FindControl("lnkTime"), LinkButton)

            If Not (lnk Is Nothing) Then
                lnk.CommandName = "SortCommand"
                lnk.CommandArgument = "lnkTime"
            End If

            lnk = DirectCast(e.Item.FindControl("lnkType"), LinkButton)

            If Not (lnk Is Nothing) Then
                lnk.CommandName = "SortCommand"
                lnk.CommandArgument = "EventType"
            End If

        End If
    End Sub

How to filter and sort in Dataset

Here is the way to filter or to sort dataset and then you can bind into your datagrid

              If intEventID = 0 Then
                ds = DataAccess.Events.GetAllEventsByRegionID(Me.radStartDate.SelectedDate, Me.radEndDate.SelectedDate, intRegionID, intVenueID)

            Else
                ds = DataAccess.Events.GetEventByIDDS(intEventID)
            End If

            'this is used to show the valid event only
            Dim eventView As DataView
            eventView = ds.Tables(0).DefaultView
            eventView.RowFilter = "Valid = true"

            'this is used to sort
            eventView.Sort = "EventID Desc"

           grdEvents.DataSource = eventView

Get current page name in ASP.NET

In order to get current page name , we need to get it from server variables of “ScriptName” but that’s not enough since it will bring up the whole path. you need to use System.IO in order to get the file name

C# version:

string strCurrentPage = System.IO.Path.GetFileName(Request.ServerVariables ["SCRIPT_NAME"])

VB.NET version:

 Dim strCurrentPage As String = System.IO.Path.GetFileName(Request.ServerVariables("SCRIPT_NAME"))

Page 5 of 7

Powered by WordPress & Theme by Anders Norén