Tuesday, December 30, 2008

How to get features with in an Envelope – ESRI

When we load .mxd or map file onto map control, we can find features from different feature layers been spatially distributed.
So to find a set of features which belong to a specific feature class and enclosed with in an envelope, we can write a generic function that accepts the envelope and feature layer to find features in specific feature layer.

Step 1:-
Write a function Considering IEnvelope , IFeatureLayer, MapControl as Input Parameters.
Step 2:-
Run a spatial query using ISpatailFilter interface for the feature class of the given Input feature layer with geometry as given envelope.
Note:-For SpatialRelUse (Spatial relation)
Assign enumeration values from esriSpatialRelEnum
Ex:- esriSpatialRelEnum. esriSpatialRelIntersects for considering all featuers in the feature layer which intersect the given input envelope.
Step 3:-
Query feature class with the above Spatail filter object and retrieve feature cursor.

We can retrieve feature by feature from the returned feature cursor and perform specific required operations.

Function :-
private IFeatureCursor GetFeatures(IFeatureLayer argFeatureLayer, IEnvelope argEnvelope, IMap argMap)
{
if (argEnvelope != null && argFeatureLayer != null && argFeatureLayer.FeatureClass != null && argMap != null)
{
ISpatialFilter objSpatialFilter = new SpatialFilterClass();
objSpatialFilter = new SpatialFilter();
objSpatialFilter.Geometry = (IGeometry)argEnvelope;
objSpatialFilter.GeometryField = "Shape";
objSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
return argFeatureLayer.FeatureClass.Search(objSpatialFilter, false);
}
return null;
}

Example :-

To select a set features spatially intersecting the given envelope.

private void SelectFeatures(IFeatureLayer argFeatureLayer, IFeatureCursor argFeatCursor)
{
if (argFeatCursor != null)
{

IFeature pFeature = null;
while ((pFeature = argFeatCursor.NextFeature()) != null)
{
Map.SelectFeature(argFeatureLayer, pFeature);
}
}
}

O/p





How to display second’s timer in web page?

JavaScript functions could help in this task to display timer in a web page.
We should call a function at specific time intervals repeatedly which increments the counter variable and updates on a HTML label.

“setTimeout” is a javascript function which can be used to call a specific javascript function repeatedly at specific time intervals.
“clearTimeout” is a javascript function to terminate the loop of calling function.
Ex:-
<html>
<head>
<title>Timer</title>
<script language="javascript" type="text/javascript">
var tmr;
var counter=0;
function displayTimer()
{
counter=counter+1;
document.getElementById('lbltimer').innerText=counter;
tmr=setTimeout("displayTimer();",1000);
}
</script>
</head>
<body onload="displayTimer();">
<table><tr>
<td>Timer :</td>
<td>
<label id='lbltimer'></label>
</td></tr></table>
</body>
</html>

Sunday, December 28, 2008

How to create triggers – Oracle?

Any updates made to table, specific to data but not schema can be traced using triggers.
Data updates could be like inserting new row or updating an existing row in a data base table.
So this updates are categorized into Insert and Update operations.
When creating trigger on a table parameters that are to be considered are

1) Trigger name to identify uniquely among the existing triggers.
2) Trigger event that has to be raised before or after of a specific action.
3) Event action (Insert / Update).
4) Table name on which we are placing trigger.
5) Is Insert/Update for each row? (This is because there could be bulk inserts on a table, where multiple rows are inserted at once
Bulk insert in Prog. findings).

Syntax :-
Create or Replace trigger [TRIGGER_NAME]
[AFTER/BEFORE] [INSERT/UPDATE] on [TABLE NAME]
[optional : FOR EACH ROW]
declare
variable declaration
begin
trigger body
end;

Example :-
I will place a trigger on a table of insert type.
In this trigger i need to generate new id for each record that is been inserted into this table.

Actions :-

1) We need to create 3 triggers of Insert type to handle this.
a) After Insert for each row in this table to store the relevant row id in a package.
b) Before Insert to clear the package content.
c) After Insert to get row ids from the package and update the id of the row.

Table
create table test
(
id number,
name varchar2(10)
);

Package to store row id’s
CREATE OR REPLACE PACKAGE pkg_test
AS
TYPE ridArray IS TABLE OF ROWID INDEX BY BINARY_INTEGER;
newRows ridArray;
empty ridArray;
END;
/

