Sunday, 22 October 2017

Insert multiple rows in sql table using entity framework


There is two way to insert multiple record in Database using EF.

1) As below example,  we have to call AddRange method of DbSet class, here we can add multiple record as i have useEmpDetails  list for adding multiple record. 

using (var context = new DbContextDemo())
            {
                var item = context.EmpDetailsDbSet.ToList();
                //Insert multiple record in sql table using EF

                var list = new List<EmpDetails>(); // this is my Dbset class(EmpDetails) 
                EmpDetails obj = new EmpDetails()
                {
                    EmpID = 23123,
                    EmpName = "ABC",
                    EmpAddress = "Test1",
                    EmpMobile = 1442345,
                    EmpCompany = "ABC"

                };
                list.Add(obj);
                EmpDetails obj1 = new EmpDetails()
                {
                    EmpID = 233,
                    EmpName = "ABC Test",
                    EmpAddress = "Bangalore",
                    EmpMobile = 1435235,
                    EmpCompany = "ABC Test"
                };
                list.Add(obj1);

                context.EmpDetailsDbSet.AddRange(list); // Adding list of emp inside AddRange method 
                context.SaveChanges();

}

2) We will take same as above example, we will have list of EmpDetails and we are going to make foreach loop and add one by one record in Dbset class with Add method .

               var list = new List<EmpDetails>();
                EmpDetails obj = new EmpDetails()
                {
                    EmpID = 23123,
                    EmpName = "ABC",
                    EmpAddress = "Test2",
                    EmpMobile = 1442345,
                    EmpCompany = "ABC"

                };
                list.Add(obj);
                EmpDetails obj1 = new EmpDetails()
                {
                    EmpID = 233,
                    EmpName = "ABC Test",
                    EmpAddress = "Bangalore",
                    EmpMobile = 1435235,
                    EmpCompany = "ABC Test"
                };
                list.Add(obj1);

             foreach (var item1 in list)   // Adding record one by one 
                {
                    context.EmpDetailsDbSet.Add(item1);
                }

         and finally call SaveChanges() method of context class.

          context.SaveChanges();

Tuesday, 5 September 2017

Checked and Unchecked keyword in C#

Unchecked and checked words are used to control whether or not an overflow occurred during arithmetic operations.


Overflows: When a value exceeds the limitations of a data type, it is said to overflow. This can be an inconvenience where unexpected, causing incorrect results from calculations.



Checked Arithmetic :  To prevent the incorrect or dangerous results of unchecked calculations, checked arithmetic can be used instead. One way to achieve this is to use the "checked" keyword for specific sections of code. This keyword uses a code block to surround a series of items that should be processed in this way. If an overflow occurs within a checked code block, an exception of the type System.OverflowException is thrown.



In the above code snippet you can see that I have tried to add extra value to the "z" variable which is of "int" data type and it can hold only "2147483647" value.

This is somewhat we were not expecting your expectation was the compiler should throw some error (overflow) or exception.

Let add Checked Keyword  and see what happen inside program.







After adding checked keyword , we can able to see overflow exception in program. 
Unchecked Arithmetic :  When using the default C# compiler options, arithmetic is unchecked. This means that any overflowing data from arithmetic operations is simply truncated. In the following sample code this is demonstrated by setting an integer to its maximum value, then incrementing it. The resultant value is truncated and rather than being a larger number is actually the smallest permissible integer value.

Let see below screen shoot .




As we can see its work like before it was . we not getting any exception now. 


















Extension Methods in C#

Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface.

For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class, like this:


public class MyUtils
{
    public static bool IsNumeric(string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Now we check string by executive  above code like below

string test = "4";
if (MyUtils.IsNumeric(test))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");


Note : However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

The IsNumeric() method is not a method of string data type . It is an extension method written by the programmer for the string data type. The IsNumeric() extension method will be available throughout the application by including the namespace in which it has been defined.


public static class MyExtensionMethods
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the IsNumeric() method directly on strings, like this:

string test = "4";
if (test.IsNumeric())
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");



Note : The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.


Please see below screen shoot .


Extension Methods

Different type of join in LINQ C#.

Different type of join in LINQ C#.

The following are four most common join types:

1) Inner Join 
2) Cross Join (Cross join is not equijoin)
3) Left Outer Join
4) Group Join

