Wednesday, 13 April 2016

Filter ArrayList value depend on datatype In C#


To get only specific Datatype value in ArrayList you can used below code .

OfType<DataType> ==> this is used to filter arraylist  value depend on DataType passed in.



          ArrayList list = new ArrayList();

            list.Add(1);
            list.Add(1.2);
            list.Add("StringValue");
            list.Add("StringValueOne");
            list.Add(true);

            foreach(var item in list.OfType<String or Int or Bool>()) // Here you can passed string,int ext  .
            {
                Console.WriteLine(item);
            }


Output: StringValue,StringValueOne

Monday, 4 April 2016

Find element whose id has a particular pattern in Jquery

Basically we have pattern to match with ID in jquery .


1) That selector matches all Button that have an id attribute and it starts with  "Test"

            $('input[id^="Test"]').css('background-color', 'red');
        

2)  That selector matches all Button that have an id attribute and it ends with "Test".

            $('input[id$="Test"]').css('background-color', 'red');
          

3) That selector matches all Button that have an id attribute  anywhere  with "Test" id.

            $('input[id*="Test"]').css('background-color', 'red');
         
Ex -> <asp:Button ID="Test" runat="server" Text="Button"  />
         <asp:Button ID="Test1" runat="server" Text="Button1" />
         <asp:Button ID="Test2" runat="server" Text="Button2" />
         <asp:Button ID="NotTest3" runat="server" Text="Button3" OnClick="Button1_Click"                   OnClientClick="return test();"/>

Output for 1 , 2 and 3 Pattern) 



Monday, 28 March 2016

Let Keyword In LINQ C#

Let =>The Let keyword allows storing the results of a query which can be used in a subsequent query; i.e., it creates a new variable and initializes it with the result of the expression you supply.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{

    class Employee
    {
        public string Name { getset; }
        public string EmpID { getset; }
        public int Salary { getset; }

    }
    class Program
    {
        static void Main(string[] args)
        {
            //Object Initialization for Employee class
            List<Employee> objEmployee = new List<Employee>{
                    new Employee{ Name="Sachin",EmpID="I001",Salary=800},
                    new Employee{ Name="Ankit",EmpID="I002",Salary=400},
                    new Employee{ Name="Vishal",EmpID="I003",Salary=250},
                    new Employee{ Name="Amit",EmpID="I004",Salary=300},
                    new Employee{ Name="Ravish",EmpID="I005",Salary=700},
                };          

            var objresult = from emp in objEmployee
                            let totalSalary = objEmployee.Sum(sal => sal.Salary)
                            let avgSalary = totalSalary / 5
                            where avgSalary > emp.Salary
                            select emp;
            foreach (var emp in objresult)
            {
                Console.WriteLine("Student: {0} {1}", emp.Name, emp.EmpID);

            }
            Console.ReadLine();
        }
    }
}

LINQ Query 
 
var result = from emp in objEmployee
                            let totalSalary = objEmployee.Sum(sal =>  sal.Salary)
                            let avgSalary = totalSalary / 5
                            where avgSalary > emp.Salary
                            select emp;


//output :

Student : Ankit 1002
Student : Vishal 1003
Student : Amit 1004


  • Let – Doesn’t hide the previous variable and creates a new variable. Which means you create a new variable and you can also use the previous variable, so you can use both in further operations.

Thursday, 17 March 2016

Creating Error Log file in C#


