How to create a dll in dotnet

To get something you never had, you have to do something you never did-Bimal Patel

Thursday, April 7, 2011

Track visitors of my Asp.Net

Hello guys,

welcome to my blog!.

Yesterday one of my friend asked me a question regarding how to track the vistors of  Asp.net website,so
i thought of putting in my blog so it may be helpfull even to other people.
To achieve this i am going to one of the techniques of the statemanagement called "APPLICATION".

Now question is where to write the code ,please follow the below steps in sequence.
1)Open your Global.asax file
2)Find Application_startevent
3)Now create a Application object named counter (copy paste the below code in your application_start event)
Application.Lock()
Application["counter"] = Application["counter"] + 1
Application.UnLock()

4)Now  in the Application object we have track of the count,now how to  use in our website home page.
go to your home page ,copy paste the below code in the page_load event of your page

Response.write(Application["counter"].ToString());

This should work,if any problems please put on your comments

what is Jan Lokpal Bill?

As Indians from across the world start their march against corruption from today, one of the major demands of this march (Dandi March 2) is to enact Jan Lokpal Bill. I thought it right to write a post describing what Jan Lokpal Bill is and why is it needed. To give a brief history, Lokpal Bill was first introduced in parliament in 1968. It has been brought in parliament on eight times on later occasions, but has never been passed by the parliament. It is a bill that is supposed to give powers to citizens to sue the people responsible for corruption.
The government is again thinking of introducing a Lokpal Bill in parliament this year, and the National Advisory Council (NAC) chaired by Sonia Gandhi is considering it. But as it stands today, the bill is riddled with loopholes, defeating its very purpose. Social activists have remarked it to be a toothless bill and not at all acceptable. An alternative bill, the Jan Lokpal Bill has been drafted by Justice Santosh Hegde (Lokayukta of Karnataka), Prashant Bhushan and Arvind Kejriwal after series of consultations with public and social activists. This bill is supported by Kiran Bedi, Shanti Bhushan, Anna Hazare, etc.
The Dandi March 2 event and the subsequent ‘fast unto death’ by Anna Hazare from April 5 are in support of this ‘Jan Lokpal Bill’. The activists have already sent the bill to the PM and all CMs but there has been no response. After the ‘fast unto death’ was announced by Anna Hazare, he was invited for talks by the PM, but the response was bad as the PM said the government has no time for corruption till May 13. This after the numerous corruption scams like the Commonwealth Games, Adarsh Society, 2G scam being uncovered in the past months.
The Zero Rupee Note - Stop Corruption
The Zero Rupee Note - Stop Corruption
The present system to fight corruption in India can be described in some points as below -
  1. The Anti Corruption Branch and CBI comes under the government. Despite having evidence, it is very difficult to convict people as they have to take permission from the same bosses, against whom the case has to be investigated.
  2. No corrupt officer is dismissed from the job because Central Vigilance Commission, which is supposed to dismiss corrupt officers, is only an advisory body. Whenever it advises government to dismiss any senior corrupt officer, its advice is never implemented.
  3. No action is taken against corrupt judges because permission is required from the Chief Justice of India to even register an FIR against corrupt judges
  4. The functioning of CBI and vigilance departments is secret and hence it promotes corruption.
  5. Weak and corrupt people are appointed as heads of these institutions by the government.
  6. Citizens face harassment in government offices. Sometimes they are forced to pay bribes. One can only complaint to senior officers. No action is taken on complaints because senior officers also get their cut.
  7. Nothing in law to recover ill gotten wealth. A corrupt person can come out of jail and enjoy that money.
  8. Small punishment for corruption- Punishment for corruption is minimum 6 months and maximum 7 years.
