Access Cookies from JavaScript

January 31, 2013

 

Here is the code to access Cookies from Javascript.

Happy coding Smile

 

   1:  <html xmlns="http://www.w3.org/1999/xhtml&quot;>

   2:  <head id="Head1" runat="server">
   3:   
   4:      <title>Welcome</title>
   5:      <script type="text/javascript">
   6:      
   7:        function getCookies() {
   8:              var cks = new Object();
   9:              var ckList = document.cookie.split("; ");
  10:              for (var i = 0; i < ckList.length; i++) {
  11:                  var ck = ckList[i].split("=");
  12:                  cks[ck[0]] = unescape(ck[1]);
  13:              }
  14:              return cks;
  15:          }
  16:   
  17:         
  18:          function init() {
  19:             var cookies = getCookies();
  20:             var value1 = cookies["opADFS_WTREALM"];
  21:                  alert(value1);
  22:          }
  23:          window.onload = init;
  24:      </script>
  26:  </head>
  27:  </html>

JavaScript Session Timeout Forms Authentication using JQuery Ajax and Webservice

July 9, 2012

If you want to handle your Session timeout through Javascript to Popup a window that says “you have been logged out due to time out”  Then Folllow these 3 Simple steps…

Step1: Regster a javascript function in Page_Init method of your Page.

1: private void RegisterSessionTimeOutScript() 2: {

 3:         StringBuilder csText = new StringBuilder();
 4:         csText.Append("<script type=\"text/javascript\" language=\"javascript\">");
 5:         csText.Append("var timeOut;"); 
 6:         csText.Append("var MinutesToTimeOut;");
 7:         csText.Append("function resetTimer() {");
 8:         csText.Append("clearTimeout(timeOut);");
 9:         csText.Append("if(window.abandonSession)");
 10:         csText.Append("timeOut = setTimeout(abandonSession, MinutesToTimeOut*60*1000);");
 11:         csText.Append("// 1Sec = 1000 Milli Secs");
 12:         csText.Append("}");
 13:         csText.Append(string.Format("window.onload=resetTimer; document.onmousemove = resetTimer; document.onkeypress = resetTimer; MinutesToTimeOut={0};", FormsAuthentication.Timeout.Minutes));
 14:         csText.Append("</script>");
 15:         Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SessionTimeOutScript", csText.ToString());
 16:     }
Register above javascript inside Page_Init method
 1:   protected void Page_Init(object sender, EventArgs e)
 2:     {
 3:         RegisterSessionTimeOutScript();
 4:      }

Step2: JQuery method to call ajax WebService

 1:  $(document).ready(function () {
 2:  function abandonSession() {
 3:           // alert('coming');
 4:             $.ajax({
 5:                 type: "POST",
 6:                 url: "JQuerySessionTimeOutWebservice.asmx/AbandonSessionOnTimeout",
 7:                 contentType: "application/json; charset=utf-8",
 8:                 dataType: "json",
 9:                 success: function (msg) {
 10:                     // Do something interesting here.
 11:                     if (msg.d.IsUserLoggedIn == false) {
 12:                         alert('You are about to be signed out due to your current session timeout');
 13:                         $(window).attr("location", msg.d.LoginUrl);
 14:                     }
 15:                 }
 16:             });
 17:         }

Step3: Create a web service inside your web application.

 1: WebService(Namespace = "http://tempuri.org/")]
 2: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 3: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 4: [System.Web.Script.Services.ScriptService]
 5: public class JQuerySessionTimeOutWebservice : System.Web.Services.WebService
 6: {
 7:  
 8:     public JQuerySessionTimeOutWebservice()
 9:     {
 10: 
 11:         //Uncomment the following line if using designed components 
 12:         //InitializeComponent(); 
 13:     }
 14: 
 15:     [WebMethod(EnableSession = true)]
 16:     public JsonLoginValues AbandonSessionOnTimeout()
 17:     {
 18:         if (Session != null)
 19:         {
 20:             Session.Abandon();
 21:             FormsAuthentication.SignOut();
 22:         }
 23:  
 24:         JsonLoginValues values = new JsonLoginValues();
 25:         values.IsUserLoggedIn = false;
 26:         values.LoginUrl = (DistributorPortalAPI.Common.IsClaimsAuthentication) ? System.Configuration.ConfigurationManager.AppSettings["SignOutURL"].ToString() : FormsAuthentication.LoginUrl;
 27:         return values;
 28:     }
 29:  
 30: [Serializable]
 31: public class JsonLoginValues
 32: {
 33:     public string LoginUrl;
 34:     public bool IsUserLoggedIn;
 35: }
 36: 
 37: }

You can place Class JsonLoginValues in a separate class file…

Set your Forms Authentication Timeout to one minute in your web.config and then run your application to test your code….

Happy coding…:-)

