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