As you can see, in the present system, there is no deterrent for any public official to engage in an act of corruption. Some of the salient features of the Jan Lokpal Bill are -
  1. An institution called LOKPAL in the centre and LOKAYUKTA in each state will be set up. These institutions will completely independent of the governments, just like the Supreme Court and the Election Commission. No minister can influence their investigations.
  2. Investigation in any case will have to be completed in one year. Trial should be completed in next one year so that the corrupt officer, or politician goes to jail in two years max.
  3. The loss that a corrupt person caused to the government will be recovered at the time of conviction.
  4. If any work of any citizen is not done in prescribed time in any government office, Lokpal will impose financial penalty on guilty officers, which will be given as compensation to the complainant. So, you could approach Lokpal if your ration card or passport or voter card is not being made or if police is not registering your case or any other work is not being done in prescribed time. Lokpal will have to get it done in a month’s time.
  5. Election of Lokpal officials – What if government appoint corrupt and weak people as Lokpal members? That won’t be possible because its members will be selected by judges, citizens and constitutional authorities and not by politicians, through a completely transparent and participatory process.
  6. What if some officer in Lokpal becomes corrupt? The entire functioning of Lokpal/ Lokayukta will be completely transparent. Any complaint against any officer of Lokpal shall be investigated and the officer dismissed within two months.
  7. What will happen to existing anti-corruption agencies? CVC, departmental vigilance and anti-corruption branch of CBI will be merged into Lokpal. Lokpal will have complete powers and machinery to independently investigate and prosecute any officer, judge or politician.
  8. The punishment would be minimum 5 years and maximum of life imprisonment.
Information from:www.sumit4all.com/politics/what-is-jan-lokpal-bill

Pics of Anna Hazare protesting with  fastuntill death for Jan Lokpal bill



 

Wednesday, February 2, 2011

What is a cursor?


From long time I wanted to know what cursors are ,I  did some googling and just came to know what cursor is  and here is the definition
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.
But how to make it applicable in my practical life .
Then one day my friend came up with following requirement
 I Have 3 tables Tabel-1, Table-2, Table-3
--------------------------------------------------------------------------
 Table-1
Empid   Ename  salary

Here Empid is primary key
1         RAM       20k
2         SITA       30k
3         JOHN     40K
--------------------------------------------------------------------------------------------


------------------------------------------------------------------------------------------------------
 Table-2
Empid   surname  commision

Here Empid is primary key
1         MANU  1k
2         DEVI      2k
3         ANDY    4K
4      SHAN    3K          

--------------------------------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------------------------------------
Now  Table-3

Empid   Ename  salary  surname  commission

2         SITA               30k         DEVI      2K



Now my friend requirement is he need to get the matching records from  Table1 and Table 2
and insert in to Table3 ,if that record does not exists in Table -3,so  the records below is what I should insert in to Table-3
------------------------------------------------------------------------------------------------------
1         RAM       20k        MANU  1K
3      JOHN     40K         ANDY    4K

Now  ,I need to loop through the set of records which I get from joining the Table-1 and Table-2   and  manipulate every record to meet the requirement.
 secondly the query which I use to join Table-1 and Table-2    is
SELECT e.empid
FROM Table-1 e, Table-2     e1
WHERE e.empid=e1.empid
The result will be
------------------------------------------------------------------------------------------------------
1         RAM       20k        MANU  1K
2         SITA       30k         DEVI      2K
3      JOHN     40K         ANDY    4K

Now I don’t want  employee by name sita to be inserted in to Table-3.
So my next thought went to cursor bocz definition says that we can loop through the set of records.
Then I went ahead and found what CURSOR is .
So these  is how you should use cursor
  • Declare cursor
  • Open cursor
  • Fetch row from the cursor
  • Process fetched row
  • Close cursor
  • Deallocate cursor
Now this is how I did my requirement
DECLARE @empid int -- local variable to store primay key value 
declare @empcount int ---local variable to store the count
--Now i declare the cursor
DECLARE db_cursor CURSOR FOR
SELECT e.empid
FROM Table-1 e, Table-2 e1
WHERE e.empid=e1.empid

OPEN db_cursor 
FETCH NEXT FROM db_cursor INTO @empid

WHILE @@FETCH_STATUS =
BEGIN 
--here i check if it already exists in the destination table
select @empcount=count(*) from Table-3  where num_col=@empid
if @empcount=0
insert into Table-3 (empid) values(@empid );
else
print Can not insert;

   

       FETCH NEXT FROM db_cursor INTO @empid
END 

CLOSE db_cursor 
DEALLOCATE db_cursor

---------------------------------------------------------------------------------------------------------------------
Finally Records in the Table 3 will be
------------------------------------------------------------------------------------------------------
1         RAM       20k        MANU  1K
2      SITA       30k         DEVI      2K
3      JOHN     40K         ANDY    4K

