Archive

Posts Tagged ‘ASP.Net’

Convert string to enum

April 19th, 2010 Anuraj P No comments

Sometimes we may need to read a Config value using ConfigurationSettings.AppSettings and assign it to a Enum. This function helps to convert a string to Enum.

/// <summary>
/// Function to retrive Enum value by giving the corresponding string value.(This method is case sensitive)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The value.</param>
/// <returns>Enum value</returns>
public static T ToEnum<T>(string value)
{
    //This method will throw error if the case of the value is different from the
    //enum value.
    if (Enum.IsDefined(typeof(T), value))
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }
    throw new ArgumentException("Value doesn't exists in the Enum");
}
Categories: .Net, .Net 3.0 / 3.5, ASP.Net Tags: , , ,

System.InvalidOperationException – The length of the string exceeds the value set on the maxJsonLength property.

April 16th, 2010 Anuraj P No comments

Yesterday I got a problem from one of my friend; he is getting a Javascript exception from some Ajax Page methods. The exception occurred when he tried to return a very long string from web method. The exception was like this.

Error: Sys.Net.WebServiceFailedException: The server method ‘WebServiceMethod’ failed with the following error: System.InvalidOperationException– Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

After doing some searching we resolved it. You can resolve this error by modifying the web.config file, and add / modify the Configuring JSON Serialization.

<configuration>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

The default length is 102400.
You can get more information about this from MSDN : http://msdn.microsoft.com/en-us/library/bb763183.aspx

Compiler Error Message: CS0016: Could not write to output file – Access is denied.

April 14th, 2010 Anuraj P No comments

Last Sunday the Support guys in my machine, updated the OS(Windows Vista) and monday onwards while running my web application, I got a strange error,

Compiler Error Message: CS0016: Could not write to output file - Access is denied.

Compiler Error Message: CS0016: Could not write to output file - Access is denied.

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0016: Could not write to output file ‘c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\myapp\xxxxx\xxxxx\App_GlobalResources.xxxxxxx.dll’ — ‘Access is denied. ‘

I was not done anything in the Global Resources file, but it was showing the error related to this. After doing some searching, I found it can be an issue with Antivirus software. I stopped the Antivirus software and tried, but still the problem was there. Later I found it was related to permission issue in the Temp folder. To resolve this.

  1. Go to %Systemroot%, normally C:\WINDOWS or C:\WINNT
  2. Right-click the Temporary folder (mine is C:\WINDOWS\Temp) and select Sharing and Security.
  3. Select the Security tab and take a look at the list of “Group or user names:”
  4. NETWORK SERVICE should be in the list. If it is not, click Add and type Network Service in the text box.
  5. Make sure NETWORK SERVICE have Full Control in the Permissions list. Click OK.
  6. Restart IIS (Run iisreset)

If your machine doesn’t have NETWORK SERVICE or NETWORK SERVICES Group, look for “IIS_IUSRS” and apply same permissions.

Large file uploads in ASP.Net

April 5th, 2010 Anuraj P No comments

Few days back I got problem from my client, that he want to upload Video files to our site, which is greater than 25MB of size. He said like he was able to upload up to 18 MB but he want more, minimum he requires 25 MB, and the interesting part is that, when we tried to upload a large file, it is automatically redirected to error page, but the error is not logged. Means it is not executing the Application_Error event in Global.asax file, as we set a generic error page in Web.Config, it is automatically getting redirected. After few doing some search we got the solution. It is security feature from Microsoft IIS, which helps to avoid Denial Of Service(DOS) attacks. By default the upload size is 4 MB.

You can modify the Machine.Config file, if you apply the setting to all the applications in the machine, otherwise you can apply this setting only to a specific application / folder in the application.

Machine.Config – To all the applications in the server.

<system.web>
  <httpRuntime executionTimeout="100" maxRequestLength="15000" />
</system.web>

Web.Config – Application specific.

<system.web>
  <httpRuntime executionTimeout="100" maxRequestLength="15000" />
</system.web>

You can also use with location tag to allow only for specific folders.

<location path="Upload">
<system.web>
  <httpRuntime executionTimeout="100" maxRequestLength="15000" />
</system.web>
</location>

Make sure you are also providing the execution timeout attribute.

If you are using IIS7, it support slightly less than 30 MB by default, and you can change it via appcmd.exe command

%windir%\System32\inetsrv\appcmd.exe set config "Default Web Site" -section:requestFiltering -requestLimits.maxAllowedContentLength:100000000 -commitpath:apphost

