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

Category: ASP.NET Page 2 of 7

Category for ASP.NET

Access javascript object properties with invalid character

ParseJSON returning you an object from your AJAX Call, the problem that I have is my object properties has invalid character (e.g “#”)

Assuming jsonData is my variable that contains the following information

I’d like to grab the property of “#innerxml”

Normally I can do this to get the property of an object but in this case I can’t due to invalid character

(jQuery.parseJSON(jsonData)[0]).#innerxml

So How do I access an object which has properties where one of the property name is using an invalid character (e.g “#”)

I can access with the following style

(jQuery.parseJSON(jsonData)[0])[‘#innerxml’]

Remapping svc extension in IIS 7 extension handlers

If you open your WCF/ svc file in your localhost through browser and it just display blank page then what might happen is you don’t have handler associated with svc extension

To verify it, go to your IIS and go to IIS Handler Mappings and try to find an svc extension entry, but if you couldn’t find extension SVC exists on the list, then you can remap/re-add the svc extension by running

C:\Windows\Microsoft.NET\Framework64\v3.0\Windows Communication Foundation\ServiceModelReg.exe –i

*if you are still using 32 bit then you just need to replace Framework64 with Framework

Simple Collapsible Panel using JQuery

I found a simple collapsible panel developed by a guy called Darren Ingram and I’d definitely recommend it to anyone wanted to implement collapsible panel. His Jquery implementation of collapsible panel is very simple. It just need 2 files (diQuery-collapsiblePanel.js and diQuery-collapsiblePanel.css – where the css classes can even be integrated to your own css class). I prefer this implementation because it’s just a div implementation and the JQuery script will be hooked up to the div elements (where the class name is collapsibleContainer) upon the page loaded. Simple and lightweight in comparison to the collapsible panel of AJAX toolkit (http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CollapsiblePanel/CollapsiblePanel.aspx)

the source code for the collapsible panel by Darren Ingram can be downloaded from his website (http://www.darreningram.net/pages/examples/jQuery/CollapsiblePanelPlugin.aspx)

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

                }

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)

Page 2 of 7

Powered by WordPress & Theme by Anders Norén