Please feel free  to post your comments
Happy coding.....

Sunday, January 30, 2011

How a web page is served from Server in IIS?


How do i get a page in my browser  when i type a  url in browser and press Enter key?.
This was my first  question which was in my mind when i started using  internet,i thought it was a miracle.
Then when i started learning about technologies i came to know that the page which i get  in the browser was from server.But even that i could not convince myself.
So finally i started learning dotnet ,then i realized how exactly this works.I am writing this article by referring some books and articles over internet.If visitors of this article feels some thing wrong or would like to add up some thing  you are always welcome.

click Image to see the Enlarged Image


Now see the above picture,here initially the user from his browser types a url and clicks Enter key,as soon it is done a pipeline will be opened to the server ,technically we term this as httppipeline.
Now we  can term  this as a request,bcoz the user is requesting for page  by typing the url in the browser.Now request will be travelled by the pipeline so we can assume this pipeline as a vehicle.
So Now our Request reached the server,now server checks who u are?once it authenticates ,then next step is filter .I saw that our request will be filtered,how is it filtered?
IIS (Internet Information Service) server has a filter called ISAPI filter  ,this particular searches what request is of type.
Suppose consider if requested page is aspx page,it routes the request to aspx engine,if it is some other page then it routes to some other engine.

So as soon as filtering process is done ,next step is process ,here the our requested page is identified and compiled .once it is compiled then  our request is converted in to response.

Now we have response ,this response will travel along the pipeline and reaches your browser and presented to us .
Most important thing to remember is what ever response presented on the browser will be html,irrespective of the language/framework  we use,you can use java,dotnet,php ,or any thing final output on the browser will be html.

I am going to add up what httphandlers and httpmodules are to this article soon

Friday, January 21, 2011

How grabage collection works in Dotnet?


 When People Speak about Memeory management  they speak about Garbage Collection.
And they start speaking about  dispose,finalizer.Now let us see what all this hell is about and will try to explore the hell and get habituated to the  hell.

Let me classical example ,now person A go to ATM to withdraw the money so as soon as he inserts the card , object will be created to him ,Now Person B  comes to ATM to withdraw money even a object gets created as soon as he inserts the card
In the similar way some thousands of people visits  ATM,so objects are created proportionally with the vistors.
So when objects get created it consumes memory ,now daily thousands of visitors and  thousands of objects.So at some point of time I should free my memory  to make ATM   accessible quickly and effectively.
So there should be some regular cleanup of memory  explicit or implicit.

Here in our DOTNET clr has got a weapon in its bag to deal with such scenarios ,it is none other than GARBAGE COLLECTOR.
Name itself suggests that it collects garbage,so all piled up objects  which are free will be collected by GarbageCollector(GC)  to free the memory.

Let us dive deep in to it.
When some object is  found free with out any reference for longer duration,Garbage collector(GC)  will push it to finalization queue ,next times when garbage collectoion is executed the  objects in the que are given the generations means the the rating  based on their lifeterm or age,so depending on that  GC will call  finalize method m on that object and destroy that.
Now  the problem with this Finalize method is we don’t know when it is called and will be a implicit(internal) call by dotnet framework.