Trigger after insert for each row in Test table

CREATE OR REPLACE TRIGGER TRG_TEST_AIFR
AFTER INSERT ON TEST FOR EACH ROW --after insert, for each row
BEGIN
--fills the package with inserted row id(s)
Pkg_TEST.newRows( Pkg_TEST.newRows.COUNT+1 ) := :NEW.ROWID;
END;
/


Trigger after insert in Test table

CREATE OR REPLACE TRIGGER TRG_TEST_AI
AFTER INSERT ON TEST --after insert trigger
DECLARE
tempID NUMBER;
BEGIN

FOR i IN 1.. Pkg_TEST.NEWROWS.COUNT
LOOP
select decode(max(id),null,1,max(id)+1) into tempID from test;
UPDATE TEST SET ID =tempID WHERE ROWID = Pkg_TEST.newRows(i);
END LOOP;
END;
/



Trigger before insert in Test table


CREATE OR REPLACE TRIGGER TRG_TEST_BI
BEFORE INSERT ON TEST --before insert trigger
BEGIN
--clears the package
Pkg_Test.newRows := Pkg_Test.empty;
END;
/
After running the below insert query
INSERT INTO TEST (name) VALUES('Srinivas');
ID is automatically generated from trigger, which should be '1' as this is the first record.


Saturday, December 27, 2008

Grid row data bound event - .NET?

Microsoft has provided grid view control which accepts a data source to bind when we call databind() function it prepares html content to display data from data source accordingly which browser can under stand.

So when we call databind function, web server creates the html content accordingly based upon the grid definition, data source, etc…

So when we use a normal grid with a datasource set to bind it does prepare a normal html string which browser understands to render onto browser.

We can also place html controls (table, anchor tag, image, radio button, etc...),
asp controls (asp:button, asp:checkbox etc..) with in a grid.
There could be cases where we need to access these controls exclusively to do some operation, which are appended to html string by web server for each row in the data source.
This part of handling the controls in the grid exclusively for each row that is being prepared or bounded to the grid by web server is done using “row data bound event” of a grid.

Let us consider a small example.

We should display a grid with many rows in it and 2 columns.
One column is used to display names and the second column has a link button.
When user clicks on a link button in a specific row, we should display an alert box with the specific name in that row.
<table>
<tr><td>

<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPmiTq2vrX7jkstjSvShsAFiMrNQAeHlvnSm3Liv_YTnkl6izq-wZperJlo_3cjSxBrq3lJ_9X3d7QRHQ1VzKeeCMWcmj1dn5YRLHfLbQ2g8FYnp0V7LfKv1hvqMcqBFerhkoHXmlhJcc/s1600-h/1.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 154px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPmiTq2vrX7jkstjSvShsAFiMrNQAeHlvnSm3Liv_YTnkl6izq-wZperJlo_3cjSxBrq3lJ_9X3d7QRHQ1VzKeeCMWcmj1dn5YRLHfLbQ2g8FYnp0V7LfKv1hvqMcqBFerhkoHXmlhJcc/s320/1.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5283851620652726082" /></a>


</td></tr>

<tr><td>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2MfBdoqxuOVrVd7giFXSx-sdzOZecX2Z22P-nslkGFRTNDko_SO0NdDO_1jNTPQNkSq_e30wFG9XPrUz1GRuayALC-QeLKqyqGfZcfws0devvNbk-nYzInn0BrndY2d48qaDwFXXRbrE/s1600-h/3.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 200px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2MfBdoqxuOVrVd7giFXSx-sdzOZecX2Z22P-nslkGFRTNDko_SO0NdDO_1jNTPQNkSq_e30wFG9XPrUz1GRuayALC-QeLKqyqGfZcfws0devvNbk-nYzInn0BrndY2d48qaDwFXXRbrE/s320/3.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5283851630479582994" /></a>
</td></tr>

<tr><td>

<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYw5HJmGVr51_xhQwEfRwDcgCDkO_yvpWE3vsIB4l_aLywKo2dWorW2Z33-Xwlkc3VUUWGDjMs01cWY_4vjY3rW6BpCRlUTyVqXFx6PmpJQNr8t0RW35jIxKYgkOqN9Tj-0l7y0orrwIE/s1600-h/2.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 261px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYw5HJmGVr51_xhQwEfRwDcgCDkO_yvpWE3vsIB4l_aLywKo2dWorW2Z33-Xwlkc3VUUWGDjMs01cWY_4vjY3rW6BpCRlUTyVqXFx6PmpJQNr8t0RW35jIxKYgkOqN9Tj-0l7y0orrwIE/s320/2.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5283851627794558578" /></a>
</td></tr>

