.Net Pearls -1 System.IO.Path

It’s been a while since I wrote my lost blog post. I thought start it again. Recently I was looking for a get the extn for a file. Initially it took some time for me to get extension and finally I realized System.IO.Path

Two mostly use full methods in System.IO.Path
class is “GetFileName” and “GetExtension”

    var extn = System.IO.Path.GetExtension(@”c:\temp\text.txt”);

            // Result = .txt

 

    var fileName = System.IO.Path.GetFileName(@”c:\temp\text.txt”);

            //Result = text.txt

 

And finally there may other use full methods in in it.

 

 

Validating an XML File using XSD in .NET .20

Below given is the.NET 1.1 code for validating an XML File using an XSD File.

.NET 1.1 Code

//.NET1.1 code
///
/// Methode to validate XML File
///
///

This method expects input XML as string
///
Path to schema file
/// true if xml is validated else false
private bool ValidateXmlUsingXsd(string XmlData,String SchemaPath)
{
XmlValidatingReader v = new XmlValidatingReader(XmlData, XmlNodeType.Document, null);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);  

while (v.Read())
{
// Can add code here to process the content.
}
v.Close();

return isValid;

}

///

public static void MyValidationEventHandler(object sender,
ValidationEventArgs args)
{
//these two variables should be initialized as class level variables
isValid = false;
errorMessage = “Validation event\n” + args.Message;
///
/// Method to get XML in a string from an XML file
///
///

}

///
private string GetStringFromXML(string fileName)
{
StreamReader rd = new StreamReader(fileName);
string str = rd.ReadToEnd();
rd.Close();
return str;
}

Calling the method :
bool valid = ValidateXmlUsingXsd(str, txtXSD.Text);

There are some changes in the .NET 2.0 code for XML Validation .
XmlValidatingReader is marked as obsolete. Need to use XMLReader.Create() using XmlReaderSettngs instead

There are some behavioral changes between validation using the XmlReaderSettings and XmlSchemaSet classes and validation using the XmlValidatingReader class.

The XmlReaderSettings and XmlSchemaSet classes do not support XML-Data Reduced (XDR) schema validation.

The most important difference I found out is that to do XML data validation using a schema, settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
Flag must be enabled. Otherwise the Schema check error will not be displayed.

//.NET2.0 code
private bool ValidateXmlUsingXsd2(string XmlData,String SchemaPath)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, SchemaPath);
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

More about XmlSchemaValidationFlags Enumeration

StringReader xmlStream = new StringReader(XmlData);
XmlReader reader = XmlReader.Create(xmlStream, settings);
while (reader.Read()) ;

return isValid;
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
isValid = false;
errorMessage = “Validation Error: ” + e.Message;
}

 


Member name
Description
AllowXmlAttributes
Allow xml:* attributes even if they are not defined in the schema. The attributes will be validated based on their data type.
None
Do not process identity constraints, inline schemas, schema location hints, or report schema validation warnings.
ProcessIdentityConstraints
Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation.
ProcessInlineSchema
Process inline schemas encountered during validation.
ProcessSchemaLocation
Process schema location hints (xsi:schemaLocation, xsi:noNamespaceSchemaLocation) encountered during validation.
ReportValidationWarnings
Report schema validation warnings encountered during validation.

In a nutshell, Always set settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; when a schema validation is required for the XML in .NET 2.0

 

///
/// This event handler is called only when a validation error occurs
///
///

Validating an XML File using XSD in .NET .20

Below given is the.NET 1.1 code for validating an XML File using an XSD File.

.NET 1.1 Code

//.NET1.1 code
///
/// Methode to validate XML File
///
///

This method expects input XML as string
///
Path to schema file
/// true if xml is validated else false
private bool ValidateXmlUsingXsd(string XmlData,String SchemaPath)
{
XmlValidatingReader v = new XmlValidatingReader(XmlData, XmlNodeType.Document, null);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
new ValidationEventHandler(MyValidationEventHandler);  

while (v.Read())
{
// Can add code here to process the content.
}
v.Close();

return isValid;

}

///

public static void MyValidationEventHandler(object sender,
ValidationEventArgs args)
{
//these two variables should be initialized as class level variables
isValid = false;
errorMessage = “Validation event\n” + args.Message;
///
/// Method to get XML in a string from an XML file
///
///

}

