jeudi 27 février 2014

Keeping ASP.NET Session Open / Alive

Friends, many times we get requirements to increase the session timeout expiry time on the application server, so what we do basically we go in web.config file and set session time out to some time period, by default its 20 mins, but remember sometime you increase time period in web.config file and it doesn't work why?? The reason is you also have to check your application pool recycling time period it should be more than the session expiry period which you are doing in web.config file.

 Yo! But anyways you did not avoid session expiration in your application, session will still expire in your application let's say if user filling a long form in your application or kept a page open and gone out for coffee. So now what will happen? Session will expire right? By the time use will be back and resume with the work.

Some people do session resetting in code behind by checking if session is null then read User ID () from cookies and reset it. Or if it is intranet application and AD authentication then you get the current logged in user in system and set it in session.Now if you don't wanna do all above crap In your application, what all you wanna do is don't let session to get expire unless user close the browser. To implement this behavior in your applications simply follow below steps.
  1. First of all let me give you some brief about working session state in asp.net. By default it is set to 20 min, so if user sends a request to the server (in simple language browse a page) then server stores the time when request came and extend the session time out to 20 min, so if after 10 min user send again a request so it keeps extended to 20 min, if user don't send any request to server till 20 min then session get expires. This is basic working of session state.
  2. From first step you know that, server need to get any request from client to keep session alive, so now we can think of some methodology to keep pinging the server, below is the script which will keep sending request to the server and will keep session alive.

    Create a SessionCheck.aspx page in your application; you can keep this page blank. So that if it gets called from the browser then it should not be over loaded.

    Using Java Scrip:
    Image will be used to keep session alive by changing image src, assigning this property to some 
    <img id="imgSessionCheck" width="1" height="1" />

    <script type="text/javascript" >
    //Variable used to prevent caching on some browsers and knowing the count how many times user sends request to server.
        var counter;
        counter = 0;

        function KeepSession() {
    // Increase counter value
        counter++;

        // Gets reference of image
        var img = document.getElementById("imgSessionCheck");

        // Set new src value, which will send a request to the server
    img.src = "http://servername:port/appName/SessionCheck.aspx?count=" + counter;

        // now schedule this process to happen in some time interval, in this example its 1 min
        setTimeout(KeepSession, 60000);
    }

        // Call this function for a first time
        KeepSession();
        </script>

    Using JQuery:
    <script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript">

        function KeepSession() {
        // A request to server
        $.post("http://servername:port/appName/SessionCheck.aspx");

        //now schedule this process to happen in some time interval, in this example its 1 min
        setInterval(KeepSession, 60000);
    }

        // First time call of function
        KeepSession();
     </script>

    So it's simple just you need to put this script in your page.

Downloading Files C#

A lot of questions are being asked about downloading a file from the web server to the client in ASP.NET. I have updated this blog post due to the high number of view & comments. You will realize i added a function called "ReturnExtension" which will return the proper content type and set it to the Response.ContentType property. Almost well known file types are supported.
C# Code
   // Get the physical Path of the file(test.doc)
   string filepath = Server.MapPath("test.doc");
   // Create New instance of FileInfo class to get the properties of the file being downloaded
   FileInfo file = new FileInfo(filepath);
  
   // Checking if file exists
   if (file.Exists)
   {
    // Clear the content of the response
    Response.ClearContent();
    
    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    
    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());
    // Set the ContentType
    Response.ContentType = ReturnExtension(file.Extension.ToLower());
    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
    Response.TransmitFile(file.FullName);
    // End the response
    Response.End();
   }
private string ReturnExtension(string fileExtension)
{
     switch (fileExtension)
            {
                case ".htm":
                case ".html":
                case ".log":
                    return "text/HTML";
                case ".txt":
                    return "text/plain";
                case ".doc":
                    return "application/ms-word";
                case ".tiff":
                case ".tif":
                    return "image/tiff";
                case ".asf":
                    return "video/x-ms-asf";
                case ".avi":
                    return "video/avi";
                case ".zip":
                    return "application/zip";
                case ".xls":
                case ".csv":
                    return "application/vnd.ms-excel";
                case ".gif":
                    return "image/gif";
                case ".jpg":
                case "jpeg":
                    return "image/jpeg";
                case ".bmp":
                    return "image/bmp";
                case ".wav":
                    return "audio/wav";
                case ".mp3":
                    return "audio/mpeg3";
                case ".mpg":
                case "mpeg":
                    return "video/mpeg";
                case ".rtf":
                    return "application/rtf";
                case ".asp":
                    return "text/asp";
                case ".pdf":
                    return "application/pdf";
                case ".fdf":
                    return "application/vnd.fdf";
                case ".ppt":
                    return "application/mspowerpoint";
                case ".dwg":
                    return "image/vnd.dwg";
                case ".msg":
                    return "application/msoutlook";
                case ".xml":
                case ".sdxl":
                    return "application/xml";
                case ".xdp":
                    return "application/vnd.adobe.xdp+xml";
                default:
                    return "application/octet-stream";
}
N.B:  If you want to bypass the Open/Save/Cancel dialog you just need to replace LINE1 by the below code
Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);
Response.TransmitFile VS Response.WriteFile:  1- TransmitFile: This method sends the file to the client without loading it to the Application memory on the server. It is the ideal way to use it if the file size being download is large.
 2- WriteFile: This method loads the file being download to the server's memory before sending it to the client. If the file size is large, you might the ASPNET worker process might get restarted.
