Monday, December 31, 2012

Sql Server Schema Comparision tool: Open DBDiff

Came across a nice open source tool that allows you to perform schema compares on Sql-Server. I liked it and wanted to share it!

Link: http://opendbiff.codeplex.com/

Description from the codeplex site:

Open DBDiff is an open source database schema comparison tool for SQL Server 2005/2008.
It reports differences between two database schemas and provides a synchronization script to upgrade a database from one to the other.

Screen1.jpg

Sunday, December 09, 2012

jqZoom–Javascript image zooming plugin

Came across this useful jQuery plugin called jqZoom that allows you to setup image zooming on your web-pages: http://www.mind-projects.it/projects/jqzoom/

image

Wednesday, November 21, 2012

Asp.Net MVC 4–Creating an AJAX page and using JQueryUI dialog

This is a very quick tutorial on how to create a page that displays data using AJAX. In addition, I will also show how to use the JQueryUI dialog element.

First a quick description of the page we are going to build:

image

There are 5 links on the page. When you click on one of the links 2 parts of the page are updated via jquery. (The div at the bottom and the dialog to the right).

Step 1: Create a MVC 4 Internet application.
Create a new MVC 4 internet application project, which we will use for this tutorial.

Step 2: Check to make sure “UnobtrusiveJavaScriptEnabled” is set to true in your web.config file.

Step 3: Add the references to the unobtrusive scripts in _layout.cshtml:
This is done by adding the line: @Scripts.Render("~/bundles/jqueryval") right after the line: @Scripts.Render("~/bundles/jquery")
image

Note: FYI: The reference to “~/bundles/jqueryval” is based on the bundle names defined in “BundleConfig.cs”.

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

Step 3: Add a new action to the HomeController, that will return a partial view:

public ActionResult IndexData(int id)
        {
            ViewBag.Id = id;
            ViewBag.Title = "The ID is: " + id;
            return PartialView();
        }

Step 4: Create a view for the IndexData action:

Right click in the action and select “Add View” and select the defaults.

Add the following code to the new IndexData.cshtml page:

@{
   
}
@Html.Hidden("Id",(int)ViewBag.Id)
@Html.TextBox("Title",(string)ViewBag.Title)

Step 4:Update Index.cshtml to show the links and allow calls to occur using AJAX:

Add a reference to the CSS files used by JqueryUi by adding the following code:

@Styles.Render("~/Content/themes/base/css")

Add an Ajax.ActionLink:

@Ajax.ActionLink("ajax load for id: 101", "IndexData", new {id = 101}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})

The above line, adds a link with the text “ajax load for id: 101”. It will call the “IndexData” action on the HomeController and it will pass it the value of 101. Finally, check out the AjaxOptions values:
- The AJAX call will be performed as a GET operation
- The call will result in replacing the DOM with the data that is returned
- If the call succeeds, the “SuccessFunction” will be called.
- Finally the data that is returned by the ajax call will update a DOM element named “myDiv”

We will add a few more such links:

@Ajax.ActionLink("ajax load for id: 202", "IndexData", new {id = 202}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
@Ajax.ActionLink("ajax load for id: 303", "IndexData", new {id = 303}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>

The next step is to add a couple of divs that will be used to display the data.

<div id="myDiv"></div>
<div id="myDiv2" style="border-width: medium; border-color: black"></div>

The first div will be used for the dialog and the 2nd div for updating a DOM element directly on the page.

Finally:

Add the following code to the end of the page:

@section scripts
{
    @Scripts.Render("~/bundles/jqueryui")
    <script>
        $(function() {
            $("#myDiv").dialog({ autoOpen: false });
        });
        function SuccessFunction(data) {
            $("#myDiv").dialog("open");

            $("#myDiv2").html(data);
        }
    </script>
}

Lets break down the code:

1. @Scripts.Render("~/bundles/jqueryui"): This line adds the reference to the JqueryUI scripts

2. $(function() : The ready-function, sets up myDiv to be a dialog. In addition, it sets it up to not open by default.

3. function SuccessFunction: This is the function that is called when the Ajax calls return. It opens the dialog and also updates the 2nd div to show the same data in 2 different ways.

Final code for the index.cshtml

@{
    ViewBag.Title = "Home Page";
}
@Styles.Render("~/Content/themes/base/css")
@Ajax.ActionLink("ajax load for id: 101", "IndexData", new {id = 101}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
@Ajax.ActionLink("ajax load for id: 202", "IndexData", new {id = 202}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
@Ajax.ActionLink("ajax load for id: 303", "IndexData", new {id = 303}, new AjaxOptions {HttpMethod = "Get", InsertionMode = InsertionMode.Replace, OnSuccess = "SuccessFunction", UpdateTargetId = "myDiv"})
<br/>
<div id="myDiv"></div>
<div id="myDiv2" style="border-width: medium; border-color: black"></div>
@section scripts
{
    @Scripts.Render("~/bundles/jqueryui")
    <script>
        $(function() {
            $("#myDiv").dialog({ autoOpen: false });
        });
        function SuccessFunction(data) {
            $("#myDiv").dialog("open");
            $("#myDiv2").html(data);
        }      
    </script>
}

Thursday, November 15, 2012

ASP.Net MVC–Returning XML

If you need to return xml content from an MVC controller, the easiest way to do it is to use the “Controller.Content” method.

public class TestController : Controller
{
        public ActionResult Index()
        {
             string result = “<books><book/></books>”
             return this.Content(result, "text/xml");
        }
}

Wednesday, November 14, 2012

Asp.Net WebApi–allowing format to be specified in the URL

By default WebAPI looks at the header to determine how to serve back content. But what if you cant set the header in your client app and so you need to specify the format via the URL?

What you need to do is to add a query string mapping for the XML formatter. This can be done using the following code in “Application_Start” of the Global.aspx.cs file:

MediaTypeFormatter xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xmlFormatter.AddQueryStringMapping("format", "xml", "text/xml");

And what if you want XML to be your default formatter? The easy way I found for this was to reorder the formatters in “GlobalConfiguration.Configuration.Formatters”, so that the XML formatter was the first in the list.

MediaTypeFormatter xmlFormatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
MediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

GlobalConfiguration.Configuration.Formatters.Remove(xmlFormatter);
GlobalConfiguration.Configuration.Formatters.Remove(jsonFormatter);
GlobalConfiguration.Configuration.Formatters.Insert(0,jsonFormatter);
GlobalConfiguration.Configuration.Formatters.Insert(0, xmlFormatter);

Note: If you reorder the formatters, you will need to add a query string mapper for JSON:

jsonFormatter.AddQueryStringMapping("format", "json", "application/json");

Monday, November 12, 2012

Calling webservices from SqlServer Reporting Services (SSRS)

There is surprisingly very little information on the web on how to call webservices from SSRS. So here is a quick list of stuff that I found out:

Note: I am using WCF webservices for what I was doing (shouldn’t matter if you are using some other kind of service, as long as it’s a SOAP service).

Note 2: Use something like Fiddler to inspect the traffic to figure out what the request is going out as. It can be useful to figure out why a call is erroring out.

  1. Create a new data-source.
    1. Choose “Use a connection embedded in my report”
    2. Set the “connection type” as xml
    3. Enter the url to the webservice (eg: http://myserver/ssrsTest.svc)
  2. Right click on the data-source and select add “DataSet”
    1. Select “Use a dataset embedded in my report”
    2. Open the query designer and build your query in there.
  3. Here is what a query looks like to call a method named test that takes no parameters:
    1. <Query>
      <Method Name="test" Namespace="http://tempuri.org/">
      </Method>
      <SoapAction>http://tempuri.org/ITestService/Test</SoapAction>
      </Query>

      The namespaces were found by looking at the WSDL (target namespace defines the namespace)

      <wsdl:operation name="Test">
          <soap:operation soapAction="http://tempuri.org/ITestService/Test" style="document"/>
          <wsdl:input>
              <soap:body use="literal"/>
          </wsdl:input>
          <wsdl:output>
              <soap:body use="literal"/>
          </wsdl:output>
      </wsdl:operation>

  4. Here is what a query looks like to call a method named testWithParameters that takes one parameter
  5. <Query>
    <Method Name="testWithParameters " Namespace="http://tempuri.org/">
    <Parameters>
    <Parameter Name="testParameter"><DefaultValue>1</DefaultValue></Parameter>
    </Parameters>
    </Method>
    <SoapAction>http://tempuri.org/ITestService/testWithParameters</SoapAction>
    </Query>

Saturday, November 10, 2012

How to sideload Windows 8 store apps onto a development device

Here are the steps that one must go through to sideload a Windows 8 store app on to a development device for testing (the dev device is a device other than the one on which it was developed – as on the development machine, Visual Studio takes care of loading the app).

Build the app package

  1. Under Project > Store, select “Create App Packages”
    image
  2. Select No on the first page of the dialog (Do you want to build packages to upload to the Windows Store?)
    image
  3. Make sure you select an architecture that’s appropriate for the machine where you will be testing the package.
    image
  4. The next step will create the app package.
  5. Open the folder where the app package was created, you should find a file with the extension “appxupload”. If you look in the folder, you will also find a file named “Add-AppDevPackage.ps1”
  6. Copy the folder and its contents to the target machine.

Prep the target machine to be able to sideload the a

Note: this preps the target machine as a dev machine. What this means is that your app will run for only 3 months and then expire and you will have to reacquire the dev license.

  1. Run powershell as an administrator on the target machine (the easiest way to do this is to hit Windows key + Q and search for powershell. Tap and drag the powershell icon and you will see the context menu from where you can open it in admin mode).
    image
  2. Setup powershell to run in unrestricted mode by typing “set-executionpolicy unrestriced” and hitting enter. (note: you need to do this only one time per machine).
  3. Acquire a developer license by typing “Show-WindowsDeveloperLicenseRegistration” at the command prompt and following the steps in the dialog (you will have to sign in to your Windows Live account).
  4. To install the application, find the “add-appdevpackage.ps1” file that we found in step 5 above. Run it by typing “Add-AppDevPackage.ps1” and hitting enter.
  5. The application will be installed on the target machine and you will be able to run it from the dashboard.

Monday, November 05, 2012

CRM 2011 - Action Microsoft.Crm.Setup.Server.GrantConfigDBDatabaseAccessAction failed

I got the following error when I was installing CRM 2011 on one of our servers that had CRM 4 installed previously on it:

Action Microsoft.Crm.Setup.Server.GrantConfigDBDatabaseAccessAction failed.

Windows NT user or group 'Domain\SQLAccessGroup {GUID}' not found. Check the name again.

I was able to fix the error by deleting the following logins on the SqlServer being used by CRM:

DomainName\PrivReportingGroup {GUID VALUE}
DomainName\ReportingGroup {GUID VALUE}
DomainName\SQLAccessGroup {GUID VALUE}

Sunday, November 04, 2012

Screen capture in Windows 8

To capture a screen shot on a Windows 8 machine do the following:

Windows Surface devices: Hold down the Windows key while pressing the volume-down button (both are the hardware buttons on the surface – sorry doing this on your keypad will not work). The screen captures get stored in the Photos app under “Screenshots”

Windows 8:

Press “Windows” key + “Print Screen” (PrntScr). The screen shot gets stored under “Screenshots” in your picture library.

Saturday, November 03, 2012

Colorado 2012 Elections–Information Sources

Here are some resources that I found useful to fill out the 2012 ballot

  1. Vote411.org: A very good website for vote information. Enter your address and you get presented with a personalized list of questions that appear on your ballot. In addition, you get information on all the candidates for a particular race as well as some Q&A filled in by the candidates. Was extremely useful in figuring out where different candidates stand on various issues (especially for local races)
  2. Colorado Office of Judicial Performance Review: A review panel consisting of citizens and attorneys that evaluate and provide opinions on retaining judges. A good website to determine how to vote for judges.
  3. 2012 Blue Book: Ballot information booklet published by the State’s Legislative Council Staff
  4. ColoradoBallot.Net: A site with some basic information on ballot initiatives setup by an independent small business owner.
  5. League of Women Voters – Colorado: Another useful site for ballot information

Thursday, October 18, 2012

Sql Server 2008–Optimal BlockSize for drives

Did you know that the optimal block size for Sql Server data and log drives is 64Kb? (sometimes it can be 32kb)

An appropriate value for most installations should be 65,536 bytes (that is, 64 KB) for partitions on which SQL Server data or log files reside. In many cases, this is the same size for Analysis Services data or log files, but there are times where 32 KB provides better performance. To determine the right size, you will need to do performance testing with your workload comparing the two different block sizes.

To determine the block size of your drives, run the following command:

fsutil fsinfo ntfsinfo b:

Where b: is the drive.

The value you are looking for is “Bytes Per Cluster” and its reported in bytes.

Read about it at: http://msdn.microsoft.com/en-us/library/dd758814(v=SQL.100).aspx

Visio 2010 crashes all the time–Windows 7

Visio 2010 kept on crashing on my Windows 7 64 bit machine.

Found out that if I disabled the “Send to bluetooth” plugin, the crashes went away. (File => Options => Add-Ins => Manage (Com Addins) ==> Go)

Thursday, October 11, 2012

Powershell–Get the size of a database

Here is a powershell script that uses SMO to determine the size of a database:

$dbServer = “xxxxxx”
$databaseName = "yyyyyy"

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$sqlServerSmo = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server ($dbServer)
if ($sqlServerSmo.databases[$databaseName] -ne $null)
{
    Write-Host (($sqlServerSmo.databases[$databaseName].Size * 1MB) /1GB)
}
else
{
    Write-Host "Database $databaseName does not exist on server $dbServer"
}
Write-Host "Done"

Tuesday, October 02, 2012

Colorado Elections 2012–Blue Book

The Colorado 2012 blue book is available online at

http://www.colorado.gov/cs/Satellite?blobcol=urldata&blobheader=application%2Fpdf&blobkey=id&blobtable=MungoBlobs&blobwhere=1251822971738&ssbinary=true

This year the following measures are up for voting:

Amendment S - State Personnel System
Shall there be an amendment to the Colorado constitution concerning the state personnel system, and, in connection therewith, expanding the veterans' preference; increasing the number of candidates eligible to be appointed to a position; adjusting the duration of allowable temporary employment; allowing the flexibility to remove a limited number of positions from the system; modifying the residency requirement; adjusting the terms of service for members of the state personnel board; and requiring merit-based appointments to be made through a comparative analysis process?

Amendment 64 - Use and Regulation of Marijuana
Shall there be an amendment to the Colorado constitution concerning marijuana, and, in connection therewith, providing for the regulation of marijuana; permitting a person twenty-one years of age or older to consume or possess limited amounts of marijuana; providing for the licensing of cultivation facilities, product manufacturing facilities, testing facilities, and retail stores; permitting local governments to regulate or prohibit such facilities; requiring the general assembly to enact an excise tax to be levied upon wholesale sales of marijuana; requiring that the first $40 million in revenue raised annually by such tax be credited to the public school capital construction assistance fund; and requiring the general assembly to enact legislation governing the cultivation, processing, and sale of industrial hemp?

Amendment 65 - Colorado Congressional Delegation to Support Campaign Finance Limits
Shall there be amendments to the Colorado constitution and the Colorado revised statutes concerning support by Colorado's legislative representatives for a federal constitutional amendment to limit campaign contributions and spending, and, in connection therewith, instructing Colorado's congressional delegation to propose and support, and the members of Colorado's state legislature to ratify, an amendment to the United States constitution that allows congress and the states to limit campaign contributions and spending?

More info:

League of Woman Voters: http://www.lwvcolorado.org/docs/ballot-issues-2012.pdf

Thursday, September 27, 2012

Various object existence checks in Sql Server

Here are the basic scripts you need to check for the existence of various objects in a Sql Server database (tables, columns, etc)

Check if Database exists:

IF  EXISTS (SELECT name FROM sys.databases WHERE name = N'DataBaseName')
begin

-- Database Exists

end

Check if table exists:

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[schema].[tableName]')
AND type in (N'U'))
BEGIN
    --Table exists
END

Check if foreign key exists:

IF  EXISTS (SELECT * FROM sys.foreign_keys
WHERE object_id = OBJECT_ID(N'[schema].[foreignKeyName]')
AND parent_object_id = OBJECT_ID(N'[schema].[tableName]'))
Begin
    --foreign key exists
End

Check if index exists:

IF  EXISTS (SELECT * FROM sys.indexes
WHERE object_id = OBJECT_ID(N'[schema].[tableName]')
AND name = N'IndexName')Begin
--Index exists
END

Check if view exists:

IF  EXISTS (SELECT * FROM sys.views 
WHERE object_id = OBJECT_ID(N'[schema].[viewName]'))
Begin
--View exists
END

Check if column exists:

if Exists(select * from sys.columns 
where Name = N'columnName'
and Object_ID = Object_ID(N'tableName'))

begin

    -- Column Exists

end

Check if Stored Proc exists:

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[Schema].[StoredProcName]')
AND type in (N'P', N'PC'))
begin

-- Stored Proc exists

end

Check if Function exists:

IF  EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[Schema].[FunctionName]')
AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))

begin

-- Function Exists

end

Saturday, September 22, 2012

Colorado voter registration status

Do you know if you are current registered as a voter in Colorado, or if your registration status is still active? If you don’t, you can quickly check your status at the Secretary of State’s website: https://www.sos.state.co.us/voter-classic/secuVoterSearch.do?transactionType=voterSearch

And if you are not registered, you can register on the same site: https://www.sos.state.co.us/voter-classic/secuVerifyExist.do

Friday, September 21, 2012

Allocating arrays larger than 2GB in .Net

Prior to .Net 4.5, one could create arrays of a max size of 2gb even on 64 bit machines. (On 32 bit machines, this is a theoretical limit which is very hard to hit in practice, because of the level of fragmentation of the memory).

In .Net 4.5, one can now allocate arrays that are greater than 2gb in size. But before you can do that, you need to enable a setting on the machine’s runtime settings. To enable it you need to set “gcAllowVeryLargeObjects” to true. (Its set to false by default).

More info:

<gcAllowVeryLargeObjects> Element: http://msdn.microsoft.com/en-us/library/hh285054(v=VS.110).aspx

Runtime performance improvements in .Net 4.5:http://blogs.msdn.com/b/somasegar/archive/2012/05/16/net-improvements-for-cloud-and-server-applications.aspx

The GC changes were made in recognition of the importance of memory management for various kinds of server workloads.  Another such change has to do with array sizes.  In .NET 4 and earlier, no object could be larger than 2GB in size, even in 64-bit processes.  For certain workloads that use large arrays, however, this size limit can be constraining.  As such, .NET 4.5 supports lifting the limit for arrays in 64-bit processes, such that arrays may be larger than 2GB.  This means, for example, that you could allocate an array of Int32.MaxValue Int32s, even though such an array will consume 8GB.  Large objects in .NET are allocated on a special heap, known not coincidentally as the Large Object Heap (LOH);  .NET 4.5 has also seen significant performance improvements to the LOH, including usage of better algorithms for managing free memory in the heap.

-Somasegar

Tuesday, September 18, 2012

PowerShell: Recycle an AppPool using AppCmd

Script:

cls
$path = "$env:windir\system32\inetsrv\appcmd"
$return = ."$path" list APPPOOL /apppool.name:AppPoolName
if ($return.Contains("state:Started"))
{
    ."$path" Stop APPPOOL /apppool.name:AppPoolName
}
."$path" Start APPPOOL /apppool.name:AppPoolName

Monday, September 17, 2012

Powershell–Run Sql queries and returning data-sets

Here is how you can run sql queries that return data-sets:

function execute-Sql{
    param($server, $databaseName, $sql )
   
    $sqlConn = new-object System.Data.SqlClient.SqlConnection
    $sqlConn.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $databaseName
    $sqlConn.Open()
    $sqlCmd = new-object System.Data.SqlClient.SqlCommand
    $sqlCmd.CommandTimeout = 120
    $sqlCmd.Connection = $sqlConn
    $sqlCmd.CommandText= $sql
    $text = $sql.Substring(0, 50)
    Write-Host "Executing SQL => $text..."
   
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $sqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
   
    $sqlConn.Close()
   
    return $DataSet.Tables[0]
}

Example on how to call above script

cls;

$sqlQuery = "select sub.DomainName from SystemUserBase sub join `
SystemUserRoles sur on sub.SystemUserId = sur.SystemUserId join Role rb on rb.RoleId = sur.RoleId `
where sub.IsDisabled = 0 and rb.Name = 'System Administrator'"

$result = execute-Sql -server "CrmDbServer" -databaseName "National_Cinemedia_MSCRM" -sql $sqlQuery

$result

NotePad++, Regular Expressions and Replacement using found text

Scenario:

You have the following text and you want to copy the values in old to new

<UserMapping old="abc\dfs" new="" />
<UserMapping old="abc\adfad" new="" />
<UserMapping old="abc\sfsafsd" new="" />
<UserMapping old="abc\jdjfgg" new="" />

First you need to figure out the regex to match what you want. Here is what I have:

old="([A-Za-z\\]+)".*$

What you need to notice is that the part of the string that I want to match is inside parenthesis ( () ). This allows us to use the value in the replacement. The regex will match starting from old and end at the end of line. During the match a group will be created from whatever is in the parenthesis, in this case it will include all alphabets (upper and lower case), as well as the slash.

For the replacement, we will use the following string:

old="\1" new="\1" />

Here, notice that I use \1 for the old and new. The matched group value will be used for the old and new values.

Friday, September 14, 2012

CRM 2011–Powershell: Import-CRMOrganization

If you get a “The Deployment Service cannot process the request because one or more validation checks failed”, then know this:

Import-CRMOrganization will fail if the organization already exists. For the import to succeed, you need to drop the organization if it already exists. Wish this was documented somewhere!

Note: If you have already checked to make sure the organization doesn’t already exist, make sure that the “XRMDeployment” webservice is running under an appropriate account. Check this for more information on that: http://blogs.msdn.com/b/darrenliu/archive/2011/04/27/minimum-permissions-required-for-dynamics-crm-2011-setup-services-and-components.aspx (See the section on Deployment Service).

TopShelf–Framework for writing Windows Services

imageTopShelf is a .Net framework that makes it extremely simple to write Windows Services.

A simple example from their documentation shows just how easy it is to create a Windows Service from a Console based project:

 

public class TownCrier
{
    readonly Timer _timer;
    public TownCrier()
    {
        _timer = new Timer(1000) {AutoReset = true};
        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} an all is well", DateTime.Now);
    }
    public void Start() { _timer.Start(); }
    public void Stop() { _timer.Stop(); }
}

public class Program
{
    public static void Main()
    {
        HostFactory.Run(x =>                                 
        {
            x.Service<TownCrier>(s =>                        
            {
               s.ConstructUsing(name=> new TownCrier());     
               s.WhenStarted(tc => tc.Start());              
               s.WhenStopped(tc => tc.Stop());               
            });
            x.RunAsLocalSystem();                            

            x.SetDescription("Sample Topshelf Host");        
            x.SetDisplayName("Stuff");                       
            x.SetServiceName("stuff");                       
        });                                                  
    }
}

Saturday, September 08, 2012

Samsung Series 7 Slate–Installing Windows 8 RTM

I just received my Samsung Series 7 Slate that I won at the Denver Windows 8 Hackathon. There was only one problem with it, it came installed with Windows 7. No problem, it was an easy one to remedy:

First create a Windows 8 installation USB stick. (you will need to use the Windows 7 USB/DVD tool available here: http://wudt.codeplex.com/)

Insert the USB stick into the Slate.

Reboot the Slate. While the Slate is rebooting, press and hold the windows button. This will open the BIOS menu.
Use the right side “orientation” button and the volume Up/Down buttons, to go to the “Exit” tab. There you should be able to see your USB stick listed as one of the boot options.
Select it and click the “Windows” button.

This will start of the Windows 8 installer. After this, you pretty much follow along with the installation and prompts and you should be able to successfully install Windows 8 onto the Slate.

Update software:

Visit: http://www.samsung.com/us/support/owners/product/XE700T1A-A03US and download and install the Easy Settings application. Also update the BIOS from that site. Over the next couple of months you should also see updates drivers and software specifically made for Windows 8.

After thoughts:

Upgrade to Windows 8 was painless and it just worked. And Windows 8 on a touch pad device is awesome! Love it!

Windows 7 USB/DVD download tool fails to copy files

I was trying to create a bootable USB with Windows 8 using the “Windows 7 USB/DVD download tool”. It kept failing with a message that it was unable to copy the files. (I was using a 16gb USB stick).

After some searching, I found that if you make the USB stick bootable manually, then you can use the tool and it copies all the files successfully.

Here are the steps:

Open a command prompt window in administrator mode.

Run the following commands

diskpart
list disk
select disk #
(Here replace # with the disk number. Be careful to select the correct disk number, else you may end up loosing all your data).
clean
create partition primary
select partition 1
active
format quick fs=fat32
assign
exit
Now re-run the “Windows 7 USB/DVD download tool” and you should be able to successfully create a Windows 8 installation USB stick.

Friday, September 07, 2012

Extracting CRM plugin unsecure configuration information

Here is the SQL to extract the unsecure configuration information for a CRM plugin:

Select step.* from SdkMessageProcessingStepBase as step
LEFT JOIN PluginTypeBase as pluginType on pluginType.PluginTypeId = step.PluginTypeId
LEFT JOIN PluginAssemblyBase as pluginAssembly on pluginAssembly.PluginAssemblyId = pluginType.PluginAssemblyId
LEFT JOIN SdkMessageProcessingStepImageBase as stepImage on step.SdkMessageProcessingStepId = stepImage.SdkMessageProcessingStepId
--WHERE pluginAssembly.Name like 'plugin name'

Thursday, September 06, 2012

Sql Server converting Base64 to varchar and back

Especially useful to convert all the CRM data stored in the MSCRM database

Convert from base64 to varchar:

DECLARE
    @Encoded VARCHAR(max) = 'VGVzdA==',
    @Decoded VARCHAR(max)   
SELECT @Decoded = 
CAST(
    CAST(N'' AS XML).value(
        'xs:base64Binary(sql:column("bin"))'
      , 'VARBINARY(MAX)'
    )
    AS VARCHAR(MAX)
)
FROM (
    SELECT CAST(@Encoded AS VARCHAR(MAX)) AS bin
) AS bin_sql_server_temp;
PRINT @Decoded 

Convert from varchar to base64:

DECLARE
    @plain VARCHAR(max) = 'Test',
    @encoded VARCHAR(max)
SELECT @encoded = 
    CAST(N'' AS XML).value(
          'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
        , 'VARCHAR(MAX)'
    )
FROM (
    SELECT CAST(@plain AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp;

PRINT @encoded

Thursday, August 30, 2012

MVC Error: 0x800a1391 - Microsoft JScript runtime error: 'Sys' is undefined

If you get the error:

MVC 0x800a1391 - Microsoft JScript runtime error: 'Sys' is undefined

Then first check to make sure you have included the correct MVC javascript files:

C#:

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.debug.js") %>" 
    type="text/javascript"></script> 
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js") %>"
    type="text/javascript"></script>

VB.Net:

<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>

Saturday, August 25, 2012

CRM 4 - Could not load file or assembly ‘Microsoft.Crm.Tools.Admin.DMSnapinLib’

Error message:

Could not load file or assembly 'Microsoft.Crm.Tools.Admin.DMSnapinLib' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

We fixed this error by clearing out the Asp.Net temporary folder under the Microsoft.Net\Framework64\v2.xxxxx folder. After that we had to restart IIS before we were able to load up the site.

CRM 2011 upgrade issues and solutions

The following were some issues that we encountered when upgrading a CRM 4.0 installation to CRM 4.0 and I hope it helps others out there:

Issue 1: Connection string doesn’t like FQDN

Error| System.Exception: Action Microsoft.Crm.Setup.Server.AddServerAction failed. ---> Microsoft.Crm.CrmException: Exceeded column length: Column Name
   at Microsoft.Crm.SharedDatabase.DatabaseService.RestrictLength(Column column, PropertyEntry propertyEntry)
   at Microsoft.Crm.SharedDatabase.DatabaseService.BuildBaseInsertSql(PropertyBag columnSet)
   at Microsoft.Crm.SharedDatabase.DatabaseService.Create(String tableName, PropertyBag columnSet)
   at Microsoft.Crm.Admin.AdminService.CrmServerService.Create(String serverName, Guid scaleGroupId, Guid podId, ServerRoles roles, ServerState state)
   at Microsoft.Crm.Setup.Server.Utility.ConfigUtility.AddServerToConfigDB(String serverName, ServerRoles roles, ServerRoles roleExclusionMask)
   at Microsoft.Crm.Setup.Server.AddServerAction.Do(IDictionary parameters)
   at Microsoft.Crm.Setup.Common.CrmAction.ExecuteAction(CrmAction action, IDictionary parameters, Boolean undo)
   --- End of inner exception stack trace ---, Error, RetryCancel, Option1

This turned out to be caused by the fact that we were using the fully qualified domain name in CRM 4.0. Once we went into the Deployment Mananger and edited the organization to use just the simple name for the sql connection (i.e, without the xxxxx.domain.com), We were able to restart the CRM 2011 installer. Important: at this point we had to restore a snapshot of CRM 4.0, as CRM 2011 installer had removed the old installer.

Issue 2: Corrupted performance logs:

"Action Microsoft.crm.setup.common.registerasyncserviceAction failed"

Please see: http://support.microsoft.com/kb/949092 – Although this is for CRM 4.0, the article is applicable to CRM 2011. In our case, it turned out to be corrupted performance logs. The performance logs were rebuilt using the command “lodctr /R” from c:\windows\system32.

Sunday, August 19, 2012

Enumerating a list object when you don’t know the actual type

Here is the scenario I was working with:

I needed to write an extension method that would be able to convert any class to a string representation. The class could have properties that were lists of any type (eg: List<T>), but I wouldn’t know in advance what types might be implemented as lists in the class. Here is the code I came up with. Listed below is the code for metro apps as well as for normal .net apps: (The code to enumerate any object that is a List is highlighted in the code below).

Metro

static class ObjectExtensions
    {
        public static string Convert(this object obj)
        {
            var typeInfo = obj.GetType().GetTypeInfo();
            var sb = new StringBuilder();

            foreach (var info in typeInfo.DeclaredProperties)
            {
                var val = info.GetValue(obj, null);
                string strVal;
                if (val != null)
                {
                    var valType = val.GetType();
                    var valTypeInfo = valType.GetTypeInfo();
                   
                    if ((val is string)
                        || valTypeInfo.IsValueType)
                    {
                        strVal = val.ToString();
                    }
                    else if (valType.IsArray ||
                        (valTypeInfo.IsGenericType
                            && (valTypeInfo.GetGenericTypeDefinition() == typeof(List<>))))
                    {
                        Type genericArgument = valType.GenericTypeArguments[0];

                        var genericEnumerator =
                            typeof(System.Collections.Generic.IEnumerable<>)
                                .MakeGenericType(genericArgument)
                                .GetTypeInfo()
                                .GetDeclaredMethod("GetEnumerator")
                                .Invoke(val, null);
                        IEnumerator enm = genericEnumerator as IEnumerator;
                        StringBuilder sbEnum = new StringBuilder();
                        sbEnum.AppendLine("List:");
                        while (enm.MoveNext())
                        {
                            var item = enm.Current;
                            sbEnum.AppendLine("Item: " + item.Convert());
                        }
                        strVal = sbEnum.ToString();
                    }
                    else{
                        strVal = val.Convert();
                    }
                }
                else
                {
                    strVal = "null";
                }
                sb.AppendLine(info.Name + ": " + strVal);
            }

            return sb.ToString();
        }
    }

Windows .Net

static class ObjectExtensions
    {
        public static string Convert(this object obj)
        {
            var props = obj.GetType().GetProperties();
            var sb = new StringBuilder();

            foreach (var info in props)
            {
                var val = info.GetValue(obj, null);
                string strVal;
                if (val != null)
                {
                    var valType = val.GetType();
                    if ((val is string)
                        || valType.IsValueType)
                    {
                        strVal = val.ToString();
                    }
                    else if (valType.IsArray ||
                        (valType.IsGenericType
                            && (valType.GetGenericTypeDefinition() == typeof(List<>))))
                    {
                        Type genericArgument = valType.GetGenericArguments()[0];

                        var genericEnumerator =
                            typeof(System.Collections.Generic.IEnumerable<>)
                                .MakeGenericType(genericArgument)
                                .GetMethod("GetEnumerator")
                                .Invoke(val, null);
                        IEnumerator enm = genericEnumerator as IEnumerator;
                        StringBuilder sbEnum = new StringBuilder();
                        sbEnum.AppendLine("List:");
                        while (enm.MoveNext())
                        {
                            var item = enm.Current;
                            sbEnum.AppendLine("Item: " + item.Convert());
                        }
                        strVal = sbEnum.ToString();
                    }
                    else
                    {
                        strVal = val.Convert();
                    }
                }
                else
                {
                    strVal = "null";
                }
                sb.AppendLine(info.Name + ": " + strVal);
            }

            return sb.ToString();
        }
    }

Thursday, August 16, 2012

Using Linq to concatenate strings

string[]words = new string[]{"hello","world"};
string concatenated = words.Aggregate((w,n) => w + " " + n);

Returns "hello world"

Saturday, August 11, 2012

MS Windows 8–Hackathon–My experience

Pre-prep:

  1. Installed Windows 8 Release Preview
  2. Installed VS 2012
  3. Did some exploration of the Bing Maps sdk for metro (blogged about it here: Using Bing Maps in a Metro App)

Idea: Port my OptiRoute Windows Phone 7 app to Windows 8

8:30 am : Check in. Setup my area, pickup coffee!

9:00 am : Quick sketch of how I plan on migrating OptiRoute to Windows 8. Setup a default VS project based on the “Grid App”

9:15 am: uh! oh! – VS 2012 preview does not open my Windows Phone 7 projects:

image

Need to install VS 2010 if I need to open it – screw – I just need the code – NotePad++ to the rescue.

9:30 am: Came up with basic design on paper. Watching Jerry Nixon’s demo.

WP_000301

10:00 am: Jerry Nixon’s demo is still going on. First issue encountered. Added reference to the Bing Maps Geocode Service. Looks like in WinRT there is no “GeocodeCompleted” event to which I can add my own handler. Hmmm, looks like I need to use “Await Async” model.

This Windows Phone 7 code changes:

public class GeoCoder
    {
        public void GeoCode(string query, Action<List<Coordinate>> action)
        {
            GeocodeServiceClient client = new GeocodeServiceClient();
            client.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(client_GeocodeCompleted);
            GeocodeRequest request = new GeocodeRequest();
            request.Credentials = new Credentials();
            request.Credentials.ApplicationId = "Your Bing Maps Service Key Here";
            request.Query = query;
            client.GeocodeAsync(request, action);
        }

        void client_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                Action<List<Coordinate>> action = e.UserState as Action<List<Coordinate>>;
                List<Coordinate> coordinates = new List<Coordinate>();
                foreach (GeocodeResult geocodeResult in e.Result.Results)
                {
                    foreach (GeocodeLocation geocodeLocation in geocodeResult.Locations)
                    {
                        coordinates.Add(new Coordinate(geocodeLocation.Latitude, geocodeLocation.Longitude));
                    }
                }
                action(coordinates);
            }
        }
    }

Here is what the code looks like in WinRT:

async public Task<List<Coordinate>> GeoCode(string query)
        {
            GeocodeServiceClient client = new GeocodeServiceClient(GeocodeServiceClient.EndpointConfiguration.BasicHttpBinding_IGeocodeService);
            GeocodeRequest request = new GeocodeRequest();
            request.Credentials = new Credentials();
            request.Credentials.ApplicationId = "Bing Maps Service Key Here";
            request.Query = query;

            var geoCodeResponse = await client.GeocodeAsync(request);
            List<Coordinate> coordinates = new List<Coordinate>();
            if (geoCodeResponse != null)
            {
                foreach (GeocodeResult geocodeResult in geoCodeResponse.Results)
                {
                    foreach (GeocodeLocation geocodeLocation in geocodeResult.Locations)
                    {
                        coordinates.Add(new Coordinate(geocodeLocation.Latitude, geocodeLocation.Longitude));
                    }
                }
            }
            return coordinates;
        }

Wow! that code is so much more nicer looking! Me like this new Asynchronous programming model.

10:30 am: Jerry is still demoing his rad WinRT dev skills. Using geo-location, Netflix OData feeds to make an app.

10:31 am: For the last 15 minutes was fighting with a unit test project to get an Async test to run. It would not run!!
Took out the async keyword and it ran! weird!
Modified the unit test to not use the “await” keyword, which meant I could take out the “async” qualifier on the method.
Test is passing – woo! hoo! getting geo-coded results for my query!

[TestMethod]
       public void TestGeoCoder()
       {
           var geoCoder = new Bing.GeoCoder.GeoCoder();
           var asyncReturn = geoCoder.GeoCode("1 Microsoft Way");
           List<Coordinate> coordinates = asyncReturn.Result;
           Assert.IsNotNull(coordinates);
           Assert.IsTrue(coordinates.Count > 0);
       }

Also, needed to update the manifest of the test project to allow for internet connectivity for the tests to pass!

10:45 am: Jerry is finally done with his demo! He created a complete app in about 1 hour.

10:47 am: Looks like I cant call “Array.Sort(array,array)” (where the first array are the values and 2nd are the keys) method in a Metro app. Why would they have dropped this method?!!! WTF!
Need to implement my own code for this! (Note to self – see if I can get rid of the need for this sort completely).
For now, using a List of KeyValuePairs, ordering by the key and then using Linq to select the sorted set of keys

11:00 am: Looking good. All tests passing!
image

11:05 am: Migrated most of my base routing algorithm code. Now on to the UI

11:20 am: Working on the UI.
One needs to remember to set the active configuration platform to x86 for Bing Maps to work in the designer (x64 is not supported by the designer)

12:10 pm: Its lunch time. Still working on the UI

1:30 pm: Called in Jerry to help me with setting up a wrap panel. This is why these events are so cool. You get resources to help you through some of your road blocks. Thanks Jerry!

3:20 pm: Encountered a bunch of road blocks that I had to work through:
The biggest of which was that the map control has completely been changed in how things are done with it in the Metro SDK. I am still trying to figure out a lot of the stuff that I need to make the app ready for prime time (eg: Pushpin’s cant have color, line widths arent working correctly, unable to get the view rectangle, etc).

But here is where I am:

image

6:30pm: Things are coming along real nice and I am feeling nice about my app. Lots of unfinished features, but here is what I have gotten done now:

1. Loading a sample route.
2. Optimizing the sample route
3. Fly out menu to change map type (road, aerial, birds eye)
4. Sharing via email – share the route.
5. Searching for locations

7:15 pm: And we are done. Now the presentations start – Best of luck to me!

7:30 pm: Crap my application package is not working on the demo computer. Its only my package that’s having an error during installation. Jerry thinks its because I am using Bing maps and some dependency is not resolving. Thought I could demo it using my laptop. Nope cant do that – my laptop doesn’t have a VGA port (note to self, buy a HDMI to VGA convertor and keep in bag)

8:00 pm: I have been reschedule to come on at the end. Jerry forgot! He is asking everyone to vote! WAIT…. Jerry has an idea, use his laptop. It works. App is installed and I am going to demo it now!

8:03 pm: 3 minutes fly by during a presentation. Hit upon all the major features. Crossing my fingers.

8:30 pm: 17 apps were presented. 3 apps won the grand prize (Slate + Gift Card). My app (Get Around!) was one of them. I am stoked!

Parting thoughts:

The dev intro event to Win8 on Friday and the hackathon on saturday were well organized. Microsoft had every needed resource on hand. Xaml experts, Javascript experts, sys-admins to help installing Win8, great food and awesome give-aways and prizes. All we had to do was come with our laptops. Jerry Nixon did a great job running the whole show.

Here is what my completed app looked like:

02 03 04  
Initial un-optimized route Optimized route Sharing route via email  

Links:

Jerry Nixon: http://blog.jerrynixon.com/ 
Win 8 resources used during the dev event: http://blog.jerrynixon.com/2012/08/windows-8-resources-links-to-get.html
Joe Shirey: http://www.joeshirey.com/
Michael Palermo: http://palermo4.com/
Harold Wong: http://blogs.technet.com/b/haroldwong/ (has great post on installing Win8 using VHD. Also has posted VHDs that you can use to setup Win8 on your machine)

Friday, August 10, 2012

Metro Apps–Testing lifecycle events

How do you test how your app will behave when it is suspended?

When you run your app within the debugger, life-cycle events are suspended. But you can use the “debug location” toolbar to force events to occur. Find the debug location toolbar under: image

Now you can test life cycle events such as “Suspend”, “Resume” and “Suspend” and “Shutdown”

image

Windows Metro App–ListView reordering

A quick note on enabling reordering of list view items in Metro Apps.

1. In previous version of Windows 8, there was a bug and you could not bind the ListView to an ObservableCollection and have reording work. This has been fixed since the “Windows 8 Release Preview” and you can now use ObservableCollection.

2. For reording to work, it not enough to set “CanReorderItems” to true. You ALSO need to set “AllowDrop” to true.

Thursday, August 09, 2012

Wednesday, August 08, 2012

Migrate Reporting Services to another machine–Reporting Services Scripter

Came across this nifty little tool called “Reporting Services Scripter” which can be used to migrate RDLs to a different machine. In addition, it can also move other settings like schedules, etc. Another cool feature is that you can use it to migrate RDLs from a 2005 machine to a 2008 machine.

Download it from: http://www.sqldbatips.com/showarticle.asp?ID=62

Saturday, August 04, 2012

Using Bing Maps in a Metro App

Step 1: Download the Bing Maps SDK.

This is easier now as its been made into a Visual Studio Extension.

image

Step 2: Create a blank Metro App

Step 3: Reference the SDK dlls:

You need to reference Bing Maps as well as the Visual C++ runtime (don’t worry, this is only a dependency and you will not have to write an C++ code)

image

Step 4: Get your access key

To get your access key you need to sign up for a developer account at the Bing Maps developer portal (https://www.bingmapsportal.com/). Once you have created your account, you need to create a key for your metro app. Remember to set up your app as a Metro app when creating your key.

Step 5: Drop your key into your app.

A good practice is to make your key an application resource. This will make it easy to use it on any page that uses the Maps control.

To do this, open your App.xaml page and add the following line right after the “</ResourceDictionary.MergedDictionaries>” line:

<x:String x:Key="BingMapsApiKey">Insert Your Api Key</x:String>

image

Step 6: Reference the Bing.Maps namespace in the page where you intend to use the map control. To do this add the following line to the page declaration:

xmlns:bing="using:Bing.Maps"

image

Step 7: Add the map control. To do this, just add the following line in your page (I added it to the default grid that gets created when you create a blank page).

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <bing:Map x:Name="MyFirstBingMap" Credentials="{StaticResource BingMapsApiKey}" />
</Grid>

Step 8: Run your app and admire your creation Smile

image

Doing more:

Step 9: Centering the map to your location:

First, you need to enable your app to use location data. To do that, double click the “Package.appmanifest” file and on the capabilities tab, select “location”.

image

In the designer for you page, add a MapLayer to your page:

<bing:Map x:Name="MyFirstBingMap" Credentials="{StaticResource BingMapsApiKey}">
            <bing:MapLayer x:Name="MyMapLayer">
            </bing:MapLayer>
</bing:Map>

Add the following code to the “OnNavigatedTo” event in the page containing your map:

async protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Geolocator geo = new Geolocator();
            geo.DesiredAccuracy = PositionAccuracy.Default;
            var currentPosition = await geo.GetGeopositionAsync();

            Location loc = new Location()
            {
                Latitude = currentPosition.Coordinate.Latitude,
                Longitude = currentPosition.Coordinate.Longitude
            };

            MyFirstBingMap.SetView(loc, 13, 0);

            Canvas pushPin = new Canvas();
            pushPin.Children.Add(new Ellipse() { Fill = new SolidColorBrush(Windows.UI.Colors.Red), Width = 22, Height = 22, Stroke = new SolidColorBrush(Windows.UI.Colors.Black), StrokeThickness = 2 });

            MapLayer.SetPosition(pushPin, loc);
            MyMapLayer.Children.Add(pushPin);

        }

Running the application will result in the following map:

image

Things to notice:

1. The method is labeled as “async” this is because we are using the “await” keyword on the GetGeopositionAsync method of the GeoLocator.

2. Instead of using “Pushpin” control, I am using a canvas and drawing a circle. The reason is the Pushpin control does not seem to allow changing of colors or size. (Don’t know if this is a bug in the release preview or by design). Which is why I am using a custom control as my pushpin.

Thursday, August 02, 2012

The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments

If you get the “The non-generic method 'Microsoft.Practices.Unity.IUnityContainer.Resolve(System.Type, string, params Microsoft.Practices.Unity.ResolverOverride[])' cannot be used with type arguments” compiler error while building a Prism application, remember to add a using statement for “Unity” (using Microsoft.Practices.Unity;)

CRM–Setting the default page for all users

Unfortunately there is no supported way to do this. The only way I have found to do this is by updating the “homepagearea” and “homepagesubarea” values in the usersettingbase table in the organization database of CRM.

update UserSettingsBase
    set Homepagearea='default pane’
    ,Homepagesubarea='default tab'

After running the above script, you need to reset IIS, otherwise for users already logged into the system, will now see the change.

And below are the values for some of the panes and tabs that you can use for the script above.

Pane (Homepagearea) Value
Tab (Homepagesubarea) Value

Workplace

Workplace

 
 

Activities

nav_activities

 

Dashboards

nav_dashboards

 

Queues

nav_queues

 

Calendar

nav_calendar

 

Reports

nav_reports

 

Imports

nav_import

 

Duplicate Detection

nav_duplicatedetectionjobs

Sales       

SFA

 
 

Accounts

nav_accts

 

Contacts

nav_conts

 

Opportunities

nav_oppts

 

Leads

nav_leads

 

Goals

nav_goals

 

Goal Metrics

nav_metric

 

Rollup Queries

nav_goalrollupqueries

Saturday, July 28, 2012

Software coding jargon

An interesting list of new coding jargon: http://umumble.com/blogs/Programming/321/ (or check out this page for the original content: http://www.stackprinter.com/questions/new-programming-jargon-you-coined.html)

(The page is originally from StackOverflow, but that question was deleted and hence the link to stack-printer).

One of my favorites:
"Yoda Conditions"— using if(constant == variable) instead of if(variable == constant), like if(4 == foo). Because it's like saying "if blue is the sky" or "if tall is the man".

A history of software failures....

Came across this interesting graphic from an old IEEE article: http://spectrum.ieee.org/computing/software/why-software-fails


And while you are still interested in the topic, read the following:
Some stories on failures of software: http://vu.bits-pilani.ac.in/ooad/Lesson2/topic3.htm
History's worst software bugs: http://www.wired.com/software/coolapps/news/2005/11/69355?currentPage=all
And if you are looking for some latest stories, then the "Risks Digest" is a great place to get them: http://catless.ncl.ac.uk/Risks/

Thursday, July 26, 2012

Using WCF with windows authentication with an intranet ASP.Net website

Scenario:
You want to use windows authentication to protect a WCF service and the client is an ASP.Net intranet website (and has Windows Authentication turned on).

Steps:
Create your WCF webservice website (I am assuming that the web-service website is different from the intranet website).

Enable Windows Authentication for the site.

image

For the purposes of testing create a service method that returns the user info:

public string GetUserInfo()         
{
             string userinfo = string.Empty;
             var windowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
             if (windowsIdentity != null)
                 userinfo = windowsIdentity.Name;
             return userinfo;        
}

Setup the web.config for the service so that the end point uses basicHttpBinding with a configuration where the security mode is set to “TransportCredentialOnly” and the Transport’s clientCredentialType is set to windows. Here is what it will look like:

<system.serviceModel>
     <services>
       <service name="WcfService1.Service1">
         <endpoint address="Service1.svc" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration" contract="WcfService1.IService1" />
       </service>
     </services>
     <bindings>
       <basicHttpBinding>
         <binding name="basicHttpBindingConfiguration">
           <security mode="TransportCredentialOnly">
             <transport clientCredentialType="Windows" />
           </security>
         </binding>
       </basicHttpBinding>
     </bindings>
     <behaviors>
       <serviceBehaviors>
         <behavior>
           <serviceMetadata httpGetEnabled="true"/>
           <serviceDebug includeExceptionDetailInFaults="true"/>
         </behavior>
       </serviceBehaviors>
     </behaviors>
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />   </system.serviceModel>

Create your ASP.Net website (which will act as a client to your web-service). Set its authentication mode to “Windows” and make sure that you set "identity impersonate” to true.

image

Now add a reference to your web-service.

In your web.config make sure that the security mode is set to “TransportCredentialOnly” and the Transport’s clientCredentialType is set to windows. Here is an example:

<system.serviceModel>
     <bindings>
       <basicHttpBinding>
         <binding name="BasicHttpBinding_IService1">
           <security mode="TransportCredentialOnly">
             <transport clientCredentialType="Windows"/>
           </security>
         </binding>
       </basicHttpBinding>
     </bindings>
     <client>
       <endpoint address="http://xxxxxx/Service1.svc/Service1.svc"         binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"         contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
     </client>
   </system.serviceModel>

That should be it. When you call “GetUserInfo”, you should get the name of the user that is accessing the asp.Net website.