Getting Different Shapes of * Using Loops…

         To improve the logical thinking using For loops. In this part I am using only two for loops to print the different shapes.

LEFT ALIGNMENT – straight

Here I am using number n as maximum value. Instead can use a variable to get a value from user
        Console.WriteLine(“—————————“);
         for (int i = 0; i <= n; i++)            
         {              
              for (int j = 0; j < i; j++)  
              {                  
                  Console.Write(“*”);      
                }    
            Console.WriteLine();  
         }

In the above code I used two for loops. In the outer loop I used the variable “i” and it will run ascending order from 1 to n.In the inner loop I used variable “j” runs from

zero to till the value of outer “i”.

for (int j = 0; j < i; j++)

For an example

When “i” value is zero, the inner loop will not run

When “i” value is one the inner loop will run 1 time prints single star —  *

  Now we have Writline() method which prints new line.

  When “i” value is two the inner loop will run 2 time prints single star —  **

then prints new line.

Like this the inner loop runs from 1 to current value of outer loop “i” . In our case it is up to 5. So we will get the output as follows :

* ** *** **** *****

LEFT ALIGNMENT – Reverse

  If we want to print the stars in reverse triangle then we need to iterate the outer loop from max value to min value. The inner loop “j” runs from 0 to current iteration value of outer “i” 

          for (int i = n; i >= 1; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
            Console.WriteLine("---------------------------");
 

Lets take n=5.At the first iteration ,then “i’ value will be 5.

Now the inner loop runs from 5 to 1 and prints *****

At the end of inner loop I print a new line. So that next iteration starts in new line

At next iteration **** will come. Similarly at the end of both loops we get the following triangle of stars

*****

****

***

**

*

 

If we write both codes one after another we will get a triangle facing right hand side.

*

**

***

****

*****

*****

****

***

**

*

RIGHT ALIGNMENT -Straight

The above code shows the triangle of stars facing right hand side. Similarly if we want to print the triangle of stars facing left hand side, we have the code as follows:

       Console.WriteLine("---------------------------");
            for (int i = 5; i >= 0; i--)
            {
                for (int j = 0; j < 5; j++)
                {
                    if (i > j)
                        Console.Write(" ");
                    else
                        Console.Write("*");
                }
                Console.WriteLine();
            }

 In the above code the outer loop starts from 5 to 0 and inner loop also runs from 0 to 5.So we will be having 25 iterations totally.Here I have added a if condition so that the stars start to print after leaving the required white spaces. I am printing SPACE if “if” condition is true and Star if condition fails.

At the first iteration of outer for loop, the “i” value will be 5.

So in inner loop, the i value will be checked for the each iteration of inner “j” loop.

So now — if (i >j)

if (5>0) condition true so it prints SPACE

if (5>1) condition true so it prints SPACE.

.

.

if (5>5) condition fails  so it prints SPACE.

At the end of 1st iteration of outer for loop

 

SPACE SPACE SPACE SPACE SPACE

In the 2nd iteration the i value will be 4, now in inner loop

if (4>0) condition true so it prints SPACE

if (4>5) condition fails so it prints *

At the end of the 2nd iteration of outer for loop we have

SPACE SPACE SPACE SPACE *

Similarly after running other values of “i” and “j”

we get

    *
   **
  ***
 ****
*****

RIGHT ALIGNMENT -Reverse

TO print the stars in reverse direction with right alignment we have

           for (int i = 0; i < 5; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    if (i < j)
                        Console.Write("*");
                    else
                        Console.Write(" ");
                }
                Console.WriteLine();
            }

In this code we have the made some changes of previous logic as of above code (Right alignment – Straight)

we need to iterate the outer for loop in ascending direction and checking the if condition.

We print * if condition is true and SPACE if condition fails

Here the outer loop starts from 0 to 5

At first iteration i=0; In inner loop j starts from 1

we are checking i less then j

so now  —> if (i<j)

   if (0<1) condition true so it prints Star *

if (0<2) condition true so it prints Star *

.

.

if (0<5) condition true so it prints Star *

At the end of 1st iteration of outer for loop

 

*****

In the 2nd iteration the i value will be 1, now in inner loop

if (1<1) condition fails so it prints SPACE

if (1<2) condition true so it prints Star *

if (1<5) condition true so it prints Star *

At the end of the 2nd iteration of outer for loop we have

SPACE ****

Similarly after running other values of “i” and “j”

*****

 ****

  ***

   **

    *

If we write both codes one after another we will get,

    *
   **
  ***
 ****
*****
*****
 ****
  ***
   **
    *

