ASp.Net day

Micro blog

Could not load file or assembly 'System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified

July 31
by Satalaj 31. July 2010 05:09


VS 2010 come up with easy way to refer the assembly from bin instead of GAC.

Could not load file or assembly 'System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
or one of its dependencies. The system cannot find the file specified

Quick Fix

This dll System.ServiceModel.DomainServices.Hosting is a part of RIA services SDK.

You need to install it on server. Below is url to download.


http://www.microsoft.com/downloads/details.aspx?FamilyID=7b43bab5-a8ff-40ed-9c84-11abb9cda559&displaylang=en

Another way.

Before publising web, right click on assembly references and look at the properties of it.
set Copy Local to true. This will reference the assembly from bin instead of GAC.

As soon as you build your project, you will see those assemblies in bin folder copied from GAC.

If you would like to browse the GAC and copy dll manually, you can reffer below TIP.
http://www.revenmerchantservices.com/ajax/systemwebextensions.html

 

Tags:

Asp.net | Tips

transaction

July 21
by Satalaj 21. July 2010 09:21


  Many time row processing becomes dependent process.


Below stuff will shade some lights on

1. Transaction using ADO.net application
2. Transaction using SQL server / stored procedure


E.g. Your application has processed the CC information to third party web and its waiting
       for response.
       What if their site is down? or there is network falure or communication error?

Obviousely, you need to roll back the transaction. Using C#.Net below code snippet will help you to understand and use
SqlTransaction techniuque

Code is self explanatory


// create SQL connection object and pass connection string to it from application settings

 SqlConnection sqlconnect = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);


// create SQL command object

            SqlCommand sqlcommdt = new SqlCommand();                       

// Tell command object where to connect

            sqlcommdt.Connection = sqlconnect;

// Tell command object what to do once get connected

// In this case, I'm telling it to execute Stored procedure

            sqlcommdt.CommandText = "SP_Name";