So i will explain you one by one , first of all we will start with Inner join.

Inner Join : A join clause takes two sequences as input  or many . The elements in each sequence must either be or contain a property that can be compared to a corresponding property in the other sequence. All joins performed by the join clause are equijoins.

please see below exp.

I have two type of collection class , CourseDetail and Course.

        private class Course
        {
            public string CourseId { get; set; }
            public string CourseName { get; set; }

        }

       private class CourseDetail
        {
            public string CourseId { get; set; }
            public string CourseDescription { get; set; }
            public long CourseSer { get; set; }
        }

Now we are going to bind some of data into list .

       var listCourse = new List<Course>()
            {
                new Course {CourseName = "Test", CourseId = "1"},
                new Course {CourseName = "Test2", CourseId = "2"},
                new Course {CourseName = "Test3", CourseId = "2"},
                new Course {CourseName = "Test4", CourseId = "5"}
            };

       var listCourseDetail = new List<CourseDetail>()
            {
                new CourseDetail {CourseDescription = "Test", CourseId = "1", CourseSer = 1234},
                new CourseDetail {CourseDescription = "Test2", CourseId = "2", CourseSer = 12345},
                new CourseDetail {CourseDescription = "Test3", CourseId = "3", CourseSer = 12346},
                new CourseDetail {CourseDescription = "Test4", CourseId = "4", CourseSer = 12347},
            };

Now will Perform inner join using LINQ as below

     var innerJoinResult = (from cd in listCourseDetail
                        join cour in listCourse on cd.CourseId equals cour.CourseId // here i am comparing CourseDetail list courseid to course list CourseId  , if it is match we will get result .
                        select new
                        {
                            cour.CourseName,
                            cour.CourseId,
                            cd.CourseDescription

                        }).ToList();
            foreach (var item in innerJoinResult)
            {
                 Console.WriteLine($"Course Name {item.CourseName} and its description                                                                         {item.CourseDescription}");
            }
below are output.





Cross Join: Cross join consists to perform a Cartesian product of two sets or sequences.
Cross join is not equijoin, means that no predicate expression of equality in the Join clause of the query.

Below is sample exp.

 var innerJoinResult = (from cd in listCourseDetail
                                   from cour in listCourse // here as you see i did not put any join keyword as its not a equijoin.
                                   select new
                                   {
                                       cour.CourseName,
                                       cour.CourseId,
                                       cd.CourseDescription

                                   }).ToList();
            foreach (var item in innerJoinResult)
            {
                Console.WriteLine($"Course Name {item.CourseName} and its description                                                 {item.CourseDescription}");
            }

below are output.


















Left Outer Join: In a left outer join, all the elements in the left source sequence are returned, even if no matching elements are in the right sequence. To perform a left outer join in LINQ, use the DefaultIfEmpty method in combination with a group join to specify a default right-side element to produce if a left-side element has no matches. You can use null as the default value for any reference type, or you can specify a user-defined default type. In the following example, a user-defined default type is shown:

 var leftJoinResult = (from cd in listCourseDetail
                join cour in listCourse on cd.CourseId equals cour.CourseId into coursegroup // before using DefaultIfEmpty , we have to use group join , if you put your query result into that we called group join. 
                from item in coursegroup.DefaultIfEmpty(new Course {CourseId = "0", CourseName = "None"}) // here i have provide some default value like  CourseName ="None", if above condition did not match up then we will get Courser Name as "None".
                select new
                {
                    item.CourseName,
                    item.CourseId,
                    cd.CourseDescription

                });
            foreach (var item in leftJoinResult)
            {
                Console.WriteLine($" Course Name {item.CourseName} and its description {item.CourseDescription}");
            }







Group Join: A join clause with an into expression is called a group join.
A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. Group Join sequence of object arrays.
If no elements from the right source sequence are found to match an element in the left source, the join clause will produce an empty array for that item. Therefore, the group join is still basically an inner-equijoin except that the result sequence is organized into groups.

Using lambda expressions: 

  var groupJoin = listCourse.GroupJoin(listCourseDetail, //inner sequence
                courseObj => courseObj.CourseId,  //outerKeySelector 
                courseDetailObj => courseDetailObj.CourseId,   //innerKeySelector
               (s, courseDetailGroup) => new  // resultSelector
                {
                    s.CourseName,
                    GroupArray = courseDetailGroup
                }) ;