Query the XDocument with special charecters in Element name using LINQ

April 8, 2010

Here is the code to query XDocument using LINQ Expression to get the ProgramBase Records which has special charecters in the element name

Sample Xml File

<ns0:Programs xmlns:ns1="http://tvg.ingest/MT1" xmlns:ns0="http://tvg.ingest/MT4">
    <ns0:ProgramBase ProgramScheduleSourceID="4081" ProgramPerSourceCount="81">
        <ns1:Program LO_yn="false">
            <ns1:Schedules>
                <ns1:Schedule xmlns:ns1="http://tvg.ingest/MT1" xmlns:ns0="http://tvg.ingest/MT4" ActiveFlag="1">
                    <ns1:ScheduleID>5492218</ns1:ScheduleID>
                    <ns1:JoinedInProgress JoinedInProgressDecoded="N">false</ns1:JoinedInProgress>
                    <ns1:SubjectToBlackout SubjectToBlackoutDecoded="N">false</ns1:SubjectToBlackout>
                    <ns1:IsEncrypted>false</ns1:IsEncrypted>
                    <ns1:SAPFlag SAPFlagDecoded="N">false</ns1:SAPFlag>
                </ns1:Schedule>
            </ns1:Schedules>
            <ns1:ImportID>204961</ns1:ImportID>
        </ns1:Program>
        <ns0:ProgramUpdatedFlag>false</ns0:ProgramUpdatedFlag>
    </ns0:ProgramBase>
    <ns0:ProgramBase ProgramScheduleSourceID="4081" ProgramPerSourceCount="81">
        <ns1:Program LO_yn="false">
            <ns1:Schedules>
                <ns1:Schedule xmlns:ns1="http://tvg.ingest/MT1" xmlns:ns0="http://tvg.ingest/MT4" ActiveFlag="1">
                    <ns1:ScheduleID>5492161</ns1:ScheduleID>
                    <ns1:JoinedInProgress JoinedInProgressDecoded="N">false</ns1:JoinedInProgress>
                    <ns1:SubjectToBlackout SubjectToBlackoutDecoded="N">false</ns1:SubjectToBlackout>
                    <ns1:IsEncrypted>false</ns1:IsEncrypted>
                    <ns1:SAPFlag SAPFlagDecoded="N">false</ns1:SAPFlag>
                </ns1:Schedule>
            </ns1:Schedules>
            <ns1:ImportID>204961</ns1:ImportID>
        </ns1:Program>
        <ns0:ProgramUpdatedFlag>false</ns0:ProgramUpdatedFlag>
    </ns0:ProgramBase>
    <ns0:ProgramBase ProgramScheduleSourceID="4080" ProgramPerSourceCount="81">
        <ns1:Program LO_yn="false">
            <ns1:Schedules>
                <ns1:Schedule xmlns:ns1="http://tvg.ingest/MT1" xmlns:ns0="http://tvg.ingest/MT4" ActiveFlag="1">
                    <ns1:ScheduleID>5492112</ns1:ScheduleID>
                    <ns1:JoinedInProgress JoinedInProgressDecoded="N">false</ns1:JoinedInProgress>
                    <ns1:SubjectToBlackout SubjectToBlackoutDecoded="N">false</ns1:SubjectToBlackout>
                    <ns1:IsEncrypted>false</ns1:IsEncrypted>
                    <ns1:SAPFlag SAPFlagDecoded="N">false</ns1:SAPFlag>
                </ns1:Schedule>
            </ns1:Schedules>
            <ns1:ImportID>204961</ns1:ImportID>
        </ns1:Program>
        <ns0:ProgramUpdatedFlag>false</ns0:ProgramUpdatedFlag>
    </ns0:ProgramBase>
    </ns0:ProgramBase>
