Archive

Archive for the ‘C#’ Category

Using GetProperties() in C#

February 28, 2010 Rhonda 2 comments

Reflection, in the simple terms, is the ability to extract information about an object during runtime. I found a great explanation of why Reflection is used in a tutorial titled Reflection in C#.

With reflection we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If Attributes (C#) are used in application, then with help of reflection we can access these attributes. It can be even used to emit Intermediate Language code dynamically so that the generated code can be executed directly.

I have been doing some research and test apps using the GetProperties method. GetProperties basically returns array of PropertyInfo objects.

Sample Program

using System;
using System.Reflection;

class Program
{
    static void Main(string[] args)
    {
        var person = new Person
        {
            Name = "Rhonda",
            FaveShow = "Fringe, Lost",
            FaveMovie = "Star Trek",
            FaveSong = "Contagious"
        };

        var type = typeof(Person);
        var properties = type.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine("{0} : {1}",
                             property.Name, property.GetValue(person, null));
        }

        Console.Read();
    }
}

public class Person
{
    public string Name { get; set; }
    public string FaveShow { get; set; }
    public string FaveMovie { get; set; }
    public string FaveSong { get; set; }
}

C# Listing on GitHub 

As you can see below there are several other methods available as well as GetProperties.

Reflection1

 

Output

Reflection2

 

Additional Information

^..^

Categories: .NET General, C#

HDNUG Meeting – 02/11/10 – Recap

February 14, 2010 Rhonda Leave a comment

I attended the February Houston .NET User Group meeting. There was a great turnout (80-90) considering how bad the weather was. The sponsor was New Horizons, an independent IT training company.

hdnuglogo       newhorizons

Announcements
Some people from TechSmith will be here for next month’s meeting
Meeting #100 is coming up quick. There will possibly be big prizes

Main Presentation
Markus Egger from EPS Software did a great presentation on C# 4.0 focusing mainly on the Dynamic aspects.

eps     codemag  

Types of .NET Lanuages

  • Traditional – C#, VB.NET
  • Functional – F# — Book recommendation: Expert F#
  • Dynamic – IronPython, IronRuby

Dynamic (Python, Ruby, JavaScript) – Advantages

  • Simple
  • Implicitly typed
  • No compilation

One of the main disadvantages of dynamic languages is the lack of Intellisense support.