// set type of command object

            sqlcommdt.CommandType = CommandType.StoredProcedure;
    
       

            try
            {

//  Open connection

                sqlcommdt.Connection.Open();

//  Create SQL Transaction

                SqlTransaction transaction = sqlconnect.BeginTransaction();

// Tell command object to use SQL Transaction object

                sqlcommdt.Transaction = transaction;

                DataTable dt = new DataTable();

                dt.Load(sqlcommdt.ExecuteReader());
               
                try
                {

                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {

                            // Process the row
                            // It may throw excetion. In this case, immediate catch block will throw that exception to outer one.
                         
                              ProcessRow(dr);   

                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

// If there is no exception, commit the transaction.

                sqlcommdt.Transaction.Commit();
            }

            catch (Exception ex)
            {
           
// If there is an error, you can roll back the transaction.

                sqlcommdt.Transaction.Rollback();
            }


2. When to go for SQL transaction using stored procedure?

See below code snippet.

 Begin transaction tr1
   begin try
  
           -- Do insertion on one table
           -- Do deletion from xyz table

   -- If every thing worked fine commit transaction.

    commit transaction tr1

   End try

   begin catch

-- If any error occured during insertion or delition, you can roll back that transaction.

    rollback transaction tr1

  end catch


Scenario when transaction invlove insertion / updation / deletion on multiple SQL server, you need to
go for MSDTC.

HttpHandlers configuration

July 15
by Satalaj 15. July 2010 05:30


 
   I assume here you are familiar with HttpModules and HttpHandlers.

This article will help you to create API using .Net.

1. Create classs library project say MyProject.Core
2. Add referance of System.Web
3. Create on class called xyzHandler and inherit it from IhttpHandler

E.g. 

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace MyProject.Core
{
    public class xyzHandler:IHttpHandler
    {

        #region IHttpHandler Members

        public bool IsReusable
        {

            get { return true; }

        }

        public void ProcessRequest(HttpContext context)
        {

            if (!string.IsNullOrEmpty(context.Request.QueryString["UserName"]))
            {
                string username = context.Request.QueryString["UserName"];

                context.Response.Write("Hi" + username);
            }

        }

        #endregion


    }
}


This handler will collect the username parameter posted by HTTP get method.
If you use Request.Parms, handler can accept parameters posted by both HTTP GET/POST method.
Now, you can add referance of MyProject.Core dll into your web and configure your web application to use this handler.

You need to add below httphandler element under System.Web node in your web.config. Your web.config will look like below one

<system.web>
<compilation debug="true"/>

<authentication mode="Windows"/>

<httpHandlers>

<add verb="GET" path="xyz.ashx" type="MyProject.Core.xyzHandler, MyProject.Core"/> </httpHandlers>

</system.web>


In above configuration you can use

1. verb="*" it indicates handler can accept all HTTP methods like GET,POST,OPTION etc.

2. path="*.ashx" this indicates any request coming to extension .ashx will be handled by xyzHandler

3. For type you first need to give fully qualified name of class like MyProject.Core.xyzHandler and name of assembly like MyProject.Core.

Below url will let you capture the field username posted by HTTP GET method.

TEST URL
http://localhost:17499/FastFileDownLoadDemo/xyz.ashx?username=satalaj







Tags:

Asp.net

asp.net site performance

April 30
by Satalaj 30. April 2010 04:47

   You can boost performance of web application by reducing round trips from client to web server and web server to database server.
   Here are some tips that will help you.

1. HttpResponse.IsClientConnected.
   This property will tell server whether client is still connected to the server or not. If it is still connected you can process the request to perform operations on it.

2. Caching
   If you are fetching the data which is almost static, you can consider use of caching. So, when next user request the data he will get it from CACHE.

3. Server.Transfer
   Where ever possible use Server.Transfer instead of Response.Redirect. If you had used Response.Redirect in your code, client gets redircted page address in header
   with status code 302 then ceint request the url found in header.

4. View state
   Avoid storing state of object in view state. During post back you will post unnecessory data in hiddenField called __VIEWSTATE.

5. WEB.Config
    If you are not using Session module, you can remove it by overrriding default behaviour maching.config using web.config.
    same way you can disable out put caching, authentication and authorization mechanisems.

6. Web Gardening
    Add multiple worker process in Application pool. This will boost the performance of your application.
    Adding multiple worker proccess to your application pool will consume more memory.
    Note: If your application is using session, you need to store the session out of process. You can use SQL server or State server.
    This will help worker process to access shared session values across the worker process.

7. Web Farmng
   Create multiple instances of your web application on multiple machines and bring those machines into NLB cluster (Network load balancer)
   It will increas availability of your web application.

8. Exceptions
    Avoid exceptions to occur.

9.  Ensure Debug Is Set to False    
     When debug is set to true, following occurs
     Pages do not time out.
     Additional files are generated in the Temporary ASP.NET Files folder. which creates extra I/O operations.
     make debug false in both web.config and at page level
 
    <compilation debug="false" ... />
    <%@ Page debug="false" ... %>

10. Optimize Expensive Loops
    
    
Use For loop instead of ForEach loop when performance is important for the operation.

11. Server Controls
     Turn off ViewState properties of server side control if not required.
     avoid creating deep hirarchies of controls
     use server controls whenever required else use html controls.

12. Data Binding    
      if it is inefficiently used will hit performance measures. 
      Avoid Page.DataBind instead use control specific DataBind method
      Avoid performing DataBinder.Eval operations of controls.

 

   
 

session loss in webgarden

April 19
by Satalaj 19. April 2010 11:33


Web Garden:

 In webGarden scenario application pool can have multiple worker process assigned to it.
In this case there are possiblilities like users first requests get served by workerprocess A and second request
get served by worker process B. assuming you are using In-proc session, in above scenario your worker process A
has user session and worker process B was not aware of it so when user tries to request the page and page was serverd by worker process B.
Then ultimately user will be asked to reinitiate the session.
 To overcome this situateion you need to mark the objects of classes who participate into session storing mechanisum as serializable
and you need to define the storage space for Session values like Application state server or SQL server for maintaining session state.
Why do we need to mark the classes a serializable? 
Objects while crossing the boundries of application they need to mark as serializable otherwise it's not posible for them to cross the boundries.

Application Pool recycling and session values

 When application pool pro-actively or re-actively recycles the healty/ un-healthy worker process and incase you are using in-process memory for
storing the session values, you will loose the session values. To avoid loosing session values use out of process session storing mechanisum.
use either SQL server or State server.

Web Farm:
In web farm scenario multiple machine act like single one using Network load balancing cluster. In this case there are possibilities that
first request get serverd by Machine A and second request get server by machine B of NLB cluster. If session get stored in Machine A's in process,
how is it possible to have those session value at machine b's in process. To avoid this we need to store session values as shared resource like
SQL server or State server.
I learned NLB using this article http://www.west-wind.com/presentations/loadbalancing/networkloadbalancingwindows2003.asp

To let SQL server participate into session storing mechanisum you need to execute aspnet_regSQL with appropriate switch.

-Satalaj


 

Congratulations 2010 Microsoft MVP

April 03
by Satalaj 3. April 2010 09:54

I'm very happy for being recognised as MVP.


Dear Satalaj More,

Congratulations! We are pleased to present you with the 2010 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in ASP/ASP.NET technical communities during the past year.

Also in this email:

About your MVP Award Gift
How to access www.mvpaward.com to begin taking advantage of your award benefits
Your MVP Identification Number
MVP Award Program Code of Conduct
The Microsoft MVP Award provides us the unique opportunity to celebrate and honor your significant contributions and say "Thank you for your technical leadership."

Toby Richards
General Manager
Community & Online Support

 

Tags:

Asp.net

asp.net process model

February 24
by Satalaj 24. February 2010 07:37
We can configure the Application Pool Recycling in two ways.

1. Reactive application pool process recycling.

2. Proactive application pool process recycling.

Reactive Process Recycling:
It happens when process is not functioning properly or unable to serve requests. 
Symptoms: Process deadlocks, access violations, memory leaks, Insufficiant memory and so on, in order to trigger a process recycle.
You can help control the conditions that cause a process restart by using the requestQueueLimit, memoryLimit, and shutdownTimeout configuration attributes.
For more information about these attributes, see the <processModel> Element configuration section of Machine.Config file.

Proactive Process Recycling
Proactive process recycling restarts the worker process periodically even if the process is healthy.
This can be a useful way to prevent denials of service due to conditions the process model is unable to detect.
A process can be restarted after a specific number of requests or after a time-out period has elapsed. You can enable proactive process recycling using the timeout, idleTimeout, and requestLimit configuration attributes. For more information, see the <processModel> Element configuration section of Machine.Config file.

Below are the default settings of Process model found at machine.config file.

<processModel

enable="true"

timeout="Infinite"

idleTimeout="Infinite"

shutdownTimeout="0:00:05"

requestLimit="Infinite"

requestQueueLimit="5000"

restartQueueLimit="10"

memoryLimit="60"

webGarden="false"

cpuMask="0xffffffff"

userName="machine"

password="AutoGenerate"

logLevel="Errors"

clientConnectedCheck="0:00:05"

comAuthenticationLevel="Connect"

comImpersonationLevel="Impersonate"

responseRestartDeadlockInterval="00:09:00"

responseDeadlockInterval="00:03:00"

maxWorkerThreads="20"

maxIoThreads="20"

/>


Satalaj

Connection pooling

January 29
by Satalaj 29. January 2010 12:16
kick it on DotNetKicks.com


  Hi, my name is Satalaj. Here, I'm going to explain what is connection pool with solid proof.
Connection pool as name suggest its a pool of Established connections.
When we are closing the connection in finally or in try catch block that doesn't mean we are closing Established connection with your db server.
Closing connection means notifying the application about that connection is free for future request.

Here, I will tell my connection string to use min pool size = 1 and max pool size = 2.

As soon as pool gets initialized it will establish only one connection with SQL server db.  

You can use below query to test how many connections are established with your MS SQL db server. I established the connection with asptest DB.

select db_name(dbid) as DataBaseName , count(dbid) as

NoOFConnections , loginame as LoginName

from sys.sysprocesses where dbid > 0 and db_name(dbid) = 'apitest'

group by dbid,loginame

 

Here is screen shot of Established connection.

 

 I fired a command netstat -b from my command prompt and found that WindowsApplication1.VShost.exe with process ID 6140
Established one connection with MS SQL server IP 192.168.1.1.28 on port 1433.

My application is running and it has processed his task and I have closed the connection. However, you can see the connection is Established
and it will stay established, still the life of application. If I colse the application, I will not see any connection with my DB APITEST.

   TCP    smartmirror:2096                      192.168.1.28:ms-sql-s  ESTABLISHED     6140
  [WindowsApplication1.vshost.exe]

In my application I have one established connection. What will happen If I get 2 requests simultaniouesly?

Ans. The application will establish another connection to DB server as my Max pool size is 2 and that new connection will serve the request.

What if I get 3 or 4 simultaneous requests?

If there is no free  connection available in connection pool the application will throw an error

Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
 

What happens when I set Min pool size = 10 in my connection string ?
The application will establish 10 connection with DB.

You can see it by using query above and at client / server side, you can execute netstat -a command to know
which are the ports participates in this communication. You can see how my application is talking to sql server using ports ranging from 3979 to 3988.

 TCP    smartmirror:3979       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3980       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3981       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3982       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3983       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3984       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3985       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3986       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3987       192.168.1.28:ms-sql-s  ESTABLISHED
 TCP    smartmirror:3988       192.168.1.28:ms-sql-s  ESTABLISHED

It proves that I have 10 Established connections with SQL server and my application.
when I tell the connection object to close the connection, It only notifies the application about that "free connection", which can be used to serve next request.
When I tell connection object to open a connection I get a free connection form connection pool.


To know more about, how clients talks to the server refer http://revenmerchantservices.com/post/2010/01/25/client-server-communication.aspx

You can have multiple pools in applications. Of Course, there is a limit as there is limits on available ports ranging from 0 to 65535.

Its best practice not to have connection string opened in infinite time to serve the request. If you let the connection opened for infinite loop
your application will not be able to serve other requests. you can try it yourself by setting min and max pool size of your connection string.

By default min pool size is 0 and max pool size is 100.

In IIS, if you configure you application pool to use more than one worker process then for every process you will get new instance of established connections.

if you set connection lifetime = 30 property of connection string in web.config your minimum establised connections will never get dead 
till the lifetime of your application pool.

To know how many worker processes are currently servicing your application pool. you need to execute below command on that IIS server.
It is always good practivce to set life time of connection forcefully. This ensures that connection is backed into the pool after the use of it.

IISapp.VBS

It will return details of worker process along with its process ID and name of application pool under whom it resides.


Conclusion: I told connection object to open a connection with SQL DB server means I'm telling connection object to setup actual connection with DB server? 
                No, I'm telling the connection object to get the already established free connection from connection pool.

I hope you understood the location of Connection Pool and its importance.

 Other usefull information:

Clearing the Pool
ADO.NET 2.0 introduces two new methods to clear the pool: ClearAllPools and ClearPool. ClearAllPools clears the connection pools for a given provider, and ClearPool clears the connection pool that is associated with a specific connection. If there are connections in use at the time of the call, they are marked appropriately. When they are closed, they are discarded instead of being returned to the pool.

Transaction Support
Connections are drawn from the pool and assigned based on transaction context. Unless Enlist=false is specified in the connection string, the connection pool ensures that the connection is enlisted in the Current context. When a connection is closed and returned to the pool with an enlisted System.Transactions transaction, it is set aside in such a way that the next request for that connection pool with the same System.Transactions transaction will return the same connection. If there is no connection available for that transaction, the connection is automatically enlisted when it is opened.

When a connection is closed, it is released back into the pool and into the appropriate subdivision based on its transaction context. Therefore, you can close the connection without generating an error, even though a distributed transaction is still pending. This allows you to commit or abort the distributed transaction at a later time.

Controlling Connection Pooling with Connection String Keywords
The ConnectionString property of the SqlConnection object supports connection string key/value pairs that can be used to adjust the behavior of the connection pooling logic. For more information, see ConnectionString.

Pool Fragmentation
Pool fragmentation is a common problem in many Web applications where the application can create a large number of pools that are not freed until the process exits. This leaves a large number of connections open while consuming memory, resulting in poor performance.

Pool Fragmentation Due to Integrated Security
Connections are pooled according to the connection string plus the user identity. Therefore, if you use Basic authentication or Windows Authentication on the Web site and an integrated security login, you get one pool per user. Although this improves the performance of subsequent database requests for a single user, that user cannot take advantage of connections made by other users. It also results in at least one connection per user to the database server. This is a side effect of a particular Web application architecture that developers need to weigh against security and auditing requirements.

Pool Fragmentation Due to Many Databases
Many Internet service providers host several Web sites on a single server. They may use a single database to confirm a Forms authentication login and then open a connection to a specific database for that user or group of users. The connection to the authentication database gets pooled and used by everyone. However, there is a separate pool of connections to each database, thus increasing the number of connections to the server.

This is also a side effect of the application design. There is a relatively simple way to avoid this side effect, however, without compromising security when connecting to SQL Server. Instead of connecting to a separate database for each user or group, connect to the same database on the server and then execute the Transact-SQL USE statement to change to the desired database. The following code fragment demonstrates creating an initial connection to the master database and then switching to the desired database specified in the databaseName string variable.

 

Satalaj.

C# html Parser

January 22
by Satalaj 22. January 2010 10:44

  If you came here by searching for C#.net or VB.net html parser, your search ends here.

While developing screen scrapping with C#.net, I came across very rich open source HtmlParser. Who is capable of parsing entire html document.

Here is a link to download and parse the required fields in html  
http://www.codeplex.com/htmlagilitypack.

It is very similar to librarys provided by .net to parse or iterate XMLDocuments.

code snippet:

It will give you list of  all nodes of type Input.  Here str is your actual HTML string that you received in HttpWebResponse object

 HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();

hd.LoadHtml(str);

HtmlNodeCollection hc = hd.DocumentNode.SelectNodes("//input");


You can use Xpath query to iterate nodes and ChildNodes.

Satalaj

Tags:

Asp.net

screen scrapping asp.net pages

January 22
by Satalaj 22. January 2010 10:19

  If you want to crawl asp.net pages using HttpWebRequest and HttpWebResponse, you need to POST the __VIEWSTATE, EVENTARGUMENT and EVENTTARGET
along with your Request. 
  If that page stores session or cookies you need to pass session cookies and Cookies along with the HttpWebRequest object.
You need to use Post Method.

 your post data will look like this

string postData = "__EVENTARGUMENT=" + value + "&_EVENTTARGET="+ targetValue+ "&__VIEWSTATE="+ViewState ;

You first use tools like fiddler to know how your broser post the data to .aspx pages then prepare your post string to post the data.


Satalaj

Tags:

Asp.net | General

About Satalaj

My name is Satalaj. I'm 2010 asp.net MVP. I write technical stuff here. www.satalaj.com

Ads by Lake Quincy Media

The best inline translator

Live lookup to see what asp.net developers are searching