///
private string GetStringFromXML(string fileName)
{
StreamReader rd = new StreamReader(fileName);
string str = rd.ReadToEnd();
rd.Close();
return str;
}

Calling the method :
bool valid = ValidateXmlUsingXsd(str, txtXSD.Text);

There are some changes in the .NET 2.0 code for XML Validation .
XmlValidatingReader is marked as obsolete. Need to use XMLReader.Create() using XmlReaderSettngs instead

There are some behavioral changes between validation using the XmlReaderSettings and XmlSchemaSet classes and validation using the XmlValidatingReader class.

The XmlReaderSettings and XmlSchemaSet classes do not support XML-Data Reduced (XDR) schema validation.

The most important difference I found out is that to do XML data validation using a schema, settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
Flag must be enabled. Otherwise the Schema check error will not be displayed.

//.NET2.0 code
private bool ValidateXmlUsingXsd2(string XmlData,String SchemaPath)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, SchemaPath);
settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

More about XmlSchemaValidationFlags Enumeration

StringReader xmlStream = new StringReader(XmlData);
XmlReader reader = XmlReader.Create(xmlStream, settings);
while (reader.Read()) ;

return isValid;
}

private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
isValid = false;
errorMessage = “Validation Error: ” + e.Message;
}

 


Member name
Description
AllowXmlAttributes
Allow xml:* attributes even if they are not defined in the schema. The attributes will be validated based on their data type.
None
Do not process identity constraints, inline schemas, schema location hints, or report schema validation warnings.
ProcessIdentityConstraints
Process identity constraints (xs:ID, xs:IDREF, xs:key, xs:keyref, xs:unique) encountered during validation.
ProcessInlineSchema
Process inline schemas encountered during validation.
ProcessSchemaLocation
Process schema location hints (xsi:schemaLocation, xsi:noNamespaceSchemaLocation) encountered during validation.
ReportValidationWarnings
Report schema validation warnings encountered during validation.

In a nutshell, Always set settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; when a schema validation is required for the XML in .NET 2.0

 

///
/// This event handler is called only when a validation error occurs
///
///

showModeldialogbox Postback to same page.

I almost wasted 4 to 5 hours to post back the model dialog to same page. But the solution is very simple.

ADD  <base target=”_self” /> in header field. thats all your showshowModeldialogbox  will work perfect.

Here the sample code

function openSerialWin()
{
var serialtxt = “<%=txtSerialNo.ClientID %>”;
var producttxt = “<%=txtProduct.ClientID %>”;
var SerialNoVal = document.getElementById(“<%=txtSerialNo.ClientID %>”).value;
var ProductVal = document.getElementById(“<%=txtProduct.ClientID %>”).value;
// to handle in IE7
if (window.showModalDialog)
{
var myDialog = new Object;
myDialog.seralNumber =  document.getElementById(serialtxt).value;
myDialog.product = document.getElementById(producttxt).value;
result = window.showModalDialog(‘SerialNumber_scrl.aspx’, myDialog, “dialogHeight:900px,dialogWidth:400px,resizable:no,center:yes” );

if (result==false)
return;
else {
document.getElementById(serialtxt).value = myDialog.seralNumber;
document.getElementById(producttxt).value = myDialog.product;
}
}
// to handle in Firefox
else
{
openWin(‘SerialNumber_scrl.aspx?cntrol1=’ + serialtxt + ‘&cntrol2=’ + producttxt + ‘&SerialNoVal=’ + SerialNoVal + ‘&ProductVal=’ + ProductVal,’ProductsPage’, ‘900’, ‘400’,’200′,’200′,’no’,’no’,’no’,’no’,’yes’);
}

return false;
}

this is code in child window

if (window.showModalDialog)
{
window.returnValue = true;
if (window.dialogArguments != null)
{
window.dialogArguments.seralNumber = cellSerialValue;
window.dialogArguments.product = cellProdValue;
}
window.close();
}
else
{

var query = location.search;
var aValue = query.substring(query.indexOf(“cntrol1=”) + 8, query.indexOf(“&”));
var bValue = query.substring(query.indexOf(“cntrol2=”) + 8, query.indexOf(“&SerialNoVal”));
window.opener.document.getElementById(aValue).value = cellSerialValue;
window.opener.document.getElementById(bValue).value = cellProdValue;
window.close()
}

