Saturday, September 29, 2012

login failed for user ‘rob’ reason the account has expired



Promoting this error message my application has stopped working.The reason for that is expiration of the user which i have use to connect to sql server.later on i have investigate the user account in sqlserver and identified the root cause for that.

when i was creating the user i have checked the Enforce Password Expiration Check


Finally i uncheck the check and changed the password its work fine

Friday, August 10, 2012

In C#, how to check if a TCP port is available?

When hosting wcf service which is use net tcp binding and without port sharing in a windows service , we should make sure the availability of our wcf port number. Other wise service doesn't start.

There fore as a best practice its is better to have code which will check the availability of the port when starting the service.This code should included to the service startup event. 

   1: protected override void OnStart(string[] args)
   2:        {
   3:            try
   4:            {
   5:                if (serviceHost != null)
   6:                {
   7:                    serviceHost.Close();
   8:                }
  10:                PortChecker pc = new PortChecker();
  12:                if (pc.IsPortAvailable())
  13:                {
  14:                    serviceHost = new ServiceHost(typeof(M3ISPlusService));
  15:                    serviceHost.Open();
  16:                }
  17:            }

ANd this is the port checker class

   1: public bool IsPortAvailable()
   2:         {
   3:             bool isAvailable = false;
   4:             TcpListener tcpListner = new TcpListener(GetServerIp(), GetPort());
   5:             Logger logger = Logger.GetLogger();
   7:             try
   8:             {
   9:                 tcpListner.Start();
  10:                 isAvailable = true;
  11:             }
  12:             catch (Exception ex)
  13:             {
  14:                 logger.Log(ex.Message);
  15:             }
  17:             finally
  18:             {
  19:                 try
  20:                 {
  21:                     tcpListner.Stop();
  22:                     tcpListner = null;
  23:                 }
  24:                 catch (Exception)
  25:                 {
  26:                     tcpListner = null;
  27:                 }
  28:             }
  30:             return isAvailable;
  31:         }

To get port in code please refer my previous post :- Read End point address programmatically

Happy Coding :)

Friday, August 3, 2012

Programmatically reading endpoint address from web.config file?


There are some instances where we have to read wcf endpoint url from the code.As following you can accomplish that task.

once we add a service to the code it will get added to web.config under <system.serviceModel> section.

so we can access web config like this.

ServicesSection servicesSection = (ServicesSection)ConfigurationManager.GetSection(BASE_ADDRESS_PATH);

var item = servicesSection.Services[0].Host.BaseAddresses[0].BaseAddress;
Uri baseAddress = new Uri(item);

Friday, June 29, 2012

Linq to data reader

using linq we can easily extract the data reader values without writing more coding.

example for populating anonymous object from datareader

