IIS Express – HTTP Error 400. The request hostname is invalid.

The following is the fix for the error “HTTP Error 400. The request hostname is invalid” when trying to browse an IIS Express site using a different host name or IP address.

1. Exit the IIS Express instant currently running.

2. Open IIS Express’s applicationhost.config located at the following path C:\Users\<user>\Documents\IISExpress\config\applicationhost.config

3. Find the entry for a particular site (e.g “Test” running in port 6306) which you are developing.

e.g.

<site name="FlickrTest" id="10">
    <application path="/" applicationPool="Clr4IntegratedAppPool">
        <virtualDirectory path="/" physicalPath="E:\Projects\BB Apps\FlickrTest" />
    </application>
    <bindings>
        <binding protocol="http" bindingInformation="*:6306:localhost" />
    </bindings>
</site>

4. Replace the following

bindingInformation=”*:6306:localhost” with bindingInformation=”*:6306:*

5. Save the file.

6. Start a command prompt in administrator mode and run the following command.

netsh http add urlacl url=http://*:6306/ user=Everyone

7. Now debug the site again and you should be able to access the url using IP address or host name.

WCF – The incoming message has an unexpected message format ‘Raw’

I was testing out my own WCF REST Service using Fiddler and was getting error response “The incoming message has an unexpected message format ‘Raw'”.

After spending time diagnosing the message the clue was, the WCF was getting a request with no content type.

My contract was specifically expecting the request format to be XML using the following attribute

RequestFormat = WebMessageFormat.Xml

Hence added the content type as “application/xml” and things went fine.

The following is an example of Fiddler’s request for a REST POST with composite data type

Type: POST
URL: http://localhost:1510/GalleryService.svc/RestService/GetDataUsingDataContract/
Protocol: HTTP/1.1

Request Header:

User-Agent: Fiddler
Host: localhost:1510
Content-Length: 198
Content-Type: application/xml

Request Body:

<CompositeType xmlns="http://schemas.datacontract.org/2004/07/Net.BinaryBits.Apps.BBGallery.WebService"><BoolValue>true</BoolValue><StringValue>String content</StringValue></CompositeType>

Showing items counts in SharePoint 2010 Search Refinement Panel

Bringing search count in refinement panel of SharePoint 2010 search result page is very easy and straight forward.

  1. Edit the page containing the search result page with refinement panel.
  2. Go to the web part properties of refinement panel.
  3. Expand the “Refinement” section and edit “Filter Category Definition”
  4. For each “Category” add ShowCounts=”Count”
  5. Check-in and publish the page
<Category Title="Title" Description="Use this filter to restrict results authored by a specific author" Type="Microsoft.Office.Server.Search.WebControls.ManagedPropertyFilterGenerator" MetadataThreshold="1" NumberOfFiltersToDisplay="4" MaxNumberOfFilters="20" SortBy="Frequency" SortByForMoreFilters="Name" SortDirection="Descending" SortDirectionForMoreFilters="Ascending" ShowMoreLink="True" MappedProperty="Title" MoreLinkText="show more" LessLinkText="show fewer" ShowCounts="Count"/>

If the count doesn’t show up, then uncheck the “Use Default Configuration” checkbox under the same “Refinement” section.

Intellisense for AXML files doesn’t work in Visual Studio 2012

Most of the people who work with Xamarin’s Mono for Android in Visual Studio 2012 face a bug where Intellisense doesn’t work for AXML in source view.