We get a triangle that faces towards left side.

SQUARES

To get the square with diagonals, horizontal and vertical lines like below:

***********************

**         *         **

* *        *        * *

*  *       *       *  *

*   *      *      *   *

*    *     *     *    *

*     *    *    *     *

*      *   *   *      *

*       *  *  *       *

*        * * *        *

*         ***         *

***********************

*         ***         *

*        * * *        *

*       *  *  *       *

*      *   *   *      *

*     *    *    *     *

*    *     *     *    *

*   *      *      *   *

*  *       *       *  *

* *        *        * *

**         *         **

***********************

At first we need to look at the square with whole stars

                   012...                22--->j values i=0  *********************** i=1  *********************** i=2  ***********************      ***********************      ***********************      ***********************      ***********************      ***********************

        ......

i=20 *********************** i=21 ***********************

The code is as follows:

           int n = 23;            
           for (int i = 0; i < n; i++)  
            {            
                for (int j = 0; j < n; j++)    
                 {        
                      if ((i == 0) || (j == 0) || (i == n - 1) || (j == n - 1) || (i == n / 2) || (j == n / 2) || (i == j) || (i + j == n - 1))  
                      {  
                           Console.Write("*");      
                       }          
                      else              
                       {    
                        Console.Write(" ");    
                       }
                   }
              Console.WriteLine();
            }

Here I have a integer variable “n” value 23. For this example the odd numbers woule be better to use to see the results.

Here also I have two loops and both starts from zero to “n” value.

As per our example:

The outer “i”  loop will run from 0 to 23 and  for each iteration of outer loop, the inner “j” will run from 0 to 23.

I have written 8 conditions. Note that I am using OR operator so that if any one conditon gets true the star will be printed. In else part SPACE will be printed.

The first condition i==0

This condition gets true at the first iteration of outer loop. So we get top most horizontal line of square.

***********************

The second condition is j==0, this condition gets true on each first iteration of “j” loop so we will get vertical line at the left most line of square.

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

The third condition prints bottom most horizontal line of square at the last iteration of i loop ———->     (i==n-1)

and fourth condition prints the right most vertical line of square when last iteration of “j” loops occurs each time. ————> (j==n-1)

If we have only these four condition we will be having a square as follows:

***********************

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

*                     *

***********************

Now in fifth condition i== n/2 , in our case the value will be 23/2 –> 11. Hence in 11th row that is when outer i in 11th value the horizontal line will be printed at the middle of square.

Similarly to get the vertical line in middle of square we have the sixth condition j== n/2 which is also 11.

To Print Diagonals:

when i==j prints diagonal from left to right.

If we look at square left to right diagonal will come when i value is equal to j

*   ---> i=j=0
 *
  * ---> i=j=2
   *
    *
     *
      *
       *
        *
         *
          *
           *
            *
             *
              *
               *
                *
                 *
                  *
                   *
                    *
                     *
                      * ---> i=j=22

For printing right to left diagonal of square, I am adding i and j and checking the sum is 22. Because when i is zero and j starts from 1 then the condition gets true when j is 22

so when i is 0

 0+22(j value) = 22

when i is 1

       1+21(j value) = 22

like this

when i is 22

       22+0(j value) = 22

Like this we will get

                             * ----> i val is 0 j val is 22
                     * ----> i val is 1 j val is 21
                    * ----> i val is 2 j val is 20
                   *
                  *
                 *
                *
               *
              *
             *
            *
           *
          *
         *
        *
       *
      *
     *
    *
   *
  *
 * ----> i val is 21 j val is 1
* ----> i val is 22 j val is 0

Creating a registry entry in Wix installer.

What is the registry?

    The registry is a database in Windows that contains important information about system hardware, installed programs and settings, and profiles of each of the user accounts on your   computer. Windows continually refers to the information in the registry.

         You should not need to make manual changes to the registry because programs and applications typically make all the necessary changes automatically. An incorrect change to your computer’s registry could render your computer inoperable. However, if a corrupt file appears in the registry, you might be required to make changes.

registry.gif

//RootKey

 <RegistryKey Root=”HKLM” Key=”Software\Sample” Action=”createAndRemoveOnUninstall” ForceCreateOnInstall=”yes” ForceDeleteOnUninstall=”yes”>

        //SubKey 

        <RegistryKey Key=”Folder1″ ForceDeleteOnUninstall=”yes”>

                 <RegistryKey Key=”Folder2″ ForceDeleteOnUninstall=”yes”>

                   //KEY VALUE PAIR

                       <RegistryValue Name=”KeyName” Value=”KeyValue” Type=”string” KeyPath=”no”/>

                       <RegistryValue Name=”KeyName1” Value=”KeyValue1” Type=”string” KeyPath=”no”/>               

                    </RegistryKey>

          </RegistryKey>

  </RegistryKey>

