Rhonda Tipton’s WebLog

Random Subject Matters

Archive for the 'C#' Category


File Compression Using the .NET GZipStream Class

Posted by Rhonda Tipton on June 7, 2008

The GZipStream class is a part of the System.IO.Compression namespace. This class is used for the compression of data. Before the .NET 2.0 Framework, the only choice we had for compression were third party tools.

Common Methods (Full List)

  • BeginRead - Begins an asynchronous read operation.
  • BeginWrite - Begins an asynchronous write operation.
  • Close - Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream.
  • EndRead - Waits for the pending asynchronous read to complete.
  • EndWrite - Handles the end of an asynchronous write operation.
  • Read - Reads a number of decompressed bytes into the specified byte array.
  • Write - Writes compressed bytes to the underlying stream from the specified byte array.

Below is a simple C# console application that takes an input file, compresses it and creates a compressed zip file.

C# Listing

using System;
using System.IO;
using System.IO.Compression;

public class GZipTest
{
    private static void usage()
    {
        Console.WriteLine(“My test GZip program”);
        Console.WriteLine(“gziptest [filename to be compressed]“);
    }

    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            usage();
            return;
        }
        else
        {
            string inputFile = args[0];
            string outputFile = inputFile + “.gz”;

            try
            {
                // Get bytes from input stream
                FileStream inFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, inputFile), FileMode.Open);
                byte[] buffer = new byte[inFileStream.Length];
                inFileStream.Read(buffer, 0, buffer.Length);
                inFileStream.Close();

                // Create GZip file stream and compress input bytes
                FileStream outFileStream = new FileStream(Path.Combine(Environment.CurrentDirectory, outputFile), FileMode.Create);
                GZipStream compressedStream = new GZipStream(outFileStream, CompressionMode.Compress);
                compressedStream.Write(buffer, 0, buffer.Length);
                compressedStream.Close();
                outFileStream.Close();

                Console.WriteLine(“The file has been compressed.  UR Da Bomb!!!”);
            }
            catch(FileNotFoundException)
            {
                Console.WriteLine(“Error: Specified file cannot be found.”);
            }
        }
    }
}

The command-line illustration below shows the application at work.

  • If no argument is provided, the usage syntax is echoed to the screen
  • If the argument provided cannot be located, error is echoed to the screen
  • If correct argument is provided, the file is compressed and a new file is created

compression1

The result (compressed) file created.

compression2

View the compressed file in a Zip application.

compression3

The GZipStream class is not as feature-rich as the third-party tools, but it is a convenient way to compress data.

Related Content

Happy programming…

Posted in C# | 2 Comments »

HDNUG Meeting - 04/10/08 - Recap

Posted by Rhonda Tipton on April 12, 2008

I attended the Houston .NET User Group meeting Thursday night where there was a great turnout of well over 100 people.  The sponsor was Clearpoint Technology.

hdnugsmall         clear point

The presentation was given by Mohammad Azam and the topic was LINQ to SQL and Gotchas.  Mohammad is a very interesting presenter and really knows his stuff.  He is what I like to call a coding presenter.  A presenter that codes their samples on the spot and does not have a ton of slides in the slide deck.  Although, he did present his first slide that read “Slide 1 of 347″  (or something like that) as a joke to break the ice.  Well it worked, he had the whole room laughing.

Below are some of the items/points presented.

  • CRUD operations using LINQ to SQL
  • The DelayLoaded property in the data designer
  • Data load options
  • LINQ to SQL as an alternative to calling Stored Procedures from C# code
  • Anonymous Data Types

Mohammad finished the presentation by going over some of the problems he encountered while working with LINQ to SQL.

There was a plethora of information in the presentation - so much it was difficult to note everything.

n663266440_780230_9260     n663266440_780232_9688

Related Content

Posted in C#, Community, LINQ, SQL Server | No Comments »

C# Delegates

Posted by Rhonda Tipton on February 3, 2008

A Delegate is a type that points to a method. Once a Delegate references a method, it behaves just like that method. This means it can be used like a method which includes parameters and return values. Unlike C++ function pointers, delegates are object-oriented, type safe, and secure.

Some Aspects of Delegates

Similar to C++ function pointers, but are type safe
Can be used to define callback methods
Multiple methods can be called on a single event
Methods are allowed to be passed as parameters

Delegate syntax

public delegate void Del(string message);

C# Code Example

using System;

namespace DelegateTest
{
    public delegate void TestDelegate(string message);

    class Program
    {
        public static void Display(string message)
        {
            Console.WriteLine(“”);
            Console.WriteLine(“The string entered is : “ + message);
        }

