, , , , , , , , , , , ,

How to set max limt of File Upload in Asp.net

Many times I faced the same problem with all my applications, that is Max size of file to be uploaded to server.

By default, the maximum size limit of a file to be uploaded to a server using the ASP.NET FileUpload control is 4MB. You cannot upload anything that is larger than this limit.

If you wants to upload a file more the size of 4 MB which is by default, you have to make some changes in the application's web.config:

<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>

Below is the small description of the parameters attributes.

maxRequestLength - Attribute limits the file upload size for ASP.NET application. This limit can be used to prevent denial of service attacks (DOS) caused by users posting large files to the server. The size specified is in kilobytes. As mentioned earlier, the default is "4096" (4 MB). Max value is "1048576" (1 GB) for .NET Framework 1.0/1.1 and "2097151" (2 GB) for .NET Framework 2.0.

executionTimeout - Attribute indicates the maximum number of seconds that a request is allowed to execute before being automatically shut down by the application. The executionTimeout value should always be longer than the amount of time that the upload process can take.
Share:
Read More
, , ,

How to Get/Set date time according to Different Time zones in C#

downloadDownload code example

In an Asp.net application I have developed a Forum in which I have requirement to show date and time according to the time zone of PC on which it is running, I had searched for too many examples on but all are using too complex java scripts and other methods to convert time into local time zone.

Finally I decided to make my own solution for this problem
My solution is using “TimeZoneInfo” to convert the data to local time zone, this class allow me to convert time according to any time zone, but again I got another problem which is how to take time zone of browser. Again I search on net and finally come out with a code.

<script language="javascript" type="text/javascript">
    function genarateDateValue()
    {             
        var d = new Date()      
        var str=d.toString();
        var i = str.indexOf("+");      
        var j = str.length- i;
      
        str=str.substring(i, i+5);      
        setCookie("narender",str,365);
        return true;
       }

    function setCookie(c_name,value,expiredays)
    {      
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    }  
</script>

In Sql Server still there is no method to covert from one time zone to another but My Sql Support converting date time according to provided time zone.
Following is the simple code runs on My Sql Prompt:-
CONVERT_TZ(dt,from_tz,to_tz)
CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. This function returns NULL if the arguments are invalid.
If the value falls out of the supported range of the TIMESTAMP type when converted from from_tz to UTC, no conversion occurs.
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
        -> '2004-01-01 13:00:00'
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
        -> '2004-01-01 22:00:00'

Above is the method which we can use in My Sql which will return all the values from Database itself but if we are using Sql server we need to write our own code to convert time zone in C# code.
You can also download this code from link provided on top on this post.
public string DateFormat(string str)
    {
        ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
        foreach (TimeZoneInfo timeZone in timeZones)
        {
            TimeSpan offsetFromUtc = timeZone.BaseUtcOffset;
            string offsetString;
            string strHours = string.Empty;
            string strMinutes = string.Empty;
            strHours = offsetFromUtc.Hours.ToString();
            strMinutes = offsetFromUtc.Minutes.ToString();
            if (strMinutes.Length == 1)
            {
                strMinutes = "0" + strMinutes;
            }
            if (strHours.Length == 1)
            {
                strHours = "0" + strHours;
            }

            if (Convert.ToInt32(offsetFromUtc.Hours) >= 0)
            {
                strHours = "+" + strHours;
            }
            offsetString = strHours + strMinutes;
            if (Request.Cookies["narender"] != null)
            {
                if (Request.Cookies["narender"].Value.ToString() == offsetString)
                {
                    if (str != "")
                    {
                        DateTime thisTime = Convert.ToDateTime(str);
                        TimeZoneInfo tst1 = TimeZoneInfo.FindSystemTimeZoneById(timeZone.Id);
                        DateTime tstTime1 = TimeZoneInfo.ConvertTime(thisTime, TimeZoneInfo.Local, tst1);
                        str = Convert.ToDateTime(tstTime1).ToString("dddd,MMMM dd,yyyy hh:mm:ss tt");
                    }
                    return str;
                }
            }
        }
        return str;
    }
Share:
Read More
, , , , , , , ,

How to zip a file or folder using C#

downloadDownload code example


I had searched a lot to make files zip using c#, all the solution provided only support to zip a single file but my requirement is to zip a directory selected by used, I had tried so many utilities but unfortunately all does not works for me.