Or Use Linq Query :

  var groupJoin =
                    from courseObj in listCourse
                    join courseDetailObj in listCourseDetail on courseObj.CourseId equals                                                     courseDetailObj.CourseId into courseDetailGroup 
                    select new { CategoryName = courseObj.CourseName, courseDetail =                                                    courseDetailGroup };

            foreach (var item1 in groupJoin)
            {

                Console.WriteLine(item1.CourseName);
              foreach (var item in item1.GroupArray)
                    Console.WriteLine( $"Group data is {item.CourseDescription} for courseId                                               {item.CourseId}");
                Console.Write("\n");
            }

Below are out Put.












Thursday, 29 June 2017

Get start-date and last-date based on current date in C#

There is many way to find startDate and LastDate of the week , so i have used two way to find out and print it as below.

In first example i will use simple switch case to get startDate of the week.

       private void button3_Click_1(object sender, EventArgs e)
          {
            string dayOfWeek = DateTime.Today.DayOfWeek.ToString().ToLower();
            int getValue = 0;
            switch (dayOfWeek)
            {
                case "monday":
                    getValue = 0;
                    break;
                case "tuesday":
                    getValue = 1;
                    break;
                case "wednesday":
                    getValue = 2;
                    break;
                case "thursday":
                    getValue = 3;
                    break;
                case "friday":
                    getValue = 4;
                    break;
                case "saturday":
                    getValue = 5;
                    break;
                case "sunday":
                    getValue = 6;
                    break;
            }
            DateTime startWeek = DateTime.Now.AddDays(-getValue); // Need to subtract getValue
            DateTime endWeek = startWeek.AddDays(6); // Need to add

           // Print Date of the week.

           for (int i = 0; i <= 7; i++)
            {
                DateTime dt = startWeek;
                switch (i)
                {

                    case 0:
                        Label1.Text = dt.ToShortDateString();
                        break;
                    case 1:
                        Label2.Text = dt.AddDays(i).ToShortDateString();
                        break;
                    case 3:
                        Label3.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 4:
                        Label4.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 5:
                        Label5.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 6:
                        Label6.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                    case 7:
                        Label7.Text = dt.AddDays(i - 1).ToShortDateString();
                        break;
                }

            }

}

Here is second example to get  startDate and LastDate of the week, this below example is simple and sweet .

DayOfWeek dayOf = DateTime.Now.DayOfWeek;

/* DayOfWeek  => is a Enum , its come under System.Runtime.InteropServices Namespace*/

int day = dayOf - DayOfWeek.Monday; // here we are assuming starting day is Monday  and subtracting current day of the week .

DateTime startDateTime = DateTime.Now.AddDays(-day);

DateTime endDateTime = DateTime.Now.AddDays(day);

  WriteLine($"StartDate if Week is {startDateTime.ToLongDateString()} and End date of week is {endDateTime.ToLongDateString()}");

Thursday, 15 June 2017

Find All vowels in string using C#

public static void Main()
        {
            int size = int.Parse(ReadLine());
            var inputValue = "";
            for (int i = 0; i < size; i++)
            {
                inputValue += Console.ReadLine();
            }
            var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
            bool findVowels = false;
            var findCharGroup = inputValue.GroupBy(x => x).Select(x => new
            {
                key = x.Key,
                Count = x.Count()
            }).ToDictionary(t => t.key, t => t.Count);

            foreach (var itemVowels in vowels)
            {

                if (findCharGroup.ContainsKey(itemVowels))
                {
                    findVowels = true;
                }
                else
                {
                    findVowels = false;
                    break;
                }

            }
            WriteLine(findVowels ? "YES" : "NO");
            ReadLine();
        }

Monday, 22 May 2017

How to work with Dapper in C#


What is Dapper :

Dapper is ORM (object-relational-mappers) tool.
It can be useful on even the smallest of projects. Dapper is a simple object mapper for .Net that extends the IDbConnection interface. It contains helpers that execute queries and map results in a very elegant way. The best part is the performance is close enough to plain old SQL that it’s well worth it. It will reduce the amount of code you write as well, by a long shot.


