Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Friday, July 15, 2011

Which attribute is used in order that the method can be used as WebService ?

WebMethod attribute has to be specified in order that the method and property can be
treated as WebService.

What the different phase/steps of acquiring a proxy object in Webservice ?

Following are the different steps needed to get a proxy object of a webservice at
the client side :-
√ Client communicates to UDI node for WebService either through browser or
UDDI's public web service.
√ UDII responds with a list of webservice.

√ Every service listed by webservice has a URI pointing to DISCO or WSDL
document.
√ After parsing the DISCO document, we follow the URI for the WSDL document
related to the webservice which we need.
√ Client then parses the WSDL document and builds a proxy object which can
communicate with Webservice.

What is WSDL?

Web Service Description Language (WSDL)is a W3C specification which defines XML
grammar for describing Web Services.XML grammar describes details such as:-
√ Where we can find the Web Service (its URI)?
√ What are the methods and properties that service supports?
√ Data type support.
√ Supported protocols
In short its a bible of what the webservice can do.Clients can consume this WSDL and
build proxy objects that clients use to communicate with the Web Services. Full WSDL
specification is available at http://www.w3.org/TR/wsdl.

What is DISCO ?

DISCO is the abbreviated form of Discovery. It is basically used to club or group common
services together on a server and provides links to the schema documents of the services
it describes may require.

What is UDDI ?

Full form of UDDI is Universal Description, Discovery and Integration. It is a directory
that can be used to publish and discover public Web Services. If you want to see more
details you can visit the http://www.UDDI.org .

What is a Web Service ?

Web Services are business logic components which provide functionality via the Internet
using standard protocols such as HTTP.
Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business
functionality.SOAP defines a standardized format in XML which can be exchanged
between two entities over standard protocols such as HTTP. SOAP is platform independent
so the consumer of a Web Service is therefore completely shielded from any
implementation details about the platform exposing the Web Service. For the consumer it
is simply a black box of send and receive XML over HTTP. So any web service hosted on
windows can also be consumed by UNIX and LINUX platform.

What is ObjRef object in remoting ?

All Marshal() methods return ObjRef object.The ObjRef is serializable because it
implements the interface ISerializable, and can be marshaled by value. The ObjRef knows
about :-
√ location of the remote object
√ host name
√ port number
√ object name.

What is marshalling and what are different kinds of marshalling ?

Marshaling is used when an object is converted so that it can be sent across the network
or across application domains. Unmarshaling creates an object from the marshaled data.
There are two ways to do marshalling :-
√ Marshal-by-value (MBV) :- In this the object is serialized into the channel, and
a copy of the object is created on the other side of the network. The object to
marshal is stored into a stream, and the stream is used to build a copy of the
object on the other side with the unmarshalling sequence.
√ Marshaling-by-reference (MBR):- Here it creates a proxy on the client that is
used to communicate with the remote object. The marshaling sequence of a
remote object creates an ObjRef instance that itself can be serialized across
the network.
Objects that are derived from “MarshalByRefObject” are always marshaled by reference.
All our previous samples have classes inherited from “MarshalByRefObject”

To marshal a remote object the static method RemotingServices.Marshal() is
used.RemotingServices.Marshal() has following overloaded versions:-
public static ObjRef Marshal(MarshalByRefObject obj)
public static ObjRef Marshal(MarshalByRefObject obj, string objUri)
public static ObjRef Marshal(MarshalByRefObject obj, string objUri,Type
requestedType)
The first argument obj specifies the object to marshal. The objUri is the path that is
stored within the marshaled object reference; it can be used to access the remote object.
The requestedType can be used to pass a different type of the object to the object reference.
This is useful if the client using the remote object shouldn't use the object class but an
interface that the remote object class implements instead. In this scenario the interface is
the requestedType that should be used for marshaling.

What is Asynchronous One-Way Calls ?

One-way calls are a different from asynchronous calls from execution angle that the .NET
Framework does not guarantee their execution. In addition, the methods used in this kind
of call cannot have return values or out parameters. One-way calls are defined by using
[OneWay()] attribute in class.

How can we call methods in remoting Asynchronously ?

