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

Find unique characters from string in C#


       Below code will help out , how to find unique characters from string .

       char[] chars = "abdccddbbzcyxzwwwww"?.ToCharArray();
            {
             var dic = new Dictionary<char, int>();
                 foreach (var c in chars)
                {
                    if (!dic.ContainsKey(c))
                    {
                        dic[c] = 0;
                    }
                    dic[c]++;
                }
                foreach (var charCombo in dic)
                {
                    if (charCombo.Value == 1)
                    {
                        Console.WriteLine(charCombo.Key.ToString());
                    }
                }
             
            }