Archive for the ‘C-Sharp’ Category

PostHeaderIcon Manual Installing Windows Service – InvalidOperationException

Whe installing a windows service manually you are bound to run into the following problem

System.InvalidOperationException: Installation failed due to the absence of a ServiceProcessInstaller.
The ServiceProcessInstaller must either be the containing installer, or it must be present in the Installers collection on the same installer as the ServiceInstaller.

Check the Service Installer design file that both the ServiceInstaller and ServiceProcessInstaller are present, eventhough they are both visible and present in the UI.


// Installer1
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
   this.serviceInstaller1,
   this.serviceProcessInstaller1
});

PostHeaderIcon WCF Service AddressAccessDeniedException

When trying to run WCF service as a normal user you are bound to run into the following error.
System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL http://+:8080/CalculationEngineService/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details). ---> System.Net.HttpListenerException: Access is denied

at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
--- End of inner exception stack trace ---
at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)
at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)
at System.ServiceModel.Channels.HttpChannelListener.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at RapidABC.WCF.Service.WindowService.RapidABCWindowService.OnStart(String[] args)


On older versions of windows run the following command. Note I have never used this command.
httpcfg set urlacl -u http://+:8080/TELUSPHRService/ -a D:(A;;GX;;;S-1-5-20)

On newer versions of windows run the followig command

netsh http add urlacl url=http://+:8080/ user="NT AUTHORITY\NETWORK SERVICE"

Additional Commands that will come in handy

netsh http show urlacl -- to show all listings

netsh http delete urlacl url=http://+:8888/ -- to remove a listing

PostHeaderIcon Use XML attributes to specify a unique XML name and/or namespace for the type.

The following error

Types ‘NameSpace1.MyClass’ and NameSpace2.MyClass’ both use the XML type name, ‘MyClass’, from namespace XMLNameSpace’. Use XML attributes to specify a unique XML name and/or namespace for the type.

happens because there is a major difference between .net namespaces and the xml namespaces. The serializer does not pick up .net namespaces and gets confused by seeing the same class in two different namespaces. To resolve the error add the following attribute to both classes

[System.Xml.Serialization.XmlRoot(Namespace = "NameSpace1")] and [System.Xml.Serialization.XmlRoot(Namespace = "NameSpace2")] this way the .net namespace and the xml namespace are in sync.

PostHeaderIcon The output char buffer is too small to contain the decoded characters

The output char buffer is too small to contain the decoded characters, encoding ‘Unicode (UTF-8)’ fallback ‘System.Text.DecoderReplacementFallback’.


if (brEventReader.PeekChar() != 0)
{
  return new string(brEventReader.ReadChars(stringLength)).Trim();
}
else
{
  brEventReader.ReadChars(stringLength);
  return "";
}

In general, this arises when the incorrect encoding is set on the BinaryReader (the default one is UTF8) from what is encoded in the stream. PeekChar() (and ReadChar()) methods in BinaryReader will attempt to decode the bytes in the stream to fit in with the specified encoding and can fault if they are not compatible

The solution is to not use the PeekChar or ReadChar methods on the binary reader but to always use the Bytes methods.

Changed to


byte[] tvByteArray = new byte[stringLength];
tvByteArray = brEventReader.ReadBytes(stringLength);

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
string tvTemp = enc.GetString(tvByteArray);

//remove all the \0 and trim the string
return tvTemp.Replace("\0", "").Trim();  

PostHeaderIcon Computer Automation

Over the last few weeks have been working a lot with computer automation. The challenge with automation is to keep it running even when exceptions are happening.

The project I have been working on moves data on a regular interval between MySQL database and a SQL Server database. The MySQL database lives on a linux machine and is accessed via a SSH tunnel.

The following three rules will ensure that the automation runs quite reliable.

  1. Be able to restart the process at any point.
  2. Be able to process the same data without causing issues E.g. duplication
  3. Be able to chunk the data. E.g. if the process has not run in a long time only process a limited number of records at a time.

PostHeaderIcon XML – Binary – JSon Serialization

It appears that there are more than one way to skin a cat and sometimes it tough to decide on how to skin a cat. With serialization there are three common ways to serialize an object each has there advantages and disadvantages.

XML Serialization

XML serialization allows you to exchange data between disjoint systems e.g. C# and PHP. The downside of XML serialization is that it is very verbose and out of the box C# does not support serialization of a dicationary.

Example of XML Serialization


using System.Xml.Serialization;
StreamWriter _XMLOut = new StreamWriter(_filepath);
XmlSerializer _ProjectSerializer = new XmlSerializer(typeof(MyObject));
_ProjectSerializer.Serialize(_XMLOut, _MyObject);
_XMLOut.Close();

Example of XML Deserialization


using System.Xml.Serialization;
StreamReader _XMLIn = new StreamReader(_filepath);
XmlSerializer _ProjectSerializer = new XmlSerializer(typeof(MyObject));
_MyObject = (MyObject)_ProjectSerializer.Deserialize(_XMLIn);
_XMLOut.Close();

Binary Serialization

Binary serialization is less verbose and does support serialization of dicationaries however you can not exchange binary serialized messages between disjoint systems.

Example of Binary Serialization


using System.Runtime.Serialization.Formatters.Binary;
FileStream _stream = new FileStream(_filepath, FileMode.CreateNew);
BinaryFormatter _Formatter = new BinaryFormatter();
_Formatter.Serialize(_stream, _MyObject);
stream.Close();

Example of Binary Deserialization


using System.Runtime.Serialization.Formatters.Binary;
FileStream _stream = new FileStream(_filepath, FileMode.Open);
BinaryFormatter _Formatter = new BinaryFormatter();
_MyObject = (MyObject)objFormatter.Deserialize(_stream);