All previous examples are a synchronous method calls that means client has to wait until
the method completes the process. By using Delegates we can make Asynchronous method
calls.

What are LeaseTime, SponsorshipTime, RenewonCallTime and LeaseManagerPollTime?

This is a very important question from practical implementation point of view. Companies
who have specific requirement for Remoting projects will expect this question to be answered.
In normal .NET environment objects lifetime is managed by garbage collector. But in
remoting environment remote clients can access objects which are out of control of
garbage collector. Garbage collector boundary is limited to a single PC on which framework
is running; any remote client across physical PC is out of control of GC (Garbage
Collector).
This constraint of garbage collector leads to a new way of handling lifetime for remoting
objects, by using concept called as “LeaseTime”. Every server side object is assigned by
default a “LeaseTime” of five minutes. This leasetime is decreased at certain intervals.
Again for every method call a default of two minutes is assigned. When i say method call
means every call made from client. This is called as “RenewalOnCallTime”.
Let’s put the whole thing in equation to make the concept more clear.
Total Remoting object life time = LeaseTime + (Number of method calls) X
(RenewalTime).
If we take NumberOfMethodCalls as one.
159
Then default Remote Object Life Time = 5 + (1) X 2 = 10 minutes (Everything is in
minutes)
When total object lifetime is reduced to zero, it queries the sponsor that should the object
be destroyed. Sponsor is an object which decides should object Lifetime be renewed. So
it queries any registered sponsors with the object, if does not find any then the object is
marked for garbage collection. After this garbage collection has whole control on the
object lifetime. If we do not foresee how long a object will be needed specify the
“SponsorShipTimeOut” value. SponsorShipTimeOut is time unit a call to a sponsor is
timed out.
“LeaseManagerPollTime” defines the time the sponsor has to return a lease time extension

Is it a good design practice to distribute the implementation to Remoting Client ?

It’s never advisable to distribute complete implementation at client, due to following
reasons:-
√ Any one can use ILDASM and decrypt your logic.
√ It’s a bad architecture move to have full implementation as client side as any
changes in implementation on server side you have to redistribute it again.
So the best way is to have a interface or SOAPSUDS generated meta-data DLL at client
side rather than having full implementation.

In CAO model when we want client objects to be created by “NEW” keyword is there any precautions to be taken ?

Remoting Clients and Remoting Server can communicate because they share a common
contract by implementing Shared Interface or Base Class (As seen in previous examples).
But according to OOP’s concept we can not create a object of interface or Base Classes
(Abstract Class). Shipping the server object to client is not a good design practice. In
CAO model we can use SOAPSUDS utility to generate Metadata DLL from server which
can be shipped to client, clients can then use this DLL for creating object on server. Run
the SOAPSUDS utility from visual studio command prompt for syntax see below :-
soapsuds -ia:RemotingServer -nowp -oa:ClientMetaData.dll
Where RemotingServer is your server class name.
ClientMetaData.dll is the DLL name by which you will want to create the metadll.
Server code will change as follows :-
ChannelServices.RegisterChannel(objHttpChannel)
RemotingConfiguration.ApplicationName = “RemoteObject”
RemotingConfiguration.RegisterActivatedServiceType(GetType(InterFaceRemoting.InterFaceRemoting))
Note :- We have to provide applicationname and register the object as ActivatedServiceType.
On client side we have to reference the generated ClientMetaData.dll from SOAPSUDS
utility. Below are changes which are needed to be incorporated at the Remoting Client :-
RemotingConfiguration.RegisterActivatedClientType(typeof(RemoteObject),“http://
localhost:1234/MyServer”)
Dim objRemoteObject as new RemoteObject().

RemoteObject is class which is obtained from ClientMetaData.dll which we created using
SOAPSUDS utility. Now you can reference the object as normal object.

Are CAO stateful in nature ?

Yes. In CAO remoting model client creates a instance on server and instance variable set
by client on server can be retrieved again with correct value.

What are the ways in which client can create object on server in CAO model ?

There are two ways by which you can create Client objects on remoting server :-

√ Activator.CreateInstance().
√ By Keyword “New”.

What is fundamental of published or precreated objects in Remoting ?