Hope this helps,

mardi 25 février 2014

Crypter et Décrypter en C#

        public string encrypt(string message)
        {
            byte[] results;
            string passphrase = "Password123";
            UTF8Encoding utf8 = new UTF8Encoding();
            //to create the object for UTF8Encoding  class
            //TO create the object for MD5CryptoServiceProvider
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));
            //to convert to binary passkey
            //TO create the object for  TripleDESCryptoServiceProvider
            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;//to  pass encode key
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] encrypt_data = utf8.GetBytes(message);
            //to convert the string to utf encoding binary

            try
            {
                //To transform the utf binary code to md5 encrypt   
                ICryptoTransform encryptor = desalg.CreateEncryptor();
                results = encryptor.TransformFinalBlock(encrypt_data, 0, encrypt_data.Length);
            }
            finally
            {
            //to clear the allocated memory
            desalg.Clear();
            md5.Clear();
            }
            //to convert to 64 bit string from converted md5 algorithm binary code
            return Convert.ToBase64String(results);
            }
           
           
         public string decrypt(string message)
        {
            byte[] results;
            string passphrase = "Password123";
            UTF8Encoding utf8 = new UTF8Encoding();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(passphrase));
            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] decrypt_data = Convert.FromBase64String(message);
            try
            {
                //To transform the utf binary code to md5 decrypt
                ICryptoTransform decryptor = desalg.CreateDecryptor();
                results = decryptor.TransformFinalBlock(decrypt_data, 0, decrypt_data.Length);
            }
            finally
            {
                desalg.Clear();
                md5.Clear();

            }
            //TO convert decrypted binery code to string
            return utf8.GetString(results);
        }

jeudi 20 février 2014

JavaScript alert et accents

Dans certains cas, un accent saisi dans le code source javascript ne sera pas affiché correctement, mais remplacé par un point d’interrogation.

Encodage octal des caractères

Il suffit de remplacer les caractères accentués par leur équivalent en octal précédé de \ (anti-slash)
Par exemple :
  • é : \351
  • è : \350
  • ê : \352
  • à : \340
 Pour plus de détail : http://www.pjb.com.au/comp/diacritics.html

mercredi 12 février 2014

Executer Sharepoint Designer avec un compte précis


1.lancer cmd
2. tapez la commande suivante : runas /user:username "chemin du exe"
à savoir "chemin du fichier = C:\Program Files\Microsoft Office\Office15\SPDESIGN.exe"
3. entrez votre password

mardi 4 février 2014

SQL utilities

-- Permet d'afficher les noms des colonnes 
d'une table séparé par virgule. 
select name + ', ' as [text()] 
from sys.columns 
where object_id = object_id('YourTable') 
for xml path('')

Programme console qui insère les données dans une base précise en C#



public class Program
{
public static void Main(string[] args)
{

Console.WriteLine("This program will insert data in database");
SqlConnection sqlConnection = new SqlConnection(@"data source=NOMDUSERVEUR;initialcatalog=NOMBASEDEDONNES;user id=IDUSER;password=PASSWORD;Trusted_Connection=true;");
sqlConnection.Open();
// Insértion des comptes
for (int i = 0; i < 9000; i++)
{
String insertSql = String.Format("INSERT INTO [dbo].[Compte]([Login],[Email] ,[Nom], [Prenom],[Pays_Id],[Password],[isValid],[langue]) VALUES ('Login','XXX@yahoo.fr','XXX', 'XXXX',60,'111',1,null)");
SqlCommand sqlCommand = new SqlCommand(insertSql, sqlConnection);
sqlCommand.ExecuteNonQuery();
}
Console.ReadLine();