        static void Main(string[] args)
        {
            //– Instantiate the delegate
            TestDelegate t = new TestDelegate(Display);

            //– Input some text
            Console.WriteLine(“Please enter a string:”);
            string message = Console.ReadLine();

            //– Invoke the delegate
            t(message);
            Console.ReadLine();
        }
    }
}

Result

result.gif

Related Content
Delegates and Events in C# / .NET
C# Delegates Explained
The dark side of C# Delegates

Happy Programming.

Posted in C# | No Comments »

Creating a Data Set From Scratch in C#

Posted by Rhonda Tipton on January 12, 2008

In a previous post, I outlined the process of creating a DataSet graphically using the Visual Studio Data Set Designer. In this post, however, I am going to go through how to create a Date Set from scratch in code. Sometimes it takes doing something from scratch to learn more about the namespaces and classes.

The System.Data namespace provides access to the ADO.NET architecture. It contains several classes that are used to build and interact with data sets.

DataSet
DataTable
DataRow
DataColumn

The below example is simple, but it shows the classes in action.

C# Program Listing

using System;
using System.Data;
namespace CrtDataSet
{
    class Program
    {
        static void Main(string[] args)
        {
            //– Instantiate the data set and table
            DataSet SongDS = new DataSet();
            DataTable songTable = SongDS.Tables.Add();
            //– Add columns to the data table
            songTable.Columns.Add(“ID”, typeof(int));
            songTable.Columns.Add(“Band”, typeof(string));
            songTable.Columns.Add(“Song”, typeof(string));
            //– Add rows to the data table
            songTable.Rows.Add(1, “Breaking Benjamin”, “Diary of Jane”);
            songTable.Rows.Add(2, “Three Days Grace”, “Pain”);
            songTable.Rows.Add(3, “Seether”, “Fake It”);
            songTable.Rows.Add(4, “Finger Eleven”, “Paralyzer”);
            songTable.Rows.Add(5, “Three Doors Down”, “Citizen Soldier”);
            //– Cycle thru the data table printing the values to the screen
            foreach (DataTable table in SongDS.Tables)
            {
                foreach (DataRow row in table.Rows)
                {
                    Console.WriteLine(row["Band"] + ” ~ “ + row["Song"] );
                }
            }
        }
    }
}

DataSet/DataTable in Debug Mode

datasetvisualizer.gif

Result to Console

result1.gif

In a future post, I will be exploring other classes of the System.Data namespace.

kick it on DotNetKicks.com

Posted in C# | No Comments »

Copy/Delete Files in C#

Posted by Rhonda Tipton on December 29, 2007

I have often had the need to programmatically copy files from one location to another. In C#, the System.IO namespace contains the classes needed to deal with file and directory operations.

In the below example, I use the following classes & methods:

Directory
.GetFiles - Returns the names of files in a specified directory.

File
.Exists - Determines whether the specified file exists.
.Copy - Copies an existing file to a new file.
.Delete - Deletes the specified file.

The illustration below shows the source files that are being copied.

C# Code Sample

using System;
using System.IO;