One of the fix which worked for me is mentioned below.

  1. Launch Visual Studio 2012
  2. Open a solution with .AXML file in it
  3. Now XML main menu should be visible on top
  4. Open “Schemas…” menu
  5. Sort by “File Name” column and see if “android-layout-xml” and “schemas.android.com.apk.res.android” are there. If found, skip to step 13
  6. If not found, go to “Program Files” if 32-bit system or “Program Files (x86)” if 64-bit system.
  7. Then go to “\MSBuild\Novell” or “\MSBuild\Xamarin\Android”
  8. You should be able to see 2 files “android-layout-xml.xsd” and “schemas.android.com.apk.res.android.xsd”
  9. Copy these 2 files to “\Microsoft Visual Studio 11.0\Xml\Schemas”
  10. Again open the “Schemas…” menu as mentioned in steps 3&4
  11. Now click “Add…” button and add these 2 files which should be located as mentioned in step 7 & 8
  12. Now restart visual studio and the XML editor for design layout should work fine with Intellisense
  13. From step 5….
  14. If above steps don’t work, then close the Visual Studio 2012.
  15. Now open “Developer command prompt for VS2012” under Windows programs menu.
  16. Type “Devenv /ResetSettings” without quotes.
  17. Launch Visual Studio 2012 and see if Intellisense works.
  18. If still not working, better go to Xamarin  forums and post there.

Bringing Window to front in WPF

Recently I was working on WPF application where the Window would be minimized to tray and when user click’s the tray icon, the window has to show up in front of other windows.

I tried lot many variants and had trouble with Windows 7 and Windows 2008 R2. The following code finally worked for me.

Note: This code was present in the Window which was supposed to be controlled. If required replace “this” with actual reference of the Window.

if (!this.IsVisible)
{
    this.Show();
}
this.WindowState = WindowState.Normal;
this.Activate();
this.Topmost = true;
this.Topmost = false;
this.Focus();

Convert List<int> to List<string> in C#

I was faced with a micro challenge, of converting a List<int> to List<string>. After struggling for some time, decided to Google and found the the following solution !

List intList = new List();
List stringList = new List();

for (int i = 0; i < 10; i++)
	intList.Add(i);

stringList = intList.ConvertAll(delegate(int i) { return i.ToString(); });

Source: http://stackoverflow.com/questions/44942/cast-listint-to-liststring-in-net-2-0

TFS 2010: MSF Agile vs. Visual Studio SCRUM 1.0 Smackdown

TFS 2010: MSF Agile vs. Visual Studio SCRUM 1.0 Smackdown – Chris’s Blog – Just weedin around Microsoft – Site Home – TechNet Blogs(Click to view)

 

TFS 2010: MSF Agile vs. Visual Studio SCRUM 1.0 Smackdown– Planning w/ Agile (Part II) – Chris’s Blog – Just weedin around Microsoft – Site Home – TechNet Blogs(Click to view)

 

TFS 2010: MSF Agile vs. Visual Studio SCRUM 1.0 Smackdown — Planning w/ Agile (Part III) – Chris’s Blog – Just weedin around Microsoft – Site Home – TechNet Blogs(Click to view)

Access Denied – SharePoint code execution

When doing certain code operations in SharePoint like getting list of templates will lead to “Access Denied” exceptions. For such instances we can wrap the code within the following lines to execute code with elevated privileges.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
        //Code goes here
});

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

We were developing a Server Object Model based functionality in SharePoint involving site creation using template. During development we use to get the following error in quick watch window.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

To solve this issue we added the following code before the actual statement and issue was solved.

SPSecurity.CatchAccessDeniedException = false;

 

Deleting a file from library using SharePoint ASMX web service

The following is the code for deleting a particular file from a library using SharePoint ASMX web service.
The technique involves identifying the document ID using “GetListItems” of the file and then executing “UpdateListItems”