Finally I found a solution which is using Java utility to zip file. This solution is quite easy to implement and debug.

To implement this solution you need to add reference of “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vjslib.dll” to your application.
Share:
Read More
, , , , , , , ,

How to pass server values to Javascript using Eval()

In my application I have a target to show message if user does not have permission to navigate to another page. I can do this by using server code but it will make a round trip to server and make a bad user experience so, I decided to use java script.

Following is the function of Java Script

<script language="javascript" type="text/javascript">
function func_Message(obj)
{
if (parseFloat(obj)>0)
{
return true;
}
else
{
alert("Please assign a value before viewing the details");
return false;
}
}
</script>


And following is the code of Link Button from where I am passing value to Java Script Function

<asp:LinkButton ID="lnk_Details" runat="server" Text="Details" CommandArgument='<%# Eval("festi_id") +"~" + Eval("user_id") %>'
CommandName="ViewDetails" OnClientClick='<%# "return func_Message(" + Eval("user_id") + ");"%>'></asp:LinkButton>
Share:
Read More
, , , , , ,

Disbale JIT in .net / Application level Exception handling in .net

downloadDownload Code Example

I was developing windows application for a well known company of World. This application was in C#.net 2005.

As per requirement I have to show user defined message whenever an Exception occurs in the application.

The answer is very simply write a simple Try{},Catch{} statement to handle exception.
Suppose I have a code of 1000 line unwanted code and error handling creates extra thread while executing the application. I had search on the internet and found a solution to disable the JIT debugger. It works but still it is showing the application information related to functions etc. used in the code.

Now, a major issue had risen from client, i.e. he don’t want to show JIT information to user he wants to show his own message whenever any Exception occurs.

Offf…. Now that’s the task to which needs to done. I cannot use Try{},Catch{} as this decrease the application performance. Finally I came to the solution. I had wired an event with application to handle application error. Here is the code.

static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show("Illegal operation or command.", "Illegal operation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
Now, run your code and click on the button, it will show are exception while you are running the application within the .net environment.

Now browser the directory and Run you EXE file and again click in the button, now it will not show exception rather show the message which you wants to display.

This is a good approach it will show exception and source in while debugging and show and user defined message in EXE



Share:
Read More
, , , , , ,

How to alter Auto Increment field in Sql server

It is not possible to remove Auto Increment field using Alter command in Sql Server.

What we can use is SET IDENTITY_INSERT

Take this following example this creates a table with auto increment field and still insert data to the same.

Generally if you try to insert the data into auto increment field it will through error.

But if we use SET IDENTITY_INSERT <Table Name>ON it will allow you to insert data into auto increment field.

Note: Make sure after completing this operation you set the value to SET IDENTITY_INSERT <Table Name>OFF

--Create table and its columns
CREATE TABLE [test].[Table_1] (
[Id][int] NOT NULL IDENTITY (1, 1),
[Name][nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL);
GO

ALTER TABLE [test].[Table_1] ADD CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED ([Id])
GO

SET IDENTITY_INSERT [test].[Table_1] ON
GO
INSERT INTO [test].[Table_1] ([Id], [Name])
VALUES (1, 'Narender')

GO
INSERT INTO [test].[Table_1] ([Id], [Name])
VALUES (3, 'Rohit')

GO
INSERT INTO [test].[Table_1] ([Id], [Name])
VALUES (4, 'Mohit')

GO
INSERT INTO [test].[Table_1] ([Id], [Name])
VALUES (5, 'Shipra')

GO
SET IDENTITY_INSERT [test].[Table_1] OFF
GO

The above example simply insert the data into table without incrementing the values and keep the error shut..

If you try to insert any data after SET IDENTITY_INSERT [test].[Table_1] OFF it will through an error.
Share:
Read More
, ,

C# too many database connections error

Every database is having some number of connection limits which you can increase up to an extend.

But database can support up to an number of connections.

This error occurs when we open a connection and forget to close that. Verify each line of your code and make sure you had closed the connection after completing your database operations.

I had faced this error in C# My sql application. I had crossed verify my code and find a code where I am not closing my connection after completing my operations. I had simply write connection.Close(); and it had worked.
Share:
Read More