Welcome

Hello, Welcome to my blog. If you like feel free to refer others

Monday, 5 October 2015

Difference between var and dynamic in C#


vardynamic
Introduced in C# 3.0Introduced in C# 4.0
Statically typed – This means the type of variable declared is decided by the compiler at compile time.Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.
Need to initialize at the time of declaration.
e.g., var str=”I am a string”;
Looking at the value assigned to the variable str, the compiler will treat the variable str as string.
No need to initialize at the time of declaration.
e.g., dynamic str; 
str=”I am a string”; //Works fine and compiles
str=2; //Works fine and compiles
Errors are caught at compile time.
Since the compiler knows about the type and the methods and properties of the type at the compile time itself
Errors are caught at runtime
Since the compiler comes to about the type and the methods and properties of the type at the run time.
Visual Studio shows intellisense since the type of variable assigned is known to compiler.Intellisense is not available since the type and its related methods and properties can be known at run time only

e.g., var obj1;
will  throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.
e.g., dynamic obj1; 
will compile;
e.g. var obj1=1;
will compile
var obj1=” I am a string”;
will throw error since the compiler has already decided that the type of obj1 is System.Int32 when the value 1 was assigned to it. Now assigning a string value to it violates the type safety.
e.g. dynamic obj1=1;
will compile and run
dynamic obj1=” I am a string”; 
will compile and run since the compiler creates the type for obj1 as System.Int32 and then recreates the type as string when the value “I am a string” was assigned to it.
This code will work fine. 

Wednesday, 8 April 2015

Last modified time of a file reside in FTP server

Add reference in your class:
using System.Net;
Then copy below mentioned method
 /// <summary>
        /// Get Server File TimeStamp
        /// </summary>
        /// <param name="serverPath"></param>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        ///  <param name="fileName"></param>
        /// <returns></returns>
        ///
        public static DateTime GetServerFileTimestamp(string serverPath, string userId, string password, string fileName)
        {
            // Get the object used to communicate with the server.
            String serverUrl = String.Format("{0}{1}/{2}", @"ftp:", serverPath, fileName);
            Uri serverUri = new Uri(serverUrl);
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(serverUrl);
            reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;           
            reqFTP.Credentials = new NetworkCredential(userId, password);
            try
            {
                using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                {
                    // Return the last modified time.
                    return response.LastModified;
                }
            }
            catch (Exception ex)
            {
                // If the file doesn't exist, return min date Otherwise rethrow the error.
                if (ex.Message.Contains("File unavailable"))
                    return DateTime.MinValue;
                throw;
            }
            finally
            {
                reqFTP = null;               
            }
        }

Above mentioned code  will return you last modified time.

Happy learning.............

Check ftp server is available or not

Add reference in your class:
using System.Net;
Then copy below mentioned method
/// <summary>
        /// GetServerAvailability to check ftp server is available or not
        /// </summary>
        /// <param name="userId">userId</param>
        /// <param name="password">password</param>
        /// <param name="ftpServerPath">ftpServerPath</param>
        /// <returns>status</returns>
        public static bool GetServerAvailability(string userId, string password, string ftpServerPath)
        {           
            FtpWebRequest reqFTP;
            bool isServerConnected = false;
            try
            {
                String serverUrl = String.Format("{0}{1}", @"ftp:", ftpServerPath);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverUrl));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                using (WebResponse response = reqFTP.GetResponse())
                {
                    isServerConnected = true;
                }
               
            }
            catch (Exception ex)
            { 
                if (string.Compare(ex.GetType().ToString(), "System.Net.Sockets.SocketException", true) == 0)
                {
                    System.Net.Sockets.SocketException socketError = (System.Net.Sockets.SocketException)ex;
                    if (socketError.ErrorCode == 11004)
                        isServerConnected = false;
                }
                else
                {                   
                    isServerConnected = false;
                }
            }
            finally
            {
                reqFTP = null;
            }
            return isServerConnected;
        }

Above mentioned code will return you true if server is available else false.

Upload file into FTP server

Add 2 reference in your class:
using System.Net;
using System.IO;

Then copy below mentioned method