public string DeleteFileFromSharePoint(string siteUrl, string libraryName, string fileName, FileDeleteInput input)
    {
        Lists listService = new Lists(); //Web reference of http://<server>/sites/<site>/_vti_bin/lists.asmx
        listService.Url = "http://<server>/sites/<site>/_vti_bin/lists.asmx";
        listService.UseDefaultCredentials = true;
        string sourceUrl = fileName;
        string output = string.Empty;

        try
        {
            int fileId = GetFileIdFromList(siteUrl, libraryName, fileName, listService.Url);

            XmlDocument doc = new XmlDocument();
            XmlElement Batch = doc.CreateElement("Batch");
            Batch.SetAttribute("OnError", "Continue");
            Batch.SetAttribute("ListVersion", "1");
            Batch.SetAttribute("ViewName", "");
            string strBatch = "<Method ID='1' Cmd='Delete'>";
            strBatch += "<Field Name='ID'>" + fileId + "</Field>";
            strBatch += "<Field Name='FileRef'>" + siteUrl + libraryName + "/" + fileName + "</Field>";
            strBatch += "</Method>";
            Batch.InnerXml = strBatch;

            XmlNode returnvalue = listService.UpdateListItems(libraryName, Batch);

            if (returnvalue.InnerXml.Contains("0x00000000"))
            {
                output = "Success: File Deleted";
            }
            else if (returnvalue.InnerXml.Contains("Invalid file name"))
            {
                output = "Failure: No such file exists";
            }
            else if (returnvalue.InnerXml.Contains("Access denied"))
            {
                output = "Failure: No such file exists";
            }
            else
            {
                output = "Failure: File couldn't be deleted";
            }
        }
        catch (SoapException ex)
        {
            throw ex;
        }
        catch (Exception)
        {
            throw ex;
        }
        return output;
    }

    protected int GetFileIdFromList(string siteUrl, string libraryName, string fileName, string serviceUrl)
    {
        int id = 0;

        Lists listService = new Lists(); //Web reference of http://<server>/sites/<site>/_vti_bin/lists.asmx
        listService.Url = serviceUrl;
        listService.UseDefaultCredentials = true;

        // Build the CAML Query
        System.Text.StringBuilder queryStringBuilder = new System.Text.StringBuilder();
        queryStringBuilder.Append("     <Query>");
        queryStringBuilder.Append("         <Where>");
        queryStringBuilder.Append("             <Eq>");
        queryStringBuilder.Append("                  <FieldRef Name=\"FileLeafRef\" />");
        queryStringBuilder.Append("                  <Value Type=\"Text\">" + fileName + "</Value>");
        queryStringBuilder.Append("             </Eq>");
        queryStringBuilder.Append("        </Where>");
        queryStringBuilder.Append("    </Query>");

        XmlDocument query = new XmlDocument();
        query.LoadXml(queryStringBuilder.ToString());

        //Build the View Query 
        queryStringBuilder.Clear(); // Clear the string builder
        queryStringBuilder.Append("    <ViewFields>");
        queryStringBuilder.Append("    <FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" /><FieldRef Name=\"Name\" />");
        queryStringBuilder.Append("    </ViewFields>");

        XmlDocument viewFields = new XmlDocument();
        viewFields.LoadXml(queryStringBuilder.ToString());

        //Build the CAML Query Options
        queryStringBuilder.Clear(); // Clear the string builder
        queryStringBuilder.Append("    <QueryOptions>");
        queryStringBuilder.Append("         <Folder>" + libraryName + "/</Folder> />");
        queryStringBuilder.Append("    </QueryOptions>");

        XmlDocument queryOptions = new XmlDocument();
        queryOptions.LoadXml(queryStringBuilder.ToString());

        XmlNode listItems = listService.GetListItems(libraryName, null, query, viewFields, null, queryOptions, null);

        foreach (XmlNode outerNode in listItems.ChildNodes)
        {
            if (outerNode is XmlWhitespace)
                continue;
            else
            {
                if (outerNode.Name == "rs:data")
                {
                    foreach (XmlNode innerNode in outerNode.ChildNodes.OfType<XmlNode>())
                    {
                        if (innerNode is XmlWhitespace)
                            continue;
                        else
                        {
                            id = Int32.Parse(innerNode.Attributes["ows_ID"].Value.ToString());
                        }
                    }
                }
            }
        }

        return id;
    }