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

Category: VB.NET Page 1 of 3

VB.NET

Enter button in TextBox ASP.NET

This article is demonstrating how to wire up an enter key into a textbox. For example you have a search text box where you press enter then it will click go button and at the same page you have another textbox where you want to do another button click when you press the enter which means it’ is not necessary to post the page. This java script is used to capture the key event of enter and execute the LinkButton and ASP.NET button Click Event on the server side. Please add this javascript to your javascript common library or add this to your master page. This piece of code works in Firefox as well


function ButtonKeyPress(evt, thisElementName)
{
    if(evt.which || evt.keyCode)
    {
        if ((evt.which == 13) || (evt.keyCode == 13))
        {
            // alert('post back href: ' +document.getElementById(thisElementName).href);

            if (typeof document.getElementById(thisElementName).href != 'undefined')
            {
                location = document.getElementById(thisElementName).href;
            }
            else
            {
                document.getElementById(thisElementName).click();
            }
            return false;
        }
    }
    else
    {
        return true;
    }
}

And add this to your .NET code behind on the page load

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
         If Not Page.IsPostBack Then


            If (User.Identity.IsAuthenticated) Then
                Response.Redirect("frmTimeMain.aspx")
            End If

            txtGUID.Attributes.Add("onkeydown", "ButtonKeyPress(event, '" + lnkSubmit.ClientID + "')")
            txtPassword.Attributes.Add("onkeydown", "ButtonKeyPress(event, '" + lnkSubmit.ClientID + "')")
          End If
    End Sub

ASP.NET Calendar selected day on click method

I’ve a case where I have an ASP.NET calendar that has a page load method that automatically select a date when it’s loaded. I also have an event defined for Selected_Changed which will be triggered only when the user select any other date other than pre-selected date on the load

Private Sub ctlCalendar_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ctlCalendar.SelectionChanged
        If (Not String.IsNullOrEmpty(CalendarPreviousPage)) Then
            BaseCalendar.SelectedDate = ctlCalendar.SelectedDate
            Response.Redirect(CalendarPreviousPage)
        End If
    End Sub

But how do I wire up an event or when the selecteddate being clicked?You can use DayRender event and attach it to a javascript in this case I want to go back to previous page. BaseCalendar.Selected date can be any date where you want to set up/wire up the logic

 Private Sub ctlCalendar_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles ctlCalendar.DayRender
        Dim d As CalendarDay
        Dim c As TableCell
        d = e.Day
        c = e.Cell

        If (BaseCalendar.SelectedDate.Value = d.Date) Then
            c.Attributes.Add("OnClick", "history.go(-1)")
        End If

    End Sub

Telerik SL Gridview Cell Foreground color dynamically based on multiple binding

I had a problem before where I build dynamic system (light dataset) for doing CRUD (Create, Read, Update and Delete) and I need to store the history of previous record before Update/Delete and at the same time I also need to indicate the column(e.g changing the color of the column) that has been changed per record in history table. I’ve been struggling for a day in order to accomplish this.

1. You need to add reference and import System.Windows.Interactivity from SL3 SDK
2. Create a TableHistoryColorConverter.vb

Imports System.Windows.Data
Imports System.Globalization
Imports System.Reflection

Public Class TableHistoryColorConverter
    Implements IValueConverter

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim cellColor As SolidColorBrush = New SolidColorBrush(Colors.Black)

        Try

            Dim columnList As String = value.ToString()
            Dim currentColumnName As String = parameter.ToString()
            'Dim changeColumnParam As String = parameter.ToString()
            Dim changedColumnList As String() = columnList.Split(New Char() {","c})

            If changedColumnList.Contains(currentColumnName) Then
                cellColor = New SolidColorBrush(Colors.Red)
            End If

        Catch ex As Exception

        End Try

        Return cellColor
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New Exception("Not Implemented")
    End Function
End Class

