Thursday 30 January 2014

Write and Read XML file from datatable in C#

Hello guys,
Today i am sharing my code with you for writing and reading XML file
from datatable.

Fill the datatable with data first from database or any other source.

eg. datatabel named "Student" is loaded datatable.

Now write this data into XML and then read that XML file into another new datatable.

string path = string.Concat(AppDomain.CurrentDomain.BaseDirectory, @"StudentData\");

Here "StudentData" is my folder name in my project solution.

String fileName = path + Guid.NewGuid() + ".xml";

This is file name with full path.
Here is used Guid to give filename, you can use anything you like here.

Now create file

var fs = File.Create(fileName);
fs.Close();

Above code will create the file in a specified folder eg. StudentData here.

Now its time to write XML file.

ds.Tables[0].WriteXml(fileName, XmlWriteMode.WriteSchema);

Above code will write the data with schema in xml file.
Why this? Because when you use writexml method with file name only then it'll write only data into the file on with schema.

When you read XML into datatabl at that time you must have new datatable with schema that's why i wrote the above code that write the XML file with schema.

Now its time to read XML file.

DataTable Newdt = new DataTable();
Newdt.ReadXml(fileName);

That's it. Hope this help you...
Thanks... Enjoy coading...

Tuesday 21 January 2014

.format method in javascript

I was having a problem with date format method in javascript.

My friend suggest me to put below code on the page

<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="360000"
        EnablePageMethods="true" EnablePartialRendering="true">

and it worked.

Just put scriptManager on page and .format method will work.

var dt = new Date($("#txtinDateShow").val());
dt = dt.format("yyyy/MM/dd");

Hope this will helpful to you.
Happy scripting...

Read/Get/Find control id using jQuery/JavaScript

So many times we developers needs to read the id of control to get the data.
When the control written in pure HTML then we get the data by simply using
document.getElementById("ControlID")

but when asp.net server control used that control's id is changed when the page
is loaded from the server. At that time it's difficult to get the value.

To solve this problem jQuery has the solid mechanisium to read the control id from page.

*****  Use following for server controls *****

* if you want to use javaScript then use following:
document.getElementById('<%="ControlID".ClientID%>')
e.g. document.getElementById('<%=StudentName.ClientID%>').value

* now if you want to use jQuery then use following:
$("[id$='ControlID']").val()
e.g. $("[id$='StudentName']").val()


*****  Use following for HTML controls  *****

* if you want to use javaScript then use following:
document.getElementById('ControlID')
e.g. document.getElementById('StudentName').value

* now if you want to use jQuery then use following:
$("#ControlID").val()
e.g. $("#StudentName").val()

Hope this will helpful to you.
Happy scripting...

XML parsing with namespaces using jQuery/JavaScript

So many times XML will come with namespaces specially when data comes from web service.
Developers get confused to handle that data using jQuery/Javascript.
I was the same who was suffering from this type of problem.
Here i am sharing my way to handle this.

I used following js for this.

<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/jscript"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js" type="text/jscript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" type="text/jscript"></script>

Demo xml:

<SearchResponse>
<SearchResult>
<a:BookingRequest.DetailsSearch>
 <a:ErrorMessage i:nil="true"/>
 <a:Name>Sydney, Australia</a:Name>
 <a:Number>1</a:Number>
 <a:Url>test.aspx?City=Sydney&Country=Australia</a:Url>
 <a:type>City</a:type>
 </a:BookingRequest.DetailsSearch>
<a:BookingRequest.DetailsSearch>
 <a:ErrorMessage i:nil="true"/>
 <a:Name>Sydney, Canada</a:Name>
 <a:Number>2</a:Number>
 <a:Url>test.aspx?City=Sydney&Country=Canada</a:Url>
 <a:type>City</a:type>
 </a:BookingRequest.DetailsSearch>
<a:BookingRequest.DetailsSearch>
 <a:ErrorMessage i:nil="true"/>
 <a:Name>North Sydney, Canada</a:Name>
 <a:Number>3</a:Number>
 <a:Url>test.aspx?City=North Sydney&Country=Canada</a:Url>
 <a:type>City</a:type>
 </a:BookingRequest.DetailsSearch>
<a:BookingRequest.DetailsSearch>
 <a:ErrorMessage i:nil="true"/>
 <a:Name>North Sydney, Australia</a:Name>
 <a:Number>4</a:Number>
 <a:Url>test.aspx?City=North Sydney&Country=Australia</a:Url>
 <a:type>City</a:type>
 </a:BookingRequest.DetailsSearch>
</SearchResult>
</SearchResponse>

Here i am parsing the XML and storing the data into array.
Now you can use this array according to your requirement.
Here both the code i am sharing for IE and other browser.

Here is my code.

if ($.browser.msie && window.XDomainRequest) {
                if (window.XDomainRequest) {
                    var query = 'Your URL Here';
                    var xdr = new XDomainRequest();
                    if (xdr) {
                        xdr.onload = function () {
                            searchtext = request.term;
                            data = $.parseXML(xdr.responseText);
                            var item = [];
                            var pets = data.getElementsByTagName("a:BookingRequest.DetailsSearch");
                            var Name = data.getElementsByTagName("a:Name");
                            var Number = data.getElementsByTagName("a:Number");
                            var Url = data.getElementsByTagName("a:Url");
                            var type = data.getElementsByTagName("a:type");

                            for (var i = 0; i < pets.length; i++) {
                                var obj = { value: Name[i].textContent.toString(), URL: Url[i].textContent.toString(), Number: Number[i].textContent.toString(), Type: type[i].textContent.toString() };
                                item.push(obj);
                            }
                            response(item);
                        }
                        xdr.onerror = function () { /* error handling here */ }
                        xdr.open('GET', query);
                        xdr.send();
                    }
                }
            }
            else {
                var query = 'Your URL Here';
                $.ajax({
                    type: "GET",
                    crossDomain: true,
                    url: query,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data1) {
                        if (data1 != null) {
                            var data = data1.SearchResult;
                            var item = [];
                            for (var i = 0; i < data.length; i++) {
                                var obj = { value: data[i].Name, URL: data[i].Url, Number: data[i].Number, Type: data[i].type };
                                item.push(obj);
                            }
                            response(item);
                        }
                    },
                    error: function (response, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }
        }


Now if you want to directly bind these XML data into page then just use following

var count = 0;
$(data).find('SearchResult').each(function () {

    var Name = $(this).find('a\\:Name').text();
    var Number = $(this).find('a\\:Number').text();
    var Url = $(this).find('a\\:Url').text();
    var type = $(this).find('a\\:type').text();  
    count++;
});

I used count only to check number of occurrence of XML node.
You can use this value any way you like.

Hope this will help and save your time.
Happy coading...

Friday 10 January 2014

Call WCF Restful service from cross domain including IE7,8,9,10 and other well known browsers

Hello guys,

Last time i put some example code to call wcf restful service in cross domain but it was not working in IE.

My previous code of javascript was not able to call WCF service from IE because my code uses httpXMLRequest while IE only supports XDomainRequest ( earlier version of IE10 ).

Here, i improved my code and put example below that will work in all the most usable
versions of IE - IE7, IE8, IE9, IE10 and all other well know browsers.

So developers no need to worry about cross domain call making from IE.

Just refer below code:

if ($.browser.msie && window.XDomainRequest) {
            if (window.XDomainRequest) {
                var xdr = new XDomainRequest();
                var query = 'MyUrl';
                if (xdr) {
                    xdr.onload = function () {
alert(xdr.responseText);
                     }
                    xdr.onerror = function () { /* error handling here */ }
                    xdr.open('GET', query);
                    xdr.send();
                }
            }
        }
        else {
$.ajax({
                type: "GET",
                crossDomain: true,
                url: 'MyUrl',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
alert(data);
                },
                error: function (response, textStatus, errorThrown) {
                    alert('not OK ' + response.responseText);
                    alert('not OK ' + textStatus.responseText);
                    alert('not OK ' + errorThrown);
                }
            });
}


that's it.
It was the standard method to do that.

Now one js is also available to do the same thing, you can just put below js in your page and call the wcf service by just your old code ($.ajax(...)) and you can get the result.

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js"></script>

This js is responsible to convert the request as per the browser used.


One more thing if your data is not showing properly on page then set your
document mode as standard so IE will use its maximum capacity of supports.
other browsers are so intelligent so no need to explain more here.
To set document mode standard just put below line in header part of your page.

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

it'll work in IE7, IE8 and IE9, IE10 supports all the things so no need to put this.

Enjoy Scripting...

Thursday 9 January 2014

Read xml file/string/data using jQuery/JavaScript

Hi,

Add latest version of jquery in your page first.

You can add following too.

<script src="jquery.js" type="text/javascript"></script>

Now put this code in your page if you want to catch xml data from other resource like webservice or webmethod.

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: 'yourURLHere',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            ProcessData: true,
            success: function (data) {
                if (data1 != null) {
data = $.parseXML(data);
$(data).find('Table').each(function () {
                        var Name = $(this).find('Name').text();
                       var Code = $(this).find('Code').text();
                        alert(Name);
                               alert(Code);
                   });

                }
            },
            error: function (response, textStatus, errorThrown) {
                alert('not OK ' + response.responseText);
                alert('not OK ' + textStatus.responseText);
                alert('not OK ' + errorThrown);
            }
        });
    });