Thats all .

ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

CAUSE

loadTOCNode(1, ’cause’);

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application’s event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.


RESOLUTION

loadTOCNode(1, ‘resolution’); To work around this problem, use one of the following methods:

For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:

  Response.Redirect ("nextpage.aspx", false);

If you use this workaround, the code that follows Response.Redirect is executed.

For Server.Transfer, use the Server.Execute method instead.

Active Directory Reading and updating Properties

Here I am created a class File lke bleow

 public class Userdetails
{
    public static string ADPath = ConfigurationManager.AppSettings.Get(“ADPath”); // Get the ADAM Path from web config fiel
    public static string ADUser = ConfigurationManager.AppSettings.Get(“ADUser”); //ADAM Administrator
    public static string ADPassword = ConfigurationManager.AppSettings.Get(“ADPassword”); //ADAM Administrator  password

    public static DirectoryEntry GetUserDetails(string userID)
    {
            AuthenticationTypes AuthTypes;  // Authentication flags.
            // Set authentication flags.
            // For non-secure connection, use LDAP port and
            //  ADS_USE_SIGNING |
            //  ADS_USE_SEALING |
            //  ADS_SECURE_AUTHENTICATION
            // For secure connection, use SSL port and
            //  ADS_USE_SSL | ADS_SECURE_AUTHENTICATION
            AuthTypes = AuthenticationTypes.Signing |
                AuthenticationTypes.Sealing |
                AuthenticationTypes.Secure;
            DirectoryEntry De = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthTypes);
        DirectorySearcher Ds = new DirectorySearcher(De);
        SearchResult Sr;
        Ds.SearchScope = SearchScope.Subtree;
        Ds.Filter = “(&(objectclass=*)(cn= ” + userID + “))”;
        Sr = Ds.FindOne();
        if (!(Sr == null))
        {
            De = new DirectoryEntry(Sr.Path, ADUser, ADPassword, AuthTypes);
            return De;
        }
        else
        {
            return null;
        }
    }

//Updating the ADAM password.   

 public static void SetUserPassword(DirectoryEntry oDE, string Password)
    {
        int intPort = int.Parse(“389”);
        const long ADS_OPTION_PASSWORD_PORTNUMBER = 6;
        const long ADS_OPTION_PASSWORD_METHOD = 7;
        const int ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0;
        const int ADS_PASSWORD_ENCODE_CLEAR = 1;

        oDE.Invoke(“SetOption”, new object[] { ADS_OPTION_PASSWORD_PORTNUMBER, intPort });
       oDE.Invoke(“SetOption”, new object[] {ADS_OPTION_PASSWORD_METHOD, ADS_PASSWORD_ENCODE_CLEAR});
        oDE.Invoke(“SetPassword”, new object[] { Password });
    }