Create New Thread [C#]

This example shows how to create a new thread in .NET Framework. First, create a newThreadStart delegate. The delegate points to a method that will be executed by the new thread. Pass this delegate as a parameter when creating a new Thread instance. Finally, call theThread.Start method to run your method (in this case WorkThreadFunction) on background.


[C#]

using System.Threading;

Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();

The WorkThreadFunction could be defined as follows.

[C#]

public void WorkThreadFunction()
{
  try
  {
    // do any background work
  }
  catch (Exception ex)
  {
    // log errors
  }
}

Force Download Pdf File in C# (Asp.Net Mvc 4)

In my project, I tried to download a pdf file where pdf file is located within my project. I tried  to  download file by binding the path to <a href=”url”/>  and window.open=URL but i Cant able to achieve that because of some default properties of browser. 

         You should look at the “Content-Disposition” header; for example setting “Content-Disposition” to “attachment; filename=FileName.pdf” will prompt the user (typically) with a “Save as: FileName.pdf” dialog, rather than opening it.

       This, however, needs to come from the request that is doing the download, so you can’t do this during a redirect. However, ASP.NET offers Response.TransmitFile for this purpose. For example (assuming you aren’t using MVC, which has other preferred options):

Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf");
Response.TransmitFile(filePath);
Response.End(); 

If You Are try to open then the file in ApiController Convert Stream to BytesArray and then Fill the content

            HttpResponseMessage result = null;
            result = Request.CreateResponse(HttpStatusCode.OK);
            FileStream stream = File.OpenRead(path);
            byte[] fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();           
            result.Content = new ByteArrayContent(fileBytes);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "FileName.pdf";  

Creating Zip File Having Pdf Files Generated From stream(link).

In this I am creating a Zip File Having pdg files(get from a link).

       
 using (var outStream = new MemoryStream())
 {
   using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
   {
     for (String Url in UrlList)
     {
       WebRequest req = WebRequest.Create(Url);
       req.Method = "GET";
       var fileInArchive = archive.CreateEntry("FileName"+i+ ".pdf", CompressionLevel.Optimal);
       using (var entryStream = fileInArchive.Open())
       using (WebResponse response = req.GetResponse())
        {
         using (var fileToCompressStream = response.GetResponseStream())
           {
             entryStream.Flush();
             fileToCompressStream.CopyTo(entryStream);
             fileToCompressStream.Flush();
            }
        }
          i++;
       }
   }
   using (var fileStream = new FileStream(@"D:\test.zip", FileMode.Create))
   {
      outStream.Seek(0, SeekOrigin.Begin);
      outStream.CopyTo(fileStream);
   } 
 }
Namespace Needed:
   using System.IO.Compression;
   using  System.IO.Compression.ZipArchive;

Reading And Writing A Zip file Using ZipArchive.


Reading Zip File:

After calling ZipFile.Open, we can loop over the individual entries within the ZIP file by using the Entries property on the ZipArchive class. We use the 
using-statement for cleaner code.
To start: 

please create a “Sample.zip” file. You can do this directly in the Windows operating system by creating a new compressed folder. Drag a file “testsample.txt” to the new ZIP file to add it.

    using System.IO.Compression;
 class Program { static void Main() { 
// ... Get the ZipArchive from ZipFile.Open. 
using ( 
                ZipArchive archive = 
                ZipFile.Open(@"C:\folder\Sample.zip", ZipArchiveMode.Read))
    { 
// ... Loop over entries. 
foreach ( 
                ZipArchiveEntry entry in archive.Entries) 
       { 
// ... Display properties.
 // Extract to directory. 
Console.WriteLine("Size: " + entry.CompressedLength); 
Console.WriteLine("Name: " + entry.Name); 
entry.ExtractToFile(@"C:\folder\" + entry.Name); 
          } 
       } 
    }
 }

Creating Zip File:
CASE 1:Creating File at the Time of creating entry in ZipArchive

        
               using (var memoryStream = new MemoryStream())
            {
            using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    var demoFile = archive.CreateEntry("Sample.txt");

                    using (var entryStream = demoFile.Open())
                    using (var streamWriter = new StreamWriter(entryStream))
                    {
                        entryStream.Flush();
                        streamWriter.Write("Bar!");
                    }
                }

                using (var fileStream = new FileStream(@"D:\test.zip", FileMode.Create))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    memoryStream.CopyTo(fileStream);
                }
            }

CASE 2:Reading anotherfile and creating entries in Zip Archive.

        
            using (var memoryStream = new MemoryStream()) {
     using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
     var demoFile = archive.CreateEntryFromFile("Path","EntryName");
                  
     }
     using (var fileStream = new FileStream(@"D:\test.zip", FileMode.Create))
        {
             memoryStream.Seek(0, SeekOrigin.Begin);
              memoryStream.CopyTo(fileStream);
         }
    }             
        
       

Creating A Zip File From in c#.

ZipFile:
The ZipFile class makes it easy to compress directories(.NET 4.5). With CreateFromDirectory, we specify an input folder and an output file. A compressed ZIP file is created. To expand a compressed folder, we use ExtractToDirectory.

Namespace: 
System.IO.Compression.FileSystem.
The directory we want to compress is “sourcepath.” The output file is “destinationpath“.

NOTE:
This program will cause an error if it is run twice. You must manually delete the previous output files for correct operation.

Code for Zip files in a directory:

 using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
string sourcepath = @"c:\example\start";            
string destinationpath=@"c:\example\result.zip";
string extractPath = @"c:\example\extract";      ZipFile.CreateFromDirectory(sourcepath,destinationpath,CompressionLevel.Fastest, true); 
ZipFile.ExtractToDirectory(destinationpath,extractPath);  
 }   
 }
}              
            

 


 