3. Create a vb class file called HistoryRecordFormatting.vb

Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Windows.Interactivity
Imports Telerik.Windows.Controls
Imports Telerik.Windows.Controls.GridView
Imports System.Windows.Data
Imports SLCoreLib

Public Class HistoryRecordFormatting
    Inherits Behavior(Of RadGridView)

    Protected Overrides Sub OnAttached()
        MyBase.OnAttached()
        AddHandler AssociatedObject.RowLoaded, New EventHandler(Of Telerik.Windows.Controls.GridView.RowLoadedEventArgs)(AddressOf AssociatedObject_RowLoaded)
    End Sub

    Private Sub AssociatedObject_RowLoaded(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.GridView.RowLoadedEventArgs)
        If (TypeOf e.Row Is GridViewHeaderRow) OrElse (TypeOf e.Row Is GridViewFooterRow) OrElse (TypeOf e.Row Is GridViewNewRow) Then
            Return
        End If


        For Each cell In e.Row.Cells
            'we want to apply logic to data rows only
            'ChangedColumns is the list of the column that has been edited (comma separated value) for that history record
            Dim colorBinding As New Binding("ChangedColumns") With { _
                .Converter = New TableHistoryColorConverter(), .ConverterParameter = cell.Column.UniqueName _
            }

            cell.SetBinding(GridViewCell.ForegroundProperty, colorBinding)
        Next
        'e.Row.Cells(1).SetBinding(GridViewCell.ForegroundProperty, colorBinding)
        'e.Row.Cells[1].SetBinding(GridViewCell.BackgroundProperty, colorBinding);
    End Sub
End Class

4. Add behavior in your XAML (Interaction.Behaviors) tag and HistoryRecordFormatting.


    
        
            
                
                    
                
            
        
        
            
        
        
            
                
            
        
    

Basically what it does is adding the converter on every single cell and use the column name to compare with the changed column. It uses Column.UniqueName to pass it to the ConverterParameter and check whether it’s on the list of changed column or not. The problem looks simple at the beginning but when it comes to silverlight then it’s different mechanism of applying the format compared with ASP.NET

The behavior and AssociatedObject_RowLoaded for me looks like itemdatabound event on repeater.

Reflection GetProperty case sensitive issue

Reflection on .NET by default is case sensitive for the class member. To make it case insensitive you need to pass BindingFlags.IgnoreCase . I’ve passed the ignorecase flag and now it doesn’t return anything!!!


 Dim pi As PropertyInfo = Me.[GetType]().GetProperty(fieldname, BindingFlags.IgnoreCase)

Basically, if you pass one flag then the other flags will be overwritten by default which means all the default flags are disappeared. So to make it case insensitive then you need to pass other binding flags


 Dim pi As PropertyInfo = Me.[GetType]().GetProperty(fieldname, BindingFlags.IgnoreCase Or BindingFlags.Public Or BindingFlags.Instance)

Compression in Silverlight Isolated Storage

Isolated storage in silverlight is used to store information or object therefore we don’t need to go to database to get all the information over and over again but again to use isolated storage or not should be based on case by case. Based on the implementation of the code below, I’ve found that it can compress the isolated storage file from 0.8Mb becoming 0.1 MB which is great enough for me since the quota limit is 1 mb and we try not to exceed that limit.

I’ve got this compression method from Peter Bromberg blog.

This compression method is a wrapper to SharpZip Library for Silverlight, you can download it from here, you need this library before using the code below. You can download the code below from here.

I’ve also created a Isolated Storage File with the assembly version as the file name to make sure that we have clean isolated storage file assuming the uncompressed version of isolated storage is already in production and we need to clean it up. “AssemblyVersion” properties will return the property of the current version no of the running assembly. CheckIsolatedStorageFileVersion will make sure that we always have the clean isolated storage for the new assembly.

Sample of usage
1. How to read/deserialize object from isolated storage

 Dim objMessageCodes As MessageCodes = GetIsolatedStorage(Of MessageCodes)("MyFile.txt")