</table>
Aspx page :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<link href="Styles/Stylesheet.css" rel="stylesheet" type="text/css" />

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdData" runat="server" CssClass="grid_td" Width="100%" AutoGenerateColumns="false" OnRowDataBound="grdData_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate >Name</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblName" Text='<%#Eval("Name")%>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Click</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server">Link</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>

</form>
</body>
</html>

Code behind page :

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
DataRow dr = null;
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr["Name"] = i.ToString();
dt.Rows.Add(dr);
}
grdData.DataSource = dt;
grdData.DataBind();
}

//Row data bound event function
protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
{
//For each row from data source when bounded to grid this event is raised
LinkButton lnk = e.Row.FindControl("lnk") as LinkButton;
Label lblName = e.Row.FindControl("lblName") as Label;
//checking the controls found from each row based on id is null or nut
if (lnk != null && lblName != null)
{
//Adding java script alert box to display associated name on the corresponding label
//control
lnk.Attributes.Add("onclick","alert('"+lblName.Text+"'); return false;");
}
}
}

Friday, December 26, 2008

Handling radio buttons using javascript in web applications

In windows application we place radio buttons like male or female, which are required to be grouped in a group box.
Since in web application we don’t have such control to place required radio button with in a group we need to handle it exclusively.

So one option is to post back the page when user clicks on one of the radio button to un check the active option.
This is not effective process of again loading the entire page just because of changing the option. We can write a JavaScript function that checks specific radio button among the group and uncheck the other radio buttons.

Let us consider a grid which has multiple rows and each row having a radio button as a column.
Now when user clicks on any one of these radio buttons available in different rows, we should uncheck the other radio buttons.

1) We shall assign same title for all radio button which belong to same group like (male or female),(married or unmarried) etc…
Each group will have its own title and all radio buttons in a group should have same title.

2) When user clicks on a radio button option, we should call a JavaScript function passing the radio button id which user has clicked. With which we can get the title or group name to which that radio button belongs and there fore Unchecking the other radio buttons which have same title or belong to same group.
Code behind page :

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
DataRow dr = null;
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr["Name"] = i.ToString();
dt.Rows.Add(dr);
}
grdData.DataSource = dt;
grdData.DataBind();
}

}















Thursday, December 25, 2008

How to create excel report in ASP.NET?

In web applications, the final reach is the client browser. So if the requirement says that it should display excel, it mean that client browser should display a file dialog to download/save/cancel the file.

It all depends upon the type of content written to browser. If content type is ”xls” then it is excel document or “doc” mean it is word document etc….
So depending upon the type of file we should set the content type.




Please find below example:-

In this case I am creating a file in server side and transmitting it to client browser

