Search This Blog

Wednesday, July 25, 2012

Creating ZIP and UNZIP files in ASP.NET using DotNetZip library.

DotNetZip is easy to use free class library for ziping and extracing the zip files.
Check this DotNetZip for more information.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ionic.Zlib;
using Ionic.Zip;
using System.IO;
 
 
 
 
namespace ZipFilesAspDotnet
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
        #region Download ZIP File
        private void DownloadFile()
        {
            if (FileUpload1.HasFile)
            {
                //file upload folder App_Data
                string _fileName = FileuploadUtility.UploadFile(FileUpload1, Server.MapPath("~/App_Data/"), Session.SessionID);
                string[] _zip_fileName = _fileName.ToString().Split('.');
                Response.Clear();
                Response.ContentType = "application/zip";
                Response.AddHeader("content-disposition", "filename=" + "download_" + _zip_fileName.ToString() + ".zip");
 
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddEntry(_fileName.ToString(), File.ReadAllBytes(Server.MapPath("~/App_Data/" + _fileName.ToString())));
                    zip.Save(Response.OutputStream);
                }
            }
 
        }
        #endregion
 
        #region EXTRACT THE ZIP FILE
        private void ExtractZipFile()
        {
            string _fileName = FileuploadUtility.UploadFile(FileUpload1, Server.MapPath("~/App_Data/"), Session.SessionID);
 
            using (ZipFile zip1 = ZipFile.Read(Server.MapPath("~/App_Data/" + _fileName.ToString())))
            {
                 
                foreach (ZipEntry e in zip1)
                {
                    //destination folder zipfiles
                    e.Extract(Server.MapPath("~/ZipFiles/"), ExtractExistingFileAction.OverwriteSilently);
                }
            }
 
        }
        #endregion
 
        protected void Button1_Click(object sender, EventArgs e)
        {
            DownloadFile();
 
        }
 
        protected void Button2_Click(object sender, EventArgs e)
        {
            ExtractZipFile();
        }
    }
}

What is SlidingExpiration ?


When the SlidingExpiration is set to true, the time interval during which the authentication cookie is valid is reset to the expiration Timeout property value. This happens if the user browses after half of the timeout has expired.
For example, if you set an expiration of 30 minutes by using sliding expiration, a user can visit the site at 3:00 PM and receive a cookie that is set to expire at 3:30 PM. The expiration is only updated if the user visits the site after 3:10 PM. If the user visits the site at 3:09 PM, the cookie is not updated because half of the expiration time has not passed. If the user then waits 12 minutes, visiting the site at 3:21 PM, the cookie will be expired.

true if the sliding expiration is enabled; otherwise, false. The default is true.

When using forms authentication with slidingExpiration set to true (default), the cookie is updated only when more than half the timeout value has elapsed. As a result of this, you might be logged off sooner than you think.

Consider this: You have set the timeout to 30 minutes. You logon on at 3:00 pm; a FormsAuthenticationTicket is set to expire at 3:30 pm. The expiration of this ticket will not be extended for another 30 minutes until you make a request after 3:15 pm. So, if you made your last request at 3:15 pm, the ticket will still expire at 3:30 pm as more than half the timeout value has not elapsed (giving you a 15 minute window before you get logged out).

On the other had, if you had made a request at 3:16 pm, the expiration of the ticket is extended to 3:46 p.m.

From MSDN:
timeout  :   Specifies the amount of time, in integer minutes, after which the cookie expires. The default value is 30. If the SlidingExpiration attribute is true, the timeout attribute is a sliding value, expiring at the specified number of minutes after the time the last request was received. To prevent compromised performance, and to avoid multiple browser warnings for users that have cookie warnings turned on, the cookie is updated when more than half the specified time has elapsed. This might result in a loss of precision. Persistent cookies do not time out.

Cookies are stored in the location

The cookies are stored in the location provided below in Windows 7.
 C:\Users\(User-Name)\AppData\Roaming\Microsoft\Windows\Cookies\Low
AND
C:\Users\(User-Name)\AppData\Roaming\Microsoft\Windows\Cookies

Saturday, May 26, 2012

swap value without useing 3rd variable

A=3 and B=4    out put  A=4 and B=3

A=A + B     =  3 + 4 = 7

A=7

B=A - B    =7 - 4 = 3

A=A - B  = 7 - 3 = 4

query for full outer join with no repated value or column

Select * from R1 r1 full outer join R2 r2 on r1.NameId=r2.NameId
Select * from R1 r1 full outer join R2 r2 on r1.NameId=r2.NameId where r2.NameId is null or r1.NameId is null
Select * from R1 r1 full outer join R2 r2 on r1.NameId=r2.NameId where r1.NameId is null

Select r1.NameId, r1.FirstName,r1.LastName from R1 r1 full outer join R2 r2 on r1.NameId=r2.NameId where r2.NameId is null
union
Select r2.NameId,r2.FirstName,r2.LastName from R1 r1 full outer join R2 r2 on r1.NameId=r2.NameId where r1.NameId is null

table r1:-
NameId    FirstName    LastName
1    yogesh               pd
2    mohit              ranjan

table r2
NameId    FirstName    LastName
2    ashish        dsf
3    mohit        sdfdfs

result need:--
NameId    FirstName    LastName
1    yogesh        pd
3    mohit        sdfdfs

