Category Archives: C#

Stripping the Decimal From a Value in .NET

I am working on a project in which the final output is an EDI file that is translated into claims by the state. I had an issue in which I needed to strip the decimal point from both amount and diagnosis code fields. They also need to be right justified and padded with zeroes. (ie, 123.98 = 00012398)

Coming from a Visual FoxPro background, I knew how to do this in that language, but not in C#. I was able to accomplish my task by using the Replace and PadLeft methods which can be found in String Class.

C# Program

using System;
namespace StripDecimal_CS
{
  class RemoveDecimal
  {
     static void Main(string[] args)
     {
         double testNum = 255.95;
         string noDecimalVal = 
             testNum.ToString().Replace(".", "").PadLeft(9, '0');
         
         Console.WriteLine("Original Value: " + testNum.ToString());
         Console.WriteLine("Value w/No Decimal: " + noDecimalVal);
     }
  }
}

C# Listing on GitHub

VB.NET Program

Imports System
Namespace StripDecimal_VB
    Class RemoveDecimal
        Shared Sub Main(ByVal args As String())
            Dim testNum As Double = 255.95
            Dim noDecimalVal As String = _
                testNum.ToString().Replace(".", "").PadLeft(9, "0"c)

            Console.WriteLine("Original Value: " + testNum.ToString())
            Console.WriteLine("Value w/No Decimal: " + noDecimalVal)
        End Sub
    End Class
End Namespace

VB.NET Listing on GitHub

 

The Result

stripdecimalresult

Until later…

The C# Null Coalescing Operator (??)

I was looking through some code the other day and ran across something that looked remotely familiar.  It was the null coalescing (??) operator.  I had read about this operator, but never used it.  It was introduced with the .NET 2.0 Framework.

The null coalescing operator basically checks to see if a value is null and if so returns an alternate value.  Below is a simple example.

View the C# code sample [HERE] 

Results

Related Content

“I am learning all the time.  The tombstone will be my diploma.” -Eartha Kitt

Houston C# SIG Meeting – 07/15/08 – Recap

I attended both the Beginning C# and C# Special Interest Group meetings tonight.  The meetings were held at the Microsoft Houston office rather than the normal HAL-PC office and in my opinion had a much better turnout.  There were about 25-28 in attendance for the Beginning C# and an additional 15-20 showed up for the regular C# (Total ~45).

The Beginning C# SIG topic was Classes and Interfaces.  Bobby Schaffer gave a great overview and followed by stepping through a console application that performed banking calculations.

The speaker for the C# SIG was J Sawyer and the topic was ASP.NET Dynamic Data.  Wikipedia defines ASP.NET Dynamic Data as follows:  "ASP.NET Dynamic Data is a web application scaffolding framework from Microsoft, shipped as an extension to ASP.NET, that can be used to build data driven web applications. It exposes tables in a database by encoding it in the URI of the ASP.NET web service, and the data in the table is automatically rendered to HTML. The process of rendering can be controlled using custom design templates. Internally, it discovers the database schema by using the database metadata."

Below is an overview of what was discussed.

J went through some great examples in which he built a Dynamic Data web site containing a maintenance grid.  The grid was editable and was created with little to no code.  He also went over the importance of server-side validation as well as several aspects of security.

All in all, it was a great meeting and a great turnout.  I honestly hope the move to the Microsoft office is permanent.

C# SIG Presentation – Slides and Demo

File Compression Using the .NET GZipStream Class

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.

View the C# code sample [HERE]

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…

HDNUG Meeting – 04/10/08 – Recap

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

C# Delegates

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);

Source Code Example (C#)

Source Code Example (VBNET)

Result

result.gif

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

Happy Programming.

Creating a Data Set From Scratch in C#

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"]);
                }
            }
        }
    }
}

C# Listing on GitHub

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

Copy/Delete Files in C#

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

Recursive Directory Search

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).

.

Tutorials for C# and ASP.NET

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.

Follow

Get every new post delivered to your Inbox.