//Transmiting server side created file to browser where client can save or open file from dialog
Response.Clear();
//Setting the content type for response
Response.ContentType = "text/.xls”;
//Adding the attachement file name
Response.AppendHeader("Content-Disposition", "attachment; filename=Sample.xls”);
Response.TransmitFile(filepath);
Response.Flush();
Response.Close();


some times it is not required to create file but just create content and through the content


//Transmiting server side content to browser where client can save or open file from dialog
Response.Clear();
//Setting the content type for response
Response.ContentType = "text/.xls”;
//Adding the attachement file name
Response.AppendHeader("Content-Disposition", "attachment; filename=Sample.xls”);
Response.write(filecontent);
Response.Flush();
Response.Close();


Note :-
So when we say depending upon the content type it writes the required type.
In Excel document we can observe the data is in tabular format.
So to prepare such content, we should html table string in server side according to the display we expect and then write the prepared content to client browser.

How to do Serialization in .NET ?

To save an object or to support object persistence, Serialization helps in more.

Say suppose we have a user defined class and when we create object for that class it gets created in heap memory which is volatile or temporary.
So to save the object content we can Serialize the content which is in memory and save it into a text file.
So after de Serializing the content from text file to object type we get the object into hand to perform operations.

.NET Frame work has
System.Runtime.Serialization;
System.Runtime.Serialization.Formatters;
System.Runtime.Serialization.Formatters.Soap;
libraries to support Serialization and De Serialization.


Ex :-

Serialization

public int SaveUserDetails(UserInfo objUserInfo,string strFilePath)
{
FileStream objStream = null;
IFormatter formatter = null;
try
{

objStream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write, FileShare.Write);
formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(objStream, objUserInfo);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (objStream != null)
{
objStream.Close();
}
}
}

De Serialization


public UserInfo GetUserDetails(string strFilePath)
{
FileStream objStream = null;
IFormatter formatter = null;
try
{
if (!File.Exists(strFilePath))
{
return null;
}
objStream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (UserInfo)formatter.Deserialize(objStream);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (objStream != null)
{
objStream.Close();
}
}
}

Wednesday, December 24, 2008

How to find whether geometry is with in Feature class extent ESRI ?

Every feature class has its own extent for spatially distributing its features.

So we can check whether a given geometry lies in a given extent or envelope.

public static bool IsWithinExtent(IGeoDataset geoDataset, object geometry)
{
IGeometry pGeometry;
IRelationalOperator pRelOp;
try
{
//If given geometry is element then tracing its gemoetry to find
//with in extent
if (geometry is IElement)
pGeometry = ((IElement)geometry).Geometry;
//If given geometry is dimension, then considering all points lieing at the
//dimension feature boundaries
else if (geometry is IDimensionShape)
{
//Extracting the geometry of the dimension feature
IDimensionShape pDimShape = (IDimensionShape)geometry;
IPointCollection pPointCol = new PolygonClass();
object pBefore = Type.Missing;
object pAfter = Type.Missing;
//Creating a closed polygon with lines joining the dimension line point,
//dimension begin point, dimension end point
pPointCol.AddPoint(pDimShape.DimensionLinePoint, ref pBefore, ref pAfter);
pPointCol.AddPoint(pDimShape.BeginDimensionPoint, ref pBefore, ref pAfter);
pPointCol.AddPoint(pDimShape.EndDimensionPoint, ref pBefore, ref pAfter);
//Then taking geometry of finally created polygon
pGeometry = (IGeometry)pPointCol;
}
else
//Taking the exact geometry of the given object
pGeometry = (IGeometry)geometry;
//relation operator helps tp spatially licate the geometry
// and then chek its extent
pRelOp = (IRelationalOperator)pGeometry;
if (pRelOp.Within(geoDataset.Extent))
return true;
else
//Throughing coordinates out of boundary when give geometry
// does not lie with in the feature class extent
throw new Exception(conCoordsOutofBound);
}
catch
{
throw new Exception(conCoordsOutofBound);
}
}










Sunday, December 21, 2008

How to spatially select a feature in Map – ESRI?

When we load map control with map (.Mxd) file, there could be many layers available.
So to select a specific feature from a layer, we need to know the feature class to which this feature belongs.

To get the feature class of a feature, we can say [feature object].Featureclass.
Ex: - argFeature.Featureclass.

Now we need to iterate through each layer available on the loaded map file, then we need to find the layer that loads features from the above feature class.

I would like to update such function which expects map and feature as input parameters to spatially select a feature in the given map.


public static void setSelected(IFeature pFeature,IMap pMap)
{
try
{
IFeatureLayer pFeaturelayer;
ICompositeLayer pCompositeLayer;
IFeatureClass pFeatureClass;
int layerCount;
int compositeLayerCount;

//Loop to iterate through each layer in the given map
for (layerCount = 0; layerCount <= pMap.LayerCount - 1; layerCount++)
{
//If retrieved layer is a group layer (layer having a group of layers in it)
if (pMap.get_Layer(layerCount) is IGroupLayer)
{
pCompositeLayer = (ICompositeLayer)pMap.get_Layer(layerCount);
//Looping through each layer in the group layer
for (compositeLayerCount = 0; compositeLayerCount <= pCompositeLayer.Count - 1; compositeLayerCount++)
{
//Checking if the layer is feature layer (a map layer that consists of features
if (pCompositeLayer.get_Layer(compositeLayerCount) is IFeatureLayer)
{
pFeaturelayer = (IFeatureLayer)pCompositeLayer.get_Layer(compositeLayerCount);
pFeatureClass = pFeaturelayer.FeatureClass;
//Checking with the feature class name asscoiated with the layer is same as
//given feature's feature class
if (pFeatureClass != null && pFeature != null)
{
if (((IDataset)pFeatureClass).Name == ((IDataset)(IFeatureClass)(pFeature.Class)).Name)
{
//If feature class name's are equal
pMap.SelectFeature((ILayer)pFeaturelayer, pFeature);
}

}
}
}
}
//Checking if the layer is feature layer (a map layer that consists of features
else if (pMap.get_Layer(layerCount) is IFeatureLayer)
{
pFeaturelayer = (IFeatureLayer)pMap.get_Layer(layerCount);
pFeatureClass = pFeaturelayer.FeatureClass;
//Checking with the feature class name asscoiated with the layer is same as
//given feature's feature class
if (pFeatureClass != null)
{
if (((IDataset)pFeatureClass).Name == ((IDataset)(IFeatureClass)(pFeature.Class)).Name)
{
//If feature class name's are equal
pMap.SelectFeature((ILayer)pFeaturelayer, pFeature);
}
}
}

}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message +" setSelected",Constants.DIALOG_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}
Please click in below image links to look at comments








Saturday, December 20, 2008

How to make asynchronous calls in .NET ?

Method calls what we build in applications are always synchronous. I mean
Ex:-

Main()
{
Fun2();
Fun3();
.
.
.
}

Fun2()
{
.
.
}
Fun3()
{
.
.
}
In this in Main function, first function Fun2() is called but Fun3() is called only Fun2() is completed and returned.
Though Fun3() does not required input from Fun2() but it has to wait.

When we build windows application, there might me a logic when user clicks on a button a process runs to perform operation.
Consider if it is a long running process, while process is running and if user disturbs the window or User interface, the screen gets hanged saying “not responding”.

When user moves the screen while a process is being run synchronously by application, then
Since Moving window is also a process that has to run but it will wait till the long running process is completed.
In above example,
Fun2() is long running process and Fun3() is the function that has to be runned when user moves the window or UI.
So if I make Fun2() to run asynchronously then Fun3() can be executed when and then required.

So in windows application long running process need to run in a thread or asynchronously, where UI is still interactive.

Delegates help to make a call asynchronously.
Since delegates store the address of the method, we need to invoke a delegate that handles the memory address of the method stored by it to processor which runs it concurrently or separately.

So in windows application when a separate thread or long running process is called asynchronously or runned separately, this process cannot assign values to window components which are on different thread.











Ex:-
//delegate to store the long running method address
private delegate void dlgDelayer();

//button click from user interface
private void btnStart_Click(object sender, EventArgs e)
{
//creating an nstance for delegate with address of long running //method or process
dlgDelayer objDel = new dlgDelayer(this.Delay);
//Invoking delegate
//This mean to initiate the process or method pointed by delegate
//AsyncCallback mean to call methos “ProcessDone” when long running //method is completed
objDel.BeginInvoke(new AsyncCallback(ProcessDone), objDel);
}
//Long running method
private void Delay()
{
int i = 1;
while (true)
{
string tt = lblProcess.Text;
i++;
UpdateLabel( i.ToString());
Thread.Sleep(2000);
if (i == 8)
break;
}
//To update a label (windows component
UpdateLabel( "Done");
}
//Method that gets called when long running method is completed
private void ProcessDone(IAsyncResult ar)
{
((dlgDelayer)ar.AsyncState).EndInvoke(ar);
//To update a label (windows component
UpdateLabel("Sucess");
}
//delegate to update windows label
delegate void StringParameterDelegate(string value);

private void UpdateLabel(string strMsg)
{
//varaible to check whether the caller has to invoke, when caller is //running on separate thead to where control is created
if (InvokeRequired)
{
//When caller method has to invoke or call the function //asynchronously
BeginInvoke(new StringParameterDelegate(UpdateLabel), new object[] { strMsg});
return;
}
//Updating label when caller running in same thread where the label
//control is
lblProcess.Text = strMsg;
}

Friday, December 19, 2008

Whar are delegates in .NET?

Delegate can be said as container or a reference type which encapsulates the address of a function mentioned.

It can be clearly said as when a specific event is required to be raised on button click, check box check changed then frame work calls the specific delegate assigned to the control event and accordingly the function whose address was encapsulated by that delegate will be called

Ex:-

Public delegate delhandler ()

Public void source()
{
Delhandler objdelhandler;
objdelhandler=new Delhandler(this. DelTest);
objdelhandler.Invoke();
}


Public void DelTest()
{
Console.WriteLine(“Hai”);
}




So when the function "DelTest" is invoked, then "Hai" is written on console.

Multi Cast Delegates

This can be said as multiple functions getting called from a single delegate invoke call.

This includes the process of combining multiple delegates into one and then dynamically invoking at once.

Public void DelTest1()
{
Console.WriteLine(“Hai 1”);
}



Public void DelTest2()
{
Console.WriteLine(“Hai 2”);
}



Public Delegate Delhandler ()


Public void source()
{
Delhandler objdelhandler1;
Delhandler objdelhandler2;
Delegate [] objdelAll;
Objdelhandler1=new Delhandler(this. DelTest1);
Objdelhandler2=new Delhandler(this. DelTest2);

objdelAll=MultiCastDelegate.Combine(Objdelhandler1, Objdelhandler2);
objdelAll.DynamicInvoke(null);
}




From the above process it is clear that we have two delegates, ofcourse of same type the two delegates encapsulating different function addresses.

So there is a process of invoking 2 delegates with 2 invoke statements each or combing two delegates using multi cast delegate getting into an array and then by dynamic invoke.

Thursday, December 18, 2008

What Is difference between Viewstate and Session in .NET?

I hope we all know that browser to web server http request is always state less.
I mean web server when recieves request from the same browser/client again and again it does not know it or handles each request as request from a new browser or new request.

Keeping the above point in mind , we can have few queries.
How are web applications able to maintain user credentials among different pages when navigated. This should not be possible when each request made to web server for different pages to navigate is a new request (state less) from web server side.
It is made possible by using these sessions, Viewstates and few others to provide persistence of data/information among requests between server and client.

1) Viewstate:-

This helps to persist/hold values in specific page and purely handled on client side.
But remember this is different to cookies.
Cookies are stored but Viewstate value is hold. The exact difference is Viewstate values are not in existence when user navigates to another page.
Where as cookies can still be accessed from another page since they are stored.

Viewstate values are saved on the page as information or html data on the browser as
“Hidden value”, so when post back happens in the page, it sends the hidden values (Viewstate values) to web server from which server can retrieve and probably do required actions.
Sine I said Viewstate values are stored on client browser when page is loaded, so it very clear that Viewstate value can hold only strings.

So I mean to say that Viewstate is valid for all kind of objects which are serializable.

Since Viewstate is meant to be loaded on client’s browser, it is suggested not to store secured data in Viewstate object.

Example:-



i) I have created an aspx page in my web site.
ii) Then added a Viewstate value whose key is “Name” and value is “Srinivas” in page load event of added aspx page.
Note: - We key “Name”, is used further in this page to retrieve its value (“Srinivas”);
iii) Output