Static (C#, VB.NET) languages – Advantages

  • Performant
  • Intelligent tools
  • Better scaling

DLR – Dynamic Language Runtime

dlr

DynamicObject class

REST

Named and Optional Parameters

Improved COM Support

Markus Egger’s Information

hdnugpic2     hdnugpic1

^..^

Categories: .NET General, C#, Community

Houston C# SIG Meeting – 01/19/10 – Recap

February 2, 2010 Rhonda Leave a comment

A couple of weeks ago I attended the Houston C# SIG meeting. Ken Getz did presentations on both Silverlight and LINQ to Objects.

Silverlight

Ken defined Silverlight as a programmable browser plugin that supports animations, vector graphics and videos.

Some features include –

  • Works on Mac/Linux/Windows
  • Client-side technologies
  • Uses XAML for declarative design
  • Expression Blend – best software to use for Silverlight/XAML design
  • Visual Studio 2010 includes the components needed to build Silverlight apps out of the box

The following site allows you to verify if your pc is able to run Silverlight applications http://www.microsoft.com/silverlight/get-started/install/default.aspx

Silverlight is basically an HTML page with an <object> tag.

LINQ to Objects

There are several LINQ providers –

  • Objects
  • SQL
  • DataSets
  • XML
  • Entities

Example Usage

string[] geeks = { “Sheldon”, “Leonard”, “Howard”, “Raj”};

var myQuery = from g in geeks
              orderby g
              select g;

Console.WriteLine(“My Favorite Geeks”);

foreach (var x in myQuery)
{
    Console.WriteLine(x);
}

image

Ken provided a very informative presentation on LINQ to Objects and I am glad I was able to catch it.

Ken’s LINQ demo code

^..^

Categories: .NET General, C#, Community

More on Timers in .NET

December 5, 2009 Rhonda 1 comment

In a previous post, I mentioned the three types of timers in the .NET Framework. In the comments of that post I had someone ask about the differences in why/when to use the different timers, so I thought I would do a little more research. 

I posted this inquiry to the ALT.NET Google Group and received the following responses:  

Ben Scheirman 

Windows Forms timers are more to update things on the UI.

System.Threading.Timer is for performing timed actions in any .NET code.
For example, say you want to execute a function, but at a later time…
like “Call this method in 10 seconds”.  You can also set it up to execute
some code at a regular interval.

The short answer, use WinForms timer when you’re working on a WinForm, and
use Threading.Timer everywhere else.

Mohammad Azam suggested a great article that goes into great detail by Comparing the Timer Classes in the .NET Framework Class Library.

High point quotes from the article:

[Talking about Windows.Forms.Timer] Just like the rest of the code in a typical Windows Forms application, any code that resides inside a timer event handler (for this type of timer class) is executed using the application’s UI thread. During idle time, the UI thread is also responsible for processing all messages in the application’s Windows message queue.

The System.Timers.Timer class will, by default, call your timer event handler on a worker thread obtained from the common language runtime (CLR) thread pool. This means that the code inside your Elapsed event handler must conform to a golden rule of Win32 programming: an instance of a control should never be accessed from any thread other than the thread that was used to instantiate it.

[Talking about System.Threading.Timer] Instances of this class are not inherently thread safe, given that it resides in the System.Threading namespace. (Obviously, this doesn’t mean it can’t be used in a thread-safe manner.) The programmatic interface of this class is not consistent with the other two timer classes and it’s also a bit more cumbersome.

From reading this article and the replies to my inquiry on the ALT.NET Google Group, it sounds like if your needing a timer for the UI, use System.Windows.Forms.Timer; otherwise, the System.Threading.Timer is the way to go.

^..^

Categories: .NET General, C#

Method Overloading

November 27, 2009 Rhonda 3 comments

Polymorphism is one of the main characteristics of Object Oriented Programming (OOP). Put simply, it allows an object to behave in various ways depending on the manner in which it is used. For example, you could have a method execute differently based on the type and/or number of parameters passed to it. Method Overloading is what makes this example possible.  To accomplish Method Overloading, a developer can define two or more methods with the same name. Each method will take a different set of parameters.  The parameter combination or signature, is what the compiler uses to determine which method to use.

image

Good examples of Method Overloading in the .NET Framework include (but are not limited to) the Console.WriteLine() and Substring() methods.  You can pass different types to the Console.WriteLine() method and it will work because there are variations of the methods that will accept the different types.

image

C# Program

using System;
namespace MethodOverloading
{
  class Program
  {
     static void Main(string[] args)
     {
         MethodOverloadPlay(10, 3);
         Console.WriteLine("+++++");
         MethodOverloadPlay(5, 5, 6);
         Console.WriteLine("+++++");
         MethodOverloadPlay("SP");
         Console.ReadLine();
     }

     static void MethodOverloadPlay(int number1, int number2)
     {
         int result = number1 + number2;
         Console.WriteLine(result);
     }

     static void MethodOverloadPlay(int number1, int number2, int number3)
     {
         int result = number1 + number2 + number3;
         Console.WriteLine(result);
     }

     static void MethodOverloadPlay(string string1)
     {
         Console.WriteLine("Breaking Benjamin & Sick Puppies Rock!");
     }
  }
}

C# Listing on GitHub 

Result

method-overloading_result

The main advantage of Method Overloading is code readability. Programming languages that do not allow Method Overloading require the developer to create totally separate methods for each variation of the input.  Blackwasp Consulting states the following example: in the ANSI C programming language to truncate a value you would use trunc, truncf or truncl according to the data type being rounded.  In C#, method overloading allows you to always call Math.Truncate.

Additional Information

^..^

Categories: .NET General, C#, Development

Timers in .NET

November 6, 2009 Rhonda 4 comments

I was researching timers the other day and realized that there are three variations in the .NET Framework.

stopwatch

The three types of timers are explained below.

1 – System.Timers.Timer

The System.Timers.Timer class timer is considered a server-based timer that was designed and optimized for use in multithreaded environments. It can be accessed safely from multiple threads.

C# Program

using System;
using System.Timers;

public class Program
{
  private static System.Timers.Timer testTimer;

  public static void Main(string[] args)
  {
    testTimer = new System.Timers.Timer(5000); // 5 seconds
    testTimer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);

    testTimer.Interval = 5000;
    testTimer.Enabled = true;

    Console.WriteLine("Press the enter key to stop the timer");
    Console.ReadLine();

  }

  private static void OnTimerElapsed(object source, ElapsedEventArgs e)
  {
    Console.WriteLine("Timer elapsed at {0}", e.SignalTime);
  }
}

C# Listing on GitHub 

 

Output

image

2 – System.Threading.Timer

The System.Threading.Timer class timer uses a TimerCallBack Delegate to specify the associated methods. The methods do not execute in the thread that created the timer; they execute in a separate thread that is automatically allocated by the system.

C# Program

using System;
using System.Threading;

