A Place for C Sharpers/.Netters

I Will do coding till last moment of life-Kiran Patil

Archive for September, 2008

Hosting a WCF Service in IIS 7.0

Posted by kiranpatils on September 29, 2008

If you would like to deploy your WCF Service within following environment:

  1. Windows Server 2008
  2. IIS 7.0

Or facing following Error:

Server Error in Application “DEFAULT WEB SITE/ EmployeeService “Internet Information Services 7.0

Error Summary

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map. Detailed Error InformationModule StaticFileModule

Notification ExecuteRequestHandler

Handler StaticFile

Error Code 0×80070032

Requested URL http://localhost:80/EmployeeService/ EmployeeService.svc

Physical Path

C:\inetpub\wwwroot\Pepperio.Net.Services\/EmployeeService \EmployeeService.svc

Logon Method Anonymous

Logon User Anonymous

Most likely causes:

It is possible that a handler mapping is missing. By default, the static file handler processes all content.

The feature you are trying to use may not be installed.

The appropriate MIME map is not enabled for the Web site or application. (Warning: Do not create a MIME map for content that users should not download, such as .ASPX pages or .config files.)

If ASP.NET is not installed.

Things you can try:

In system.webServer/handlers:

Ensure that the expected handler for the current page is mapped.

Pay extra attention to preconditions (for example, runtimeVersion, pipelineMode, bitness) and compare them to the settings for your application pool.

Pay extra attention to typographical errors in the expected handler line.

Please verify that the feature you are trying to use is installed.

Verify that the MIME map is enabled or add the MIME map for the Web site using the command-line tool appcmd.exe.

To set a MIME type, use the following syntax: %SystemRoot%\windows\system32\inetsrv\appcmd set config /section:staticContent /+[fileExtension='string',mimeType='string']

The variable fileExtension string is the file name extension and the variable mimeType string is the file type description.

For example, to add a MIME map for a file which has the extension “.xyz”: appcmd set config /section:staticContent /+[fileExtension='.xyz',mimeType='text/plain']

Warning: Ensure that this MIME mapping is needed for your Web server before adding it to the list. Configuration files such as .CONFIG or dynamic scripting pages such as .ASP or .ASPX, should not be downloaded directly and should always be processed through a handler. Other files such as database files or those used to store configuration, like .XML or .MDF, are sometimes used to store configuration information. Determine if clients can download these file types before enabling them.

Install ASP.NET.

Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click here.

And looking some work around for it then this article for you…..go ahead…

For deploying WCF you need to do one way from the following one:

  1. You have to run servicemodelreg -i as an administrator using VS 2008 Command prompt (you can find it in <WINDOWSDRIVE>:\Windows\WinFx\v3.0\Windows Communication Foundation).

Credit goes to: http://www.u2u.info/Blogs/Peter/Lists/Posts/Post.aspx?ID=151

2. If you want to do it from scratch…just follow this article:

http://blah.winsmarts.com/2008-4-Host_a_WCF_Service_in_IIS_7_-and-amp;_Windows_2008_-_The_right_way.aspx

That’s it…

Let me know if you face some problem…may be i can help..

-Kiran

Posted in WCF | Tagged: , | 2 Comments »

Convert XDocument to GZip format

Posted by kiranpatils on September 25, 2008

Here is the method which will help you..

/// <summary>
/// This function will be used to Compress XML DATA
/// using Gzip Stream
/// </summary>
/// <param name=”xDocument”>XMLDocument to compress</param>
/// <returns>byte array</returns>
private byte[] ConvertXDocumentToGzip(XDocument xDocument)
{
//buffer to write Compressed data
byte[] buffer;

//Compress the XML DATA
MemoryStream memoryStream = new MemoryStream();
XmlWriter xmlWriter = XmlWriter.Create(memoryStream);

//Save data to memoryStream
xDocument.Save(xmlWriter);

//writer Close
xmlWriter.Close();

//Reset Memorystream postion to 0
memoryStream.Position = 0;

//create buffer of total content Length
buffer = new byte[memoryStream.Length];

//Create a stream to compress the data
GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress);
//compress the data
gzipStream.Write(buffer, 0, buffer.Length);

//Close the underlying streams
gzipStream.Flush();
gzipStream.Close();

memoryStream.Flush();
memoryStream.Close();

//return compressed data as byte array
return buffer;
}

Posted in LINQ | Tagged: | Leave a Comment »

Generic List to XML using LINQ

Posted by kiranpatils on September 23, 2008

