Measure execution time in C#

To measure execution time in C#, substract start and end datetime.

         public void MeasureTime()
        {

            // Capture start time
            DateTime startDateTime = DateTime.Now;

            // Do something for 1000ms...
            Thread.Sleep(1000);

            // Capture end time
            DateTime endDateTime = DateTime.Now;

            // Determine duration
            TimeSpan duration = endDateTime - startDateTime;

            // Show duration
            Console.WriteLine(string.Format("Hours{0} Minutes{1} Seconds {2}, Milliseconds{3}",duration.Hours, duration.Minutes, duration.Seconds,duration.Milliseconds));
        }

Google wave – nice error message on contact search

Wave rules, but I can’t find the meaning of the message: yyyy@googlewave.com  could not be found. Would you like to add it to your contacts?
If the contact is not found, how can it be added. Unless the meaning is: Search for a contact in “mine contacts list”. It is not found in “mine contacts list”, but there exists a yyyy@googlewave.com account in the “global account list”, would you like to add the contact to “you’re contact list”?

image

C# – Property snippet

Some C# code snippets for C# properties:

        /// <summary>
        /// A object property with null check
        /// </summary>
        private Type _propertyName = null;
        public Type PropertyName
        {
            get
            {
                if(_propertyName == null)
                {
                    throw new NullReferenceException("The property [MyClass.PropertyName] can't be null");
                }
                return _propertyName;
            }
            set
            {
                _propertyName = value;
            }
        }

        /// <summary>
        /// A string property with empty and null check
        /// </summary>
        private string _myString = null;
        public string MyString
        {
            get
            {
                if (string.IsNullOrEmpty(_myString))
                {
                    throw new NullReferenceException("The property [MyClass.MyString] can't be null");
                }
                return _myString;
            }
            set
            {
                _myString = value;
            }
        }

Leadtools error message “Operation failed” on Leadtools.Barcode.BarcodeException.CheckErrorCode

If you get the leadtools error message “Operation failed” in function Leadtools.Barcode.BarcodeException.CheckErrorCode, you should check if the following files are in the same folder as the assemlby that uses the leadtools assemblies:

Leadtools .NET assemblies:
Leadtools.Barcode.dll
Leadtools.Codecs.dll
Leadtools.dll
Leadtools.Forms.dll
Leadtools.Forms.Ocr.dll
Leadtools.Forms.Ocr.Plus.dll
Leadtools.ImageProcessing.Core.dll
Leadtools.ImageProcessing.Utilities.dll

Leadtools not .NET assemblies:
Ltbar4u.dll
Ltbar6ru.dll
Ltbar6wu.dll
Ltbar7ru.dll
Ltbar7wu.dll
Ltbar8ru.dll
Ltbar8wu.dll

Leadtools engine initialization error, or there is no appropriate license

If you get the error:

Leadtools.Forms.Ocr.OcrException : Engine initialization error, or there is no appropriate license.
at Leadtools.Forms.Ocr.Plus.OcrEngine.StartupEngine(String startupParameters)
at Leadtools.Forms.Ocr.Plus.OcrEngine.Startup(RasterCodecs rasterCodecs, String workDirectory, String startupParameters)

make sure the ocr engine is started with the correct path to the installation of the Leadtools.

 // Start OCR-engine var ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Plus, false);
            if (!ocrEngine.IsStarted)
            {
                ocrEngine.Startup(null, null, @“C:\InstallationFolderLeadTools”);
            }

 

The LeadTools OCR Engine should be installed in  C:\InstallationFolderLeadTools.

 

Adding LeadTools installation folder to the PATH variable

The error can some times be caused by the folder C:\InstallationFolderLeadTools not being in the PATH variable.

Add the [C:\InstallationFolderLeadTools] to the PATH variable.

Control Panel > System > Advanced System Settings

 

image

 

 

enable32BitAppOnWin64

This error can also be caused by an IIS or IIS express application pool not running in 32-bit application mode.

 

IIS

Change IIS Application Pool setting [Enable 32-bit Applications] to [True]

image

 

IIS Express

Add enable32BitAppOnWin64="true" in [C:\Users\User1\Documents\IISExpress\config\applicationhost.config].

<applicationPools>

            <add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" enable32BitAppOnWin64="true">

                <processModel loadUserProfile="true" />

            </add>

            <add name="Clr4ClassicAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" enable32BitAppOnWin64="true"/>

            <add name="Clr2IntegratedAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" enable32BitAppOnWin64="true"/>

            <add name="Clr2ClassicAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" enable32BitAppOnWin64="true"/>

            <add name="UnmanagedClassicAppPool" managedRuntimeVersion="" managedPipelineMode="Classic" autoStart="true" enable32BitAppOnWin64="true"/>

            <applicationPoolDefaults managedRuntimeLoader="v4.0">

                <processModel />

            </applicationPoolDefaults>

        </applicationPools>

