Search Service Administration Component Issue

This is a SharePoint 2010 problem a client was facing. Essentially they had installed SharePoint and were in the process of manually configuring their services. They had setup the Search Service Application, but when the went into the Search Administration, the got the error below.

The search service is not able to connect to the machine that hosts the administration component. Verify that the administration component ‘c200182e-0520-4f00-bd2c-50321fc377e8′ in search application ‘Search Service Application’ is in a good state and try again.

There are various posts out on the Internet describing a resolution for this. But prior to attempting any of those, please check to see if your SharePoint Foundation Search is up an running. If it is not, then do start it and try again.

Always remember to lookout for the obvious prior to digging deeper, and it will save you time and grief.


Configuration Wizard KeyNotFoundException Error

This is a SharePoint error that occurred on a SharePoint 2010 environment post-install. Essentially, the user tried running the SharePoint Configuration Wizard to get things going but got the error message below.

err001

In order to resolve this, you will need to give the service account READ access to all Authenticated Users.

Basically, on Active Directory Users and Computers, ensure that Advance Features is selected from the View menu. Then, open the property window of the desired account, select the Security tab and find Authenticated Users. Finally, select Authenticated Users and give them READ access.

err002

Microsoft has release a knowledge base article for this, see KB2463865 for full information.


NUnit System.IO.FileNotFoundException Error

I keep getting this error when I try to open my assembly System.IO.FileNotFoundException Could not load file or assembly or one of its dependencies. The system cannot find the file specified.

There was nothing wrong with the assembly nor the location of it’s files. I can actually build and run the solution with no errors at all.

I eventually discovered that that the .NET runtime set on the NUnit config file by default is for .NET version 2.0 and my solution was built on .NET 4.0.

In order to get this going, navigate to your NUnit bin directory location, and open up the nunit.exe.config file with a text editor. Look for element as shown below:

   1: <startup useLegacyV2RuntimeActivationPolicy="true">

   2:   <!-- Comment out the next line to force use of .NET 4.0 -->

   3:   <supportedRuntime version="v2.0.50727" />

   4:   <supportedRuntime version="v4.0.30319" />

   5: </startup>

As the comment line indicates, just comment out the version of .NET runtime that you’re not going to be using. And now we can begin Unit Testing :)


Data Binding Inline Evaluation

There are time in where you may like to display a certain value inline, depending on the Eval() value that is data bound. At times like this, the ternary operator helps a great deal.

For example, I have a datetime object (“DatePaid”) that is being retrieved from the database using Linq to Sql. And every time the value is null it display the date on the user interface as such “1/01/0001”. I would really like a blank column displayed instead. I achieved this by using the ternary operator inline as below:

   1: <%# Eval("DatePaid") == null ? "&nbsp;" : Eval("DatePaid")

The above translates as such, if “DatePaid” is null then insert blank space “&nbsp;”, else show “DatePaid”

What if you had multiple conditions? Such as If-Else If-Else If-Else. In circumstances like this, it’s probably best handle the values server side, using a data bound event for example.

Hope this helps.


Error Entering break mode failed

I got the following error after copying over my solution from my development server into my laptop and tried debugging the solution. The full error is as below:

Entering break mode failed for the following reason <filename> does not belong to the project being debugged.