Implementation:

Install Dapper from your Package Manager Console:

Install-Package Dapper

We should create an entity class for this database table for simplicity when working with Dapper. Here's the entity class named Test.

 public class Test
    {
        public int EmpId { get; set; }
        public string  EmpName { get; set; }
        public string EmpAddress { get; set; }
    }


Query() :

The Query() extension method in the Dapper framework enables you to retrieve data from the database and populate data in your object model. The following method retrieves all the records from the Test table, stores them in memory and returns the collection.

 public async Task<List<Test>> GetAllRecord(string id)
        {
            var parameters = new DynamicParameters(); //this is used to passed parameter value in SQL query 
            parameters.Add("@EmpID", id);
            SqlQuery =
                @"select  * from Test where EmpID=@EmpID";

            using (IDbConnection connection = new SqlConnection(ConnectionString))
            {
                var res = await Query<Test>(SqlQuery, parameters);
                return res.ToList();
            }
        }

Execute():

The Execute() method of the Dapper framework can be used to insert, update, or delete data into a database. This method returns an integer value that implies the number of rows that have been affected on execution of the query.

 public async Task<int> UpdateRecord(string id,string Name, string Address)
        {
            var parameters = new DynamicParameters(); //this is used to passed parameter value in SQL query 
            parameters.Add("@EmpID", id);
            parameters.Add("@EmpName", Name);
            parameters.Add("@EmpAddress", Address);
            SqlQuery =
                @"select  * from Test where EmpID=@EmpID";

            using (IDbConnection connection = new SqlConnection(ConnectionString))
            {
                string sqlQuery = "UPDATE Test SET EmpName= @EmpName, " +
               " EmpAddress= @EmpAddress " + "WHERE EmpID = @Id";
                int rowsCount = await connection.ExecuteAsync(sqlQuery, parameters);
                return rowsCount;
            }
        }

 If you want to work with stored procedures using the Dapper framework, you should mention the command type explicitly when calling the Query or the Execute methods.Please see below exp.


public List<Test> Read()

        {

            using (IDbConnection db = new SqlConnection

              (ConfigurationManager.ConnectionStrings

              ["TestConnection"].ConnectionString))

               {

                string readSp = "GetAllEmp";

                return db.Query<Author>(readSp,

                commandType: CommandType.StoredProcedure).ToList();

               }


        }


Sunday, 21 May 2017

Get enum description from value in c#


In this post I will show how to read a description attribute of an enum value by reflection. Let us assume we have a enum like that .



 public enum TestEnum
    {
        [Description("Select")]
        NotAssigned,
        [Description("First Test Pass")]
        FirstTestPass,
        [Description("Second Test Pass ")]
        SecondTestpass
    }


The code above, basically takes in the enumeration, uses Reflection to find the "DescriptionAttribute" on the member, and then returns the Description. If the DescriptionAttribute is not present on the enum, then we just call a ToString() on the enum to get the name.

public static string GetEnumDescription(Enum value)
        {
            AppLogger.Instance.Info();
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi?.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes?.Length > 0)
                return attributes[0].Description;
            return value.ToString();

        }

So if call my above function like that .

 var getEnumDescripation =
                         GetEnumDescription(
                             "1");



Input Enum Value ="1";
Out Put ="First Test Pass";

Wednesday, 5 April 2017

Download file from an ASP.NET Web API method using C#

[HttpGet]
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> DownloadFileAsync(inputmodel context)
        {
            HttpResponseMessage result = null;
             var documentDownload = await _documentManager.DownloadFileAsync(context);

//After getting byte array from below function we will pass to MemoryStream and this MemoryStream add to HttpResponseMessage

                if (documentDownload != null)
                {
                    var stream = new MemoryStream(documentDownload);
                    result = Request.CreateResponse(HttpStatusCode.OK);
                    result.Content = new StreamContent(stream);
                    result.Content.Headers.ContentType =
                        new MediaTypeHeaderValue("pdf");
                    result.Content.Headers.ContentDisposition =
                        new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = string.Concat(FileName, ".", "pdf")
                        };
                }
                else
                {
                    result = Request.CreateResponse(HttpStatusCode.NoContent);
                }
            }
            return ResponseMessage(result);
        }


        Note => Below method is going to convert file into byte array    