2. How to write/serialize object to isolated storage

      Dim _messageCodes As New MessageCodes(mListMessage)
      WriteIsolatedStorage(_messageCodes, "myfile.txt")

These are the definition of the above function to serialize/deserialize object from your silverlight, this function is created based on Generic so it’s flexible enough to accept anything

Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.Threading
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Xml.Serialization
Imports System.Runtime.Serialization
Imports System.Reflection

Public Class MySL
 Private mAppStorage As IsolatedStorageFile

    ''' 
    ''' This is used to write the compressed object to Isolated Storage
    ''' 
    ''' 
    ''' 
    Private Sub WriteIsolatedStorage(Of T)(ByVal obj As T, ByVal filename As String)
        Try
            Dim xmlByte As Byte() = Compression.SerializeAndCompress(obj)

            Using _stream As IsolatedStorageFileStream = mAppStorage.CreateFile(filename)
                _stream.Write(xmlByte, 0, xmlByte.Length)
            End Using
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    ''' 
    ''' this is used get the compressed object from Isolated storage
    ''' 
    ''' 
    ''' 
    ''' 
    ''' 
    Private Function GetIsolatedStorage(Of T)(ByVal fileName As String) As T
        Try
            Using _stream As IsolatedStorageFileStream = mAppStorage.OpenFile(fileName, FileMode.Open)
                Using _reader As BinaryReader = New BinaryReader(_stream)
                    Dim tmpBytes As Byte()
                    ReDim tmpBytes(1024)
                    Dim fullBytes As Byte() = Nothing
                    Dim xmlStream As MemoryStream = New MemoryStream()

                    While True
                        Dim read As Integer = _reader.Read(tmpBytes, 0, tmpBytes.Length)

                        If (read <= 0) Then
                            fullBytes = xmlStream.ToArray()
                            Exit While
                        End If

                        xmlStream.Write(tmpBytes, 0, read)
                    End While

                    Dim xmlTempbyte As Byte() = xmlStream.ToArray()
                     Return Compression.DecompressAndDeserialize(Of T)(xmlTempbyte)
                End Using

            End Using

            Return Nothing

        Catch ex As Exception
            Throw ex
        End Try

    End Function

Private _compression As Compression = Nothing

    Private ReadOnly Property Compression() As Compression
        Get
            If (_compression Is Nothing) Then
                _compression = New Compression()
            End If

            Return _compression
        End Get
    End Property

    ''' 
    ''' get the assembly version
    ''' 
    ''' 
    ''' 
    ''' 
    Private ReadOnly Property AssemblyVersion() As String
        Get
            Dim name As String = Assembly.GetExecutingAssembly().FullName
            Dim asmName As AssemblyName = New AssemblyName(name)
            Return asmName.Version.ToString().Replace(".", "")
        End Get
    End Property

''' 
    ''' try to clear isolated storage
    ''' 
    ''' 
    Private Sub CheckIsolatedStorageFileVersion()
        Try
            Dim isoStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForSite

            If Not mAppStorage.FileExists(AssemblyVersion + ".txt") Then
                'clear all the isolated storage
                isoStorage.Remove()
                mAppStorage.Remove()

                mAppStorage = IsolatedStorageFile.GetUserStoreForApplication()

                Using _stream As IsolatedStorageFileStream = mAppStorage.CreateFile(AssemblyVersion + ".txt")
                    Using sw As StreamWriter = New StreamWriter(_stream)
                        sw.Write(AssemblyVersion)
                    End Using
                End Using
                'Throw New Exception("Clearing!!!")
            End If

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

End Class

Wrapper Class to SL SharpZipLib

Imports System
Imports System.Text
Imports System.IO
Imports System.Collections
Imports System.Diagnostics
Imports System.Collections.Generic
Imports System.Runtime.Serialization
Imports ICSharpCode.SharpZipLib.Zip.Compression
Imports System.Xml.Serialization
Imports System.Text.RegularExpressions