//Getting the ADAM Properties
    public static string GetProperty(DirectoryEntry De, string PropertyName)
    {
        if (De.Properties.Contains(PropertyName))
        {
            return De.Properties[PropertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

//Setting the ADAM Propertie   

public static void SetProperty(DirectoryEntry De, string PropertyName, string PropertyValue)
    {
        if ((PropertyValue != string.Empty) && (PropertyValue != null))
        {
            if (De.Properties.Contains(PropertyName))
            {
                De.Properties[PropertyName][0] = PropertyValue;
            }
            else
            {
                De.Properties[PropertyName].Add(PropertyValue);
            }
        }
    }
 
}

 

In your code behind file access the field like this.

To get the Properties

DirectoryEntry DeUserDetails = new DirectoryEntry();
DeUserDetails = Userdetails.GetUserDetails(strUserName);

txtFirstName.Text = Userdetails.GetProperty(DeUserDetails, “givenName”);

To Set the properties like this

System.DirectoryServices.DirectoryEntry deAddUserDetails = Userdetails.GetUserDetails(txtUserName.Text);
Userdetails.SetProperty(deAddUserDetails, “mail”, txtEmail.Text);

deAddUserDetails.CommitChanges();

 

To update the Password

 Userdetails.SetUserPassword(deAddUserDetails, txtPassword.Text);

Adding a new user to ADAM

 System.DirectoryServices.DirectoryEntry myDE = new DirectoryEntry(Userdetails.ADPath, Userdetails.ADUser, Userdetails.ADPassword, AuthenticationTypes.Secure);
            DirectoryEntries myEntries = myDE.Children;
            System.DirectoryServices.DirectoryEntry deAddUserDetails = myEntries.Add(“CN=” + UserName.Text, “user”);
            Userdetails.SetProperty(deAddUserDetails, “userPrincipalName”, UserName.Text);
            //Userdetails.SetProperty(deAddUserDetails, “userPassword”, txtPassword.Text);
            deAddUserDetails.CommitChanges();

Gridview CustomData sorting and paging

In page load event bind the Datasource to your Grid view

 Private Sub PopulatePublishersGridView()

 

        Dim connectionString As String = AccessConnectionString()

        Dim accessConnection As OleDbConnection = New OleDbConnection(connectionString)

 

        Dim sqlQuery As String = “SELECT [PubID], [Name], [Company Name], [Address], [City], [State], [Zip], [Telephone], [Fax], [Comments] FROM Publishers ORDER BY [Name] ASC;”

 

        Dim accessCommand As New OleDbCommand(sqlQuery, accessConnection)

 

        Dim publishersDataAdapter As New OleDbDataAdapter(accessCommand)

        Dim publishersDataTable As New DataTable(“Publishers”)

        publishersDataAdapter.Fill(publishersDataTable)

 

        Dim dataTableRowCount As Integer = publishersDataTable.Rows.Count

 

        If dataTableRowCount > 0 Then

            gridViewPublishers.DataSource = publishersDataTable

            gridViewPublishers.DataBind()

        End If

    End Sub

 

    Private Function AccessConnectionString() As String

        Dim accessDatabasePath As String = Server.MapPath(“~/App_Data/biblio.mdb”)

        Return String.Format(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};”, accessDatabasePath)

    End Function

 

    Private Property GridViewSortDirection() As String

        Get

            Return IIf(ViewState(“SortDirection”) = Nothing, “ASC”, ViewState(“SortDirection”))

        End Get

        Set(ByVal value As String)

            ViewState(“SortDirection”) = value

        End Set

    End Property

 

    Private Property GridViewSortExpression() As String

        Get

            Return IIf(ViewState(“SortExpression”) = Nothing, String.Empty, ViewState(“SortExpression”))

        End Get

        Set(ByVal value As String)

            ViewState(“SortExpression”) = value

        End Set

    End Property

 

    Private Function GetSortDirection() As String

        Select Case GridViewSortDirection

            Case “ASC”

                GridViewSortDirection = “DESC”

 

            Case “DESC”

                GridViewSortDirection = “ASC”

        End Select

 

        Return GridViewSortDirection

    End Function

 

    Protected Sub gridViewPublishers_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)

        gridViewPublishers.DataSource = SortDataTable(gridViewPublishers.DataSource, True)

        gridViewPublishers.PageIndex = e.NewPageIndex

        gridViewPublishers.DataBind()

    End Sub

 

    Protected Function SortDataTable(ByVal dataTable As DataTable, ByVal isPageIndexChanging As Boolean) As DataView

        If Not dataTable Is Nothing Then

            Dim dataView As New DataView(dataTable)

            If GridViewSortExpression <> String.Empty Then

                If isPageIndexChanging Then

                    dataView.Sort = String.Format(“{0} {1}”, GridViewSortExpression, GridViewSortDirection)

                Else

                    dataView.Sort = String.Format(“{0} {1}”, GridViewSortExpression, GetSortDirection())

                End If

            End If

            Return dataView

        Else

            Return New DataView()

        End If

    End Function

 

    Protected Sub gridViewPublishers_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)

        GridViewSortExpression = e.SortExpression

        Dim pageIndex As Integer = gridViewPublishers.PageIndex

        gridViewPublishers.DataSource = SortDataTable(gridViewPublishers.DataSource, False)

        gridViewPublishers.DataBind()

        gridViewPublishers.PageIndex = pageIndex

    End Sub

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

        PopulatePublishersGridView()

    End Sub