</script>

In above javascript i am getting below data and i handled that in js

<ListCurrencyResponse xmlns="http://webservice.hotel.com.au/"><ListCurrencyResult><xs:schema id="NewDataSet" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"><xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Table" msdata:Locale=""><xs:complexType><xs:choice minOccurs="0" maxOccurs="unbounded"><xs:element name="Table"><xs:complexType><xs:sequence><xs:element name="Name" type="xs:string" minOccurs="0"/><xs:element name="Code" type="xs:string" minOccurs="0"/><xs:element name="IsHC" type="xs:boolean" minOccurs="0"/><xs:element name="IsEAN" type="xs:boolean" minOccurs="0"/><xs:element name="Symbol" type="xs:string" minOccurs="0"/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"><NewDataSet xmlns=""><Table diffgr:id="Table1" msdata:rowOrder="0"><Name>AUD Australian Dollars</Name><Code>AUD</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>$</Symbol></Table><Table diffgr:id="Table2" msdata:rowOrder="1"><Name>CAD Canadian Dollars</Name><Code>CAD</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>$</Symbol></Table><Table diffgr:id="Table3" msdata:rowOrder="2"><Name>CHF Swiss Francs</Name><Code>CHF</Code><IsHC>false</IsHC><IsEAN>true</IsEAN><Symbol>CHF</Symbol></Table><Table diffgr:id="Table4" msdata:rowOrder="3"><Name>DKK Danish Kroner</Name><Code>DKK</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>kr</Symbol></Table><Table diffgr:id="Table5" msdata:rowOrder="4"><Name>EUR Euros</Name><Code>EUR</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>€</Symbol></Table><Table diffgr:id="Table6" msdata:rowOrder="5"><Name>GBP British Pounds</Name><Code>GBP</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>£</Symbol></Table><Table diffgr:id="Table7" msdata:rowOrder="6"><Name>HKD Hong Kong Dollars</Name><Code>HKD</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>$</Symbol></Table><Table diffgr:id="Table8" msdata:rowOrder="7"><Name>INR Indian Rupee</Name><Code>INR</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>Rs</Symbol></Table><Table diffgr:id="Table9" msdata:rowOrder="8"><Name>JPY Japanese Yen</Name><Code>JPY</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>¥</Symbol></Table><Table diffgr:id="Table10" msdata:rowOrder="9"><Name>MYR Malaysian Ringgit</Name><Code>MYR</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>M$</Symbol></Table><Table diffgr:id="Table11" msdata:rowOrder="10"><Name>NOK Norwegian Kroner</Name><Code>NOK</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>kr</Symbol></Table><Table diffgr:id="Table12" msdata:rowOrder="11"><Name>NZD New Zealand Dollars</Name><Code>NZD</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>$</Symbol></Table><Table diffgr:id="Table13" msdata:rowOrder="12"><Name>SEK Swedish Kronas</Name><Code>SEK</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>kr</Symbol></Table><Table diffgr:id="Table14" msdata:rowOrder="13"><Name>SGD Singapore Dollars</Name><Code>SGD</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>$</Symbol></Table><Table diffgr:id="Table15" msdata:rowOrder="14"><Name>THB Thai baht</Name><Code>THB</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>฿</Symbol></Table><Table diffgr:id="Table16" msdata:rowOrder="15"><Name>USD U.S. Dollars</Name><Code>USD</Code><IsHC>true</IsHC><IsEAN>true</IsEAN><Symbol>$</Symbol></Table></NewDataSet></diffgr:diffgram></ListCurrencyResult></ListCurrencyResponse>

Here table is my node and name and code is my child nodes.

Refference :

http://think2loud.com/224-reading-xml-with-jquery/
http://api.jquery.com/jquery.parsexml/

enjoy scripting...

Read confige (web.confing,app.config etc) file settings from javascript

hi all,

so many times we need to read config (web.confing,app.config etc) file settings from javascript
i searched a lot and finally i got the answer.

var setting = '<%=System.Configuration.ConfigurationManager.AppSettings["YourKeyNameHere"].ToString() %>';
alert(setting);

this is simple.
enjoy scripting...