public async Task<byte[]> DownloadFileAsync(ModelClass context)
        {
            string filepath = "Your Server path or local path" + @"\\" + context.Id + @"\\" + context.Guid + @"." + "pdf";
            var directorypath = "Your server path or local path" + @"\\" + context.Id;
            if (!Directory.Exists(directorypath)) return null;
            if (!File.Exists(filepath)) return null;
            var bytes = await Task.Run(() => File.ReadAllBytes(filepath));
            return bytes;
        }

Searching for a Specific Word in a Text File and Displaying in C#


      public static void Main()
        {
             Task.Run(async () => await Writefilecontent());
             Console.ReadLine();
         }


     private static async Task Writefilecontent()
        {
            string sourceFilePath = @"D:\Test\Source.txt";
            string destinationFilePath = @"D:\Test\Destination.txt";
            if (File.Exists(filepath))
            {
                var sb = new StringBuilder();
                var fs = new FileStream(sourceFilePath , FileMode.Open, FileAccess.Read);
                using (var sr = new StreamReader(fs))
                {
                    string line;
                    while ((line =await sr.ReadLineAsync()) != null)
                    {
                        if (line.Contains("this"))
                        {
                            sb.Append("this done !!!!!" + Environment.NewLine);
                        }
                    }
                }
                using (var sw = new StreamWriter(destinationFilePath , true)) // This is for writing text into some other file , you can do as your requirement. 
                {
                   await sw.WriteAsync(sb.ToString());
                }
                Console.WriteLine(sb.ToString());
                Console.ReadLine();
            }
        }

Note=> In StreamWriter we have to pass true other wise ,it will overwrite all text into  destination file.

like this

var sw = new StreamWriter(destinationFilePath , true)

Sunday, 19 March 2017

Convert binary string to decimal in c#


To convert a binary number to decimal is to look at the bits of the binary number and raise 2 to the power of the index of the “on” bits and add those together. I define an “on” bit as a bit that is 1 as opposed to 0.


For example, the binary number 100 can be looked at as
22 + 0 + 0 = 4
public static void Main()
        {
            var strbinary = "100"; // binary all way read from right to left
            Console.WriteLine(BitStringToInt(strbinary));
            Console.ReadLine();
        }


In the code example below, I first reverse the array to allow the index of our loop (Power) match up with the index of the binary string (the power in which we want to raise 2 to).

private static int BitStringToInt(string bits)
        {
            var reversedbinary = bits.Reverse().ToArray();
           // So we have to get max power of bit , that why we have reversed string value
            var num = 0;
            for (var power = 0; power < reversedbinary.Count(); power++)
            {
                var currentBit = reversedbinary[power];
                if (currentBit == '1')
                {
                    var currentNum = (int)Math.Pow(2, power);
                    num += currentNum;
                }
            }
            return num;
        }

Ouput => 4


Friday, 17 March 2017

How to call Stored Procedure in Entity Framework 6 (Code-First)


    I have the following classes:
     public class LoanProgramInfoes
    {
      //  [Key]
       // [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int LoanProgramInfoId { get; set; }
        public int LoanProgramID { get; set; }
        public string LoanProgramCode { get; set; }
        public string LoanProgramName { get; set; }
     
    }

My context class is as in the following. In this class, I overrode the OnModelCreating method to map the Identity column with the LoanProgramInfoes entity.

 public class DbContextDemo:DbContext
    {
        public DbContextDemo()
            : base("PortalContext")
        {
        }
      
        public virtual DbSet<LoanProgramInfoes> LoanProgramInfoDbSet { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<DbContext>(null);

              modelBuilder.Entity<LoanProgramInfoes>().HasKey(x => x.LoanProgramInfoId);
            modelBuilder.Entity<LoanProgramInfoes>()
                .Property(x => x.LoanProgramInfoId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        }

    }

 Now i am calling SP using entity frame work 

 using (var context = new DbContextDemo())

            {
 using (var dbContextTransaction = context.Database.BeginTransaction())
                {
                    try

                    {
                     var searchdata = context.Database.SqlQuery<LoanProgramInfoes>(
                    "proc_GetLoanProgramInfo @LoanProgramInfoId,@LoanProgramID",
                    new SqlParameter("@LoanProgramInfoId", loanProgramInfoId),
                    new SqlParameter("@LoanProgramID", loanProgramId))
    .Select(x => new LoanProgramInfoes()
                        {
                        LoanProgramID = x.LoanProgramID,
                        LoanProgramInfoId = x.LoanProgramInfoId,
                        LoanProgramCode = x.LoanProgramCode,
                        LoanProgramName = x.LoanProgramName
                       

                   }).ToList();
                  foreach (var itemvalue in searchdata)
                        {
                                Console.WriteLine("LoanProgramID  {0}  of LoanProgramCode {1}  and its name -                                 {2}",  itemvalue.LoanProgramID, itemvalue.LoanProgramCode,                                                               itemvalue.LoanProgramName);

                        }
               dbContextTransaction.Commit();
             }
              catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        dbContextTransaction.Rollback();
                        

                    }
       }
}

