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

Category: VB.NET Page 2 of 3

VB.NET

Enums with description in c#

Sometime when we have Enum , we want to use it /bind it on the list as well with a better description/ word. With this method you can bind enum to a list which display its description but store its value as well.This is very useful function.

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.ComponentModel;

public class Enums
    {
        #region helpers
        public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
              (DescriptionAttribute[])fi.GetCustomAttributes
              (typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        public static T Parse(string input)
        {
            return (T)Enum.Parse(typeof(T), input);
        }
        #endregion

        #region enums
        public enum ResultsType
        {
            [Description("Featured Products")]
            FeaturedProducts,
            [Description("New Products")]
            NewStock,
            CategoryResults,
            [Description("Specials")]
            Specials,
            Brand,
            Row1,
            Row2,
            Row3,
            [Description("This Weeks Specials")]
            ThisWeeksSpecials,
            [Description("Top 10 Best Sellers")]
            Top10BestSellers,
            [Description("Special Offers")]
            SpecialOffers,
            [Description("Buy 1 Get 1 Free")]
            Buy1Get1Free,
            [Description("Half Price Bargains")]
            HalfPriceBargains,
            [Description("Top Sellers")]
            TopSellers,
            [Description("Summer Specials")]
            SummerSpecials,
            [Description("CUSTOMERS WHO BOUGHT THIS ALSO BOUGHT")]
            AlsoBought,
            [Description("Related Products")]
            Upsell
        }

          public enum ReportType
         {
            [Description("Monthly Sales Report")]
            MonthySalesReport = 1,
            [Description("Dispatched Orders Report")]
            DispatchedOrdersReport = 2,
            [Description("Order Report")]
            OrderReport = 3
         }

#endregion

}

This is how you bind it

Private Sub PopulateReportType()

        ddlReportType.Items.Clear()
        ddlReportType.Items.Add(New ListItem(Enums.GetEnumDescription(Enums.ReportType.MonthySalesReport), Convert.ToInt32(Enums.ReportType.MonthySalesReport)))
        ddlReportType.Items.Add(New ListItem(Enums.GetEnumDescription(Enums.ReportType.DispatchedOrdersReport), Convert.ToInt32(Enums.ReportType.DispatchedOrdersReport)))
        ddlReportType.Items.Add(New ListItem(Enums.GetEnumDescription(Enums.ReportType.OrderReport), Convert.ToInt32(Enums.ReportType.OrderReport)))

    End Sub

Raise Event in User Control

I need to create a payment gateway user control that will be used accross all of the modules. This user control should be as simple as doing the transaction ONLY. So what I need to do is to let the host/page container knows whether the transaction is succeeded or not, if it is succeeded then the rest of the logic will be handled on ASPX page.

In order to do so I need to create an event on the user control that will be bubbled up to the page container/host. This sample might not be the best solution but it works perfectly for my needs and only requires several lines of code.

Write this in your user control including declaration(signature) of parameter that you want to pass

Partial Class usercontrols_MyPaymentGateway
    Inherits System.Web.UI.UserControl

#Region "Property"

    ''' 
    ''' this is an event for process status
    ''' 
    ''' 
    Public Event getProcessStatus(ByVal isPaid As Boolean)

Write this in your user control where you want to raise the event and pass the parameter

     RaiseEvent getProcessStatus(True)

Write this in your page container(Create an Event handler to handle your user control events) (NOTE: paymentGateway is the name of your user control)

 ''' 
    ''' event handler to the payment gateway controls
    ''' 
    ''' 
    ''' 
    Private Sub paymentProcessed(ByVal isPaid as boolean) Handles paymentGateway.getProcessStatus

        If (paymentGateway.IsPaid) Then
            ltMessage.Text = "Payment Successful " + paymentGateway.ResponseMessage

            'if it is paid then we need to clear the remaining text boxes
            paymentGateway.ClearFields()
        Else
            ltMessage.Text = "Payment Failed " + paymentGateway.ResponseMessage
        End If

    End Sub

Reference to user control in web.config

I’ve seen that most of people put their user control declaration in individual aspx page, and they declare it on the top of that page. What will happen if you are going to use it on multiple number of pages and i believe most of you would like to have a kind of tag that you can simply use on your web page to add your user control. In here, we declare all the user controls in web.config which I believe is more clean and manageable.

Web.Config


      
        
		
	  
    
	  
		  
		  
		  
		  
		  
		  
    

How to use it in ASPX Page






    Untitled Page


    
        
    


Find a control in ContentPlaceHolder

I have a user control and I would like to hide a control on the page container that host this user control. I try to use

Page.FindControl("litContent")

But It throws an error of object not found. The solution is you need to find the contentplaceholder first on the master page then you find the control that you want from that placeholder. It’s a bit tricky since i thought once you get a Page instance then you can get all control hosted on the Page instance itself.

1. Place this tag on your asp.net page where it hosts your control


2. go to the page behind of the user control/page where you want to place your logic to hide/show it

'hide the dynamic page from the parent page
Dim mainContent As ContentPlaceHolder = CType(Page.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)

If Not (mainContent Is Nothing) Then
   Dim contentPlaceHolder As Literal = CType(mainContent.FindControl("litContent"),Literal)
   If Not (contentPlaceHolder Is Nothing) Then
       contentPlaceHolder.Visible = False
   End If
End If

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

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"))

System.OutOfMemoryException in mscorlib.dll

I’ve got a problem when i tried to read some file in asp.net which is like 35mb large over the network. I also need this to be reliable since the file will be growing quickly within a few weeks. I tried to use my method to get the file and then when the file is 32mb in size it works fine but when it’s growing larger then it throws me an error of System.OutOfMemoryException in mscorlib.dll and it’s coming from this code “sr.ReadToEnd()”.

What i suspect was it’s because I’m reading the file which is too large to fit all in one big chunk of string. And i tried to fix my method which is reading the file in smaller piece of file and start to omit it to browser slowly. The fix is included in below:

Original File

Public Sub DishUpFile(ByVal filename As String)

              'first map a path to the file
             Dim filepath As String = filename

             Using sr As System.IO.StreamReader = New System.IO.StreamReader(filepath)

                 Dim buff As Byte() = System.Text.UTF8Encoding.UTF8.GetBytes(sr.ReadToEnd())

                 Response.Clear()
                 Response.Buffer = True
                 Response.ClearHeaders()
                 Response.ContentType = "text/csv"
                 Response.AddHeader("Content-Disposition","attachment;filename=AllMembers.csv")
                 Response.BinaryWrite(buff)
                Response.End()

             End Using

         End Sub

Fix:

Public Sub DishUpCFile(ByVal filename As String)

            Dim nBytesRead As Integer = 0
            Const mSize As Integer = 1024

            Dim bytes As Byte() = New Byte(mSize - 1) {}

            'Open or override a file in the local directory
            Dim fsFile As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)

            Response.Clear()
            Response.Buffer = True
            Response.ClearHeaders()
            Response.ContentType = "text/csv"
            Response.AddHeader("Content-Disposition", "attachment; filename=AllMembers.csv")

            'Read the first bit of content, then write and read all the content
            'From the FromStream to the ToStream.
            nBytesRead = fsFile.Read(bytes, 0, mSize)

            While nBytesRead > 0
                Response.OutputStream.Write(bytes, 0, nBytesRead)
                nBytesRead = fsFile.Read(bytes, 0, mSize)
            End While

            Response.OutputStream.Close()
            fsFile.Close()

       End Sub

Page 2 of 3

Powered by WordPress & Theme by Anders Norén