iv) Right click on the page and say “View source” to look into html content.






We can find the input type = hidden whose id is “_VIEWSTATE” that holds the Viewstate objects. The values of the Viewstates are encrypted and this is configurable.

2) Session:-

This helps to persist/store on server side which are specific to user as Viewstate specific to a web page.

Since these session values are stored on server side, client is not aware about this data that is been maintained in session.

So when request comes from same browser multiple times to a web server, though it is state less since a session is allotted for that user, so required information that is important can be stored in session.
So when request comes from same browser, though server cannot find it is the request from same client but can access the information stored in session variable.
Even when user navigates among different pages the session values persist, as they are stored in server memory.

Session variables are meant to be expired when user closes the browser.

Note:-
Web server has an option saying “Session timed out” which is configurable, this mean when user opens the application and is not interacting with it (not sending request to web server) for a time more than this “Session timed out” value , session of that specific user is expired. At this instant if user sends request to web server, it cannot access session data that is stored earlier as it is expired.

As Session variables are stored in server memory it can be used to store any kind of objects which are not even serializable.

I am taking the same page as example replacing “Viewstate” with “session”
Example:-


i)




ii) Run the application




iii) Right click on the page and say “View source” to look into html content.





Still you can see Viewstate values rendered.
This is because web server appends the Viewstate values to hold the state of controls used in this page.
But this Viewstate does not include the encrypted content for Name=Srinivas.