Monday, February 6, 2012

how can use Ternary operator

We can  replace an if(){} else {} sequence, by Ternary  operator like so:
txtname.Text = ue.name != string.Empty ? TextUtils.Prettyname(ue.name) : string.Empty;
instead of
if (ue.name != string.Empty)
{
 txtname.Text = TextUtilss.Prettyname(ue.name);
}
else
{
 txtname.Text = string.Empty;
}
<%# (Eval(Container.DataItem,"Col_3").ToString()=="")?DataBinder.Eval(Container.DataItem,"Col_2"):DataBinder.Eval(Container.DataItem,"Col_3")%>

Example:
var value = ViewState["AValue"];
MyTextbox.Text = (value != null) ? value .ToString() : String.Empty;

Change DB owner in SQL Server Database

DECLARE @old sysname, @sql varchar(1000)
 
SELECT
 
 @old = 'oldOwner_CHANGE_THIS'
 
 , @sql = '
 
 IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
 
 WHERE
 
     QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
 
     AND TABLE_SCHEMA = ''' + @old + '''
 
 )
 
 ALTER SCHEMA dbo TRANSFER ?'
 
EXECUTE sp_MSforeachtable @sql

Wednesday, February 1, 2012

How can increase command time out.

ExecuteNonQuery(SqlConnection conn, CommandType cmdType, string cmdText, params SqlParameter[] cmdParameters)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout =60000;PrepareCommand(cmd, conn, cmdType, cmdText, cmdParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}

System.InvalidOperationExceptionOperation is not valid due to the current state of the object.

Issue:

System.InvalidOperationExceptionOperation is not valid due to the current state of the object.
System.InvalidOperationException: Operation is not valid due to the current state of the object.
   at System.Web.HttpRequest.FillInFormCollection()
   at System.Web.HttpRequest.get_Form()
   at Rhino.Commons.LongConversationManager.LoadConversationFromRequest(Boolean& privateConversation)
   at Rhino.Commons.LongConversationManager.LoadConversation()
   at Rhino.Commons.HttpModules.UnitOfWorkApplication.UnitOfWorkApplication_BeginRequest(Object sender, EventArgs e)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
          
Cause:

Microsoft recently (12-29-2011) released an update to address several serious security vulnerabilities in the .NET Framework. MS11-100 was introduced just recently that handles potential DoS attacks.

Unfortunately the fix has also broken page POSTs with very large amounts of posted data (form fields). MS11-100 places a limit of 500 on postback items. The new default max introduced by the recent security update is 1000.

Adding the setting key to the web-config file overcomes this limitation, as in this example increases it to 2000.
<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
 </appSettings>

Friday, December 16, 2011

How can URL Rewrite in Window Server

If you want rewrite your page from http://abc.com to http://www.abc.com then follow below step in window server.
Step1:open server and click on URL Rewrite


 Step2: Add Rule for domain.




Step3: Add rewrite URL in given box and submit. 












How can check in SQL 2008 which query execute in sql


SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC

Tuesday, December 6, 2011

global.asax works on local computer but not after i publish to server

instead of the Application_Start because the first request might be local but later you could call the application on some other domain and it will no longer be local.
Local system code:

protected void Application_Start(object sender, EventArgs e)
{
Application["Visitors"] = 0;
// Code that runs on application startup
}

On Server Code:

protected void Application_OnStart(object sender, EventArgs e)
{
Application["Visitors"] = 0;
// Code that runs on application startup
}

How can implement Restful API


Restful Web Service:
                                     Case 1: It is not work on Add reference process
                                     Case 2: It is not use soap protocol
                                     Case 3: It is Call by HttpWebRequest HttpWebResponse
                                     Case4: In this case get post method  are use for getting response and           request.
The Methods
The interface of REST is generic. There is no need for protocol conventions for the communication between client and server. The following list describes the meaning of the HTTP methods and how they are used by REST.
Table 1: HTTP Methods
Method
Description
GET
GET queries the representation of a resource. The execution of requests should be free from side effects. GET requests can be sent arbitrarily often. You cannot blame the client for effects caused by GET requests. That means a GET can be sent heedlessly.
POST
With POST you can change the state of a resource. For example you can add a good to a shopping cart. POST isn't free from side effects. For example you can change fields in a data base or start a new process on the server with a POST request.
PUT
New resources can be produced with PUT or you can replace the content of existing resources.
DELETE
Resources can be deleted using DELETE.
How to call:
    Case: 1 First Request Format
         1: text
         2: Xml
         3: html
   Case 2: Check your query string name for send request or any variable name
  Case 3: url of rest web service
         Ex: http://shop/articles/585560
   Method: For Xml Format

     private string PostData_new(string url, string postData)
    {
        HttpWebRequest request = null;

        Uri uri = new Uri(url);
        request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postData.Length;
        using (Stream writeStream = request.GetRequestStream())
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytes = encoding.GetBytes(postData);
            writeStream.Write(bytes, 0, bytes.Length);
        }


        string result = string.Empty;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
                {
                    result = readStream.ReadToEnd();
                }
            }
        }
        return result;
    }
 
 Call function:
  Postdate=”variable name/Query string name=your date”
   private string PostData_new(: http://shop/articles/584460,postData);