using (SqlDataReader dataReader = command.ExecuteReader())
var annonymousObject = from IDataRecord record in dataReader
select new
Code = (string)record["Code"],
Description = (string)record["Description"]
example for populating custom object from datareader
using (SqlDataReader dataReader = command.ExecuteReader())
DataRecord dataRecord= (from IDataRecord record in dataReader
select new DataRecord
Code = (string) record["Code"],
Description = (string)record["Description"]

Wednesday, May 16, 2012

linq orderby custom comparer

I need to orderby Customer Collection.There fore i have to write new class extending with IComparer<T> interface.

public class EntityComparer<T> : IComparer<T> where T : class
        #region IComparer<T> Members

        public int Compare(T x, T y)
            string valuex = string.Empty;
            string valuey = string.Empty;

            if (x is StringField && y is StringField)
                valuex = GetStringFieldValue(x as StringField);
                valuey = GetStringFieldValue(y as StringField);

            if (x is BasicDataField && y is BasicDataField)
                valuex = GetBasicDataFieldValue(x as BasicDataField);
                valuey = GetBasicDataFieldValue(y as BasicDataField);

            return Compare(valuex, valuey);


        #region Helpers

        private string GetBasicDataFieldValue(BasicDataField field)
            string value = string.Empty;

            if (null !=  field && null != field.NewValue && !string.IsNullOrEmpty(field.NewValue.Description))
                value = field.NewValue.Description;

            return value;

        private string GetStringFieldValue(StringField field)
            string value = string.Empty;

            if (null != field && !string.IsNullOrEmpty(field.NewValue))
                value = field.NewValue;

            return value;

        private  int Compare(string x, string y)
            return string.Compare(x, y, true, CultureInfo.InvariantCulture);


Then we can do our linq ordering like bellows
bomLines.OrderBy(record => record.BOMCategoryType, new EntityComparer<BasicDataField>());
Here we have to create new instance of the our Custom comparer class.
Related Posts:

Thursday, May 10, 2012

execute scalar function in sql server

As follows you can test your scalar function in sql server.Result holding variable type should be same as the function return type.




Note:My sql server  version is 2008 R2.If you use sql server  2008 some time you might have to use schema also.


Wednesday, April 11, 2012

How to Order by Multiple in Linq

When Ordering custom collection in Linq  using multiple fields you can use OrderBy and ThenBy methods.


private BOMLineDTO[] SortBOMLines(BOMLineDTO[] bomLines)
BOMLineDTO[] sortedBOMLines = null;

if (null != bomLines)
sortedBOMLines = bomLines.OrderBy(record => record.ItemDescription, new BOMLineComparer<StringField>()).
ThenBy(record => record.BOMCategoryType, new BOMLineComparer<BasicDataField>()).
ThenBy(record => record.GMTColor, new BOMLineComparer<BasicDataField>()).
ThenBy(record => record.GMTSize, new BOMLineComparer<BasicDataField>()).ToArray();
return sortedBOMLines;
Here BOMLineComparer<T> is My own class which is derived form IComparer<T> interface

Related Posts:

Tuesday, March 27, 2012

Return empty IEnumerable<T> in C sharp

In order to return empty IEnumerable  in csharp you can use static Empty<T>() method in Enumerable class.

Suppose i have custom class called Foo  then,


Thursday, March 22, 2012

The workflow could not update the item, possibly because one or more columns for the item require a different type of information

I have SPD work flow which associated with a list that derived from content type. Using my .net application which was written using SharePoint Client Object Model i update .list item.But in some instances my workflow corrupted  by mentioning  above error.As well as my workflow has configured to initiate when list item creation only.

Finally i figure out reason for this strange behavior

There is one instance in my application in which i create list item and then updates same item to particular state.Due to these two step happen in instantly my workflow getting failed.


As solution what i have done is to make sure properly workflow initiated or not by querying the workflow instance id.Once i confirmed it then i execute rest of the code.other wise my operation is sleep till workflow initiated.From the beginning of my work flow i saved workflow instance id as list item.

As follows you can get the workflow instance id,

public string GetWorkflowURL(string styleNo, int versionId)
/*Getting the update list item */
ListItem listItem = GetUpdateItem(styleNo, versionId);
ListColumns listColumns = new ListColumns();

return listItem != null
? (listItem[listColumns.WorkFlow] != null
? ((FieldUrlValue) (listItem[listColumns.WorkFlow])).Url
: string.Empty)
: string.Empty;

This work around has worked to me.

Monday, March 19, 2012

What is Func<T> and Action<T> ?

These two are inbuilt delegate types which can use without defining a new delegate type with each and every parameter type and return type.

Func(Of TResult)

Which can hold method references  which have return types with input parameters or not.As well as there are bunch of overloads
example-:Here I need to add two integers and return the result.. 
Here my Adding method ,which expects the Func with two inputs and one out put.
public static void PerformAction(Func<int,int,int> method,int x,int y)
   int result=method.Invoke(x, y);
Here my is my controller class
static void Main(string[] args)
   Func<int, int, int> addingFunc = (x, y) => (x + y);
   PerformAction(addingFunc , 5, 10);

Action(Of T)

Which can hold method references which have no return types.There are bunch of overloads for the Action delegate,
here i use same example without retuning the result,instead of that i write it in to a just Console.
public static void PerformAction(Action<int,int> method,int x,int y)
   method.Invoke(x, y);
Here my is my controller class
static void Main(string[] args)
   Action<int, int> addingAction = (x, y) => Console.WriteLine(x + y);
   PerformAction(addingAction, 5, 10);

Friday, March 16, 2012

Method Overloading error in WCF

In normal behavior of  WCF if you try to implement method overloading in WCF service contract it will throw the an InvaildOperationException once you invoke the service.

[FaultContract(typeof (ServiceException))]
BasicDataDTO[] RetrieveGenericData(EBasicDataType genericType, string descriptionPart);

[FaultContract(typeof (ServiceException))]
BasicDataDTO[] RetrieveGenericData(string styleNo, int versionId, EBasicDataType genericType, string descriptionPart);
In generally above statement will throw the InvaildOperationException.To overcome this problem you have to put OperationContractAttribute with Name Property.
[OperationContract(Name = "GetGenericData")]
[FaultContract(typeof (ServiceException))]
BasicDataDTO[] RetrieveGenericData(EBasicDataType genericType, string descriptionPart);

[OperationContract(Name = "GetAllgenericData")]
[FaultContract(typeof (ServiceException))]
BasicDataDTO[] RetrieveGenericData(string styleNo, int versionId, EBasicDataType genericType, string descriptionPart);
In Object Oriented aspect above code is correct ,WCF always generate proxy using the WSDL.The problem is WSDL does not support the concepts like inheritance and overloading.

Tuesday, February 21, 2012

Send Ping Command in C#

I had a scenario which need to test  whether server available or not for my application.So i wrote following code to accomplish that.

.net framework has set of classes which support to Ping to the specified host.

public bool IsAvailableHost(string hostName)
var ping = new Ping();
PingReply reply = ping.Send(hostName);
return reply != null && reply.Status == IPStatus.Success;
catch (Exception ex)
throw ex;

Set Alternative Background Color for Wpf ComboBox


Using style we can set the alternative background color of a combo box without any code behind.first we have to define the style that targets the combo box item.i have defined this style under the resources section of window

 <Style x:Key="alternativeStyle" TargetType="{x:Type ComboBoxItem}">
    <Trigger Property="ItemsControl.AlternationIndex" Value="0">
              <Setter Property="Background" Value="Aqua"></Setter>
         <Trigger Property="ItemsControl.AlternationIndex" Value="1">
   <Setter Property="Background" Value="Red"></Setter>

*Note-:You have to defined AlternativeIndex as attached property(ItemsControl Class) Other wise Xaml parser doesn't recognize the AlternationIndex property

Then bind relevant style to the our combo box using Item Container Style

 <ComboBox ItemTemplate="{StaticResource ResourceKey=ListViewModel}" Margin="148,116,180,159" Name="cmbTest" IsDropDownOpen="True" AlternationCount="2" ItemContainerStyle="{StaticResource ResourceKey= alternativeStyle}" />

Finally it shows as…


Tuesday, January 24, 2012

compile error can't find project or library vb6

In my vb6 solution even i have referred the appropriate module complier always warn me “compile error can't find project or library” with highlighting some functions.Again I go to my references and double check it gain.Then i have noticed that there are some missing module indicating in that list.


Then I uncheck missing module and recompile the solution and its work perfeclty .

Wednesday, January 18, 2012

Spell Suggestion and Checking in WPF Text Box


WPF text box controller shipped with a inbuilt spell suggestion and checking feature.We can simply enable that feature setting the SpellCheck.IsEnabled="True"/.

Here is the Code

<TextBox Name="dummy" SpellCheck.IsEnabled="True"/>
And Here is the output

Friday, January 13, 2012

Change Background Color of a Button in WPF using trigger


There was a situation where i need to change the Background and Foreground color of a button when mouse is over .

In this case i have tried to use normal Style like below.

<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Bisque"/>
<Setter Property="Background" Value="IndianRed" TargetName="Chrome"/>

But this is only changed the foreground.this style did not for the Background.There fore i have to change the control template of the button.


                        <ControlTemplate TargetType="{x:Type Button}">
                            <Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding Button.IsDefaulted}" SnapsToDevicePixels="True">
                                <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                <Trigger Property="IsKeyboardFocused" Value="True">
                                    <Setter Property="RenderDefaulted" TargetName="Chrome" Value="True"/>
                                <Trigger Property="ToggleButton.IsChecked" Value="True">
                                    <Setter Property="RenderPressed" TargetName="Chrome" Value="True"/>
                                <Trigger Property="IsEnabled" Value="False">
                                    <Setter Property="Foreground" Value="Lavender"/>
                                <Trigger Property="IsMouseOver" Value="true">
                                    <Setter Property="Foreground" Value="Bisque"/>
                                    <Setter Property="Background" Value="IndianRed" TargetName="Chrome"/>

There are few things to be remember .

  • In our custom ControlTemplate used  "ButtonChrome"  class under the "Microsoft_Windows_Themes" namespace alias.In order to use "ButtonChrome" class inside UI, have to include "PresentationFramework.Aero" dll and

  • xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" to user window level name spaces.