Web Service Tester

This is an application to access your Web Service/API without worrying to create your own client application for the sake of testing. Personally, I’m using soapUI (an open source application to test web service)

http://sourceforge.net/projects/soapui/files/

I’d prefer to use tool this because it provides you a transparent communication between the client and the Web Service and it’s really simple to use and configure. It’d save you a lot of time to debug the issue for your client. You can trace it down whether the issue is in the client or in the web service itself

Profiling CLR for .NET application

CLR Profiler can be used to analyse how your object is allocated in memory and which object has taken the most memory. It also can be used to detect memory leak

To download CLR profiler for .NET 2.0 please visit http://www.microsoft.com/download/en/details.aspx?id=13382 , there is another version for .NET framework 1.1

-Extract the file into your desired location

-you also need to run “regsvr32 ProfilerOBJ.dll” otherwise you will get dialog message that mentioned it’s waiting for the CLR and you will not get any result

– Run the CLRProfiler.exe in Binariesx86 if your app is 32 bit and Binariesx64 if your app is 64 bit

For profiling windows app, you can do the following steps:

1. Select the exe file

2. Do stuff/interact with your application

3. Once you are finished then you can close your application or select “Kill Application”

4. Upon completion it will give you the screen below

For profiling ASP.NET app, you can do the following steps:

1. Select Profile ASP.NET from file menu

2. It will restart your IIS with the necessary trace

3. Select “Start ASP.NET”

4. Once you are finished then select “Kill ASP.NET”

5. It will restart the IIS and remove the trace added before

6. Upon completion it will give you the screen below

*You can use this for service as well –

This is the information for GC

Using Disposable object

First method is to use the “Using” keyword which is quite clean and simple

using (IDisposable obj = new DataTable())

{

//do your logic with obj variable

}

Second method is to use Try and finally keyword

IDisposable obj = null;

try

{

obj = new DataTable();

}

finally

{

if (obj != null)

{

obj.Dispose();

}

}

Remove UTF8 BOM Character from the file

Normally when you have a UTF8 encoded file then it might have BOM character that will be rendered when you read it using filestream even though when you open the file with the notepad it doesn’t have that character.

I’ve created a function to remove the BOM character from the file

private void removeBoms(string filePattern, string directory)

{

try

{

foreach (string filename in Directory.GetFiles(directory, filePattern))

{

var bytes = System.IO.File.ReadAllBytes(filename);

if (bytes.Length > 2 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)

{

System.IO.File.WriteAllBytes(filename, bytes.Skip(3).ToArray());

}

}

MessageBox.Show(“Files have been processed completely!”);

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

//uncomment this for recursive

//foreach (string subDirectory in Directory.GetDirectories(directory))

//{

//    removeBoms(filePattern, subDirectory);

//}

}

How to call it

private void btnProcess_Click(object sender, EventArgs e)

{

string extension = txtExtensions.Text;

if (extension.Trim().Length > 0 || folderBrowserDialog1.SelectedPath.Trim().Length > 0)

{

if (!extension.StartsWith(“*.”))

{

extension = “*.” + extension;

}

//just process the html files

removeBoms(extension, folderBrowserDialog1.SelectedPath);

}

else

{

if (extension.Trim().Length == 0)

{

txtExtensions.Focus();

MessageBox.Show(“Please specify the extension files”);

}

else if (folderBrowserDialog1.SelectedPath.Trim().Length == 0)

{

MessageBox.Show(“Please select target folder”);

}

}

}

Tag Replacement using Regex in .NET

This snippet of code shows how to do Synchronisation or HTML tag replacement

-My problem is i want to synchronise of tags between 2 HTML document

Issue

-Source.htm

my source.htm has this tag

<xml id=STATIC_CRITERIA_>

  <fields>

    <field fieldID=OPEN_FLAG displayType=checkboxGroup searchType=checkboxGroup underlyingType=int />

    <field fieldID=PARTITION displayType=dropdown searchType=profile profileID=SU_PARTITIONS underlyingType=int />

    <field fieldID=TEMPLATE_IND displayType=checkbox searchType=checkbox underlyingType=int />

    <field fieldID=INCLUDE_DELETED displayType=checkbox searchType=checkbox underlyingType=string />

  </fields>

</xml>

 -Target.htm has this tag

<xml id=STATIC_CRITERIA_>

</xml>

So now the problem is how do I fill the gap in XML tag in target.htm with the value from mySource.htm. We can do this using regex and it’s very simple

 

  string originalDocument = Load(“c:\\MySource.htm”);

                string syncDocument = Load(“c:\\Target.htm”);

 

                MatchCollection mc = Regex.Matches(originalDocument, “<xml([ ]?.*?)>(.*?)</xml>”, RegexOptions.Singleline | RegexOptions.IgnoreCase);

 

                foreach (Match m in mc)

                {

                    string token = “<xml{0}>”;

                    syncDocument = Regex.Replace(syncDocument, String.Format(token, m.Groups[1].Value) + “(.*?)</xml>”,

                                                               String.Format(token, m.Groups[1].Value) + m.Groups[2].Value + “</xml>”,

                                                               RegexOptions.Singleline | RegexOptions.IgnoreCase);

                }

 MatchCollection is used to return all the instances of that regular expression (e.g you might have multiple XML tags with different ID)

What does this tag means

“<xml([ ]?.*?)>(.*?)</xml>”

 ([ ]?.*) means that I don’t care whatever after it (e.g it can be ID or attributes etc). this is the first parameter that we stored on variable

(.*?) means that whatever inside the tag are captured into the second parameter that we stored on variable

You can access the first variable (e.g any attributes after the XML) by doing

m.Groups[1].Value

you can access the value inside the xml bracket by using

m.Groups[2].Value

so what  contains in

m.Groups[0].Value

it contains the whole xml tag that we extracted using regex

 then we can use regex.replace method to replace the tag in target html. When you replace the tag you need to replace the whole xml tag. You can’t just replace the inner part of it

   foreach (Match m in mc)

                {

                    string token = “<xml{0}>”;

                    syncDocument = Regex.Replace(syncDocument, String.Format(token, m.Groups[1].Value) + “(.*?)</xml>”,

                                                               String.Format(token, m.Groups[1].Value) + m.Groups[2].Value + “</xml>”,

                                                               RegexOptions.Singleline | RegexOptions.IgnoreCase);

                }

Setting the Silverlight (Telerik) RadGrid Culture

I have this date column and it has DateConverter that i created to apply the current thread culture. The problem that I have is
-On load it display the date format perfectly based on the current culture
-The problem is when i double click the cell/edit mode then it applies different format but then when i exit edit mode then it shows the right formatting

e.g
on load the cell display 07/08/2010 (07th August 2010) but when I go to edit mode it shows as 08/07/2010 (08th July 2010) but again when I finish editing then it shows 07/08/2010

so basically my current thread date format is dd/mm/yyyy but in edit mode it applies the us formatting which is mm/dd/yyyy. Finally I found out how to set the grid culture

Dim _LocaleLanguage as String = .String.Empty

_LocaleLanguage = CultureInfo.CreateSpecificCulture(System.Web.HttpContext.Current.Request.UserLanguages(0)).Name.ToString()

dgResults.Language = Windows.Markup.XmlLanguage.GetLanguage(_LocaleLanguage)

Viola!! and it solves my culture problem

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