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

Transaction (Process ID ) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

July 13
by Satalaj 13. July 2010 09:17


   You had written update or delete  statements without SQL hints like nolock, updlock, readpast etc.
This is very bad practice when you are dealing with multiple udates on rows or tables without locks.
Below scenario will explain how to use those hints to avoid deadlocks aswell as concurrency issues.

e.g.

UPDATE top 10 xyzTable with (updlock)

set x = 1

In this case if second user comes in to update xyzTable, he has to wait for first user operation to finish.

To let second user do update on next top 10 rows which are not locked by first user, you can

modify above query using readpast hint.

ReadPast hint will return row sets which are not locked by any transaction in that contxt.

UPDATE top 10 xyzTable with (updlock,readpast)
set x = 1


ReadPast and NoLock are two different hints
Readpast Only return rows which are not locked, while nolock returns
commited as well as non commited rows by other transaction this is also called as dirty reads.

SP_LOCK will written locks details.

You can avoid concurrency issues with your transaction using those lock hints.

For more information about locks in MS SQL you can visit

http://msdn.microsoft.com/en-us/library/aa213026(SQL.80).aspx


 

Tags:

sql server

C# read csv file

July 02
by Satalaj 2. July 2010 13:06

Some one asked me to write a program to read csv file in 5 min.

To read CSV file you can use OledbProvider which come up with System.Data.Oledb namespace.

you can refer
www.connectionstrings.com to know connection string required to open your CSV.

you can fire select * from syntax queries on that CSV.

Here below code

   private void Form1_Load(object sender, EventArgs e)
        {

            string connectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\;Extended Properties='text;HDR=Yes;FMT=Delimited';";
            OleDbConnection connection = new OleDbConnection();
            connection.ConnectionString = connectionstring;
            OleDbCommand command = new OleDbCommand();
            command.CommandType = CommandType.Text;
            command.Connection = connection;
            command.CommandText = "select * from [xxx.csv]";
            connection.Open();
           

            DataTable dt = new DataTable();
            dt.Load(command.ExecuteReader());


            connection.Close();

           
        }

I have created demo.csv file on my d:\ drive. After excuting this code your will get all data in data table
on which you can do further processing.

Remove .net framework 4.0

June 28
by Satalaj 28. June 2010 06:20
 To remove .net framework 4.0 from your machine you need to follow below steps.

1. Open control panel and click on add remove programs
2. Fine Microsoft .net framework 4.0 Extended
3. Click to remove it
4. Restart the computer
5. follow step 1.
6. Find Microsoft .net framework 4.0 Client profile maintenance and click to remove it.

You need to follow above steps otherwise you will suffer from blocking issues.

Tags:

General

It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

June 11
by Satalaj 11. June 2010 05:23

  To avoid this error, makesure that you don;t have web.config file in sub folders of your virtual directory.
you might have created backup folder of web application along with web.config under same root where there already exist web.config.

Tags:

IIS

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.

 

   
 

IRequiresSessionState and session

April 28
by Satalaj 28. April 2010 07:40


   When you are accesing session values in HttpHandlers or HttpModule, you need to Inherit an interface called IRequiresSessionState

 e.g. 

  public class Handler : IHttpHandler,IRequiresSessionState 
  {
        public void ProcessRequest(HttpContext context)
       {
           // perform operation on request
          // Now you can store values into session and retrive it back
        } 
      
     public bool IsReusable
    {
        get
        {
            return false;
        }
    }
  }

 You can see we didn't implemented IRequiresSession at all. We just inherited it in handler calss.

Tags:

General

Sql server cpu utilisation

April 23
by Satalaj 23. April 2010 08:50

 Days ago I wanted to know which query is taking lots of time and cpu utilisation for execution.
and I came to one blog from where I copied below query. It tells details of all query. You need to fire it on your SQL server to know more.

SELECT
    substring(text,qs.statement_start_offset/2
        ,(CASE   
            WHEN qs.statement_end_offset = -1 THEN len(convert(nvarchar(max), text)) * 2
            ELSE qs.statement_end_offset
        END - qs.statement_start_offset)/2)
    ,qs.plan_generation_num as recompiles
    ,qs.execution_count as execution_count
    ,qs.total_elapsed_time - qs.total_worker_time as total_wait_time
    ,qs.total_worker_time as cpu_time
    ,qs.total_logical_reads as reads
    ,qs.total_logical_writes as writes
FROM sys.dm_exec_query_stats qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
    LEFT JOIN sys.dm_exec_requests r
        ON qs.sql_handle = r.sql_handle
ORDER BY 3 DESC

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