public static void SaveMT4BySourceID(string mt4string,string path)
        {
            XNamespace ns1 = "http://tvg.ingest/MT1";
            XNamespace ns0 = "http://tvg.ingest/MT4";

            var xd = XDocument.Parse(mt4string);

            var programSourceids =
                    (from c in xd.Descendants(ns0 + "ProgramBase")
                    select (int)c.Attribute("ProgramScheduleSourceID")).Distinct();

            foreach (int programSourceId in programSourceids)
            {
                XElement domQuery = new XElement(ns0 + "Programs",
                                     new XAttribute(XNamespace.Xmlns + "ns1", ns1.NamespaceName),
                                     new XAttribute(XNamespace.Xmlns + "ns0", ns0.NamespaceName));

                domQuery.Add((from c in xd.Descendants(ns0 + "ProgramBase")
                              where (int)c.Attribute("ProgramScheduleSourceID") == programSourceId 
                              select c));
                domQuery.Save(Path.GetDirectoryName(path)+@"\" + programSourceId.ToString() + ".xml");
            }
Happy Coding 😉

LINQ Using XDocument

April 8, 2010

 

Here is the code to query XDocument using LINQ Expression to get the Employees whose salary is greater than 2000 and save it to another XML File

Sample Xml File

<Employees>
 <Employee Id="1">
   <Firstname> John</Firstname>
   <Lastname> Dora</Lastname>
   <Salary>1000</Salary>
 </Employee>
 <Employee Id="2">
   <Firstname> Mark</Firstname>
   <Lastname> Thomson</Lastname>
   <Salary>2000</Salary>
 </Employee>
 <Employee Id="3">
   <Firstname> Dale</Firstname>
   <Lastname> Steyn</Lastname>
   <Salary>3000</Salary>
 </Employee>
 <Employee Id="4">
   <Firstname>Shane</Firstname>
   <Lastname> Bond</Lastname>
   <Salary>4000</Salary>
 </Employee>
 <Employee Id="5">
   <Firstname> Michale</Firstname>
   <Lastname> Lumb</Lastname>
   <Salary>5000</Salary>
 </Employee>
</Employees>
      public static void SaveEmployees(string xmlemployees)
        {
            var xd = XDocument.Parse(xmlemployees);
            XElement xRoot = new XElement("Employees", "");
            
            xRoot.Add((from c in xd.Descendants("Employee")
                          where (int)c.Element("Salary") > 2000 
                          select c));
            
            xRoot.Save(@"C:\NewEmplyees" + ".xml");
        }
Happy Coding 😉
 
 

C# code to Merge Multiple PDFs into Single PDF

February 12, 2010
 

Here is the C# code to Merge Multiple PDF documents into one PDF document. This might require the ITextSharp dll to be downloaded.

To use the MergePDF class:

1) Initialize the class with list filenames of the PDFs that need to be merged.

2) Set the DestinationFile properties

4) Call the Execute Method

If everything works fine you will find your Merged PDF Document at your stated destination file.

The code is pretty much self decribed. If there is any question, i can always be contacted via this post.

