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

Month: August 2008 Page 3 of 5

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

Getting the last day for each month in SQL server

This is the function in SQL server to get the last day for each month until the day that you define in a variable which is in this case is “@genDate”.

I used this function to iterate some stored procedure every last day in the month

DECLARE @genDate datetime
SET @genDate = '1/31/2006'

WHILE @genDate <= getdate()
	BEGIN
		PRINT @genDate
		SET @genDate = DateAdd(month,1,@genDate)

		--this is used to get the last day for each month
		SET @genDate = DateAdd(day, -1, DateAdd(month, DateDiff(month, 0, @genDate)+1, 0))
	END

NOTE: “-1” in this statement means that it’s minus one day from the beginning of the month which gives you the last day for each month
SET @genDate = DateAdd(day, -1, DateAdd(month, DateDiff(month, 0, @genDate)+1, 0))

COMException (0x80040154): Retrieving the COM class factory for component with CLSID

I’ve got this error when i tried to deploy my service with .NET wrapper for VB6 component :
System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} failed due to the following error: 80040154
.

The workaround of this problem are:

  • Go to regedit and check for this entry {D8749532-0D3D-43B6-973C-C1D62BB6B3C7} ,(replace this with your clsid key) which is under “\HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID”, If it is not exist then it almost certainly that you haven’t registered your VB6 component it self
  • Now you need to go to your project folder and find a reference folder and then copy the DLL that you created before (there will be several DLL under that folder, I believe you need to pick DLL with the largest size) and copy it to the same folder with your .NET DLL on production server
  • Register that DLL using “regsvr32 filename” (e.g regsvr32 APLCryptoCore.dll) and then restart your service and then it should be working
  • Get Selected Item with Gridview in ASP.NET

    I was having a problem before to get selected item with grid view when you click edit button. After spending sometime researching on the internet. I found that we can get the item that you selected by using DataKeynames

    
    
          
          
          
          
          
          
          
    
    
      Protected Sub gvPlayerSearch_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvPlayerSearch.RowCommand
    
                If (e.CommandName = "ViewResult") Then
                   //casting the object to gridview
                    Dim gv As GridView = DirectCast(sender, GridView)
    
                    Dim objEventResults As  MembersDatasetTableAdapters.EventsResultByMemberIDTableAdapter = _
                                            New   MembersDatasetTableAdapters.EventsResultByMemberIDTableAdapter()
    
       //get the selected ID
       Dim dtEventResults As MembersDataset.EventsResultByMemberIDDataTable = _
                                    objEventResults.EventsResultByMemberID(gv.DataKeys(0).Value)
    
       gvPlayerListEvent.DataSource = dtEventResults
       gvPlayerListEvent.DataBind()
      End If
    End Sub
    

    Page 3 of 5

    Powered by WordPress & Theme by Anders Norén