Like that you can call for update and delete .
In case of select query no need to use Transaction, you can remove it.

Check if string contains only numbers c#

            string myString = "354";
         
            var Output= !string.IsNullOrEmpty(myString) && myString.All(char.IsDigit);

             Result => True

        Note=> If you put instated of ALL with Any in above line ,its will return true if                                                 myString contain at least one number . 

         **************** OR Try below******************

                int number;
                bool isNumeric = int.TryParse(myString , out number);
if(isNumeric)
{
// Do your TASK with int n
}

             **************** OR Try With Regex******************
              
                var regex = new Regex(@"^[0-9]+$");
if(regex.IsMatch(myString ))
{
return true;
                       //  Do your TASK

}

Monday, 13 February 2017

Get file count from directory using C#



public static void Main()
        {
            var file =new  DirectoryInfo(@"E:\Your Folder path");
            var fileinfo = file.GetFiles("*", SearchOption.AllDirectories);
            foreach (var item in fileinfo)
            {
                Console.WriteLine("File Name => " + item.FullName);
            }
            Console.WriteLine("File total count => " + fileinfo.Length);
            Console.ReadLine();
        }

Note=> you will gave your Directory info path and it will find all find SubDirectory or Directory

//OR we can write in one line like that below .


int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;


but it will gave you how many file are  inside your folder path.

Generate random number using C#



       static object locker = new object();
        public static long Generate15DigitsUniqueNumber()
        {
            try
            {
                lock (locker)
                {
                    Thread.Sleep(100);
                    return Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssff"));
                }
            }
            catch (Exception ex)
            {
                return Convert.ToInt64(DateTime.Now.ToString("yyyyMMddHHmmssff"));
            }
           
        }

OutPut=> 2017021412354472

    // OR using string and byte

        public static string GenerateRandomString(Random rnd)
        {
            byte[] bytes = new byte[255];
            rnd.NextBytes(bytes);
            string szRandom = System.Text.Encoding.ASCII.GetString(bytes);
            char[] c = szRandom.ToCharArray();
            StringBuilder sb = new StringBuilder();
            foreach (char cc in c)
            {
                if (Char.IsLetter(cc))
                {
                    sb.Append(cc);
                }
            }
            return sb.ToString();

        }

       public static void Main()
        {
             Random rnd = new Random();
            Console.WriteLine("RandomPassword={0}", GenerateRandomString(rnd));
        }


OutPut like that=> sEmVYckDVHXpCVkQHhNNbnKNeefGQaWzlvBjlAqQCosDLWzkflER


C# find repeated numbers in an array


Integer Array has  numbers ,some are repeated, if you want to find which number is repeated how many time., Here is the logic using LINQ.

       static   void FindRepeatedNumbers()
        {
             int[] arraytest = new int[] { 50, 20, 100, 10, 30, 10, 30, 20};

            var query = from d in arraytest
                        group d by d into test
                        select test;

            foreach (IGrouping<int, int> intagroup in query)
            {
                Console.WriteLine("Key={0},Repeated {1} Times", intagroup.Key, intagroup.Count());
            }
   }

  1. First group by  each number
  2. there will a unique groups ,then find each group has how many numbers.
Here is the output.

Number=50,Repeated 1 Times
Number=20,Repeated 2 Times
Number=100,Repeated 1 Times
Number=10,Repeated 2 Times
Number=30,Repeated 2 Times