Public Class Compression

    Public Sub New()
    End Sub

    Public Function Serialize(Of T)(ByVal inst As T) As Byte()
        Dim dcs As New DataContractSerializer(GetType(T))

        Using ms As New MemoryStream
            dcs.WriteObject(ms, inst)
            Return ms.ToArray()
        End Using

    End Function

    Public Function Deserialize(Of T)(ByVal objectData As Byte()) As T
        Dim dcs As New DataContractSerializer(GetType(T))

        Using ms As New MemoryStream(objectData)
            Return CType(dcs.ReadObject(ms), T)
        End Using

    End Function

    Public Function SerializeAndCompress(Of T)(ByVal inst As T) As Byte()
        Dim b As Byte() = Serialize(Of T)(inst)
        Return Compress(b)
    End Function

    Public Function DecompressAndDeserialize(Of T)(ByVal bytData As Byte()) As T
        Dim bytes As Byte() = Decompress(bytData)
        Return Deserialize(Of T)(bytes)
    End Function

    Public Function Compress(ByVal strInput As String) As Byte()
        Try
            Dim bytData As Byte() = System.Text.Encoding.UTF8.GetBytes(strInput)
            Dim ms As New MemoryStream()
            Dim defl As New Deflater(9, False)

            Using s As Stream = New Streams.DeflaterOutputStream(ms, defl)
                s.Write(bytData, 0, bytData.Length)
                s.Close()
            End Using

            Return DirectCast(ms.ToArray(), Byte())
        Catch
            Throw

        End Try
    End Function

    Public Function Compress(ByVal bytData As Byte()) As Byte()
        Try

            Dim ms As New MemoryStream()
            Dim defl As New Deflater(9, False)

            Using s As Stream = New Streams.DeflaterOutputStream(ms, defl)
                s.Write(bytData, 0, bytData.Length)
                s.Close()
            End Using

            Return DirectCast(ms.ToArray(), Byte())
        Catch
            Throw

        End Try
    End Function

    Public Function Compress(ByVal bytData As Byte(), ByVal ParamArray ratio As Integer()) As Byte()

        Dim compRatio As Integer = 9
        Try
            If ratio(0) > 0 Then
                compRatio = ratio(0)
            End If
        Catch

        End Try

        Try
            Dim ms As New MemoryStream()
            Dim defl As New Deflater(compRatio, False)

            Using s As Stream = New Streams.DeflaterOutputStream(ms, defl)
                s.Write(bytData, 0, bytData.Length)
                s.Close()
            End Using

            Return DirectCast(ms.ToArray(), Byte())
        Catch
            Throw
        End Try
    End Function

    Public Function Decompress(ByVal bytInput As Byte()) As Byte()
        Try

            Dim ms As New MemoryStream(bytInput, 0, bytInput.Length)
            Dim bytResult As Byte() = Nothing
            Dim strResult As String = [String].Empty
            Dim writeData As Byte() = New Byte(4095) {}

            Using s2 As Stream = New Streams.InflaterInputStream(ms)
                bytResult = ReadFullStream(s2)
                s2.Close()
            End Using

            Return bytResult
        Catch
            Throw
        End Try
    End Function

    Public Function ReadFullStream(ByVal stream As Stream) As Byte()
        Dim buffer As Byte() = New Byte(32767) {}
        Using ms As New MemoryStream()
            While True
                Dim read As Integer = stream.Read(buffer, 0, buffer.Length)
                If read <= 0 Then
                    Return ms.ToArray()
                End If
                ms.Write(buffer, 0, read)
            End While
        End Using

        Return buffer
    End Function

End Class

FormsAuthentication.GetRedirectUrl only get the first parameter of querystring

I found the issue with FormsAuthentication.GetRedirectUrl when it redirects then it redirects with the first querystring that you have while in fact you might have more than one querystring

