Sunday, April 10, 2011

Problem: How to access master page controls from content page in ASP.NET

Impact: You cannot change the text of textbor or label in your master page. There are situations when you want to do that according to the page viewed by the user.

Solution: The solution to this problem is very simple. All you have to do is to create a public property to get and set the text of a textbox in the master page(.cs file). Then you can access this public property from any content page.

Example:

<%-- Copy and paste this line in you contentPage.aspx and change the value of virtualPath attribute according to you master page's name --%>
<%@ MasterType  virtualPath = "~/MasterPage.master" %>

//Create this public property in the masterpage.cs file
public String Textbox1
{
        get { return txtTextbox1.Text; }
        set { txtTextbox1.Text = value; }
}

//In the content page's code behind use these lines of code
Master.Textbox1 = "Arshdeep Virdi";
string myName = Master.Textbox1;

Problem: ASP.NET page not updating the content of page

Impact: Sometimes when you are working with xml(or some other data source) and changes are made to the xml file. These changes are not reflected in the aspx page.

Solution: When I first started working with XML and ASP.NET, I came across this problem. I was working on an project where I was supposed to create a xml file of user comments. When a user posted comment, the comment was written to the xml file but was not shown on the aspx page. I tried refreshing the page, response.Redirect() and server.Transfer() but was not able to get the currently posted comments.

To get rid of this problem simply write Response.Cache.SetNoStore(); in the Page_Load method.

Example:

protected void Page_Load(object sender, EventArgs e)
{
        Response.Cache.SetNoStore();
        Response.Expires = -1000;
}

Saturday, April 9, 2011

Problem: Call an aspx page and have it decrypt and return an image

Impact: If you are working with images which are encrypted and stored in a folder. You cannot show the images directly in your aspx page as they are encrypted, by calling another aspx page you can open the encrypted image, decrypt it and return it back to the requesting page.

Solution:

1. Create an aspx page, name it DecryptImage.aspx and copy the code below.

protected void Page_Load(object sender, EventArgs e)
{
    string filePath = Page.Request.QueryString["filePath"];
    Response.ContentType = "image/jpg";
    FileStream encFile = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    //Code to decrypt image goes here

    Response.BinaryWrite(decFileBytes);
    Response.Flush();
    Response.End();
}

2. Then in the calling page use an asp image control to display the image and set its url in the code behing the page file(the .cs file).

Example: 

<asp:Image ID="Image1" runat="server"></asp:Image>

protected void Page_Load(object sender, EventArgs e)
{
    Image1.ImageUrl = "DecryptImage.aspx?filePath=folderName/fileName.jpg";
}

Problem: Host WCF service with netTcpBinding on IIS6

Impact: Service will not work

Solution: IIS 6 does not support netTcpBinding, in order to use netTcpBinding host you service on IIS 7 or change the binding to wsDualHttpBinding or any other http binding if you want to use IIS 6.

Following are the few bindings that you can use with IIS6:
  • basicHttpBinding
  • wsDualHttpBinding
  • wsHttpBinding

Problem: Minimizing SQL injection attacks

Impact: SQL injections can expose private data and modify information stored in database.

Solution: SQL injection attacks can be the most harmful common server attack. Every skilled developer can make mistakes that lead to SQL injection vulnerabilities. To minimize SQL injections you can do the following things.
  1. Use Stored Procedures.
  2. Use Parameterized SQL Commands.
  3. Sanatize the user input to replace characters in the input with special characters.
Example of sanitization:

string output = input.Replace("*", "star");

Problem uploading large files from a client to WCF service

Impact: ProtocolException is thrown displaying message "The remote server returned an unexpected response: (400) Bad Request".

Solution: If you have just started working with WCF applications and are trying to upload small files then you might get rid of this exception, but if you are trying to upload larges files then you might have to face this exception. The solution to this problem is very simple, all you have to do is to follow the steps mentioned below.
  1. Open you WCF application's Web.config or App.config file.
  2. Find a node called <system.serviceModel>.
  3. Inside the <system.serviceModel> nodes create a node <bindings>.
  4. Then create a node matching the binding you are using. For example <basicHttpBinding></basicHttpBinding> for basicHttpBinding.
  5. In the last copy and paste the following code: <binding name="basicBinding" maxBufferPoolSize="104857600" maxReceivedMessageSize="5242880">

Note: Change the binding name according to the bindingConfiguration attribute of you endpoint and also change the size(in bytes) as per you requirement.

Example:

<system.serviceModel>
    <bindings>
      <wsDualHttpBinding>
        <binding name="DualBinding" maxBufferPoolSize="104857600" maxReceivedMessageSize="5242880">
        </binding>
      </wsDualHttpBinding>
    </bindings>

</system.serviceModel>

Problem saving/accessing files in a folder in WCF

Impact: Not able to save and access files to and from a folder of your choice in WCF application

Solution: Like a web service in ASP.NET if you try to use HttpContext.Current.Request.MapPath() to save the file to a directory of your choice or to create an absolute URL of the file, when you try to run you application you will end up with exceptions. You can get rid of these exceptions by enabling the ASP.NET compatibility mode in WCF application. To enable compatibility mode follow the steps mentioned below.

  1. Open Web.config file and find the node <system.serviceModel>.
  2. Inside <system.serviceModel> nodes write: <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />.
  3. Now in the class which extends you service interface, add the following attribute at the top: [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]

Sunday, March 13, 2011

Problem running WCF service on Windows Vista using Visual Studio

Impact: The project throws AddressAccessDeniedException while opening a service host using host.Open()

Solution: This exception occurs due to the new security settings in Windows Vista. This impacts your ability to run HTTP web services because listening at a particular HTTP address is a restricted operation. By default, every HTTP path is reserved for use by the system administrator. Your services will fail to start giving you an exception. To get rid of this exception follow the steps mentioned below.
  1. Close Microsoft Visual Studio if opened.
  2. Right click on the Microsoft Visual Studio in Start -> All Programs or from the shortcut on your desktop.
  3. Then click on Run as administrator.
  4. Now try to run your WCF project.

Sunday, March 6, 2011

Problem sending exception from webservice to client in WCF

Impact: Web service throws The creator of this fault did not specify a Reason exception

Solution: When you try to throw an exception back to client using the FaultContract() attribute, the web service doesn't send the fault message to the client. Instead it will give you an exception saying 'the creator of the fault did not specify a Reason'. If you are getting the same exception then please follow the steps mentioned below before you come to any conclusion regarding the code that you have written.

  • Open your project(web service) in Visual Studio.
  • Click on Debug in the menu bar.
  • Then click on Exceptions...
  • Uncheck the checkbox next to Common Language Runtime Exceptions, under the category User-Unhandled.
  • Click OK and now try to run your project.

Monday, February 21, 2011

Problem uploading large files in ASP.NET

Impact: Application throws System.Web.HttpException: Maximum request length exceeded exception.

Solution: This is the most common problem that most of the new developers face while developing ASP.NET applications which require files to be uploaded to the server. ASP.NET restricts the size of file being uploaded to a maximum of 4MB, however you can change the default value by following the steps mentioned below.
  1. Open you application's web.config file.
  2. Find a node called <httpRuntime>, if the node doesn't exist then create one inside <system.web> nodes.
  3. Change the value of attribute maxRequestLength to the file size you want in KB. 
  4. You may also have to change the value of attribute executionTimeout, this value is in seconds.
Example:

<system.web>
    <httpRuntime maxRequestLength = "10240" executionTimeout = "240" />
</system.web>