So session is very different to Viewstate to store values.

Wednesday, December 17, 2008

How to create Web Control effectively by embedding resources ?

The intension of this post is to update viewers that we can create web site in ASP.NET not only just by using the same default web controls (asp:button , asp:checkbox, asp:Textbox , etc…) provided by Microsoft but also we can generate such kind of components which could be more specific to requirements by customizing or creating our own web control.


Earlier I have updated blog about this. But I mean to explain in more which I have in learnt past few days.

Let us consider a normal asp:Button which is provided in asp.net framework.
When we just zoom in more about it, it is also a web control that is developed which implements “System.web.UI.webcontrols” to generate HTML content also IButtonControl, IpostBackEventHandler to handle post back events.
Let us concentrate on “System.web.UI.webcontrols”.
This base class helps to create a web control which web server can understand to generate a html content for the requested browser. Broswer shall understand the response content as it is in HTML format and displays specific web control as HTML component effectively.

In this post I am going to explain each and every step how to create such web control (a web control could be a combination of many resources like image, html page, style sheets, etc…).


Note: Please click on each image to look into and observe each step and understand easily.
Step 1:
Create your own website using visual studio as usual.

Right click on solution explorer to add new project.





Step 2:
When web control library is created with your own name “MyWebControls”, by default a class is created with same name.
I wish to change as “MyButton.cs”.