e.g http://localhost/myweb/login.aspx?returnurl=myview.aspx?viewID=123&viewname=abc&viewall=false then the standard FormsAuthentication will redirect to http://localhost/myweb/myview.aspx?viewID=123

but where’s the remaining viewname querystring and viewall querystring??to fix this, just use the code below to pick the remaining querystring

Methods:

  'this is used to fix the issue with FormsAuthentication.GetRedirectUrl only pick the first query string
            'get the original Redirect URL
            Dim redirectUrl As StringBuilder = New StringBuilder(FormsAuthentication.GetRedirectUrl(" ", True))
            Dim coll As NameValueCollection = objRequest.QueryString

            'iterate through every key in query string
            'add the missing query string
            For Each key As String In coll.AllKeys
                If (String.Compare(key, "returnurl", True)  0) Then
                    Dim values As String() = coll.GetValues(key)

                    If (values.Length > 0) Then
                        Dim pair As String = String.Format("{0}={1}", key, values(0))

                        If (redirectUrl.ToString().IndexOf(pair) < 0) Then
                            redirectUrl.Append("&" + pair)
                        End If
                    End If
                End If
            Next

            'this is to retain the original URL as in the query string
            objResponse.Redirect(redirectUrl.ToString())

an activex control on this page might be unsafe to interact with other parts of the page. do you want to allow this interaction?

I keep getting this message “an activex control on this page might be unsafe to interact with other parts of the page. do you want to allow this interaction” when I try to access a page that use Javascript to access ActiveX Code. I’ve spent quite sometime to get rid of this error message and I found out that

  1. The code need implement IObjectSafety Interface
  2. You need to digitally sign the code with valid certificate

Step 1 : Detail on how to implement IObjectSafety
-Create an interface file called as IObjectSafety.vb/IObjectSafety.cs

CSharp (IObjectSafety.cs) :

[ComImport()]
[Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IObjectSafety {
   [PreserveSig()]
   int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions);

   [PreserveSig()]
   int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions);
}
Imports System.Runtime.InteropServices

 _
 _
 _
Interface IObjectSafety
     _
    Function GetInterfaceSafetyOptions(ByRef riid As Guid, ByRef pdwSupportedOptions As Integer, ByRef pdwEnabledOptions As Integer) As Integer

     _
    Function SetInterfaceSafetyOptions(ByRef riid As Guid, ByVal dwOptionSetMask As Integer, ByVal dwEnabledOptions As Integer) As Integer
End Interface

in your ActiveX code you need to implement IObjectSafety

CSharp:


VB.NET:

 _
 _
 _
 _
Public NotInheritable Class ClientUtility
    Implements IObjectSafety


#Region "IObjectSafety Constants"

    Private Const INTERFACESAFE_FOR_UNTRUSTED_CALLER As Integer = &H1
    Private Const INTERFACESAFE_FOR_UNTRUSTED_DATA As Integer = &H2
    Private Const S_OK As Integer = 0

#End Region

#Region "IObjectSafety Methods"

    Public Function GetInterfaceSafetyOptions(ByRef riid As System.Guid, ByRef pdwSupportedOptions As Integer, ByRef pdwEnabledOptions As Integer) As Integer Implements IObjectSafety.GetInterfaceSafetyOptions
        pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER Or INTERFACESAFE_FOR_UNTRUSTED_DATA
        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER Or INTERFACESAFE_FOR_UNTRUSTED_DATA
        Return S_OK
    End Function

    Public Function SetInterfaceSafetyOptions(ByRef riid As System.Guid, ByVal dwOptionSetMask As Integer, ByVal dwEnabledOptions As Integer) As Integer Implements IObjectSafety.SetInterfaceSafetyOptions
        Return S_OK
    End Function

#End Region

CSharp:

