Fransiscus Setiawan | EV Charging & Azure Solution Architect | Sydney

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

ORDER BY in UNION

I was having a problem this morning in using a ORDER BY in UNION Clause. The solution is to use keyword of “TOP 100 PERCENT” on the related ORDER BY SELECT query.

CREATE PROCEDURE MyAPLRank
@MemberID int
AS
      SET NOCOUNT ON;
BEGIN
      SELECT r.ResultName,r.PlayerOfTheYearID,r.MemberID,r.RankID,r.memberCode,
            r.FirstName,r.Surname,r.State,r.NumEvents,r.Points,r.AvgPoints,
                  r.MeetsRequirements,r.Valid,r.IsLeaderBoard,r.RowNum
      FROM
      (
            SELECT
                  'Player of The Year' As ResultName,PlayerOfTheYearID,MemberID,
                  RankID,memberCode,FirstName,Surname,State,NumEvents,Points,
                  AvgPoints,MeetsRequirements,Valid,'0' as IsLeaderBoard,1 as RowNum
            FROM
                  PlayerOfTheYearQuery
            WHERE
                  PlayerOfTheYearID
                  =
                  (
                        SELECT
                              TOP 1 poy.PlayerOfTheYearID
                        FROM
                              PlayerOfTheYear poy
                        INNER JOIN
                              Schedule s
                        ON
                              (s.ScheduleID = poy.ScheduleID)
                        WHERE
                              (s.MonthID IS NULL AND s.WeekID IS NULL AND s.QuarterID IS NULL)
                        ORDER BY
                              s.ScheduleID
                        DESC
                  ) AND MemberID = @MemberID AND MeetsRequirements = 1
            UNION
            SELECT
                  'Player of The Month' As ResultName,PlayerOfTheYearID,MemberID,
                  RankID,memberCode,FirstName,Surname,State,NumEvents,Points,
                  AvgPoints,MeetsRequirements,Valid,'0' as IsLeaderBoard,2 as RowNum
            FROM
                  PlayerOfTheYearQuery
            WHERE
                  PlayerOfTheYearID
                  =
                  (
                        SELECT
                              TOP 1 poy.PlayerOfTheYearID
                        FROM
                              PlayerOfTheYear poy
                        INNER JOIN
                              Schedule s
                        ON
                              (s.ScheduleID = poy.ScheduleID)
                        WHERE
                              (s.MonthID IS NOT NULL AND s.WeekID IS NULL)
                        ORDER BY
                              s.ScheduleID
                        DESC
                  ) AND MemberID = @MemberID AND MeetsRequirements = 1
            UNION
            SELECT
                  'Player of The Week' As ResultName,PlayerOfTheYearID,MemberID,
                  RankID,memberCode,FirstName,Surname,State,NumEvents,Points,
                  AvgPoints,MeetsRequirements,Valid,'0' as IsLeaderBoard,3 as RowNum
            FROM
                  PlayerOfTheYearQuery
            WHERE
                  PlayerOfTheYearID
                  =
                  (
                        SELECT
                              TOP 1 poy.PlayerOfTheYearID
                        FROM
                              PlayerOfTheYear poy
                        INNER JOIN
                              Schedule s
                        ON
                              (s.ScheduleID = poy.ScheduleID)
                        WHERE
                              (s.MonthID IS NOT NULL AND s.WeekID IS NOT NULL)
                        ORDER BY
                              s.ScheduleID
                        DESC
                  ) AND MemberID = @MemberID  AND MeetsRequirements = 1
      UNION

                SELECT TOP 100 PERCENT
                         v.venue As ResultName,l.leaderboardID as PlayerOfTheYearID,lq.MemberID,
                         lq.RankID,lq.membercode,lq.name as FirstName,lq.name as Surname,s.State,
                        lq.NumEvents,lq.Points,lq.points as AvgPoints,lq.valid as MeetsRequirements,
                        lq.Valid, '1' as IsLeaderBoard,4 as RowNum
                FROM
                        leaderboardquery lq
                INNER JOIN
                        leaderboard l
                ON
                        (
                                l.leaderboardid = lq.leaderboardid
                            AND
                                l.venueid IS NOT NULL
                            AND
                                lq.MemberID = @MemberID
                            AND
                                l.scheduleID =
                                        (
                                         SELECT    ScheduleID
                                         FROM    Schedule
                                         WHERE    GETDATE() BETWEEN FromDate AND ToDate
                                                AND MonthID IS NOT NULL
                                        )
                        )
                INNER JOIN
                        venues v
                ON
                        (v.venueID = l.venueid)
                INNER JOIN
                        states s
                ON
                        l.StateID = s.StateID
                ORDER BY
                    l.ScheduleID
                DESC
      ) r
