Last
day my colleague asked me the provide her a solution to call the Web
service from classic ASP. (Yes Classic ASP. still people are using
this :D )
We
can call web service SOAP toolkit also. But invoking the service
using the XMLHTTP object was more easier & fast.
To
create the Service I used the normal Web Service in .Net 2.0 with
[Webmethod]
public
class
WebService1
: System.Web.Services.WebService
{
[WebMethod]
public
string
HelloWorld(string
name)
{
return
name + "
Pay my dues :) ";
// a reminder to pay my consultation fee :D
}
}
In
Web.config add the following entry in System.web<webServices><protocols><add
name="HttpGet"/><add
name="HttpPost"/></protocols>
</webServices>
Alternatively,
you can enable these protocols for all Web services on the computer
by editing the <protocols> section in Machine.config. The
following example enables HTTP GET, HTTP POST, and also SOAP and HTTP
POST from localhost:
<protocols>
<add
name="HttpSoap"/>
<add
name="HttpPost"/>
<add
name="HttpGet"/>
<add
name="HttpPostLocalhost"/>
<!--
Documentation enables the documentation/test pages -->
<add
name="Documentation"/>
</protocols>
By
adding these entries I am enabling the HTTPGET & HTTPPOST (After
.Net 1.1 by default HTTPGET & HTTPPOST is disabled because of
security concerns)
The
.NET Framework 1.1 defines a new protocol that is named
HttpPostLocalhost. By default, this new protocol is enabled. This
protocol permits invoking Web services that use HTTP POST requests
from applications on the same computer. This is true provided the
POST URL uses http://localhost, not http://hostname. This permits Web
service developers to use the HTML-based test form to invoke the Web
service from the same computer where the Web service resides.
Classic
ASP Code to call Web service
<%Option
Explicit
Dim
objRequest, objXMLDoc, objXmlNode
Dim
strRet, strError, strNome
-
Dim
strName
strName=
"deepa"
Set
objRequest = Server.createobject("MSXML2.XMLHTTP")
-
With
objRequest
.open
"GET",
"http://localhost:3106/WebService1.asmx/HelloWorld?name="
& strName, False
.setRequestHeader
"Content-Type", "text/xml"
.setRequestHeader
"SOAPAction",
"http://localhost:3106/WebService1.asmx/HelloWorld"
.send
End
With
-
Set
objXMLDoc = Server.createobject("MSXML2.DOMDocument")
objXmlDoc.async
= false
Response.ContentType
= "text/xml"
Response.Write(objRequest.ResponseText)
-
%>
In
Line 6 I created an MSXML XMLHTTP object.
Line
9 Using the HTTPGET protocol I am openinig connection to WebService
Line
10:11 – setting the Header for the service
In
line 15, I am getting the output from the webservice in XML Doc
format & reading the responseText(line 18).
In
line 9 if you observe I am passing the parameter strName
to the
Webservice You can pass multiple parameters to the Web service by
just like any other QueryString Parameters.
In
similar fashion you can invoke the Web service using HTTPPost. Only
you have to ensure that the form contains all th required parameters
for webmethod.
Happy
coding !!!!!!!
Consider the following class
public string FirstName { get; set; }
private string LastName { get; set; }
protected string Email { get; set; }
public int Age { get; set; }
virtual public void showName()
Console.WriteLine("base class");
To
add additional methods to a class you have to subclass it or add the
function directly to the class. If the class is sealed then you will
have very limited options only.
In
C#, you can use the new extension method feature to add a new method to
an existing type. To add the method to the existing class, define a new
static class and define the
extension method (a static method) within it like the following
static class ExtensionMethods
public static string AddMarks(this Person per,double marks1, double marks2)
return (marks1 + marks2).ToString();
The
first parameter of an extension method is prefixed by the this keyword,
followed by the type it is extending (Person in this example,
indicating to the compiler that this extension method must be added to
the Person class). The rest of the parameter list (if any) is then the
signature of the extension method.
(In the figure you can see the new extension method for the Person object )
If
an extension method has the same signature as another method in the
class it is trying to extend, the method in the class will take
precedence and the extension method will be ignored.
http://thetechjungle.blogspot.com/
Sometimes we have to create generic dictionary from the values in datatable. Usually we will loop through all the rows in the datatable and add the relevant keys to dictionary object
for (int _iExRowCnt = 0; _iExRowCnt < dsReturn.Tables[0].Rows.Count; _iExRowCnt++)
{
//add some code to chek null values & other validations if any
_dictObj.Add(dsReturn.Tables[0].Rows[iExRowCnt][0].dsReturn.Tables[0].Rows[iExRowCnt][1]);
}
After LINQ was introduced there better way of doing the same addition.
In the following code i am creating a datatable and populaing few dummy records.
DataTable dtTable = new DataTable();dtTable.Columns.Add(new DataColumn("ColumnNo", typeof(System.String)));
dtTable.Columns.Add(new DataColumn("controlType", typeof(System.String)));
dtTable.Columns.Add(new DataColumn("showVal", typeof(System.Boolean)));
DataRow dr;for (int i = 0; i < 10; i++)
{
dr = dtTable.NewRow();
dr[0] = dtTable.Rows.Count + 1;
dr[1] = i.ToString() + "Value";
dr[2] = false;
dtTable.Rows.Add(dr);
}
//In the following code I am using LINQ to create a new Dictionary<string,string>
//You can filter the data and checf for the conditions in data which you dont want in dictionary
var dic = (from order in dtTable.AsEnumerable()
where order.Field<Boolean>("showVal") == false
select new
{
myColumnNo = order.Field<String>("ColumnNo"),myControlType = order.Field<String>("controlType")
}).AsEnumerable().ToDictionary(k => k.myColumnNo, v => v.myControlType);
This code snippet uses Enumerable.ToDictionary Method
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx
var dic will hold Dictionary<string,string> object. In the sample code it will have 10 elements
For further reading
Most of us would have encountered these questions
- What is the difference between constant and readonly fields?
- When to use constant and when to use readonly fields?
- What is the advantage/disadvantage of each?
Constants
- In C# you can declare a constant like this "const" is a keyword.
public const string _constStrVar = "I am a static const str val";
- A constant variable should have value at design time.
- All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".
- Constants are copied to all the dlls where is refereeing the parent class ie even if you change the the original constant value and recompile the parent dll , the other dll will still use the old value. The size of the executable goes up since all these constants are copied to the respective dlls
Read Only
- Read only variables are created usually in the constructor of class. there fore it will have values before the constructor of the class exists
class MyClass
{
public readonly string _strReadonly;
public void MyClass(string strVal) { _strReadonly = strVal; } } a read only variable will have different values for each object whereas a constant variable will have only one.
http://thetechjungle.blogspot.com/
Normally to return top N rows we use an SQL statement similar to the one belowSelect top N * from table
but How can we achieve the same thing in DataTableI have seen many examples, using different methods. Most of the methods centered around the idea of creating new columns with automatic values increment and using them as index
There is better method using LINQ
public DataTable GetTopNFromDataTable(int TopRowCount, DataTable dtSource)
{
var dtTrec = from item in dtSource.AsEnumerable()
select item;
var topN = dtTrec.Take(TopRowCount);
DataTable dtNew = new DataTable();
dtNew = dtSource.Clone();
foreach (DataRow drrow in topN.ToArray())
{
dtNew.ImportRow(drrow);
}
return dtNew;
}
var dtTrec - stores the item in datatable, Using the Take function of Linq the first N rows is filtered
var topN = dtTrec.Take(TopRowCount);
Now how to retrieve the rows between N1 & N2, just use the skip function along with Take as shown below
public DataTable GetTopBetweenFromDataTable(int intFrom, int intTo, DataTable dtSource)
{...... var topN = dtTrec.Skip(intFrom).Take(intFrom); ......}
Few days ago I was asked to look into an issue. In our application we have created dynamic grids to show data from database. This ASPX page was Ajax enabled. Moreover all the rows of the grid were in edit mode ie. the normal controls like textbox,dropdowns etc were displayed in all the rows. This grid was Paginated. But for the past few days the paging was not working.
I executed the page and found that the page was generating an error 12031 with the following message
Sys.webForms.PageRequestManagerServerErrorException:An unknown error occurred while processing the request on the server .the status code returned from the server was:12031.
On my first round of analysis I found the issue with Viewstate. If the viewstate is large then connection is reset (ERROR_INTERNET_CONNECTION_RESET ). In local machine with less load this problem will not occur but as the load & network latency increases this error will come. Once this error is generated the general events of grid is not triggered. So advised my team to minimize the use of viewstate. It will help in to load the page faster & reduce the network traffic. I can increase the maxRequestlength value to allow more data but ideally i shouldn't increase that.
In the page tested by me a page with grid with 372 rows generated a viewstate of 4.2 mb. you can disable viewstate using EnableViewState="false" for the individual controls and for the entire page also.
With every post back this much of data is transferred back & fro & this will result in low response time.
The developer was saving all the data into viewstate in page load and from that the data was populated to the grid.
Better solution is to retrieve only the required data from database, minimize the use of viewstate, Viewstate can be compressed also. About all these I will update in another post.