/// <summary>
        /// Upload Design File into FTP server
        /// </summary>
        /// <param name="serverPath"></param>
        /// <param name="localPath"></param>
        /// <param name="fileName"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static bool UploadDesignFile(string serverPath, string localPath, string fileName,Dictionary<string,string> credentials)
        {           
            bool status = false;
          
            FtpWebRequest reqFTP;
            int bufferSize = 2048;
            try
            {
                String uploadUrl = String.Format("{0}{1}/{2}", @"ftp:", serverPath, fileName);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadUrl));
                 string username = string.Empty;
                credentials.TryGetValue("UserId",out username);
                string passwd = string.Empty;
                credentials.TryGetValue("Password",out passwd);
                reqFTP.Credentials = new NetworkCredential(Decrypt(username), Decrypt(passwd));
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;
                reqFTP.KeepAlive = true;
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
               
                using (Stream uploadStream = reqFTP.GetRequestStream())
                {
                    string localFilePath = String.Format("{0}/{1}", localPath, fileName);
                    using (FileStream localFileStream = File.OpenRead(localFilePath))
                    {
                        /* Buffer for the Downloaded Data */
                        byte[] byteBuffer = new byte[localFileStream.Length];
                        int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                        /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
                        try
                        {
                            while (bytesSent != 0)
                            {
                                uploadStream.Write(byteBuffer, 0, bytesSent);
                                bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                            }
                            status = true;
                        }
                        catch (Exception ex)
                        {
                            status = false;
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                status = false;
            }
            finally
            {               
                reqFTP = null;
            }
           
            return status;
        }


Above mentioned code will upload your file into FTP server. If file exists it will override that file.

Happy learning.....

Download file from FTP

Add 2 reference in your class:
using System.Net;
using System.IO;

Then copy below mentioned method
public static bool DownloadFile(string userId, string password, string ftpServerPath, string fileName, string localPath)
        {
            FtpWebRequest reqFTP;
            bool status = false;
            try
            {
                String downloadUrl = String.Format("{0}{1}/{2}", @"ftp:", ftpServerPath,fileName);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(downloadUrl));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, password);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                using (WebResponse response = reqFTP.GetResponse())
                {
                    using (Stream downloadStream = response.GetResponseStream())//;//read the download file from his stream
                    {
                        using (FileStream fs = File.Create(localPath + @"\" + fileName))
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = downloadStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            }
                            while (read != 0);
                            status = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                status = false;
            }
            finally
            {               
                reqFTP = null;
            }
            return status;
        }

Above mentioned method will download the desired file from FTP server to your local file system.

Happy learning......

Thursday, 15 May 2014

Difference between Lamda expression and LINQ query

Each style has their pros and cons. Query syntax is nicer when it comes to joins and it has the useful letkeyword that makes creating temporary variables inside a query easy.
Fluent syntax on the other hand has a lot more methods and operations that aren't exposed through the query syntax. Also since they are just extension methods you can write your own.
I have found that every time I start writing a LINQ statement using the query syntax I end up having to put it in parenthesis and fall back to using fluent LINQ extension methods. Query syntax just doesn't have enough features to use by itself.

There are some LINQ extension methods which do not have counterparts in LINQ query expressions, and will require the use of Lambda Expressions. A good example is Enumerable.ToLookup - if you want to create an ILookup, you need to use lambdas to generate this

Tuesday, 13 May 2014

Programatically setting up Physical Path Credential on IIS server for a virtual directoty

Below mentioned function will do the same for you. But only thing you need to do add the reference of Microsoft.Web.Administration dll on your project(7.0.0.0)

private void SetPhysicalPathCredential(string virDirName)
        {
            try
            {
                if (!String.IsNullOrEmpty(physicalPathCredentialUserDomain) && !String.IsNullOrEmpty(physicalPathCredentialUserUserName) && !String.IsNullOrEmpty(physicalPathCredentialUserPassword))
                {
                    using (ServerManager manager = new ServerManager())
                    {
                        Site defaultSite = manager.Sites["Default Web Site"];

                        // Read the data back from the updated configuration system, 
                        // then modify the Physical Path credential.
                        Application apps = manager.Sites["Default Web Site"].Applications["/" + virDirName];
                        VirtualDirectory appDir = apps.VirtualDirectories[0];
                        LogMessage("Setting up Physical Path Credential: " + virDirName);
                        appDir["userName"] = physicalPathCredentialUserDomain + "\\" + physicalPathCredentialUserUserName;
                        appDir["password"] = physicalPathCredentialUserPassword;
                        LogMessage("Successfully set up Physical Path Credential");
                        manager.CommitChanges();
                    }
                }
            }
            catch (Exception e)
            {
                LogMessage("ERROR: Error Setting up Physical Path Credential " + virDirName);
                throw e;
            }
            
        }