// If you want store error in notepad file , can use this code .

        public bool ErrorLog(string ErrorMessage)
        {

            try
            {
             
            string     lstrErrFilePath = System.Windows.Forms.Application.StartupPath + "\\DBLog" + "\\" + System.DateTime.Now.ToString("dd-MMM-yyy") + ".txt";
                if (!(Directory.Exists(System.Windows.Forms.Application.StartupPath + "\\DBLog")))
                {
                    Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + "\\DBLog");
                }
                FileStream tmpFile;
                if (File.Exists(lstrErrFilePath))
                {


                    tmpFile = new FileStream(lstrErrFilePath, FileMode.Append);
                    StreamWriter sw = new StreamWriter(tmpFile);
                    sw.WriteLine(" DT:" + System.DateTime.Now.ToString("dd-MMM-yyy hh:mm:ss") + "DB Error Message:" + ErrorMessage);
                    sw.Close();

                }
                else
                {
                    tmpFile = new FileStream(lstrErrFilePath, FileMode.Create);
                    StreamWriter sw = new StreamWriter(tmpFile);
                    sw.WriteLine(" DT:" + System.DateTime.Now.ToString("dd-MMM-yyy hh:mm:ss") + "DB Error Message:" + ErrorMessage);
                    sw.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {

            }
        }

Sending Mail using C#

++++++++Sending mail using C# and Async and Await .


*********** I have used this setting in Web.config file ***************
<add key="fromMail" value="donotreply@DomainName" />
    <add key="actualId" value="0" />
    <add key="SmtpServer" value="SmtpServer Name" />
    <add key="Username" value="UsernameOfYourServer" />
    <add key="Password" value="SmtpServerPassword" />
**************End here ******************************


 $$$$$$$$$$$$$$$$ function for sending mail $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

public async Task<string> SendMail(string Body, string ToaddressEmailID, string Subject)
        {
            MailAddress toAddress = null;
            MailAddress fromAddress = new MailAddress(ConfigurationManager.AppSettings["fromMail"].ToString());
            if (ConfigurationManager.AppSettings["actualId"].ToString() == "0") //  This for local testing , i have put 0 for local testing
            {
                toAddress = new MailAddress("ankit@gamil.com");
            }
            else
            {
                toAddress = new MailAddress(ToaddressEmailID);
            }
            var message = new MailMessage(fromAddress, toAddress);
               
            message.Subject = Subject;
            message.Body = Body;
            message.IsBodyHtml = true;
            message.Priority = MailPriority.High;
            message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
            string ServerName = ConfigurationManager.AppSettings["SmtpServer"].ToString(); // SMTP server name here you need to configur your server
            string Username = ConfigurationManager.AppSettings["Username"].ToString(); // getting value from Web.config file as you can see in above code 
            string Password = ConfigurationManager.AppSettings["Password"].ToString();
            using (var smtp = new SmtpClient(ServerName))
            {
                var credential = new NetworkCredential
                {
                    UserName = Username,
                    Password = Password
                };
                smtp.Credentials = credential;
              //  smtp.EnableSsl = true; // if you want to enable ssl for security you can uncomment that line but you need  SSL certificate
             
                try
                {
                    await smtp.SendMailAsync(message);
               
                    return "Successfully sent mail";
                }
                catch (Exception ex)
                {
                    return ex.Message.ToString();
                }
            }


        }

Monday, 14 March 2016

Download file from FTP server using C# (async and await)

// to download file from FTP server.
  
   private async void button1_Click(object sender, EventArgs e)
        {
         
            try
            {
                bool blnfilestatus = await FileDeleteAndCopy(); // to copy file and delete from folder "Refer my old post copy file and delete"
                bool CheckStatus = true;
                if (blnfilestatus == true)
                {
                    label1.Text = "Reading file from FTP server";
                    string lstrFTPServerPath = "ftp://172.11.11.11/Employee.xlsx";
                    string localPath = @"G:\New\";
                    string fileName = "Employee.xlsx";
                 
                    FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(lstrFTPServerPath);
                    requestFileDownload.Credentials = new NetworkCredential("UserName", "Password");
                    requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
                    FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
                    Stream responseStream = responseFileDownload.GetResponseStream();

                    FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create, FileAccess.ReadWrite,
                    FileShare.ReadWrite, bufferSize: 4096, useAsync: true);

                    int Length = 4096; // size of file 4MB only
                    Byte[] buffer = new Byte[Length];
                    int bytesRead = await responseStream.ReadAsync(buffer, 0, Length);
                    while (bytesRead > 0)
                    {
                        await writeStream.WriteAsync(buffer, 0, bytesRead);
                        //bytesRead = responseStream.Read(buffer, 0, Length);
                        bytesRead =await responseStream.ReadAsync(buffer, 0, Length); // Read file using await keyword 
                    }
                    responseStream.Close();
                    writeStream.Close();
                    requestFileDownload = null;
                    responseFileDownload = null;
                    label1.Text = "Done !";
                    string FilePathafterUpdate = localPath + "\\" + fileName;
                    FileInfo fiinfo = new FileInfo(localPath + "\\" + fileName);
                    if (fiinfo.Exists)
                    {
                        label1.Text = "Checking file exists in directory";
                        if (fiinfo.CreationTime < DateTime.Now && fiinfo.CreationTime > DateTime.Now.AddMinutes(-1)) // for checking file is crated in folder or not just before 1 min ago.its depend on your requirement you can use what you want 
                        {
                            if (fiinfo.Extension == ".xlsx" || fiinfo.Extension == ".xls")
                            {
                             
                                 // write your code.
                                 
                                   
}
                           
                        }
                    }
                    else
                    {
                        label1.Text = "File not found at target location !";
                     
                    }
                }
                else
                {
                    label1.Text = "Not able to move file from target to source folder";
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message.ToString());
            }
        }

Copy file and delete from Directory(Task Based) in C#

 /// <summary>
        /// To move file source to target and delete from source
        /// </summary>
        /// <returns>bool type may be true or false</returns>
        public async Task<bool> FileDeleteAndCopy()
        {
            try
            {
                string sourcePath = @"G:\New";
                string targetPath = @"G:\Old";
                string sourceFile = System.IO.Path.Combine(sourcePath);
                string destFile = System.IO.Path.Combine(targetPath);

                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                    label1.Text = "Creating directory for target path";
                }

                if (!System.IO.Directory.Exists(sourcePath))
                {
                    System.IO.Directory.CreateDirectory(sourcePath);
                    label1.Text = "Creating directory for source path";
                }

                if (System.IO.Directory.Exists(sourcePath))
                {
                    string[] files = System.IO.Directory.GetFiles(sourcePath);
                    foreach (string filename in files)
                    {
                        string strDatetime = DateTime.Now.ToString("ddMMyyyyHHss");
                        string FileNameArray = System.IO.Path.GetFileName(filename);
                        destFile = System.IO.Path.Combine(targetPath, strDatetime + FileNameArray);
                        System.IO.File.Copy(filename, destFile, false);
                        label1.Text = "Moving file to target folder " + filename.ToString();
                    }
                    //Delete from source folder.
                    string[] fileList = Directory.GetFiles(sourceFile);
                    foreach (var flist in fileList)
                    {
                     
                        await Task.Run(() =>
                        {
                            File.Delete(flist);
                        });
                        label1.Text = " Deleting file from source folder " + flist.ToString();
                    }
                    return true;

                }
                return true;
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message.ToString());
                return false;
            }

        }

MVC 5 Bind Attributes

Bind Attribute - Basically its used to bind your property depend on attribute.

Ex - 

[Bind(Include="Name")]
Public class User{
public string Name{get;set;}

public string Address{get;set;}
}

Note- Basically when we want to bind 1 or more property with your view and model that time we used bind.
its also used for Security region, suppose if you want to bind only on property with your model.

so in above class when we try to get class property value like this

            User objUserCls = new User();
            this.TryUpdateModel(objUserCls);    

we will get only Name value in Controller class other class value will we by default value with datatype  .

In Same we can also use  -

[Bind(exclude="Name")]

Now you want able to get Name value in Controller class