Let us see  how to generate list of XML using LINQ.
 
Scenario
I have one generic List of Employee and want to convert it in to XML format.
 
Solution:
I can do this using XmlDocument class which is .NET 2.0 but it can take more than 30-40 lines..and i want to achieve[achieved also!!]
it in 4-5 Lines…sounds cool idea..so lets see how can we achieve it using LINQ–Language integrated Query new poweful tool of Micro.
 
First i have this Simple Class for storing Employee value:
 
Employee.CS
——————-
using System;
namespace LinqtoXMLDemo
{
 public class Employee
 {
  public int EmployeeID
  {
   get;
   set;
  }
  public string EmployeeName
  {
   get;
   set;
  }
  public string EmployeeAddress
  {
   get;
   set;
  }
 }
}
 
Ok Lets start
 
1. Add some sample values in list
List<Employee> employeeList = new List<Employee>();
      
   employeeList.Add(new Employee()
   {
    EmployeeAddress=”BARODA”,
    EmployeeID=1,
    EmployeeName=”XYZ”    
   });
   employeeList.Add(new Employee()
   {
    EmployeeAddress = “Bangalore”,
    EmployeeID = 2,
    EmployeeName = “ABC”
   });
 
2. Now i want to convert it into XML format..which should look like this..
<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>
<Employees>
 <Employee>
  <EmployeeID>1</EmployeeID>
  <EmployeeName>XYZ</EmployeeName>
  <EmployeeAddress>BARODA</EmployeeAddress>
 </Employee>
 <Employee>
  <EmployeeID>2</EmployeeID>
  <EmployeeName>ABC</EmployeeName>
  <EmployeeAddress>Bangalore</EmployeeAddress>
 </Employee>
</Employees>
 
3. Method to achieve our desire..[Which is self explanatory)
/// <summary>
  /// This Method will generate list TO XML using LINQ
  /// </summary>
  /// <param name=”employeeList”>Collection of Employe</param>
  /// <returns>XmlDocument</returns>
  private static XDocument GenerateListToXML(List<Employee> employeeList)
  {
   XDocument xmlDocument = new XDocument(new XDeclaration(“1.0″, “UTF-8″, “yes”),
              new XElement(“Employees”,
              from employee in employeeList
              select new XElement(“Employee”,
              new XElement(“EmployeeID”, employee.EmployeeID),
                  new XElement(“EmployeeName”, employee.EmployeeName),
                   new XElement(“EmployeeAddress”, employee.EmployeeAddress))));
   return xmlDocument;
  }
 
4. From main call it like this:
 
XDocument employeeXML = GenerateListToXML(employeeList);
That’s it we are ready!!!!
Okay XML Looks cool..But now i want it with namespace so it should look like this..
<?xml version=”1.0″ encoding=”utf-8″ standalone=”yes”?>
<Employees xmlns=”
http://www.abc.org/employees/0.9“>
 <Employee>
  <EmployeeID>1</EmployeeID>
  <EmployeeName>XYZ</EmployeeName>
  <EmployeeAddress>BARODA</EmployeeAddress>
 </Employee>
 <Employee>
  <EmployeeID>2</EmployeeID>
  <EmployeeName>ABC</EmployeeName>
  <EmployeeAddress>Bangalore</EmployeeAddress>
 </Employee>
</Employees>
Method to generate XML with Namespace
/// <summary>
  /// This Method will generate list TO XML with namespace using LINQ
  /// </summary>
  /// <param name=”employeeList”>Collection of Employe</param>
  /// <returns>XmlDocument</returns>
  private static XDocument GenerateListToXMLWithNameSpace(List<Employee> employeeList)
  {
   XNamespace employeeNameSpace = “
http://www.abc.org/employees/0.9“;
   XDocument xmlDocument = new XDocument(new XDeclaration(“1.0″, “UTF-8″, “yes”),
              new XElement(employeeNameSpace + “Employees”,
              from employee in employeeList
              select new XElement(employeeNameSpace + “Employee”,
              new XElement(employeeNameSpace + “EmployeeID”, employee.EmployeeID),
                  new XElement(employeeNameSpace + “EmployeeName”, employee.EmployeeName),
                   new XElement(employeeNameSpace + “EmployeeAddress”, employee.EmployeeAddress))));
   return xmlDocument;
  }
 
That’s it…Happy LINQ!!
 
 

Posted in LINQ | Tagged: | Leave a Comment »

How to open RadWindow from another RadWindow.

Posted by kiranpatils on September 22, 2008

Scenario:

You have parent Window A and from it you have opened Modal Window[Child window] B..which is quite simple using radopen method…

But now you want to open Window C as a Modal Window [Child window]from Window B…using RADWINDOW Control. Sounds interesting na?? Let’s see how to achieve it?

Solution:

For your simplicity I have created one function which will do this for you and function is self explanatory..so you can gauge  what it is doing..

Here is the JS Function for it

//This function will act as a common function

//for opening up a RadEditor window

//PageToOpen = Retlative path of page of page which you want to open

//windowToOpen=name of RadWindow which you want to open it nothing pass NULL

function ShowModalFromModalWindow(PageToOpen,windowToOpen)

{

//Get the Applicationpath

var rootURL=’<%=Request.ApplicationPath%>’

//manipulate URL

var CompleteURL = rootURL+PageToOpen;

//Get window manager

var aWindowManager = GetRadWindow().GetWindowManager();

var oradPopupWindow =  aWindowManager.Open(CompleteURL,windowToOpen);

oradPopupWindow.Show(); //To Open Popup in Modal

//For opening a child window under the child window as a modal and active window

window.setTimeout(function()

{

oradPopupWindow.setActive(true);

oradPopupWindow.SetModal(true);

oradPopupWindow.center();

//Set Size Width,Height

oradPopupWindow.setSize(“405″,”280″);

},0);

return false;

}

Use of it.

<asp:Button ID=”btnChildOpen” runat=”server” Text=”Open” onClientClick=”return ShowModalFromModalWindow(‘http://www.google.com’,’myradWindow’);”

That’s it!!!

Posted in RadControls | Tagged: | Leave a Comment »

“The underlying connection was closed: The connection was closed unexpectedly.” While returning Data Table from WCF service.

Posted by kiranpatils on September 22, 2008

Error:

“The underlying connection was closed: The connection was closed unexpectedly.”

StackTrace:

System.ServiceModel.CommunicationException was unhandled by user code

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”mscorlib”

StackTrace:

Server stack trace:

at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)