Now “MyButton” web control is going to be manufactured, with combination of an image (eye.gif) and style sheet (Stylesheet.css).
When user clicks on this control in browser, I wish to redirect browser to an html page (HTMLPage1.htm).
Resources I am using for “MyButton” for Demo
1) Eye icon –




2) Html page



Step 3:
So add all the required files to this web control library.



Select all added resources or files (eye.gif, Stylesheet.css, HTMLPage1.htm) and go to properties (click F4).
Change “Build action” from “content” to “Embedded resource”.

The reason for changing this “build action” is, when we build this “web control library”, .dll file is created for this library and these resources are said to be embedded or included as well.
If they are not embedded then the url of the image/html/style sheets should be used in the web pages to access them which is very absurd.

If these resources are embedded and build, then we have specialized classes which read content using assembly name and apply the image instead of using the actual path of resources.


Step 4:
Open “Assembly.Info.cs” file under “Properties” in web control library.
Define the resources available in the library folder with the web resource name to access them or identify the resource and the content type as shown below.




Step 5:
Open the “MyButton.cs” class files and perform required updates to customize or define your own web control accordingly.

Please consider as example the below source code developed for my web control.
(Click on each image to look into to understand)










Step 6:
Build the web control library in “release” mode.
Now create an aspx page in your web site, open its aspx page.
Step i) Open tool box and right click to add your web control.




Step ii) Browse to find the .dll file created in above web control library folder (release) to add.



Step iii) you can find your web control (MyButton) created and added to the tool box.



Step iv) Drag and drop “MyButton” object onto your aspx page.




Step 7: Run the application to view added aspx page.

Output:





After clicking on the “eye” view icon.






Note:
1) Observe the url of the html page redirected after clicking on the control.
It consists of saying “webresource.axd” , where this page does not exist in reality but considered to be to read the embedded resource and give response.
http://localhost/WebSite1/WebResource.axd?d=Tb3uAvtpQ05CR2eVpDNr-rngltSt7NDObe-eLHjHIX9lRnOBakawlyx0ztjvRvjQ0&t=633649438827814974
2) Please see below diagram to understand in detail the above process.




3) When we embed required resources to manufacture "MyButton" and add to tool box try to do below steps.
i) Unload the web control library project from solution.
ii) Delete all embedded resources (eye.gif, html page)that are been used to build "MyButton" and access the web site by running application.
Still we can find that the control is fine with required images/html page.
Confimration :- Once the web control library is build and dll is added to the tool box, required resources which are embedded are included in .dll file and need not worry about resources used to build web control.

Monday, December 15, 2008

How to create webservice in .NET?

Please refer about services at
Services in prog. findings

In this post , I am creating a webservice which gives me live cricket score as explained in earlier posts.


Step 1:
Right click on the project solution and say” add new web site”.
Choose “ASP.NET webservice” with location as specified in screen shot.





Step 2: Click on “Service.asmx” and say F7 to open “Service.cs” file.

You can observe a by default “Hello World” web method defined in it.
(web method mean a function defined in webservice).
Shall explain in detail about webservice in later posts.

Please view below screen shot, sample code written to return “live cricket score” based upon authorised license sent by web page and match id.






Step 3:
Now build this “webservice.

Create a new .aspx page in your website not in this webservice to call this webservice over there.
Now right click on the web site and say “Add web referenece”.