Happing Coding 😉
using iTextSharp.text;
using iTextSharp.text.pdf;
public class MergePDF
   {
       #region Fields
       private string sourcefolder;
       private string destinationfile;
       private IList fileList = new ArrayList();
       #endregion 

       public MergePDF(IList _fileList)
       {
           this.fileList = _fileList;
       }
       #region Public Methods
       ///
       /// Add a new file, together with a given 
docname to the fileList and namelist collection
       ///
       public void AddFile(string pathnname)
       {
           fileList.Add(pathnname);
       } 

       ///
       /// Generate the merged PDF
       ///
       public void Execute()
       {
           MergeDocs();
       }
       #endregion 

       #region Private Methods
       ///
       /// Merges the Docs and renders the destinationFile
       ///
       private void MergeDocs()
       { 

           //Step 1: Create a Docuement-Object
           Document document = new Document();
           try
           {
           //Step 2: we create a writer that listens to the document
               PdfWriter writer = PdfWriter.GetInstance(document, 
              new FileStream(destinationfile, FileMode.Create)); 

               //Step 3: Open the document
               document.Open(); 

               PdfContentByte cb = writer.DirectContent;
               PdfImportedPage page; 

               int n = 0;
               int rotation = 0; 

               //Loops for each file that has been listed
               foreach (string filename in fileList)
               {
                   //The current file path
                 //  string filePath = sourcefolder + filename; 

                   // we create a reader for the document
                   PdfReader reader = new PdfReader(filename); 

                   //Gets the number of pages to process
                   n = reader.NumberOfPages; 

                   int i = 0;
                   while (i < n)
                   {
                       i++;
      document.SetPageSize(reader.GetPageSizeWithRotation(1));
                       document.NewPage(); 

                       //Insert to Destination on the first page
                       if (i == 1)
                       {
                           Chunk fileRef = new Chunk(" ");
                           fileRef.SetLocalDestination(filename);
                           document.Add(fileRef);
                       } 

                       page = writer.GetImportedPage(reader, i);
                       rotation = reader.GetPageRotation(i);
                       if (rotation == 90 || rotation == 270)
                       {
                           cb.AddTemplate(page, 0, -1f, 1f, 0, 0, 
                         reader.GetPageSizeWithRotation(i).Height);
                       }
                       else
                       {
                           cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                       }
                   }
               }
           }
           catch (Exception e) { throw e; }
           finally { document.Close(); }
       }
       #endregion 

       ///
       /// Gets or Sets the DestinationFile
       ///
       public string DestinationFile
       {
           get { return destinationfile; }
           set { destinationfile = value; }
       }
   }

Calling Web Service from your Java Script

January 26, 2010

Here we will see how to call a web service from your javascript.

Open Visual Studio 2005/2008 and create “New WebApplication”.

Add an aspx page and name it to WebService.aspx. Inside the page declare a static method called Add.

This “Add” method takes parametes called “Input” which is structure with two member variables and returns a Result object which in turn a structure object with “result”  as a member variable which is an integer

public partial class WebService : System.Web.UI.Page
   {

[WebMethod]
       public static Result Add(Input input)
       {
           Result c = new Result();
           c.result = input.item1 + input.item2;
           return c;
       }

  public struct Input
  {
      public int item1;
      public int item2;
  }

public struct Result
{
     public int result;
}

}

Now add one more page called Default.aspx.

On the top of this page, add script manager, which allows you to call web service using javascript. You can see that i have added two more text boxes and html button.

<form id=”form1″ runat=”server”>
    <asp:ScriptManager ID=”s1″ runat=”server”></asp:ScriptManager>
<div>
   Input value 1 <asp:TextBox ID=”t1″ runat=”server”></asp:TextBox>
    <br />
   Input value 2 <asp:TextBox ID=”t2″ runat=”server”></asp:TextBox>
    <br />
   <input type=”button” id=”b1″ onclick=”javascript:CallWebService();” value=”Click”/>

<br />
    Result : <asp:Label ID=”l1″ runat=”server”></asp:Label>

       </div>
  </form>

Now we will write javascript that calls web service, that adds two integer values and displays the result in a Label

As You can see that i have added three javascript methods CallWebService, OnResultFoundand OnFailed.

CallWebServicehas the code that actually makes a call to web service.

if we look deeper into the syntax, Sys.Net.WebServiceProxy.Invoke takes few parameters.

The first parameter is the path of the web service. “/WebService.aspx”

The second parameter is the name of web method to invoke: “Add”

next parameter is useHttpGet (Optional) false if the Web request HTTP verb is POST; otherwise, true. The default is false.

next Parameter is the Javscript dictionary that contains named properties (fields) that correspond to the parameters of the method to call, as in this example we are passing input values:

{ "input": { "item1":item1 ,"item2":item2 } }

note

The field names in the dictionary must match the names of Web service methods.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken when the Web service method finishes successfully.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken if an error occurs during the Web service method call.

(Optional) Any user-specific information. userContext can be any JavaScript primitive type, array, or object.

next parameter is the contents of userContext are passed to the callback functions (if any). If userContext is not provided, null is passed to the callback function.

last parameter is (Optional) the time in milliseconds that the network executor must wait before timing out the Web request. timeout can be an integer or null. By defining a time-out interval, you can control the time that the application must wait for the callback to finish.