JSon Serialization

JSon serialization is less verbose allows for seriaization of dictionaries and can be used to exchange messages between disjoint systems the downfall of JSon is that the serialized information contains no type definitions.

Example of JSON Serialization


using System.Runtime.Serialization.Json;
DataContractJsonSerializer _Serializer = new DataContractJsonSerializer(_MyObject.GetType());
MemoryStream _DataMemoryStream = new MemoryStream();
_Serializer.WriteObject(_DataMemoryStream , _MyObject);

Example of JSON Deserialization


using System.Runtime.Serialization.Json;
MemoryStream _MemoryStream = new MemoryStream(_DataStream);
DataContractJsonSerializer _Deserializer = new DataContractJsonSerializer(_MyObject.GetType());
return (MyObject)_Deserializer.ReadObject(_MemoryStream);

One major negative aspect JSON serialization is that you need the same version of the object to serialize and deserialize it. The deserializer will fail if the newer version of the object as an additional property.

PostHeaderIcon Dicationary Serialization

Back to serialization again this is a beast that just wont die every time I think I know everything about serialization that there is to know about I get whacked over the head with it. One of the big issues with xml serialization is that it will not serialize a dictionary if you try you get an error like this

Cannot serialize member SSD.SourceControl.Modules.Files.Monitors.Business.MonitorSettings.Accesses of type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], because it implements IDictionary.

You have four ways to deal with this

Personally my preference is to either user binary serialization or JSON serialization if that is an option.

PostHeaderIcon Updating MS Access Linked Tables With c#

For one of my contracts I decided to split the MS Access into two database one to collect the data and one for reporting. The reporting database would linked in all the tables from the data database. This way I can modify the reports email the client the report database and do not need to port any data over to the newer database or provide scripts to update the database.

The problem is that the linked table source database is full hardcoded path. To keep it easy for the clients I needed a way to have the program updated the linked table source database path from the program.

I googled around but was not able to find a solution but did find some leads which led to the following code snippet. The code snippet reset the linked tables source database path.


ADODB.Connection Con = new ADODB.Connection();
ADOX.Catalog Cat = new ADOX.Catalog();

Con.Open(connectionString, null, null, 0);
Cat.ActiveConnection = Con;
Cat.Tables[LinkedTableName].Properties["Jet OLEDB:Link Datasource"].Value = LinkedDatabaseLocation;
Con.Close();

The same code can also be used to create a new linked table as well.

PostHeaderIcon ASP.Net UpdatePanel Triggers

Any control residing inside an updatepanel automatically causes a partial refresh and updates the update panel. However, sometimes you want to trigger an update on an update panel from a control that is outside of the control panel and that is where triggers come in.


<asp:UpdatePanel ID="MyUpdatePanel" UpdateMode="Conditional" runat="server">
  <Triggers>
    <asp:AsyncPostBackTrigger ControlID="MyButton" EventName="OnClick" /> 
  </Triggers>
  <ContentTemplate>
  </ContentTemplate>
</asp:UpdatePanel>

This works fine a dandy however if you are in some sort of template e.g. a create user wizard template you are bound to get the following error
A control with ID ‘MyButton’ could not be found for the trigger in UpdatePanel ‘MyUpdatePanel’.

My first approach was to use the ScriptManager RegisterAsyncPostBackControl

Master.GetScriptManager.RegisterAsyncPostBackControl(MyButton);

Two Notes
<li>The script manager is accessed via a property on the master page
<li>The MyButton is referenced via a findcontrol call

This does not work since the postback is not tied to an update panel and causes a full postback. The solution is to register a trigger on the update panel from the code behind page like so


UpdatePanel MyUpdatePanel = ControlFinder.FindChildControl<UpdatePanel>(Page, "MyUpdatePanel");
AsyncPostBackTrigger MyUpdatePanelTrigger = new AsyncPostBackTrigger();
MyUpdatePanelTrigger.ControlID = MyButton.UniqueID;
MyUpdatePanelTrigger.EventName = "Click";
MyUpdatePanel.Triggers.Add(MyUpdatePanelTrigger);

PostHeaderIcon Inheritance, Interfaces & Base Classes

Recently I ran into the problem where I needed a common object, containing a lookup list, accessible to all the objects in the object graph. The first two easy solutions that came to mind where
1) Load the common object in each object of the object graph this is very simple solution however very inefficient since the same object is being loaded many times.
2) Load the common object once and than copy it to all the objects in the object graph. This is gets tricky since it means that you have to traverse the whole object graph to set the common object. A second downfall to this is that if you add objects to the object graph you also have to update you object graph traversal code to include the new object.

After these two less than ideal solutions I could not see an option on how to implement this elegantly. Having a talk with Jason he mentioned making use of a base class with a static variable for the lookup list. The base class would solve both problems it would only load the list once and since all objects would be derived from the base object they would all have access to the lookup list.

My utopia ended pretty quickly since each object in the object graph already inherits from another class. In c# you can only inherit from one class; a class can implement many interfaces.

Having my mind set on using a base class I Googled around a bit and came up with the following solutions


interface ILookupList
{
   List<String> LookupList { get; set; }
}

public LookupList: ILookupList
{
  private static List<String> _LookupList;
  public List<String> LookupList
  {
     get { return _LookupList ;}
     set { _LookupList = value;}
   }
}

public MyClass: BaseCass, ILookupList
{
  private LookupList _LookupListAccessor;

  public List<String> LookupList
  {
     get { return _LookupListAccessor.LookupList ;}
     set { _LookupListAccessor.LookupList = value;}
   }
}

As long as all the objects in the object graph implement ILookupList using the LookupList class, with the static lookuplist variable, the Lookup List is accessible by all the objects and it only has to be loaded once.