Archive for the ‘Development’ Category
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
});
WCF Service AddressAccessDeniedException
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
Select Into with OpenRowSet Collation
Importing data into SQL server using the the openrowset command can cause the Collation Conflict when using the imported table against existing tables. This happens because SQL Server selects the Collation that best fit the data being imported. The following import statements allows you to set the Collation when doing a select into using the OpenRowSet
SELECT * INTO [NewTable]
FROM
(
SELECT
[Field1] collate database_default as [Field1]
, [Field2] collate database_default as [Field2]
, [Field3] collate database_default as [Field3]
FROM OPENROWSET(
'Microsoft.ACE.OLEDB.12.0',
'Text;Database=Folder;HDR=Yes;FORMAT=TabDelimited();',
'SELECT field1 as Field1, field2 as Field2, field3 as Field3 FROM [FileName]')
) as qImport
Apply Unique Styles To JQuery-UI Dialog Window
The below example shows how to apply a unique style to a jquery-ui dialog window
$("#divGallery_dialog").dialog
(
{
title: "Gallery",
show: 'fade',
autoOpen: false,
height: 600,
width: 1000,
modal: true,
resizable: false,
create: function(event, ui)
{
//here we can apply unique styling
$(this).parents(".ui-dialog:first").find(".ui-dialog-titlebar").css("display","none");
$(this).parents(".ui-dialog").css("padding", 0);
$(this).parents(".ui-dialog").css("border", 0);
$(this).parents(".ui-dialog:first").find(".ui-dialog-content").css("padding", 0);
}
}
);
The above example also show how to remove all paddings and margins from a JQuery-UI Dialog window.
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.
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();
CSS Select Parent Element
It is impossible to modify the parent element when something is happening to a child example.
For example if a textbox has focus I would like to change the parent div element background color.
The way to do this is with javascript. I know it is not ideal to have to use Javascript to get the desired result but in this case it only takes two lines of javascript and it looks pretty sharp.
To get the desired effect you need to add an event to the child onFocus and onBlur event. You can use different events to get differente effects such as the onMouseEnter, onMouseLeave to have a hover effect.
<style>
/*These are not required for the example but it makes it appear nicer*/
input
{
border:1px solid #28557c;
}
div
{
padding:3px;
}
</style>
<script>
function TextBoxOnFocus(obj)
{
obj.parentNode.style.backgroundColor = '#4789c3';
}
function TextBoxOnBlur(obj)
{
obj.parentNode.style.backgroundColor = '';
}
</script>
<div style="background-color:#bad3e9;"> <div> <input type=text onfocus="TextBoxOnFocus(this)" onblur="TextBoxOnBlur(this)"/> </div> <div> <input type=text onfocus="TextBoxOnFocus(this)" onblur="TextBoxOnBlur(this)"/> </div> <div> <input type=text onfocus="TextBoxOnFocus(this)" onblur="TextBoxOnBlur(this)"/> </div> </div>
Demo, click on the textboxes to see the background div’s color change.
Since this only requires one line of code you can even inline the javascript.
SQL Server Alter Statements
It is not very common to create a database via scripts or modify a database via scripts, most often the changes are done via a designer which does make the job a lot easier.
In some cases it is worthwhile to do it via a script one of the instances where I use scripts a lot is when I make changes to a development database and I know that I have to make same changes to a production database at some point.
Below is a list of the most common alter statements to modify the structure of a database
- Add a column to a database
ALTER TABLE table_name ADD column_name datatype
- Add a primary key to a database
ALTER TABLE table_name ADD CONSTAINT constraint_name PRIMARY KEY (field_name)
- Add an index to a table
CREATE NONCLUSTERED INDEX index_name ON table_name (field_name ASC)
- Add a foreign constraint to a table
ALTER TABLE table_name WITH CHECK ADD CONSTRAINT contraint_name FOREIGN KEY (field_name) REFERENCES table_name (field_name) ALTER TABLE table_name CHECK CONSTRAINT constraint_name
Note that there are some very good tools out there as well to determine the structural changes between a development and production database but you may not always have access to these tools.
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.
- Be able to restart the process at any point.
- Be able to process the same data without causing issues E.g. duplication
- 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.
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.