In scenarios of singleton or single call the objects are created dynamically. But in situations
where you want to precreate object and publish it you will use published object scenarios.
Dim obj as new objRemote
obj.Initvalue = 100
RemotingServices.Marshal(obj,”RemoteObject”)
As shown in above sample following changes will be needed on server side.
RemotingConfiguration.RegisterWellKnownServiceType is replaced by
RemotingServices.Marshal(obj,”RemoteObject”) where “obj” is the precreated objected
on the server whose value is initialized to 100.

What are the situations you will use singleton architecture in remoting ?

If all remoting clients have to share the same data singleton architecture will be used.

What are two different types of remote object creation mode in .NET ?

There are two different ways in which object can be created using Remoting :-
√ SAO (Server Activated Objects) also called as Well-Known call mode.
√ CAO (Client Activated Objects)
SAO has two modes “Single Call” and “Singleton”. With Single Call object the object is
created with every method call thus making the object stateless. With Singleton the object
is created only once and the object is shared with all clients.
CAO are stateful as compared to SAO. In CAO the creation request is sent from client
side. Client holds a proxy to the server object created on server

Which class does the remote object has to inherit ?

All remote objects should inherit from System.MarshalbyRefObject.
(I)

What is .NET Remoting ?

.NET remoting is replacement of DCOM. Using .NET remoting you can make remote
object calls which lie in different Application Domains. As the remote objects run in
different process client calling the remote object can not call it directly. So the client uses
a proxy which looks like a real object.
When client wants to make method call on the remote object it uses proxy for it. These
method calls are called as “Messages”. Messages are serialized using “formatter” class
and sent to client “channel”. Client Channel communicates with Server Channel. Server
Channel uses as formatter to deserialize the message and sends to the remote object.

What is an application domain?

Previously “PROCESS” where used as security boundaries. One process has its own
virtual memory and does not over lap the other process virtual memory; due to this one
process can not crash the other process. So any problem or error in one process does not
affect the other process. In .NET they went one step ahead introducing application domains.
In application domains multiple applications can run in same process with out influencing
each other. If one of the application domains throws error it does not affect the other
application domains. To invoke method in a object running in different application domain
.NET remoting is used.

Thursday, July 14, 2011

Difference between Stored procedures and User Defined functions

Stored procedure
A stored procedure is a program (or procedure) which is physically stored within a database. They are usually written in a proprietary database language like PL/SQL for Oracle database or PL/PgSQL for PostgreSQL. The advantage of a stored procedure is that when it is run, in response to a user request, it is run directly by the database engine, which usually runs on a separate database server. As such, it has direct access to the data it needs to manipulate and only needs to send its results back to the user, doing away with the overhead of communicating large amounts of data back and forth.

User-defined function
A user-defined function is a routine that encapsulates useful logic for use in other queries. While views are limited to a single SELECT statement, user-defined functions can have multiple SELECT statements and provide more powerful logic than is possible with views.

In SQL Server 2000
User defined functions have 3 main categories
  1. Scalar-valued function - returns a scalar value such as an integer or a timestamp. Can be used as column name in queries
  2. Inline function - can contain a single SELECT statement.
  3. Table-valued function - can contain any number of statements that populate the table variable to be returned. They become handy when you need to return a set of rows, but you can't enclose the logic for getting this rowset in a single SELECT statement.
Differences between Stored procedure and User defined functions
  1. UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
  2. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  3. Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  4. Of course there will be Syntax differences and here is a sample of that
Stored procedure

Code: SQL
CREATE PROCEDURE dbo.StoredProcedure1   /*      (       @parameter1 datatype = default value,       @parameter2 datatype OUTPUT      )   */   AS      /* SET NOCOUNT ON */      RETURN
User defined functions

Code: SQL
CREATE FUNCTION dbo.Function1      (      /*      @parameter1 datatype = default value,      @parameter2 datatype      */      )   RETURNS /* datatype */   AS      BEGIN       /* sql statement ... */      RETURN /* value */      END

Thursday, July 7, 2011

How to add javascript validation event to textbox inside Gridview?

