Showing posts with label Dotnet. Show all posts
Showing posts with label Dotnet. Show all posts

Friday, June 1, 2012

Self restarting windows services

I recently went through an interview where the interview was running over and the interviewer was trying to kill time so he was telling me about a GDI+ handle bug in .NET. Now for those who know me and have read my published works, you know that I am a UI specialist, so my ears instantly perked up to listen to this issue.

The situation was that they were using a windows service that was creating images and printing them off or something. Anyhow since the service wasn’t a GUI app it was not constantly being started and stopped and so with time it would use up all the available handles.

The solution that this person came up with was to create another service to watch the handles in the other service and when it had to many it would start another service to restart the first service.

To clarify:

Service A creates and prints images that use up handles in GDI+

Service B watches Service A for high handle usage, on detection it starts Service C

Service C restarts Service A

Wow that’s a lot of code and work. How I would deal with it is a combination of configuration and code all in Service A.

So we have Service A keep track of the handle counts, then when we hit the thresh hold we have the service call Environment.Exit with an error code greater than 0, which seems appropriate. Then on install we configure the service to restart on error.

Voila a self restarting service, well sort of, but much less complex than the previous scenario.

Monday, March 9, 2009

Code Contracts in C#

One of the new technologies Microsoft has coming down the pipeline for .NET 4 is Code Contracts. What are code contracts?

Code Contracts provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, post-conditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.

But what they are is so much more, they bring design by contract to .NET. Traditionally one would set up some type of argument checking to verify the validity of what was passed in, and probably return some type of invalid argument exception upon failure, like the following:


public class DummyObject
{
public DummyObject(int n)
{
if(0 < n)
throw new InvalidArgumentException("n must be greater than 0.");
}
}


This isn’t the most elegant of solutions, also it is only verified at runtime. With Code Contracts, you now have static checking of your code conditions to see if you violated the contract at compile time. As far as testability this is great. But even better is that we as developers can tailor our code, to make the compiler a little bit smarter. In the code above everything would compile just fine if we initialized a new instance of our “DummyObject” with a 0, only when we ran it would we see an error. Now if we were to rewrite this with code contracts it would look like this:



public class DummyObject
{
public DummyObject(int n)
{
Contract.Requires(0 < n);
}
}


Now with static checking turned on we would see an error at compile time telling us that we have violated the contract. This is one of the simplest examples there is a great deal more that can be done. I recommend reading the Microsoft research site and look for other articles out there.

Thursday, March 5, 2009

Microsoft MVC Digg Sample

So I recently was writing an MVC sample just to familiarize myself with the Microsoft MVC Framework. One of my favorite samples recently was one done by Scott Guthrie for Silver Light. It was a Digg sample so I wanted to make one that was similar to that one. So with no further adieu.


The source code can be downloaded here.

I will be updating it with more features as I build it out and will probably be doing posts to explain the different parts, so keep checking for new entries.

Monday, March 2, 2009

Microsoft MVC Tip #1

Well here is my first tip for MVC, how nice that I actually hit a head scratcher.

So recently I was doing some Model binding in MVC, and couldn’t get the binding to work. I had a simple object:

public class SimpleObject 
{
public string TestHiddenField;
public SimpleObject
{
TestHiddenField = "2";
}
}

In my Controller I was assigning the instance of my SimpleObject to my Model:


public ActionResult Index() 
{
ViewData.Model = new SimpleObject();
return View();
}

And in my markup I had this:


<%= Html.Hidden("TestHiddenField") %> 

The markup that was produced was this:



 

Now notice the value is blank. The model should have bound the value “2” to this control and that should have been the value. But without knowing it I did something stupid. I have a public field but it seems that the Model Binder expects a property with a getter and a setter. Well at least a getter.


So to fix the problem I had to fix my SimpleObject:


public class SimpleObject 
{
public string TestHiddenField{ get; set; };
public SimpleObject
{
TestHiddenField = "2";
}
}

So in conclusion it seems that under the covers MVC Model Binder looks for properties and not fields on the object. This is interesting since I would think that it would look for both. Though it is a good practice to use properties rather than fields I just didn’t expect it.

Thursday, February 26, 2009

Question Mark is a Nullable Type

One of the questions I keep seeing is what is int? or DatTime? and the like?

Well in .NET 2.0 the Nullable Type was introduced and that is what those type declarations mean. So what is a Nullable type?

 