[ProgId("Fransiscus.Authentication.ClientUtility")]
[ClassInterface(ClassInterfaceType.AutoDual), ComSourceInterfaces("ControlEvents")]
[Guid("0577147B-6941-4f15-9EFB-2551FEB3D6CC")]
[ComVisible(true)]
public sealed class ClientUtility : IObjectSafety
{


    #region "IObjectSafety Constants"

    private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x1;
    private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x2;
    private const int S_OK = 0;

    #endregion

    #region "IObjectSafety Methods"

    public int GetInterfaceSafetyOptions(ref System.Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)
    {
        pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
        pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
        return S_OK;
    }

    public int SetInterfaceSafetyOptions(ref System.Guid riid, int dwOptionSetMask, int dwEnabledOptions)
    {
        return S_OK;
    }
#endregion

}

Step 2:
You need to obtain certificate and sign it, You also need Windows Server 2008 SDK to sign your code using SignTool.exe (type Signtool SignWizard in command prompt to follow the wizard and sign your DLL)
For more detail please open verisign website (http://www.verisign.com/support/code-signing-support/code-signing/identity-authentication.html) or click here

Upload Multiple Files to FTP in .NET

I’ve played around with FTP couple of weeks back. My application is required to feed FTP folder with 1000+ files daily. I’ve been googling around and I found one of the methods is to use WebApplication so I decided to put this WebApplication method to upload while iterating every single files in the directory. After 5 files, it keeps giving me error The remote server returned an error: (503) Bad sequence of commands. Strangely the only the first 4 files always uploaded successfully, my thought was the FTP server forcely terminated the connection which is right. After googling I found that we should set KeepAlive property to false which means new connection is always created instead of maintained but unfortunately WebClient class doesn’t have KeepAlive property. Finally, I’ve come up with this code which solves my issue in uploading 1000+ files one after the other by doing Asynchronous Upload

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;

namespace Helpers
{
    public class FtpHelpers
    {
        public class FtpState
        {
            private ManualResetEvent wait;
            private FtpWebRequest request;
            private string fileName;
            private Exception operationException = null;
            string status;

            public FtpState()
            {
                wait = new ManualResetEvent(false);
            }

            public ManualResetEvent OperationComplete
            {
                get { return wait; }
            }

            public FtpWebRequest Request
            {
                get { return request; }
                set { request = value; }
            }

            public string FileName
            {
                get { return fileName; }
                set { fileName = value; }
            }
            public Exception OperationException
            {
                get { return operationException; }
                set { operationException = value; }
            }
            public string StatusDescription
            {
                get { return status; }
                set { status = value; }
            }
        }

        public void AsynchronousUpload(string destinationPath, string sourcePath, string userName, string password)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;

            Uri target = new Uri(destinationPath);
            string fileName = sourcePath;
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.KeepAlive = false;
            request.Proxy = null;

            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified.
            // The example specifies the credential only to
            // control how actions are logged on the server.

            if (!(string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password)))
            {
                request.Credentials = new NetworkCredential(userName, password);
            }

            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;

            // Get the event to wait on.
            waitObject = state.OperationComplete;

            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback(EndGetStreamCallback),
                state
            );

            // Block the current thread until all operations are complete.
            waitObject.WaitOne();

            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }

        }

        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState)ar.AsyncState;

            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback(EndGetResponseCallback),
                    state
                );
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }

        }

        // The EndGetResponseCallback method
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState)ar.AsyncState;
            FtpWebResponse response = null;
            try
            {
                response = (FtpWebResponse)state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }

    }
}

Usage:

#Region "Properties"

    Private _ftpUploader As FtpHelpers = Nothing

    Private ReadOnly Property FtpUploader() As FtpHelpers
        Get
            If (_ftpUploader Is Nothing) Then
                _ftpUploader = New FtpHelpers()
            End If

            Return _ftpUploader
        End Get
    End Property

#End Region