class Program
{
  static void Main()
  {
     AutoResetEvent reset = new AutoResetEvent(false);
     StatusChecker status = new StatusChecker(5);

     // Invoke methods for the timer via a Delegate
     TimerCallback timerDelegate = new TimerCallback(status.CheckStatus);

     // Create a timer that signals the delegate to invoke
     // Check status after one second, and then every 1/4 second
     Console.WriteLine("{0} Creating the timer.\n",
         DateTime.Now.ToString("h:mm:ss.fff"));

     Timer stateTimer = new Timer(timerDelegate, reset, 1000, 250);

     // When the auto reset executes, change to every 1/2 second
     reset.WaitOne(5000, false);
     stateTimer.Change(0, 500);
     Console.WriteLine("\nChanging the timer period.\n");

     reset.WaitOne(5000, false);
     stateTimer.Dispose();
     Console.WriteLine("\nDestroying the timer.");
  }
}

class StatusChecker
{
  int invokeCount, maxCount;

  public StatusChecker(int count)
  {
     invokeCount = 0;
     maxCount = count;
  }

    // This method is called by the timer delegate.
  public void CheckStatus(Object stateInfo)
  {
     AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
     Console.WriteLine("{0} Checking status {1,2}.",
         DateTime.Now.ToString("h:mm:ss.fff"),
         (++invokeCount).ToString());

     if (invokeCount == maxCount)
     {
         // Reset the counter and signal Main.
         invokeCount = 0;
         autoEvent.Set();
     }
  }
}

Output

image

3 – Windows.Forms.Timer

The Windows.Forms.Timer class works synchronously with the Windows Form, so that it will not interrupt any operations. It initializes on the UI thread.

C# Program

using System;
using System.Windows.Forms;

namespace WindowsFormsTimer
{
  public class Class1
  {
     static System.Windows.Forms.Timer theTimer =
         new System.Windows.Forms.Timer();

     static int alarmCounter = 1;
     static bool exitFlag = false;

      // Timer raised method
      private static void TimerEventProcessor(Object myObject,
          EventArgs myEventArgs)
      {
         theTimer.Stop();

         // Displays a message box asking whether to continue to run the timer
         if (MessageBox.Show("Continue running?", "Count is " +
             alarmCounter, MessageBoxButtons.YesNo) == DialogResult.Yes)
         {
             // Restarts the timer and increments the counter
             alarmCounter += 1;
             theTimer.Enabled = true;
         }
         else
         {
             // Stops the timer
             exitFlag = true;
         }
     }

     public static int Main()
     {
         //Adds the event and the event handler for the method that will
         //process the timer event to the timer
         theTimer.Tick += new EventHandler(TimerEventProcessor);

         // Sets the timer interval to 5 seconds
         theTimer.Interval = 2000;
         theTimer.Start();

         // Runs the timer, and raises the event
         while (exitFlag == false)
         {
             // Processes all the events in the queue
             Application.DoEvents();
         }
         return 0;
     }
  }
}

C# Listing on GitHub  

Output

image  image  image

There are three choices for timers in .NET.  It just depends on what you want to do.

More Information

Until next time…

^..^

Categories: .NET General, C#

HDNUG – October/09 Meeting – Recap

October 9, 2009 Rhonda Leave a comment

I attended the Houston .NET User Group October ’09 meeting last night. There was a good turnout of about 75-85 people in attendance.

 hdnuglogo    

Announcements -

  • Next month Zain Naboulsi will be presenting on Windows 7 for developers
  • There is an upcoming ASP.NET User Group that will likely be on the 4th Tuesday of each month – no dates set yet

Main topic -

photo

Claudio Lassala gave a great talk titled Be a Professional Developer and Write Clean Code. Below are some of the points covered.

  • What is clean code? Elegant and efficient, can be read and enhanced, simple and direct, etc…
  • Computers do not care what your code looks like
  • Name variables so that you don’t need comments

          Instead of –

     //Setting employee’s first name
     string field1 = “Rhonda”
;

          Use this –

     string employeeFirstName = “Rhonda”;

  • If you have source control, there is no reason to keep code commented
  • NDepend – a good tool that provides metrics for your code
  • Functions should do one thing and do it well
  • Vertical Distance – Declare variables close to where they are used. There is no need to declare all variables at the top of the program.

Presentation Materials for Be a Professional Developer and Write Clean Code

There were a lot more great points, but I had to leave before Claudio was finished. He did a great job of explaining how bad code should be rewritten.

hdnug

Looking for a user group meeting to attend? Check out my Houston Tech Groups and Events page.

Until next time…

^..^

Stripping the Decimal From a Value in .NET

June 7, 2009 Rhonda 4 comments

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…

Categories: .NET General, C#

The C# Null Coalescing Operator (??)

September 27, 2008 Rhonda 3 comments

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

Categories: C#

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

July 15, 2008 Rhonda Leave a comment

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

Categories: C#, Community