I tried re-building my solution and closing and opening up Visual Studio with no luck :(

Eventually, I tried to clean my solution, but because I only had Visual Studio Express this option was not available to me.

The resolution? I manually deleted the bin and obj folders from my solution directory then opened the solution and rebuild it again. This worked like a charm, hope it helps you.

err


.NET Why Code to Interface?

You may have seen programming design patterns and practices encourage coding to interfaces. And you may have also seen examples as to how to achieve this. The question is, why? Why should a programmer make this his second nature.

The following example would hopefully, shed some light into this, and hopefully help you get into the habit of good coding habits.

Let’s just say we take the “Game of Thrones”. In the book and TV series you would have noticed the numerous characters involved. I begin with creating two classes, representing two types of characters, one for a Knight and another for a Lord.

    class Knight
    {
        // TODO 
    }

    class Lord
    {
        // TODO
    }

As you can see, they do absolutely nothing at the moment. But one of the main functionality for my program is to retrieve character’s attributes. I have the method for this ready, the idea of this method is to retrieve the attributes from a particular character and return them as a string array.

        public string[] GetCharacterAttributes()
        {
            // TODO
        }

I could instantiate my required object from the concrete classes before as below.

        public string[] GetCharacterAttributes()
        {
            var character = new Knight();
            // Retrieve the attributes from Knight
        }

The above would be ok and have absolutely no problems. However, what if I needed to get attributes for a Lord character type as well? I could pass them in as parameters, as below.

        public string[] GetCharacterAttributes(Knight character)
        {
            //  Retrieve Knight attributes.
        }

        public string[] GetCharacterAttributes(Lord character)
        {
            //  Retrieve Lord attributes.
        }

But this would make the code messy and complex. Alternatively, I could do something like the below instead.

        public string[] GetKnightAttributes()
        {
            var character = new Knight();
            // Retrieve the attributes from Knight
        }

        public string[] GetLordAttributes()
        {
            var character = new Lord();
            // Retrieve the attributes from Lord            
        }

The above will work, the code will not be messy, and there would not be any complications. However, I am repeating the code, and I have to do it for each of my concrete class or character. And for those of you who have read the “A Song of Ice and Fire” books would know that this will get insanely hard as more and more characters are introduced.

This is where coding to an interface becomes valuable. I first create an interface called ICharacter, and then use that interface on my concrete character classes as below.

    // Interface for Game of Thrones Characters
    public interface ICharacter
    {
        string Name { get; set; }
    }

    // Implementation of Interface on Knight concrete class.
    class Knight : ICharacter
    {
        public string Name { get; set; }
    }

    // Implementation of Interface for Lord concrete class.
    class Lord : ICharacter
    {
        public string Name { get; set; }
    }

Now let’s go back to our method of retrieving character attributes. I can now have just the one method, with no issues. All I’m doing now, is passing in the interface as the method parameter.

        public string[] GetCharacterAttributes(ICharacter character)
        {
            // character passed in can be a Knight or a Lord
            // or it can be any other new characters that may get
            // created using the ICharacter interface.
        }

As you can see from the above, by coding to an interface, I do not have to deal with messy or complex code, and I do not need to repeat my code. Please note, there are ways in improving this through, Dependency Injection, but that will be a another post. I hope this helps, thank you.


.getJSON Error

If you get a ‘context’ is null or not an object error, have a look at the JavaScript files that you are referencing on the page. It is known that the problem lies with the vsdoc file. Remove that reference from the page and only use your jQuery file and all will be fine again.


C# Simple Password Generator

One of the simplest and easiest approach to generating random passwords, is to use the GetRandomFileName() static method from the Path class.

Snippet below demonstrates this.

   1: using System;

   2: using System.IO;

   3:  

   4: static void Main(string[] args)

   5: {

   6:     // Calls the static method from the Path type

   7:     var randomFolderFile = Path.GetRandomFileName();

   8:  

   9:     // Strips out dot characters

  10:     randomFolderFile = randomFolderFile.Replace(".", ""); 

  11:     Console.WriteLine(randomFolderFile);

  12: }

Happy Coding.


ASP.NET DataView Paging and Sorting.

This post demonstrates the use of the DataView class for simplifying Paging and Sorting operations on a GridView control.

Prior to getting into the workings of it, do note, that I’m using data from Northwind Customers table. Essentially, all I am doing is retrieving the ContactName, CompanyName and Country from all Customers records and returning them as an IEnumerable<T> object in my Data Access Layer.

To begin, I have a GridView control defined with 3 literal controls. Do note, the SortExpression defined on each TemplateField. Also note the OnSorting and OnPageIndexChanging events.

   1: <asp:GridView runat="server" 

   2:               ID="customersGrid" 

   3:               CellPadding="5" 

   4:               CellSpacing="3" AutoGenerateColumns="False" 

   5:               AllowSorting="True" 

   6:               OnSorting="CustomersSorting" 

   7:               AllowPaging="True" 

   8:               PageSize="15" 

   9:               OnPageIndexChanging="CustomersPageChaging" 

  10:               CssClass="gridStyle">

  11:     

  12:     <Columns>

  13:         <asp:TemplateField HeaderText="Name" SortExpression="Name">

  14:             <ItemTemplate>

  15:                 <asp:Literal runat="server" ID="customerName" 

  16:                              Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>'>

  17:                 </asp:Literal>

  18:             </ItemTemplate>

  19:         </asp:TemplateField>

  20:         

  21:         <asp:TemplateField HeaderText="Company" SortExpression="Company">

  22:             <ItemTemplate>

  23:                 <asp:Literal runat="server" ID="customerCompany" 

  24:                              Text='<%# DataBinder.Eval(Container.DataItem, "Company") %>'>

  25:                 </asp:Literal>

  26:             </ItemTemplate>

  27:         </asp:TemplateField>

  28:         

  29:         <asp:TemplateField HeaderText="Country" SortExpression="Country">

  30:             <ItemTemplate>

  31:                 <asp:Literal runat="server" ID="customerCountry" 

  32:                             Text='<%# DataBinder.Eval(Container.DataItem, "Country") %>'>

  33:                 </asp:Literal>

  34:             </ItemTemplate>

  35:         </asp:TemplateField>

  36:     </Columns>

  37: </asp:GridView>

Then on the code-behind, I’ve set up a property called SortOrder. This property keeps track of the ViewState[“SortOrder”] value that is saved on page postbacks.

   1: public string SortOrder

   2: {

   3:     get

   4:     {

   5:         if (ViewState["SortOrder"].ToString() == "DESC")

   6:         {

   7:             ViewState["SortOrder"] = "ASC";

   8:         }

   9:         else

  10:         {

  11:             ViewState["SortOrder"] = "DESC";

  12:         }

  13:  

  14:         return ViewState["SortOrder"].ToString();

  15:     }

  16:     set

  17:     {

  18:         ViewState["SortOrder"] = value;

  19:     }

  20: }

The Page_Load method, sets the SortOrder property to an empty string, then calls a custom method to bind the data to the GridView control.

   1: protected void Page_Load(object sender, EventArgs e)

   2: {

   3:     if(Page.IsPostBack) return;

   4:  

   5:     ViewState["SortOrder"] = "";

   6:     BindCustomersGrid("","");

   7: }

The custom bind method that is called from the Page_Load method takes in 2 string parameters. The parameters define the sort expression and the sort direction.

The method first checks if the sort expression is not an empty string. If it isn’t empty it then proceeds to use the DataView Sort property, prior to binding the data to the GridView control.

   1: private void BindCustomersGrid(string sortExp, string sortDir)

   2: {

   3:     // Custom method is called and DataView object is returned.

   4:     var view = GetCustomerData();

   5:  

   6:     // Check if Sort Expression is available.

   7:     if (sortExp != string.Empty)

   8:     {

   9:         view.Sort = string.Format("{0} {1}", sortExp, sortDir);

  10:     }

  11:  

  12:     // Bind data to GridView control.

  13:     customersGrid.DataSource = view;

  14:     customersGrid.DataBind();

  15: }

The custom method that returns the DataView object as shown in snippet above, is define in snippet below.

   1: private static DataView GetCustomerData()

   2: {

   3:     // Initialise and construct new DataTable

   4:     using (var table = new DataTable())

   5:     {

   6:         table.Columns.Add("Name", typeof(string));

   7:         table.Columns.Add("Company", typeof (string));

   8:         table.Columns.Add("Country", typeof (string));

   9:  

  10:         // Retrieve customer records from database layer

  11:         // and populate DateTable rows.

  12:         foreach (var customer in CustomerData.GetAllCustomers())

  13:         {

  14:             table.Rows.Add(customer.Name, customer.Company, customer.Country);

  15:         }

  16:  

  17:         return table.DefaultView;

  18:     }

  19: }

Now we come to the core part of this post. How do we perform sorting? Well, if you have followed the snippets along you would have noticed the custom bind method takes in 2 parameters. It then checks the sort expression parameter for a value, then uses the DataView Sort property to apply the sorting. Not too complex, but the easier bit is on the GridView OnSorting event as show below. Basically, calling the custom bind method by passing in both, the sort expression and the sort order.

   1: protected void CustomersSorting(object sender, GridViewSortEventArgs e)

   2: {

   3:     // Sorting is performed by calling custom bind method and specifying

   4:     // sort expression as defined in GridView control and the SortOrder

   5:     // property value.

   6:     BindCustomersGrid(e.SortExpression, SortOrder);

   7: }

Now to the next part of the post which is, How do we perform paging?. Well, on the GridView OnPageIndexChanging event, a new page index is set based on the GridViewPageEventArgs passed in, then the custom bind method is called again.

   1: protected void CustomersPageChaging(object sender, GridViewPageEventArgs e)

   2: {

   3:     customersGrid.PageIndex = e.NewPageIndex;

   4:     BindCustomersGrid("", "");

   5: }

Hope the post helps show how easy it is to get Paging and Sorting operations working, through the use of a DataView object.


Error Object cannot be cast from DBNull to other types.

This happens when the database is returning an object of type DBNull. Best approach towards handling this error would be to check if the object is of type DBNull first, before attempting to use it. Sample snippet below demonstrates this, using the Convert.IsDBNull method.

   1: var reader = command.ExecuteReader() // assumes SqlCommand has been initialised

   2:  

   3: if(!Convert.IsDBNull(reader["DateInDatabase"])) // if it is not returning DBNull

   4: {

   5:     // Do Something

   6: }

Hope this helps.


Follow

Get every new post delivered to your Inbox.