Private Sub ProcessFilesToFTP()

        ' make a reference to a directory
        Dim di As New IO.DirectoryInfo(ConfigurationManager.AppSettings("OutputZIPDirectory"))
        Dim jobFiles As IO.FileInfo() = di.GetFiles()

        Console.WriteLine(String.Format("FTP Location: {0}", ConfigurationManager.AppSettings("ftplocation")))

        'list the names of all files in the specified directory
        For Each jobFile As IO.FileInfo In jobFiles

            'process only zip file
            If (jobFile.FullName.Contains("zip")) Then
                Console.WriteLine(String.Format("Upload file {0}", jobFile.Name))

                FtpUploader.AsynchronousUpload(ConfigurationManager.AppSettings("ftplocation") + "/" + jobFile.Name, jobFile.FullName, _
                                   ConfigurationManager.AppSettings("ftpuser"), _
                                   ConfigurationManager.AppSettings("ftppassword"))

            End If

        Next

        Console.WriteLine(String.Format("XML files has been uploaded to {0}", ConfigurationManager.AppSettings("ftplocation")))
    End Sub

The drawback with this code is in the FTP connection where the connection always reinitialized for every single file.

the server committed a protocol violation section= responsestatusline

I’ve got this error and try to spend almost an hour to resolve this:

“the server committed a protocol violation section= responsestatusline” when I tried to get the response back from the payment gateway. It happens when you send HTTP Request one after another on the same page. The solution is to add unsafeheaderparsing to true in web.config and to seet keepAlive property to false from the http request it self

Web.Config


		
			
		
		
			
		
    
      
        
      
    
  

Calling Code:

   Private Function SendXML(ByVal strSend As String) As Boolean
        Dim blnSuccess As Boolean = False
        Dim objSendXML As XmlDocument
        Dim objRequest As HttpWebRequest
        Dim mywriter As StreamWriter
        Dim objResponse As HttpWebResponse
        Dim objReturnedXML As XmlDataDocument
        Dim objElementRoot As XmlElement
        Dim objElementTransaction As XmlNode
        Dim objElementCreditCardInfo As XmlNode
        Dim x As XmlNode

        Dim strApproved As String = String.Empty
        Dim blnCreditCardInfo As Boolean = False

        ' Must reset the variable incase of error
        Me._Paid = False

        objSendXML = New XmlDocument
        objRequest = WebRequest.Create(strPaymentURL)


        'if it is using proxy/behind proxy
        If (UseProxy And Not (String.IsNullOrEmpty(ProxyServer))) Then
            objRequest.Proxy = New System.Net.WebProxy(ProxyServer, True)

            'if there is credential
            If (UseDefaultCredential) Then
                objRequest.Proxy.Credentials = CredentialCache.DefaultCredentials
            Else
                objRequest.Proxy.Credentials = New NetworkCredential(UserName, Password)
            End If

        End If

        objRequest.Method = "POST"
        objRequest.ContentLength = strSend.Length
        objRequest.ContentType = "text/xml"

        'to solve protocol violation problem
        objRequest.KeepAlive = False

Invalid postback or call argument

It’s quite often I have this error because of the content has been changed during postback or because of the control id. I’ve read most of the article suggested to disable the event validation by putting this on the page which is loosen up the security of that particular page. I found the other method without need to change the EnableEventValidation to false. What i found is that you can reregister your control on the render method
VB.NET

Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)

Register(Me)
MyBase.Render(writer) End Sub

Private Sub Register(ByVal ctrl As Control)
For Each c As Control In ctrl.Controls

Register(c)

Next

Page.ClientScript.RegisterForEventValidation(ctrl.UniqueID)

End Sub

C#

protected override void Render(HtmlTextWriter writer)

{
Register(this);base.Render(writer);

}
private void Register(Control ctrl)

{
foreach (Control c in ctrl.Controls)

Register(c);

Page.ClientScript.RegisterForEventValidation(ctrl.UniqueID);

}

Page 1 of 3

Powered by WordPress & Theme by Anders Norén