<script type=”text/javascript”>

function CallWebService()

  {

      var item1 = document.getElementById(‘t1’).value;

      var item2 = document.getElementById(‘t2’).value;

      var lblResult = document.getElementById(‘l1’);

      Sys.Net.WebServiceProxy.invoke(“/WebService.aspx”, “Add”, false, { “input”: { “item1″:item1 ,”item2”:item2 } },

                                  OnResultFound, OnFailed, lblResult, 5000);

  }

function OnResultFound(retVal, lblResult)

{

     lblResult.innerHTML = retVal.result;

}

function OnFailed(error)

{

     alert(“There was an error “+error.toString());

}

</script>

image

Happy Coding 😉

Populate DropDownList by Calling Web Service from JavaScript

January 26, 2010

 

Now we will see how to call WeBService from your javascript and populate drop down.

Here we will see how to call a web service from your javascript.

Open Visual Studio 2005/2008 and create “New WebApplication”.

Add an aspx page and name it to WebService.aspx. Inside the page declare a static method called PopulateCountries.

This “PopulateCountries” method returns a Countries object which in turn a structure object with “countries”  as a member variable which is an array of countries.

public partial class WebService : System.Web.UI.Page
   {

      [WebMethod]
       public static Countries PopulateCountries()
       {
           Countries countries = new Countries();
           Country[] carray = new Country[5];
           Country c = new Country();
           c.countryName = “USA”;
           c.countryId = 1;
           carray[0] = c;

           c = new Country();

           c.countryName = “UK”;
           c.countryId = 2;
           carray[1] = c;

           c = new Country();

           c.countryName = “India”;
           c.countryId = 3;
           carray[2] = c;

           c = new Country();

           c.countryName = “Argentina”;
           c.countryId = 4;
           carray[3] = c;

           c = new Country();

           c.countryName = “Mexico”;
           c.countryId = 5;
           carray[4] = c;

           countries.countries = carray;

           return countries;
       }

       public struct Countries
       {
           public Country[] countries;
       }

       public struct Country
       {
           public string countryName;
           public int countryId;
       }

}

Now add one more page called Default.aspx.

On the top of this page, add script manager, which allows you to call web service using javascript. You can see that i have added drop down list and html button.

<form id=”form1″ runat=”server”>
    <asp:ScriptManager ID=”s1″ runat=”server”></asp:ScriptManager>
    <div> 
   Countries <asp:DropDownList ID=”ddCountries” runat=”server”/>    <br /> 
    <input type=”button” id=”b1″ onclick=”javascript : PopulateCountries();” value=”Click”/> 
       </div>
  </form>

Now we will write javascript that calls web service, returns a list of countries to populate the drop down list.

As You can see that i have added three javascript methods PopulateCountries, OnCountriesFound and OnFailed.

PopulateCountries has the code that actually makes a call to web service.

if we look deeper into the syntax, Sys.Net.WebServiceProxy.Invoke takes few parameters.

The first parameter is the path of the web service. “/WebService.aspx”

The second parameter is the name of web method to invoke: “Add”

next parameter is useHttpGet (Optional) false if the Web request HTTP verb is POST; otherwise, true. The default is false.

next Parameter is the Javscript dictionary that contains named properties (fields) that correspond to the parameters of the method to call, as in this example we are passing an empty braces:

{ }

note

The field names in the dictionary must match the names of Web service methods.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken when the Web service method finishes successfully.

(Optional)next Parameter is the name of the Javascript  method that would be called back if web service is executed successfully

If no callback function is provided, no action is taken if an error occurs during the Web service method call. 

(Optional) Any user-specific information. userContext can be any JavaScript primitive type, array, or object.

next parameter is the contents of userContext are passed to the callback functions (if any). If userContext is not provided, null is passed to the callback function.

last parameter is (Optional) the time in milliseconds that the network executor must wait before timing out the Web request. timeout can be an integer or null. By defining a time-out interval, you can control the time that the application must wait for the callback to finish.

<script type=”text/javascript”>

   function PopulateCountries()

   {

       var ddCountries = document.getElementById(‘ddCountries’);

Sys.Net.WebServiceProxy.invoke(“/WebService.aspx”, “PopulateCountries”, false, { },OnCountriesFound, OnFailed,  ddCountries, 5000);

   }