Leadtools assembly load error, when building on a x64 platform

When you use leadtools in an assemlby and reference this assemlby by another assembly (e.g. a dll uses the Leadtools.Forms.Ocr and an executable references that dll), make sure that both assemlbies reference the Leadtools assembly, if not referenced assemlby load errors can occur.

When building these assemblies on an x64 platform and you are using the x86 leadtools assemblies, make sure you’re assemblies are build targeting the x86 platform, else assembly load errors can occur. 

image

Erros
Could not load file or assembly ‘Leadtools, Version=16.0.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907’ or one of its dependencies. An attempt was made to load a program with an incorrect format.
or
Could not load file or assembly ‘Leadtools.Barcode, Version=16.0.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907’
or
Could not load file or assembly ‘Leadtools.Codecs, Version=16.0.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907’
or
Could not load file or assembly ‘Leadtools.Forms, Version=16.0.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907’
or
Could not load file or assembly ‘Leadtools.Forms.Ocr, Version=16.0.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907’
or
Could not load file or assembly ‘Leadtools.Forms.Ocr.Plus, Version=16.0.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907’
etc.

Resolving the System.InvalidOperationException : Could not find default endpoint element that references contract ‘xxx’ in the ServiceModel client configuration section

After renaming a WCF service reference in Microsoft Visual Studio, you can get the error:

System.InvalidOperationException : Could not find default endpoint element that references contract ‘ImportServiceReference.IImportService’ in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
    at System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(ServiceEndpoint serviceEndpoint, String configurationName)
    at System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address)
    at System.ServiceModel.ChannelFactory`1..ctor(String endpointConfigurationName, EndpointAddress remoteAddress)
    at System.ServiceModel.ChannelFactory`1..ctor(String endpointConfigurationName)
    at System.ServiceModel.EndpointTrait`1.CreateSimplexFactory()
    at System.ServiceModel.EndpointTrait`1.CreateChannelFactory()
    at System.ServiceModel.ClientBase`1.CreateChannelFactoryRef(EndpointTrait`1 endpointTrait)
    at System.ServiceModel.ClientBase`1.InitializeChannelFactoryRef()
    at System.ServiceModel.ClientBase`1..ctor()

Make sure the name in the contract attribute of the endpoint is the same as you’re Microsoft Visual Studio Service Reference name

<endpoint address="http://localhost/ImportService/ImportService.svc"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IImportService"
        contract="ImportServiceReference.IImportService" name="WSHttpBinding_IImportService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>

Must be the same as:

image

Using TSQL Like operator in LLBLGen

If you want to query you’re database with LLBLGen, by filtering entities using the TQL Like operator you should use the FieldLikePredicate

See LLGLGen v2.6 documentation: http://www.llblgen.com/documentation/2.6/hh_start.htm
Specific part: http://www.llblgen.com/documentation/2.6/Using%20the%20generated%20code/Adapter/Filtering%20and%20Sorting/gencode_filteringpredicateclasses_adapter.htm#FieldLikePredicate

FieldLikePredicate

Description
compares the entity field specified with the pattern specified, using the LIKE operator. The pattern should contain the wildcard, which is ‘%’ (also for MS Access). FieldLikePredicate performs a LIKE compare using the case sensitivity setting of the database system the query is executed on: the SQL generated does not contain any collation information nor any case insensitive setting if the database is using case sensitive comparison operations by default (Oracle, some SqlServer installations). You can perform case insensitive compares however, if the database is case sensitive, by setting the CaseSensitiveCollation property to true prior to passing the predicate to a fetch method like FetchEntityCollection(). This will perform the UPPERCASE variant of the field with the pattern specified.Please note that if you’ve set CaseSensitiveCollaction to true, you’ve to specify your pattern in uppercase as well.

SQL equivalent examples
Field LIKE ‘%bla’
Field LIKE ‘bla%’

Operators
none.

Example
This example creates a predicate which compares Customer.CompanyName to the pattern "Solution%".

  • C#
  • VB.NET
// C#
filter.Add(new FieldLikePredicate(CustomerFields.CompanyName, null, "Solution%"));

// Which is equal to:
filter.Add(CustomerFields.CompanyName % "Solution%");
' VB.NET
filter.Add(New FieldLikePredicate(CustomerFields.CompanyName, Nothing, "Solution%"))

' Which is equal to: (VB.NET 2005)
filter.Add(CustomerFields.CompanyName Mod "Solution%")

Note, that the operator syntaxis is a little odd in VB.NET, due to the fact that there isn’t an ability to add new operators to VB.NET/C#.

Can be used for in-memory filtering

Yes. When used in in-memory filters, the pattern can either be a normal LIKE statement pattern with ‘%’ wildcards, or it can be a full regular expression. If the pattern is a regular expression, be sure to set the property PatternIsRegEx to true. See also the LLBLGen Pro reference manual on more detailed information about the properties of the FieldLikePredicate