Nullable types have the following characteristics:

  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

  • The syntax T? is shorthand for Nullable<(Of <(T>)>), where T is a value type. The two forms are interchangeable.

  • Assign a value to a nullable type just as you would for an ordinary value type, for example int? x = 10; or double? d = 4.108. However, a nullable type can also be assigned the value null: int? x = null.

  • Use the Nullable<(Of <(T>)>)..::.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();

  • Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;

    • The HasValue property returns true if the variable contains a value, or false if it is null.

    • The Value property returns a value if one is assigned. Otherwise, a System..::.InvalidOperationException is thrown.

    • The default value for HasValue is false. The Value property has no default value.

    • You can also use the == and != operators with a nullable type, for example, if (x != null) y = x;

  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

  • Nested nullable types are not allowed. The following line will not compile: Nullable<Nullable<int>> n;

 

Thats about all of it. More information can be found on MSDN

Thursday, January 29, 2009

The Double Question Mark Operator

The double question mark operator, also called the null-coalescing operator, is one of the many new and often unknown things in .NET 2008. It is a very slick operator and very useful. Microsoft states that it

 

is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

 

Its usage is as follows:

 

class NullCoalesce
{
    static int? GetNullableInt()
    {
        return null;
    }
    static string GetStringValue()
    {
        return null;
    }
    static void Main()
    {
        // ?? operator example.
        int? x = null;
        // y = x, unless x is null, in which case y = -1.
        int y = x ?? -1;
        // Assign i to return value of method, unless
        // return value is null, in which case assign
        // default value of int to i.
        int i = GetNullableInt() ?? default(int);
        string s = GetStringValue();
        // ?? also works with reference types. 
        // Display contents of s, unless s is null, 
        // in which case display "Unspecified".
        Console.WriteLine(s ?? "Unspecified");
    }
}

Monday, August 15, 2005

Back to Basics .NET Part 1

Well lets kick off this series with a question:

What is .NET?

The official word from Microsoft is that

.NET is the Microsoft Web services strategy to connect information, people, systems, and devices through software. Integrated across the Microsoft platform, .NET technology provides the ability to quickly build, deploy, manage, and use connected, security-enhanced solutions with Web services. .NET-connected solutions enable businesses to integrate their systems more rapidly and in a more agile manner and help them realize the promise of information anytime, anywhere, on any device.


But in simpler terms it is a Framework for building software solutions. Not just web services, though that is one of it's "sexy" features. It is a platform, much like your computer is, except this platform is software and not hardware, though it provides access to the hardware. Like a hardware platform you have a bunch of devices that can be used to build a computer system.

In .NET you have a bunch of objects, that are smaller pieces of software, that can be used to build a software system. By writing code you can make these objects (smaller pieces of software) interact with each other and solve problems. Thus producing a software system, also refered to as a solution, that runs on the platform, this platform being .NET.

There is alot more to the subject but you can go to the Microsoft framework website and read more about it on your own.

So lets get you started with a few links and items that you will need to run the samples and other materials that I will include during this series.

First I assume that you have a computer that is running some form of Microsoft Windows XP or greater.

Second go and download the .NET Framwork SDK ( Software Developers Kit).

Run the installation and look at the samples, and then come back here for the second part of the series.

Monday, August 30, 2004

Changing the Form1

Ever get annoyed at all the work you have to do to change the "Form1" name on a new .NET project? Well if you didn't I did. There is a lot involved you have to go into the code and rename the class, then rename the constructor then rename the file itself, not really necessary but looks better.

Well after having had enough, and having nothing better to do, I decided to figure out how to change this. I have written wizards for VS.NET before , and I assume those reading this can learn that part on their own, so it is no mystery to me that allot of the wizards are nothing more than JavaScript's. Yes JavaScript's, though you would think MS would use VBScripts but that's one for the philosophers.

On to the point all the wizards have a file called Default.js, usually located in

"C:\progra~1\Microsoft Visual Studio .NET 2003\VC#\VC#Wizards\CSharpEXEWiz\Scripts\1033"

(Note:The language name and directory of the wizards not withstanding, and the wizard you want to modify.)

Inside this file you will find a function named "GetTargetName" or some variation depending on the language. Inside this file is the hard coded value "Form1". Here you can change it to whatever you want, myself I have frmMain, but it is a matter of personal preference I think.