namespace FileCopy
{
  class Tester
  {
    public void Run()
    {
      //– Setup directories and files
      string sourceDirectory = @”c:\temp\source\”;
      string logFile = @sourceDirectory + "CopyTest.log“;
      string targetDirectory = @"C:\temp2\target\“;
      string[] dirs = Directory.GetFiles(sourceDirectory, “*.xls“);

      int numOfFiles = dirs.Length;   //Gets the number of files in the directory

      if (numOfFiles > 0)
      {
        //-- Create/Open log file
        StreamWriter sw = new StreamWriter(logFile);
        sw.WriteLine("Source Directory: {0}“, sourceDirectory);
        sw.WriteLine("Target Directory: {0}“, targetDirectory);
        sw.WriteLine("“);

        //-- Cycle thru the files copying to target then delete
        foreach (string fullFileName in dirs)
        {
          string cpyFileName = Path.GetFileName(fullFileName);

          //-- Set the copy from/copy to parameters
          string sourceFile = sourceDirectory + cpyFileName;
          string targetFile = targetDirectory + cpyFileName;

          //-- Call the copy method
          CopyFiles(sw, sourceFile, targetFile);
        }

        sw.WriteLine("“);
        sw.WriteLine("Process Complete“);
        sw.Close();
      }
    }

    void CopyFiles(StreamWriter sw2, string src, string tgt)
    {
      //-- Copy the source file to the target locations
      File.Copy(src, tgt);
      sw2.WriteLine("Copied ” + src + “ to ” + tgt);

      //-- Delete the source file after making sure it was copied successfully
      if (File.Exists(tgt))
      {
        File.Delete(src);
        sw2.WriteLine("Deleted " + src);
      }
    }

    static void Main(string[] args)
    {
      //– Create new instance of the tester class and execute the Run method
      Tester t = new Tester();
      t.Run();
    }
  }
}

The program also creates a log file and writes to it providing an audit trail.

Related Content
4GuysFromRolla.com : ASP FAQS : System.IO Namespace Classes

Posted in C# | No Comments »

Recursive Directory Search

Posted by Rhonda Tipton on October 28, 2007

This post is to demonstrate a basic process of scanning directories recursively for files with a specified extension (ie *.txt or *.jpg).

The Directory class in the System.IO namespace is used to accomplish most of the task. The Directory class contains many useful methods. The two methods used are GetDirectories and GetFiles.

GetDirectories - retrieves the names of subdirectories in the specified directory.
GetFiles - retrieves the names of the files in a specified directories.

C# PROGRAM

using System;
using System.IO;

namespace DirTest
{
  class RecursiveSearch
  {
     static void Main()
     {
        //– Request top-level directory path
        Console.WriteLine(“Enter the top-level directory path to search in”);
        string dir2search = Console.ReadLine();

        //– Request the file extension
        Console.WriteLine(“Enter the file extension to search for”);
        string ext = “*.” + Console.ReadLine();

        Console.WriteLine(“”);
        Console.WriteLine(“<<– Recursive File Listing for {0} in {1} –>>”,ext.ToUpper(), dir2search.ToUpper());

        //– Call method to recursivly search the directory
        DirSearch(dir2search, ext);
     }

     static void DirSearch(string dir2Search1, string ext1)
     {
        //– If the directory input does not exist, an exception is thrown
        try
        {
            //– Cycle through directories
            foreach (string d in Directory.GetDirectories(dir2Search1))
            {
                //– Cycle through files in directory
                foreach (string f in Directory.GetFiles(d, ext1))
                {
                   Console.WriteLine(f);
                }

                //– Search next directory
                DirSearch(d, ext1);
            }
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
  }
}

RESULTS

Invalid path entered

There are several possible uses for a recursive file search. One that pops into my head would be to search a hard drive for illegal file types or limit the amount of a file type (such as audio or video files).

.

Posted in C# | No Comments »

Tutorials for C# and ASP.NET

Posted by Rhonda Tipton on October 21, 2007

There are many sites that contain great tutorials for C# and ASP.NET. Below are the ones that I have found useful.

The BlackWasp website is great. They have some very useful C# tutorials that they continually add to.

Coder Source also has some good C# Basics and Tutorials available.

When it comes to ASP.NET, I believe the best tutorials can be found in the Learn area of the ASP.NET website; however, there is some good material in the ASP.NET section of the W3Schools website as well.

In closing, there is a huge amount of beginner .NET content online, the sites that I have listed above are ones that have helped me the most. If anyone knows of anymore great tutorial sites, feel from to let me know.

Posted in ASP.NET, C#, Recommendations | No Comments »

Generating a GUID in C#

Posted by Rhonda Tipton on September 30, 2007

A GUID ([goo.id] or [gwid]) or Globally Unique IDentifer is a type of identifier used to distinguish a particular application, file or user. I have started working on a project in which we use GUIDs extensively in our databases. In the .NET framework the System.Guid.NewGuid method is used to generate the unique identifiers. In SQL Server, the uniqueidentifier data type is used to store the GUIDs.

Below is a simple console application that uses the Guid.NewGuid method.

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Data;
   4: using System.Data.OleDb;
   5: using System.Data.SqlClient;
   6:
   7: namespace foo
   8: {
   9:     class Program
  10:     {
  11:         static void Main(string[] args)
  12:         {
  13:             //– Initialize variables for the unique id, artist & name
  14:             string cdartist = Console.ReadLine();
  15:             string cdname = Console.ReadLine();
  16:             Guid id = new Guid();
  17:
  18:             //– Create new GUID and echo to the console
  19:             id = Guid.NewGuid();
  20:             Console.WriteLine(“New GUID: {0}”, id.ToString());
  21:
  22:             //– Setup a quick connection to the database
  23:             string connString = @”Data Source=.\SQLExpress;Integrated Security=true;Initial Catalog=Foo1″;
  24:             SqlConnection dbConn = new SqlConnection(connString);
  25:             dbConn.Open();
  26:
  27:             //– Setup SQL command
  28:             SqlCommand dbCommand = dbConn.CreateCommand();
  29:             dbCommand.CommandText = “INSERT INTO Test (id, cdartist, cdname) VALUES (@id, @cdartist, @cdname)”;
  30:
  31:             //– Setup values to be inserted
  32:             SqlParameter idParameter = new SqlParameter(“@id”, SqlDbType.UniqueIdentifier);
  33:             idParameter.Value = id;
  34:             dbCommand.Parameters.Add(idParameter);
  35:
  36:             SqlParameter cdartistParameter = new SqlParameter(“@cdartist”, SqlDbType.VarChar, 30);
  37:             cdartistParameter.Value = cdartist;
  38:             dbCommand.Parameters.Add(cdartistParameter);
  39:
  40:             SqlParameter cdnameParameter = new SqlParameter(“@cdname”, SqlDbType.VarChar, 50);
  41:             cdnameParameter.Value = cdname;
  42:             dbCommand.Parameters.Add(cdnameParameter);
  43:
  44:             //– Insert the values into the table and close the connection
  45:             SqlDataReader dbReader = dbCommand.ExecuteReader();
  46:             dbReader.Close();
  47:             dbConn.Close();
  48:         }
  49:     }
  50: }

Result

I believe a GUID is just about as close as you can get to a truly unique identifier. According to Wikipedia, each generated GUID is not guaranteed to be unique, but the total number of uniqe keys is so large that the probability of the same number generating twice is very small.

Related Links
Generate unique strings and numbers in C# - Mads Kristensen
GUIDs and DataSource Controls - Dan Wahlin

Posted in C# | No Comments »

Math Operations in .NET

Posted by Rhonda Tipton on August 18, 2007

The System.Math class is used to perform a number of mathematical operations. The operations include normal math such as addition, subtraction, multiplication, division as well as exponentiation, trigonometry and algebra (see list below).

Some of the members of the System.Math class include the following:

  • Trigonometric functions (Sin, Cos, Tan, etc)
  • Logarithmic functions (Log and Log10)
  • Logarithmic functions (Log and Log10)
  • Constants (PI and E)
  • Power functions (Exp, Pow, and Sqrt)
  • Boundary functions (Floor, Ceiling)
  • Comparative functions (Max, Min)
  • Sign-related functions (Abs)

Common Methods (Full List)

C# Code Sample

   1: using System;
   2: namespace MyNamespace
   3: {
   4:     class MyClass
   5:     {
   6:         static void Main()
   7:         {
   8:             Console.Write(“Enter a number: “);
   9:             string inpNumber = Console.ReadLine();
  10:             int theNumber = Convert.ToInt32(inpNumber);
  11:
  12:             if (theNumber == 0)
  13:             {
  14:                 Console.WriteLine(“Cannot use 0″);
  15:             }
  16:             else
  17:             {
  18:                 Console.WriteLine();
  19:                 Console.WriteLine(“Valid Operations: sr=square root, abs=absolute value, sign=sign”);
  20:                 Console.WriteLine();
  21:                 Console.Write(“Enter an Operation: “);
  22:                 string inpOperation = Console.ReadLine();
  23:
  24:                 switch (inpOperation)
  25:                 {
  26:                     case “sr”:
  27:                         double squareRootNumber = Math.Sqrt(theNumber);
  28:                         Console.WriteLine();
  29:                         Console.WriteLine(“The answer is {0}”, squareRootNumber.ToString());
  30:                         Console.WriteLine();
  31:                         break;
  32:                     case “abs”:
  33:                         double absNumber = Math.Abs(theNumber);
  34:                         Console.WriteLine();
  35:                         Console.WriteLine(“The answer is {0}”, absNumber.ToString());
  36:                         Console.WriteLine();
  37:                         break;
  38:                     case “sign”:
  39:                         decimal signNumber = Math.Sign(theNumber);
  40:                         Console.WriteLine();
  41:                         Console.WriteLine(“The answer is {0}”, signNumber.ToString());
  42:                         Console.WriteLine();
  43:                         break;
  44:                     default:
  45:                         Console.WriteLine();
  46:                         Console.WriteLine(“Invalid Operation”);
  47:                         Console.WriteLine();
  48:                         break;
  49:                 }
  50:             }
  51:         }
  52:     }
  53: }

Results

Square Root

Absolute Value

The System.Math class can be useful when performing mathmatical operations.

Posted in C# | No Comments »

Using the .NET Process Class

Posted by Rhonda Tipton on July 1, 2007

The Process class provides the means to monitor system processes and to start and stop system processes. It is lo