function OnCountriesFound(retVal,ddCountries)

   {

       for(var i=0; i<retVal.countries.length; i++)

       {

           ddCountries.options[i] = new Option(retVal.countries[i].countryName, retVal.countries[i].countryId);

       }

   }

function OnFailed(error)

   {

       alert(“There was an error “+error.toString());

   }

</script>

image

Happy Coding 😉

Read the XML Using XPath FROM XML Text Reader

January 18, 2010

 

Copy the below code and call GetXmlNodeValue method to pass on XMLTextReader object and Xpath and get the result.

void GetXmlNodeValue(XmlTextReader reader,string xpathQuery)
        {
            System.Console.WriteLine(“TestOne”);
            XPathDocument xdoc = new XPathDocument(reader);
            XPathNavigator nav = xdoc.CreateNavigator();
            XPathNodeIterator nodeItor = nav.Select(xpathQuery);
             //”STUFF/TYPE1/CENSUS[@COUNTRY=’USA’ and @YEAR=’1930′]/PAGE”);
            nodeItor.MoveNext();
            TraverseSiblings(nodeItor);
            System.Console.WriteLine();
        }

         void TraverseSiblings(XPathNodeIterator nodeItor)
        {
            XPathNodeIterator igor = nodeItor.Clone();
            PrintNode(igor.Current);
            igor.Current.MoveToNext();
            bool more = false;
            do
            {
                PrintNode(igor.Current);
                more = igor.Current.MoveToNext();
            } while (more);
        }

         void PrintNode(XPathNavigator nav)
        {
            System.Console.WriteLine(nav.Name + “:” + nav.Value +
                ” Type : ” + nav.NodeType.ToString());
        }

Get Rows from XML string using XML DataType Sql Server

January 18, 2010

 

DECLARE @providerXmlString XML
DECLARE @idoc int

SET @providerXmlString =’
        <Employees>
        <Employee>
        <EmployeeID>1</EmployeeID>
        <EmployeeName>John</EmployeeName>
        <Salary>10000</Salary>
        </Employee>
        <Employee>
        <EmployeeID>2</EmployeeID>
        <EmployeeName>Mark</EmployeeName>
        <Salary>13000</Salary>
        </Employee></Employees>’

DECLARE @EmployeeTable as Table(EmployeeID Int, EmployeeName varchar(50),Salary int)

INSERT INTO @EmployeeTable
SELECT
    T.c.value(‘(EmployeeID)[1]’, ‘int’) AS EmployeeID,
    T.c.value(‘(EmployeeName)[1]’, ‘varchar(50)’) AS EmployeeName,
    T.c.value(‘(Salary)[1]’, ‘int’) AS Salary
FROM  @providerXmlString.nodes(‘/Employees/Employee’) T(c)

SELECT * FROM @EmployeeTable

image

XML Validation against Schema (XSD)

January 18, 2010

In order to validate XML file against XSD schema, you create an instance of the class XmlReaderSettings and set ValidationType to ValidationType.Schema. Add the schema file to the instance of the XmlReaderSettings class. Whenever XMLReaderSettings encounters an validation error, it raises ValidationError event. Create method (as defined below XMLValidationEventHandler()) to catch those validation errors and add ValidationErrorHandler delegate to report these errors in UI or pass it to another layer as per your requirement.

/// method to validate the XML against the XSD
///
/// path of the XMl File
///
/// the default namespace of the xsd. It can be blank in case of empty namespace
public void ValidateXMLAgainstXSD(string pathToXml,string pathToXsd,string namespaceOfXSD)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(namespaceOfXSD, pathToXsd); // targetNamespace,
settings.ValidationEventHandler += new ValidationEventHandler(XMLValidationEventHandler);
XmlReader reader = XmlReader.Create(pathToXml, settings);
while (reader.Read())
{

}
}

private void XMLValidationEventHandler(object sender, ValidationEventArgs e)
{
Console.WriteLine(“Meaage : ” + e.Message + “\n Severity : ” + e.Severity + “\n Error: “);
// or you can access the reader if you have access to it
// reader.LineNumber, reader.LinePosition.. etc
}