A window appears to choose webservices whether available in local machine or solution or in network.




Since webservice is created in same solution, we can say “webservices in this solution”.
It lists out all the available webservices in the same solution.
Select the “Service” webservice displayed in dialog.
Note:-
While choosing this webservice you may get Error 403.1 Forbidden, which is because of permissions.
To avoid this, open IIS manager
i) Select the webservice listed in default web sites.
ii) Right click and say properties.
iii) Select “Scripts only” from Execute permissions.










When we click on the listed webservice, it displays the web methods available in that webservice and also gives an option to update the web reference name that can be used in web site to refer the webservice.






Click on “Add Reference”,
You can find the references being added to the web site.




I shall update more about these references later through posts.
These references are said to be as “Proxies”. These are like duplicate objects stored on web server.
This means they define/validate objects to call the web methods.

I have created my aspx page to call this live cricket webservice.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CricInf.aspx.cs" Inherits="CricInf" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">

function reloadpage()
{
window.location.reload();
}
var tmr=setTimeout("reloadpage();",3000);
</script>
</head>
<body>
<form id="form1" runat="server">
<div><table width="40%" style="border: 1px solid #d10000;text-align:left"><tr><td>
<label runat="server" id="lblCricScore"></label>
</td></tr></table>
<center> This is ABCD Bank , please click here for Free Credit card and Loans :)</center>
</div>
</form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.web;
using System.web.Security;
using System.web.UI;
using System.web.UI.webControls;
using System.web.UI.webControls.webParts;
using System.web.UI.HtmlControls;
using CricScore;
public partial class CricInf : System.web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
UpdateCricScore();
}
}
private void UpdateCricScore()
{
CricScore.Service objCricService = new Service();
lblCricScore.InnerHtml = objCricService.CricketScore("SRINIVAS", "IND_ENG_03");
}
}





We can observe JavaScript function which helps to start a timer that reloads the page to show updated cricket score retrieved from webservice.





Output:




Note:

1) We can find the page gets reloaded after every 3 seconds as timer is set for to update live cricket score.
2) We can observe that the page displays cricket score as well as it is a banks site.
It mean that whom ever it is, if they are willing to show cricket score or weather or latest new etc… in there site shall need to purchase license from the specific 3rd party webservice for authorisation and get content updated on there web page.
3) Please observe the below flow diagram of webservice



How to create windows service in .NET?

Windows service does not have User interface but can be accessed from the services list provided by windows operating system.
(Type “services.msc” in command prompt).
We also heard about web services,
This service provides information to the user but it does not have its own User interface and it is embedded or called in web applications like web pages.
So service will not have User interface to interact but runs at the back end to listen and respond for requests sent to it.
Windows service is very similar to web service, where as windows service serve specifically in desktop but web service can be accessed in internet using http protocol like a web site.
Example: - We see live cricket score board being updated in few web sites , it does not mean that each web developer stays at the stadium to update his data base data with live score :).
There runs a web service at one point which updates its database with the updated live score, all other different web sites running around the world access the same web service and share the same information.






Web service process

Windows service is very specific to desktop not as web service shown above.

Step 1:- Template in visual studio to create windows service






Step 2:- After creating windows service, we can observe the windows service class file opened and 2 methods (start and stop) in it.

For demo I am creating this service to log date and time when the service is started and stopped.



Step 3:-

After relevant logic is written in the class file for both start and stop events, we need to add installer that supports to insall the service.
(To add installer, double click on the “services.msc” in solution explorer, right click on the displayed window and click on “add installer”)




Step 4:
We can see “serviceInstaller1” object on the window after adding Installer.
Now go to properties of this “serviceInstaller1”, set attributes like service name, service description.




Step 5:
We can also see “serviceProcessInstaller1” object on the window after adding Installer.
Now go to properties of this “serviceProcessInstaller1”, set attributes going to account as “localsystem”.




Step 6:
Now build the entire solution in”release” mode.

Step 7:
After building solution go to release folder of the application and also open “.NET command prompt”.


Type “installutil “(space) drag and drop the .exe file created in release folder.




You can see windows is running steps to create service and finally a log file generated in release folder by installer.





Step 8:
Open services in your machine (go to command prompt and type “services.msc”).
You can find the service in the list created by you in all above steps.
Right click on the service and say “start”.





Step 9:
Now open the log file that will be created by your service in the release folder or the path where .exe file exists.