at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Security.SecuritySessionClientSettings`1.SecurityRequestSessionChannel.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)

at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)

at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:

at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)

at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)

at System.Web.UI.Control.OnLoad(EventArgs e)

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Control.LoadRecursive()

at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

InnerException: System.Net.WebException

Message=”The underlying connection was closed: The connection was closed unexpectedly.”

Source=”System”

StackTrace:

at System.Net.HttpWebRequest.GetResponse()

at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

InnerException:

Scenario:

I have one OperationContract defined in my service contract which was returning DatTable as its return Type So it was looking like this:

[OperationContract]

DatTable LoadEmployeeInformation(long employeeID);

And in implementation I am filling this data Table using Table Adapter and returning it.

But it was throwing me error which was really annoying i had spent 4-5 hours to figure out it…

Solution:

I have changed my operation Contract to return Dataset Instead of Data Table

[OperationContract]

DataSet LoadEmployeeInformation(long employeeID);

and it worked like a charm!!!! For me…and hope that it works for you also…then go ahead and try this change….

Root cause:

Sorry guys I don’t know the root cause of this error. But i read some forums from Microsoft and they says that don’t use Data Table as a return type because some problem occurs in deserializaing it at client side…hooh…but I think it is BUG of WCF!!

Webliography:

http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=286535

http://processmentor.com/community/blogs/scott_middleton/archive/2007/06/08/169.aspx

http://blogs.msdn.com/lifenglu/archive/2007/08/01/passing-datatable-across-web-wcf-services.aspx

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1828652&SiteID=1&mode=1

http://blogs.conchango.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx

-Kiran

Posted in WCF | Tagged: , | 4 Comments »

After building copy Assembly at some specific folder

Posted by kiranpatils on September 18, 2008

Problem:

You have created one Class Library project e.g “BusinessLogic” and other projects are also using it and they are referencing it from C:\MyLibraries folder. Where you put this “Business Logic” Class library. But what happens that you do some changes in your library and forgot to copy it at c:\MyLibraries location. And people starting shout on you…If you are using Visual studio than this thing you can automate using a feature called “Post Build Event”.

Solution

Sounds good idea na….so lets see how can you achieve this step by step:

  1. Right click on your class library and click on properties
  2. It will open up window in left side with list of tabs
  3. Click on “Build Events” Tab.
  4. Here you can see two things:
    1. PreBuild event: comes in action before build.
    2. Postbuild event: comes in action after build.
  5. you can use this DOS Command for achieving the task

COPY Source destination

Click on edit post build event button which will open a window. Here you can see

List of Macros like

TargetDir = your current Class library Bin/debug directory

TargetFileName = your Class library .dll name

And so on which you can explore on your self.

So for copying my .dll to C:\MyLibraries folder I have written like this:

Copy $(TargetDir)\$(TargetFileName) $(TargetDir)\..\..\..\..\ MyLibraries

..\..\..\ = this syntax is for coming up level from child directories. So based on your depth level you can use it wisely.

Posted in Uncategorized | Leave a Comment »

Object does not match target type+Reflection

Posted by kiranpatils on September 18, 2008

Problem:

When invoking a method using MethodInfor.InvokeMemeber() Method using Reflection.

It gives “Object does not match target type“

Solution:

For solving this error you can do two things:

  1. Declare your method which you are going to invoke as Static. [Which I don’t want to use].
  2. create instance of your type using Activator.CreateInstance(TYPE) and pass it as a first argument to InvokeMember() Method.

So final code looks like this

Assembly assembly = Assembly.LoadFile(FullAssemblyPath)

Type foundType = assembly.GetType(“TYPETOGET”)

MethodInfo foundMethod = foundType.GetMethod(“METHODTOFIND”)

Object [] params = new object [] {‘A’, 1,’B’};

Object response = foundMethod.Invoke(Activator.CreateInstance(foundType ), params);

That’s it

Posted in .NET, Reflection | Tagged: | 3 Comments »

How to Test Stored Procedure which has OUTPUT Parameter as an argument?

Posted by kiranpatils on September 17, 2008

you have created on SP which takes bunch of args and one of it is OUTPUT parameter which gives ID of last inserted record.. you want to test it using Management studio how can you do it??

Here is the steps :

DECLARE @givemebackID bigint –it can be your parameter name[not compulsory]

exec usp_AddEmployee ‘ABC’,'USA’,@givemebackID= @givemebackID OUTPUT

SELECT @givemebackID

Execute it and enjoy!!!

Posted in SQL SERVER 2005 | Tagged: | 1 Comment »

How to calculate bandwidth used by website hosted in IIS?

Posted by kiranpatils on September 17, 2008

Problem With Solution:

I need to calculate total bandwidth consumed by a website daily which is hosted on IIS. I was thinking to use urchin but can’t make it. Then after some googling I found the way and here it is:

  1. IIS Log files. Stored on

IIS 6.0 and later have request logging enabled by default. The default location for these logs is:

IIS 6.0: %windir%\System32\LogFiles\W3SVC<SiteID>

IIS 7.0: %systemDrive%\Inetpub\logfiles

2. Log Parser 2.2 – A versatile tool by micro. For fetching information from log files [I have used its COM component LogParser.dll]

So you want some reference:

Here are the good links which I would like to share:

http://microsoft.apress.com/asptodayarchive/73567/accessing-iis-log-information-to-analyse-site-metricsBasic about configuring Log files.

http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=enLog parser tool for download.

http://www.msexchange.org/tutorials/Using-Logparser-Utility-Analyze-ExchangeIIS-Logs.html good article for Log parser introduction.

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/676400bc-8969-4aa7-851a-9319490a9bbb.mspx?mfr=trueW3C Log file format.

http://books.google.co.in/books?id=vnIXo-yUT2gC&pg=PA45&lpg=PA45&dq=bytes+sent%2Bbytes+received/time+taken&source=web&ots=B3-yyUy3Ua&sig=j9VrhIVukqsIZC2KW8kwrX3eZxY&hl=en&sa=X&oi=book_result&resnum=2&ct=result#PPA46,M1Really Great book you must have this [Don’t miss Page # 57]

http://www.codeproject.com/KB/recipes/SimpleLogParse.aspxHow to create program using COM Component. [C#.NET]

http://blogs.iis.net/chrisad/archive/2006/07/13/Chris.aspx More on Log parser

http://www.iis.net/default.aspx?tabid=2&subtabid=26&i=36 — PPT

Try to implement it…if don’t make out of it do write me comment I will post my sample project here…so you can quick start….but don’t write comment without trying…it will be good fun!

What other things you can achieve using it..

  • Top browsers accessing your Websites
  • Hits by Hour
  • Request by URI
  • Top 10 Images by Size
  • Top 10 URLs for a website with some interesting data to support you
  • Top 20 clients using your website
  • Status code
  • And you can also generate Charts.

ALL THE BEST!!

Posted in ASP.NET, IIS | Tagged: | 2 Comments »