Skip to main content

Posts

Dependency Injection

Loose coupling i.e. making your code modules less tightly bound to each other. Dependency Injection helps this process, allowing clients of your code to get the application using their own code without them having to know very much at all as to how the application works internally. The article linked in the title of this post has a very brief outline of some how it can work but basically I'm interested in using Interfaces and registering my own classes with the host application with the minimum possible code work. There are lots of third party frameworks which provide implementations. The method is usually the same, create and instance of the third party class and then call a method on it which tells the framework to run a particular concrete class that you have provided when a particular interface or type is used, it's a form of mapping allowing client classes to be used at runtime. http://www.martinfowler.com/articles/injection.html

ISerializable - Serializing objects

Serializing is a mechanism to create a text/binary version of your objects state, this can be saved or sent somewhere and then deserialized back into the instance again. i.e. The member variables of your Type get written somewhere with their values of the instance of your Type. e.g. Here's the class who's instance I want to recreate somewhere else or at a later time. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleClass { public class Class1 { public int _myMemberVar; /// /// required for serialization /// public Class1() { _myMemberVar = 0; } public Class1(int value) { _myMemberVar = value; } } } Here's a class which Serializes the instance of the class above with the XMLSerializer. The version below writes the XML version of the instance to the Console, you could replace the using (Stream str = Consol...

Testing COM components

Here's some code you can use to try to load your Type through COM. You can use the GetPEKind method to get the platform that the assembly was compiled for. (Recently ran into a problem where I couldn't be sure the assembly I'd registered was registered correctly, my query was particular to win64, there are some changes in the registry entries for 64bit windows when running 32 bit applications.) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ComTest { class MyGetTypeFromCLSIDSample { public static void Main() { try { Guid myGuid1 = new Guid("3A21CE6B-8571-4955-9780-BAE1EE3215C0");//my Types GUID, regasm was ran on this assembly. // Get the type associated with the CLSID // and specify whether to throw an exception if an error occurs // while loading the type. //if this shows The typ...

Visual Studio build configuration with x64 "Any CPU"

In Visual Studio you may have noticed, and ignored, the pulldowns in your toolbar which usually contain "Release" "Any Cpu". The "Any CPU" part in particular is of interest especially if you plan on running your apps on Windows 64. These configurations are contained in each project and solution i.e. if you open the projects in a text editor you'll see sections in the XML which contain the settings. These settings are also accessible through the Visual Studio UI via the pulldowns mentioned earlier. The significance of the "Any CPU" is it's telling the compiler to compile the code into assemblies into code which can run on either 32 or 64 bit machines. If your assemblies are used by an application written in 64bit (and of course the app runs on a 64bit machine) then your assemblies will be used in the 64bit context, the same stands for 32bit (of course 32bit apps can also run on 32 or 43 bit machines). 64bit machines have an additional regi...

Roles in ASP.NET

Roles are part of the Authorization in ASPNET i.e. a mechanism to tell if the user has or has not access to resources. Roles are a mechanism to group users into sets of permissions. Roles can reuse already existing groups from windows. Roles can also be linked into a SQL database. Roles are configured on the aspnet websites web.config. http://msdn.microsoft.com/en-us/library/ff647401.aspx

XMLSerializer and .NET CLR (sgen.exe)

You might have spotted on your .NET projects in Visual Studio a radiobutton to turn on/off serialization "Generate serialization assembly" in your project's property's Build tab , so what's that all about? Serialization is a mechanism for recreating .NET objects from text. There's another post in this blog on the topic. So why is this option on your project? in brief it's there as a performance improvement for .NET CLR. .NET serializes the assemblies when loading, if you tick the "Generate serialization assembly" listbox your creating a second assembly to accompany the original, the second assembly , with extension .xmlserialize.dll , will be loaded by the CLR at load load if it exists, this improves performance at load time because now the CLR does not have to serialize the original assembly at load time instead if can just load the already existing second assembly. The second assembly is generated with Visual Studio with a tool called sgen.exe...

Interop Assemblies

What the hell are these Interop Assemblies, Primary Interop Assemblies (PIAs)? You'll see these assemblies from time to time pulled in as references in you projects, but I never really cared why they were called Interop and what it meant, I'll explain. Interop is short for interoperability meaning how to get .NET to talk to COM. Primary Interop Assembly (PIA): A PIA is an interop assembly that is signed by the originator to mark it as the one and only assembly to use to get the Type information. It's used to avoid conflicting Types. The assembly is signed in a particular way using the tlbimp.exe and then used by the client to resolve Types. http://msdn.microsoft.com/en-us/library/aa302338.aspx What have they got to do with COM? So implementations and Types available through COM is not accessible itself through .NET itself in the usual manner i.e. you cannot new up objects etc because you do not know the Type names. To get over this the COM Types are wrapped into an Interop ...

Transactions and .NETs TransactionScope, what and why?

Transactions are used to add the Rollback functionality to calls, Rollback meaning the if an exception or something is thrown your call will not be executed (Commited is the term used for this). Another benefit of using Transactions is that you can group calls together, if somethign happens to one call then all of calls in that group can also be rolled back. This type of feature is particularly useful when taking user input and saving to DB, you may not want anything to get written to the DB is some error occurs on the client. .NET provides us with the System.Transaction assembly, it's not completly straight forward to use but it does hide alot of the underlying complexities. A couple of things I've learned about using System.Transactions or more specifically the System.Transactions.TransactionScope class: The safest way to use it is with the using clause. Always call Commit() before the end of the using. The optional TransactionScopeOptions enum parameter in the constructor de...

Loading Assemblies, Assembly.Load, Assembly.LoadFrom, Assembly.LoadFile, appDomain.Load

I always find this topic a great source of confusion each time I get back to it. I've just across various Exceptions being thrown in my application, FileNotFoundException and AccessViolationException. The first caused because the application cannot location a Type that one of my assemblies references and lives in another assembly. The second is caused by that same file being found but it's locked by another process i.e. something else is reading or has read and not released the assembly. Both of the above were caused by messy code which used a simple Assembly.LoadFile(...). Looks to me like you should never use this method, I'll explain more below. There are many ways to create an Assembly instance. Assembly.Load(assemblyName); Assembly.LoadFile(assemblyName); Assembly.LoadFrom(assemblyName); or even AppDomain.Load(assemblyName); There are some subtelties however, some consequences which may later cause issues e.g. the assembly you've loaded is locked. Assembly.LoadFile...

Installer CustomAction, Debugging the CustomAction, InstallState

Custom Action The Custom Action is added to the Setup Project, select the Project node and hit the Custom Action button. This allows you add an Action to a particular phase in the Installation. But first you must create the Custom Action. To Add a Custom Action you must first have a Custom Action created, this is usually in the form of a Installer Class, this should be created in a seperate project, the Installer Class is actually one of the File Templates in the C# Projects. So it's File->New Project and select Visual C# Projects. Then add a Class Library, this will prompt you for the Class Library Types , select "Installer Class". Walkthrough - Creating Custom Action (msdn). Also here's a more comprehensive document on Setup/Installer implementations, it delves into the Registry etc Getting Started with Setup Projects (SimpleTalk). Visual Studio Setup Projects and Custom Actions (Simple Talk). Create your Installer Class and then add it as a Custom Action to the ...

TransactionScope, Transactions in .NET, A very basic level introduction

Transactions are used to prevent your application from getting into an unknown state. Transactions work on services which register with the Transaction service such as Database calls. It's useful where you cannot be sure that the resource (DB) will remain available while some data is changing and if the resource for some reason is made unavailable during a call then what happens to the data, well the Transaction should Rollback your Data so the app remains in the state it was before the data was sent. Transactions in .NET are implemented with System.Transaction.TransactionScope class. In the background this uses COM+. Wrap your DB call in a new TransactionScope instance, when the functionality is finished call TransactionScope.Complete(), then TransactionScope.Dispose(). If the execution makes it to these calls then your changes will be applied, if not your changes will be Rolled-back by the Transaction and you app will remain the same as before the call started. MSDN Video http://...

Windows Installer Tips, problem installations

With installer issues it's always difficult debug problems. If it's the Installer itself i.e. work done in the setup.vdprj itself then you maybe in a spot of bother. There are some logging options which are available to you.The other problem you may have is with your Custom Action if you have one. This maybe easier to diagnose, asyou can use the Visual Studio Debugger to attach but this in itself is not always easy todo. If you have problems with your installer itself and not the Custom Action then try this: You can also Log installer actions by activating the installer logging, this is done through a registry entry, http://support.microsoft.com/kb/223300 . All your doing is adding a "String Value" named "Logging" and a value "voicewarmupx" to the registry entry HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer I've done this and found some useful info but it's not that easy to read, at least it tells you the command that was...

ProjectAggregator

The ProjectAggregator is a dll that is required in order to use Packages developed with Visual Studio's 2005 Extensibility SDK. The projectaggregator.dll must be dropped into the C:\Program Files\Microsoft Visual Studio 8\Common7\IDE directory, if it doesn't exist then the end user will not be able to open projects in Visual Studio 2005 that are associated with your Package. Microsoft provide an installer ProjectAggregator.msi which does this work for you. The problem with this is you either tell all your clients to run the projectaggregator.msi themselves after or before installing your Package or else you include the installation of it in your own installer. The second option is of course the right one, as who would expect customers to run more than one installer. To include this in your installer however you need to create what is known as a BootStrapper project. The Bootstrapper is another installer that wraps the installer you actually wish to run. The idea is you include ...

How to access the IIS Metabase programmatically, IIS metabase

The IIS Metabase is XML representation of the IIS instance, it's actually an XML file stored in IIS. It can be access using apps like  MetaEdit   or programmatically using the Active Directory through a class  System.DirectoryServices.DirectoryEntry. using System.Collections.Generic; using System.Text; using System; using System.Data; using System.Configuration; using System.DirectoryServices; using System.Web.Configuration; namespace IISMetabase { class IISMetabase { private string _machineName = "localhost"; private System.Collections.IDictionary _applications;//collection of websites private Configuration _config; public IISMetabase() { _applications = new System.Collections.Hashtable(); } public System.Collections.IDictionary GetApplications() { DirectoryEntry webentry = new DirectoryEntry(); String path = "IIS://" + _machineName + "/W3SVC/1/ROOT"; webentry.Path = path; Boolean exists = false; try { exists = DirectoryEntry.Exists(path); } catch (Sy...

ActiveX Stopwatch Timer Control

Here's an example of a StopWatch control implemented in Csharp and used as a control on a web client. The control needs to be register on the clients machine then added to the clients web application (in html) and then called from Javascript. <OBJECT id="activeXTimerControl" name="activeXTimerControl"  classid="clsid:4F3B57CE-D9CA-41c3-ACBD-EBB2380990E7"  style="width: 504px; height: 182px"  codebase="Bin/ActiveXTimerControl.dll" class="ActiveXTimerControl.TimerControl"> </OBJECT> To start the Stopwatch call Start() and to end call End() then call Time() to return the result as a string or use the AddTimeToGrid to add the time to a DataGrid Control (supplied by the StopWatch control) or call AddTimeToLabel which adds the time to a textbox. activeXTimerControl.Start(); ///do someting activeXTimerControl.Stop(); var time = activeXTimerControl....