in this “Default Web Site” is the name of the Site you want to change the request limit.

Categories: .Net, .Net 3.0 / 3.5, ASP.Net Tags: ,

Using custom controls from App_Code folder

March 30th, 2010 Anuraj P No comments

If you are developing a web application, and when are trying to add a Class File to the project Visual Studio will ask a confirmation like “You are attempting to add a special file type (class) to an ASP.NET Web site. In general, to use this type of item in your site, you should place it in the ‘App_Code’ folder. Do you want to place the file in the ‘App_Code’ folder?” – If you say yes, it will create(if not exists) an App_Code folder and place the class file in this folder. The App_Code is an ASP.Net special folder introduced in ASP.Net 2.0 onwards, it acts as the BIN folder, where you can store source files, which will be compiled in runtime. You can find more details about App_Code folder in MSDN : Shared Code Folders in ASP.NET Web Sites.

Few days back I created a custom contol in App_Code folder, and I couldn’t found any way to add in my aspx page. After doing some search I found two ways to do it.

  1. Directly specifying App_code folder in ASPX Page.
  2. <%@ Register TagPrefix="dotnetthoughts" Assembly="__Code" Namespace="dotnetthoughts.Controls" %>
    

    In this Assembly attribute specifies the control is from App_Code folder. And the Namespace specifies the Control name space.(By default when you are adding a Class file namespace won’t be there, you need to add a Namespace.)

  3. Registering the Control to application via Web.Config.
  4. <configuration>
            <system.web>
                    <pages>
                            <controls>
                                    <add namespace="dotnetthoughts.Controls" tagPrefix="dotnetthoughts"/>
                            </controls>
                    </pages>
            </system.web>
    </configuration>
    

    In this you don’t need to specify the control is loading from App_Code folder. Hopes it will be useful.

Import Data from Excel using C# – Part 2

February 16th, 2010 Anuraj P 6 comments

In my web application, we used to import data from MS Excel file. Few days before one of the client representative posted an issue that he can’t import data from XLSX (MS Excel 2007 File Format) files. Previously we were using OLE DB provider to import data from Excel file (Checkout my previous post regarding How to Import / Export from C# : IMPORT / EXPORT DATA IN MS EXCEL USING C# ), but Microsoft worked on the Office 2007 file formats, and we are not able to connect to Excel using Microsoft.Jet.OLEDB. Yesterday I got a chance to work on this module, and thought of implementing XLSX support. After few searches I found a new provider from Microsoft to connect to Excel 2007 files, called Microsoft.ACE.OLEDB.12.0.

/// <summary>
/// Imports Data from Microsoft Excel File.
/// </summary>
/// <param name="FileName">Filename from which data need to import</param>
/// <returns>List of DataTables, based on the number of sheets</returns>
private List<DataTable> ImportExcel(string FileName)
{
    List<DataTable> _dataTables = new List<DataTable>();
    string _ConnectionString = string.Empty;
    string _Extension = Path.GetExtension(FileName);
    //Checking for the extentions, if XLS connect using Jet OleDB
    if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
    {
        _ConnectionString =
            "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0";
    }
    //Use ACE OleDb
    else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
    {
        _ConnectionString =
            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0";
    }

    DataTable dataTable = null;

    using (OleDbConnection oleDbConnection =
        new OleDbConnection(string.Format(_ConnectionString, FileName)))
    {
        oleDbConnection.Open();
        //Getting the meta data information.
        //This DataTable will return the details of Sheets in the Excel File.
        DataTable dbSchema = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null);
        foreach (DataRow item in dbSchema.Rows)
        {
            //reading data from excel to Data Table
            using (OleDbCommand oleDbCommand = new OleDbCommand())
            {
                oleDbCommand.Connection = oleDbConnection;
                oleDbCommand.CommandText = string.Format("SELECT * FROM [{0}]",
                    item["TABLE_NAME"].ToString());
                using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter())
                {
                    oleDbDataAdapter.SelectCommand = oleDbCommand;
                    dataTable = new DataTable(item["TABLE_NAME"].ToString());
                    oleDbDataAdapter.Fill(dataTable);
                    _dataTables.Add(dataTable);
                }
            }
        }
    }
    return _dataTables;
}

The connection string also supports HDR attribute, which decides, whether the Excel file first row is header or not. It can be either Yes or No. It can be used with both Excel 2003 and Excel 2007 files.

Update: You can download the Microsoft.ACE.OLEDB.12.0 provider from Microsoft : 2007 Office System Driver: Data Connectivity Components