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

Category: ASP.NET Page 6 of 7

Category for ASP.NET

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

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

Dynamic array in VB/VB.NET/ASP

Time to go back to old school ASP, I found that i need to create an array that contains a list of languages from a table in database. I would like to make this array length as many as the number of rows in language table. yes you can do it through keyword of ReDim and Preserve

     <%
                dim objLanguage
                dim languageCount
                dim languageArray()

                languageCount = 0

                set objLanguage = Server.CreateObject("ADODB.Recordset")
                objLanguage.ActiveConnection = MM_CTG_STRING
                objLanguage.Source = "SELECT * FROM Languages"
                objLanguage.CursorType = 0
                objLanguage.CursorLocation = 2
                objLanguage.LockType = 3
                objLanguage.Open()

                WHILE NOT objLanguage.EOF
                    response.Write("

") response.Write(objLanguage("Language")) response.Write("

") ReDim Preserve languageArray(languageCount) languageArray(languageCount) = objLanguage("LanguageID") languageCount = languageCount + 1 objLanguage.MoveNext() WEND objLanguage.Close() Set objLanguage = nothing %>

How to clear a gridview

Normally, we would like to clear a gridview for various reason. I want the data to be cleared from grid view everytime user does the search and the grid view will be binded again if the user click a particular button otherwise the last result will be displayed when the new dataset/datatable does not return any rows. This is the simplest way i ever think of

gvPlayerListEvent.DataSourceID = String.Empty
gvPlayerListEvent.DataBind()

Only one instance of script manager can be added to the page

I’ve got this error when i have ajax toolkit script manager on the master page while at the same time i’ve script manager on the content page. This is the primary cause of this error.

The work around this is to move the script manager which is located on the master page before the content place holder or if you have any user control which uses script manager as well, place before it. It should be placed on the top of anything which uses this control and the most important thing you need to change the script manager in the content page or user control to be script manager proxy

Page 6 of 7

Powered by WordPress & Theme by Anders Norén