javascript function to restrict user to type only numbers in textbox.
Code:
<script type = "text/javascript" language = "javascript">
            function numeralsOnly(evt)
            {
                evt = (evt) ? evt : event;
                var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
                if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode != 46))
                {
                    alert("Enter numerals only in this field!");
                    return false;
                }
                return true;
            }
       </script>

the way in which it can be specified with a textbox inside a gridview:
<asp:TextBox ID="txtProjBudget" onkeypress="return numeralsOnly(event)" runat="server"  Text='<%# Eval("Proj_Exp") %>' Width="103px"></asp:TextBox>

Friday, July 1, 2011

How To Format DateTime In GridView Boundfield And Template Columns

In many situations we will bind date and currency values to gridivew at that time our gridview is something like this

In some situations we don’t want to show complete date and time we need to display only date or only time or we need to display date in different formats and we need to change the currency format display also. To display date with different formats in gridview we need to set DataFormatString and HtmlEncodeproperties.

Here is the list of date formats for gridview.

Character
Description
Date Format
Example
Y or y
Month and year
MMMM,YYYY
May 2011
d
Short Date
MM/dd/yyyy
15/1/2011
D
Long Date
dddd,MMMM dd,yyyy
Sunday, May 15, 2011
f
Full date and time without secs
dddd,MMMM dd,yyyy HH:mm
Sunday, May 15, 2011 4:23PM
F
Full date
dddd,MMMM dd,yyyy HH:mm:ss
Sunday, May 15, 2011 4:23:45PM
g
Date time without sec
MM/dd/yyyy HH:mm
5/15/2011 4.25 PM
G
Full date
MM/dd/yyyy HH:mm:ss
5/15/2011 4.25:35 PM
M or m
Month and day
MMMM dd
May 15
R or r
Full date with GMT
ddd,dd MMMM yyyy HH:mm:ss GMT
Sun,15 May 2011 4.25:35 GMT
s
Sortable Date time
yyyy-MM-ddTHH:mm:ss
2011-05-15T16:33:55
t
Short time
HH:mm
4:56 PM
T
Long Time
HH:mm:ss
4:56:45 PM
u
Sortable DateTime Pattern using universal time
yyyy-MM-ddTHH:mm:ssz
2011-05-15T16:33:55z
U
Long Date
ddd,dd MMMM yyyy HH:mm:ss
Sunday, May 15, 2011 4:54:10 PM
C
Currency Format
$00.00
$10.00
D
Decimal Format
10
10

Now we will implement these formats in our gridview for this first bind the date

values from your database and design your aspx page like this 



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Gridvew Date format</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView runat="server" ID="gvdetails" DataSourceID="dsdetails" 

 AllowPaging="true"AllowSorting="true" AutoGenerateColumns="false">

<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>

<asp:BoundField DataField="Date1" HeaderText="Date1" HtmlEncode="false" 

DataFormatString="{0:s}" />

<asp:BoundField DataField="Date2" HeaderText="Date2" HtmlEncode="false" 

DataFormatString="{0:D}" />

<asp:BoundField DataField="Date3" HeaderText="Date3" HtmlEncode="false" 

DataFormatString="{0:m}" />

<asp:BoundField DataField="Date4" HeaderText="Date4" HtmlEncode="false"

 DataFormatString="{0:d}" />

<asp:BoundField DataField="Total" HeaderText="Total" HtmlEncode="false"

 DataFormatString="{0:C2}" />

</Columns>
</asp:GridView>

<asp:SqlDataSource ID="dsdetails" runat="server" 

SelectCommand="select * from DateFormat"

ConnectionString="<%$ConnectionStrings:dbconnection %>">

</asp:SqlDataSource>

</div>
</form>
</body>
</html>
After that set your database connection in web.config like this


<connectionStrings>

<add name="dbconnection" connectionString="Data Source=SandeepRauniyar;

Integrated Security=true;Initial Catalog=MySampleDB"/>

</connectionStrings >
Demo


If you want to use these date string formats in itemtemplate field we

need to bind fields like this


<asp:TemplateField HeaderText="Date1">
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%#Eval("Date1","{0:y}") %>'/>
</ItemTemplate>
</asp:TemplateField>
I hope it helps you to format date in gridview