Category Archives: .NET General
Reading The Windows Event Log

I had a need recently to access the Windows event logs. Reading the Event Log is useful when you want to be notified when a program fails. You read the Events and if there is a fatal error, do something like send an email the owner of the process. This is helpful if you have a console application that runs all the time unattended.
The .Net Framework offers the System.Diagnostics.EventLog class. This class gives you the power to interact with the Windows event logs.
Below is a C# program that accesses the Windows event logs.
using System; using System.Text; using System.Diagnostics; class Program { static void Main(string[] args) { StringBuilder sb = new StringBuilder(); EventLog log = new EventLog("Application"); DateTime dt = DateTime.Now.AddHours(-1.00); Console.WriteLine(dt.ToString()); foreach (EventLogEntry entry in log.Entries) { if (entry.TimeGenerated > dt) { Console.WriteLine(entry.Source); Console.WriteLine(entry.EntryType); Console.WriteLine(entry.Message); Console.WriteLine("--------"); } } Console.WriteLine("Done"); Console.ReadLine(); } }
Below is the result of executing the code above. As you can see I had a crash in my Windows Live Writer Application.
Below is the Event Viewer and you can see there as well where there was an issue with the WLW application.
I can see where this class can be very helpful and plan on doing more research into what it can do as far as reading as well as writing operations.
Related Information
C# Special Interest Group – 11/30/2010
I attended the Houston C# SIG last Tuesday. Alan Stevens did a great presentation titled The Taming of the Code.
In this presentation he talked about the importance of constant learning and refactoring.
Below are some of the high points I picked up.
1. The Goal
- Build the right thing and build it well
- Technical Debt – Shipping the right thing even though it is not perfect
- Do the simplest thing that can possibly work
- Enable change
Build architectural seams or fault lines into your code, so if need be, it can be picked up and “stitched in” somewhere else
*ilities
- Agility
- Testability
- Readability
- Reversability
- Changeability
- Flexibility
- Maintainability
2. The Guidelines
Don’t Repeat Yourself (DRY) and Separation of Concerns are the yin and yang of Software Development
Examples of Separation of Concerns are MVC, MVP, HTML, CSS, JavaScript, (UI+Service+DAL).
- Single Responsibility Principle
- Open Closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependancy Inversion Principle
3. The Practice
A feedback loop is needed (code reviews, pair programming)
–
Additional Information
- QConn Conferences
- Virtual Brown Bag – Weekly meetings held on Thursdays.
- Time Snapper – Automatic screen shot journal
- XUNIT.NET – Testing framework
- –
Debugging: Failed to Enable Constraints
I have a DataSet that has had a new field added to it recently. When my console application runs, it was throwing a “Failed to enable constraints” exception.
I needed to find out which column in the DataSet was causing the error, so a co-worker suggested I create a temporary data adapter/set, so I can examine the GetErrors() method.
/* */ //-- Table Adaptor and DataSet with issue spRoxStaffImportTableAdapter roxStaffImportTA = new spRoxStaffImportTableAdapter(); RoxStaffImport.Data.StaffImport.spRoxStaffImportDataTable importdt = roxStaffImportTA.spRoxStaffImport(); //-- Table Adaptor and DataSet with my temporary TA and DS spRoxStaffImportTableAdapter roxStaffImportTA = new spRoxStaffImportTableAdapter(); //added for debugging RoxStaffImport.Data.StaffImport myDS = new RoxStaffImport.Data.StaffImport(); //added for debugging roxStaffImportTA.spRoxStaffImportfl(myDS.spRoxStaffImport); //changed for debugging RoxStaffImport.Data.StaffImport.spRoxStaffImportDataTable importdt = myDS.spRoxStaffImport; //roxStaffImportTA.spRoxStaffImport();
Once the exception occurs, access the GetErrors() property using the Watch window. This will tell you exactly what your issue is.
Once the issue is fixed, you can remove the temporary data adapter/set.
Wizards of Smart Podcast
There is a new podcast in town that I have started listening to. It is called the Wizards of Smart and is hosted by Jonathan Birkholz (@rookieone) and Ryan Riley (@panesofglass) and has kind of a “Stackoverflow-ish” format in which they banter back and forth on a range of topics.
I believe it is a great resource whether you are learning application development or trying to keep up with the ever-changing field. Check it out.
–
^..^
Using GetProperties() in C#
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; } }
As you can see below there are several other methods available as well as GetProperties.
Output
Additional Information
–
^..^
HDNUG Meeting – 02/11/10 – Recap
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.
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.
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
DynamicObject class
REST
Named and Optional Parameters
Improved COM Support
–
Markus Egger’s Information
- Presentation and Demos for C# 4.0 Dynamic Programming
- Email – MEgger@eps-software.com
- Twitter – @MarkusEgger
- Blog – http://www.MarkusEgger.com/blog
–
–
^..^
Houston C# SIG Meeting – 01/19/10 – Recap
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);
}
Ken provided a very informative presentation on LINQ to Objects and I am glad I was able to catch it.
–
^..^
HDNUG – January 2010 Meeting – Recap
I attended the January 2010 Houston .NET User Group meeting and there was a great turnout (about 100 people in attendance) to see Rob Vettor speak on Visual Studio 2010.
Announcements
2010 Officers
- President – John Hellman
- Vice President – J Sawyer
- Treasurer – Michael Steinberg
- Secretary – Justin ???
2010 Houston Techfest – Saturday, 10/09/2010 @ University of Houston
Markus Egger will be the speaker at the February 2010 meeting
New and long awaited website design at http://www.hdnug.org
Zain Naboulsi announced the Windows 7 "Windows @ Work" Article Contest. A contest that he is putting on in conjunction with The Code Project.
Submit a great article explaining how you built an app for Windows 7 – complete with code – and if yours is the highest rated article by both The Code Project community and our judges, you could win a fully loaded HP Touchsmart tx2z Notebook!
Visual Studio 2010 is slated for release 4/22/2010
–
The main presentation was given by Rob Vettor. He talked about Visual Studio 2010 and the history of how it came about as well as some of the new features.
Some New and Extended Features in VS 2010
- CLR 4.0
- Cloud Computing
- Parallel Computing
- Visual F#
- VS UI is built in WPF
- DLR – Dynamic Language Runtime
- MEF – Managed Extensibility Framework (for building plugins for VS)
- All the normal languages have been extended (C#, VB.NET, AJAX, etc)
- Entity Framework 4.0
- Multi-Targeting – Capability of dealing with previous versions of the Framework (2.0+)
Sku Versions
The number of Visual Studio versions has been reduced. Now there are only 4 main skus to remember
Here is a comparison of the old sku setup to the new sku setup.
Below is what is included in each of the new skus.
Roadmap
- Beta 1 has come and gone
- Beta 2 is now available
- March 2010 – Release Candidate
- April 22/2010 – Official Release
Rob gave a great high-level overview of what is coming in Visual Studio 2010. As always, there were some good magazines given away.
–
Until next month…
^..^
31 Days of Silverlight Series = Awesome!
Jeff Blankenburg has created a great 31-day series on all that is Silverlight. I have just begun my journey through the plethora of information and highly recommend anyone who has plans to work with Silverlight give this series a go.
Day #1: Mouse Events in Silverlight
Day #2: Silverlight Screen Transitions
Day #3: Custom Silverlight Loading Screen
Day #4: Communicating Between Two Silverlight Controls
Day #5: Silverlight Drag and Drop
Day #6: Silverlight and the Twitter “Hello, World!”
Day #7: Using WCF Web Services With Silverlight (and LINQ)
Day #8: Custom Fonts in Silverlight
Day #9: Using Keystrokes in Silverlight
Day #10: Styling Silverlight Control
Day #11: Animating Your Silverlight Application
Day #12: Jumping From XAML to XAML in Silverlight
Day #13: Binding Elements In Silverlight 3
Day #14: Perspective 3D in Silverlight
Day #15: Silverlight Charting
Day #16: Silverlight AutoComplete Textbox
Day #17: Silverlight Layout Options
Day #18: Silverlight Effects
Day #19: Silverlight Pixel Shader Effects
Day #20: Adding Audio to Silverlight Events
Day #21: Rapid Silverlight Prototyping In SketchFlow
Day #22: Using The Farseer Physics Engine in Silverlight
Day #23: Silverlight Outside The Browser (Part 1 of 3)
Day #24: Silverlight Outside The Browser (Part 2 of 3)
Day #25: Silverlight Outside The Browser (Part 3 of 3)
Day #26: Silverlight Data Grid
Day #27: Templating Controls In Silverlight
Day #28: Silverlight Application Themesa
Day #29: Using Isolated Storage in Silverlight
Day #30: Bing Maps in Silverlight
Day #31: Geocoding and More Fun in Bing Maps for Silverlight
–
Happy Silverlighting!
^..^
More on Timers in .NET
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:
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.
–
^..^