ORDER BY
      RowNum
END

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

XML http object cross browser

I believe this will be useful for everyone who wants to implement AJAX manually and make it compatible cross browser.



           // cross-browser method to retrieve an XMLHttp object for asynchronous requests & responses
            function GetHTTPRequest()
            {
                var http_request = false;

                if (window.XMLHttpRequest)
                {
                    // Mozilla, Safari,...
                    http_request = new XMLHttpRequest();

                    if (http_request.overrideMimeType)
                    {
                        http_request.overrideMimeType("text/xml");
                    }
                }
                else if (window.ActiveXObject)
                {
                    // IE
                    try
                    {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                    }
                    catch (e)
                    {
                        try
                        {
                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {}
                    }
                }

                return http_request;
            }


SYS is undefined in AJAX Update Panel

I tried to implement AJAX on my website by using AJAX extension on visual studio .NET. I tried to drag update panel to my page and I’ve put my button event handler to the trigger collection in update panel. I was expecting when i click that particular button then it will not refresh or load up the page, but in fact it reloads the page which showing me that the AJAX panel does not work, and my firebug detects that there are errors related with sys is undefined.

This happens because I haven’t AJAX config on my web.config. The config is related with HTTP handler, you can try to put this in your web.config. Please make sure it should be inside “”


    
      
    

Set/Find item in Dropdownlist based on its list item value in ASP.NET

this is a very simple trick on how to select an item in pre binding/pre populated dropdown list from database in asp.net, you can use “FindByValue” method from dropdown list to return you a list item then you can use index of to find the index no of that list item and then set the selected index.

ddlSMSRate.SelectedIndex = ddlSMSRate.Items.IndexOf(ddlSMSRate.Items.FindByValue(drCompany.SMSRate));

Override connection string in TableAdapter with web.config

I found this tip is very useful for me in my day to day coding. Sometimes you create a table adapter in dataset in Data layer project, everything works fine but you will start wondering how to make it configurable or how to use the connection string in my web project which is in web.config.

You don’t want to keep changing it and compile it everytime you change the database right?Ok so what you can do is now to open or to add “settings.cs” which is located in your data layer project and then you can paste this piece of code

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

namespace Linq.Properties
{

    internal sealed partial class Settings
    {
        #region generated stuff

        public Settings()
        {
            // // To add event handlers for saving and changing settings, uncomment the lines below:
            //
            // this.SettingChanging += this.SettingChangingEventHandler;
            //
            // this.SettingsSaving += this.SettingsSavingEventHandler;
            //
        }

        private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e)
        {
            // Add code to handle the SettingChangingEvent event here.
        }

        private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Add code to handle the SettingsSaving event here.
        }

        #endregion

        #region ->this override

        public override object this[string propertyName]
        {
            get
            {
                if (propertyName == "scoutsJamboreeConnectionString")
                {
                    return (System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                }
                return base[propertyName];
            }

            set
            {
                base[propertyName] = value;
            }
        }

        #endregion
    }
}

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

Provide Link to a file without showing the actual path in asp.net

Let’s say you have some file that allow people to download it but you don’t want to expose the actual path for security reason.

Here is the way of doing it, You need to read the file and put that on byte variable then you start omitting slowly instead of the whole chunk. In the next article you will see the error if you omit a big file at once

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 17 of 19

Powered by WordPress & Theme by Anders Norén