So what is option for me if I need to call the garbage collector explicitly as and when it is required.
Dispose  is oasis in the desert ,this method can be called explicitly by our c# code to clean up objects.
There is interface called IDisposable(to know about t interface refer http://infobylakshmikanth.blogspot.com/2011/01/what-is-interface.html) which defines the 2 overloaded  methods for implementing the dispose methods.

See the below code to implement IDisposable(code is taken from MSDN)
-----------------------------------------------------------------------------------------------------------
public class Base : IDisposable
{
         //Implement IDisposable.
        public void Dispose()
        {
               Dispose(true);
               GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
       {
               if (disposing)
               {
                       // Free other state (managed objects).
               }
               // Free your own state (unmanaged objects).
               // Set large fields to null.
       }
       // Use C# destructor syntax for finalization code.
      ~Base()
      {
               // Simply call Dispose(false).
               Dispose(false);
      }
}
// Design pattern for a derived class.
public class Derived : Base
{
       protected override void Dispose(bool disposing)
       {
                if (disposing)
                {
                         // Release managed resources.
                }
                // Release unmanaged resources.
               // Set large fields to null.
              // Call Dispose on your base class.
              base.Dispose(disposing);
       }
       // The derived class does not have a Finalize method
       // or a Dispose method with parameters because it inherits
       // them from the base class.
}

Then in the next article  we will discuss  more about dispose and also avoid calling dispose method by “USING” keyword.

Monday, January 17, 2011

What is ViewState?


Before writing this  article what I know about view state is
It is one of the statemanagement techniques and its its scope is with in the page

Then I   spent some time on viewstate and realized its importance.

I have a  aspx page with the following code
Code Section-1
  <asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
       
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Now I type some text in textbox(Hello india!) and and click on button.now page refreshes i.e it posts the request to the server.
Once that is done you can still see the text in textbox(Hello India!).How is this possible?
We all know the http protocol suffers from memory loss and don’t remember the prevoius requests,still we are able to retain the value which is posted to the server.
This is possible by our hero “ViewState”.
So I define view state in the following way
Viewstate is a technique/process by which we can retain the values of the page between the subsequent postback.

Ok now let us go still futher and see

What happens in the page lifecycle of Asp.net page.
     

This  entire concept of the view state lies in this image which is taken from MSDN.

Now consider that  we requested  a page which is mentioned above in codesection1  from the browser.
The server presents the page requested on to your browser.Now you type some text in textbox(Hello india!) and click on the button.

Now look at the image,
Intialization:
This is the first step ,here  heirarchy of the controls are set,for example which control should come first and which is the next,so moreover the order of the controls.
Consider a girdview ,a gridview is  not a single control,it inturn will contain child controls in it,so this heirarchy of child,parent controls is set in this part of intialization.
Now we are done with intialization.

Load View State:
The data stored in viewstate can be seen by the end user.Now right click on  your page and click on viewsource,in the source you can see some thing like the below


This is how the viewstate is stored for your page.This is in Unicode format remember it is not encrypted it is only in Unicode format.

A page will have one hidden control with id & name _viewstate  which will contain all the information of the controls in that page as value.

So this value increases as the number of controls increases.So even this will be performance issue when this content increases.Because the time taken to load the page increases as the view state infomartion increases.

Infact there are ways where we can restrict this content,we will discuss this in next article.

Now lets come back now what this load viewstate does?This will load all the content in to the hidden field.This will happen only on postbacks.


Load Postback Data:

Now we have viewstate information  with us in this  stage so called LoadPostback Data,all the controls are loaded with viewstate information from the hidden field.


Load Event:

Now all the controls are loaded at this stage.


RaisePostback Event:

In asp.net there are 2 types of sever events

1)Change events (ex:selection changed events,textchanged events)

2)Raised Events(Button clicks)

So postback is raised

SaveViewstate:

In this stage all the controls information is saved to view state as the name itself suggests Saveviewstate.

Render:

The last stage is Render which will present you the output on the screen.



So at glance

Viewstate information is stored in the hidden fields , as httpprotocol has memeoryloss ,in the subsequent postbacks the values are retained from the view state.


Now as I said we have some performance issues with viewstate,so consider a gridview which is readonly and  we are showing all the employees data.

Let us consider we have some 1000 employees so if all these information is stored in viewstate then time to load the page and memory increases and piles up.

So The better approach in this case to disable the viewState.

Now question is how to disable viewstate?

Every asp.net server control has a property called “EnableViewState=True/False”

Even the viewstate can be disabled at page level,it can be done at the page directive  at the top of the aspx page

<%@ Page Language="C#" AutoEventWireup="true"  EnableViewState="false" CodeFile="Default.aspx.cs" Inherits="_Default" %>



Now Next Question is When I disable viewstate for a textbox ,still if I click the button the value is retained back in the textbox,how is this possible.

These controls do not use ViewState to preserve their state. These controls post their values with the form (form post collection) and therefore they can keep their state without ViewState (they implement IPostBackDataHandler interface).They do have use for ViewState, but to detect if value was changed between postbacks. Disabling ViewState works 100% for controls who are completely dependant on ViewState to keep their state over postback.
Plain DataGrid or DataList are examples of such controls.


please free to share our comments.