Downloading A file in c# from DownloadLink.

Even a three line code will make you to sit for long time.In my project , I need to group  number of files from a downloadlink (one link for each) and need to zip them under a file.so I have decided to download a file from a link in c#.

STEPS INVOLVED:

STEP 1:

   Create a WebRequest instance by calling Create with the URI of the resource.

     WebRequest request =WebRequest.Create(
“URL”);
STEP 2:
Set any property values that you need in the WebRequest. For example, to enable authentication, set the Credentials property to an instance of the 
NetworkCredential
 class.
request.Credentials = CredentialCache.DefaultCredentials; STEP 3:

To send the request to the server,call GetResponse object.
RETURN VALUE
: Depend on the Schema of the Requested URI.

WebResponse response = request.GetResponse();

NOTE: 

1. After finished with a WEBRESPONSE object,you must close it by calling 
the close method.

2. Alternatively ,if you have the Response stream from the res ponse object,
you can close the stream.
STEP 4:

To get the stream,containg response data send by the server, use the GetResponseStream method of the WebResponse.
Stream dataStream = response.GetResponseStream();

STEP 5:

After reading the data you must close the stream/close the WebResponse.

dataStream.close();

response.close();

Code To download Pdf/Any OtherFile From a link:

            Stream ms = new  MemoryStream();       
             FileStream file = new  FileStream("d:FileName.pdf", FileMode.Create, FileAccess.Write);                
             WebRequest req =  WebRequest.Create("URL");
             req.Method = "GET";               
             using ( WebResponse response = req.GetResponse())
             {                    
             using ( Stream newstream = response.GetResponseStream())
              {
                newstream.CopyTo(file);
                newstream.Close();
               }
              }

 


 


 


 


 

Crazy Weekend -Creating a star Programattically.

Its really good to work logically by using some basic concepts such as for and if condition.In this blog ,I created star.I know it is little bit crazy but while learning and working with new technology its time to go with some basics.

Code In c#:

 public void printStar(int n)
        {
            int i, j;
            int total = 4 * n + 1;
            int Mid = total / 2;
            if (total<=79)
            {
                for (i = 0; i <n; i++)
                {
                    for (j = 0; j < total; j++)
                    {
                        if (j >= Mid - i && j <= Mid + i)
                            System.Console.Write('*');
                        else
                            System.Console.Write(' ');
                    }
                    System.Console.WriteLine();
                }
                for (i = 0; i <= n; i++)
                {
                    for (j = 0; j < total; j++)
                    {
                        if (j >= i && j < total - i)
                            System.Console.Write('*');
                        else
                            System.Console.Write(' ');
                    }
                    System.Console.WriteLine();
                }

                for (i = 0; i <n; i++)
                {
                    for (j = 0; j < total; j++)
                    {
                        if (j < n || j >= total - n || (j >=Mid - i                          && j <= Mid + i))
                            System.Console.Write(' ');
                        else
                            System.Console.Write('*');
                    }
                    System.Console.WriteLine();
  
            }
          
            }

            System.Console.ReadLine();

        }


OUTPUT: