Sunday, February 26, 2012

WP7–providing feedback through vibration

Here is the code:

VibrateController vibrate = VibrateController.Default;
vibrate.Start(TimeSpan.FromMilliseconds(500));

Msdn: http://msdn.microsoft.com/en-us/library/microsoft.devices.vibratecontroller(v=vs.92).aspx

When to use Properties vs. Methods

From “Design Guidelines for Class Library Developers” comes the guidelines on how to chose whether you should use a property or a method: http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx#cpconpropertyusageguidelinesanchor1

Here is the info (copied from the MSDN page):

  • Use a property when the member is a logical data member. In the following member declarations, Name is a property because it is a logical member of the class.
  • Use methods when:
    • The operation is a conversion, such as Object.ToString.
    • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
    • Obtaining a property value using the get accessor would have an observable side effect.
    • Calling the member twice in succession produces different results.
    • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
    • The member is static but returns a value that can be changed.
    • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code.

Other guidelines:

Do not use write-only properties.

The following rules outline guidelines for using indexed properties:

  • Use an indexed property when the property's logical data member is an array.
  • Consider using only integral values or strings for an indexed property. If the design requires other types for the indexed property, reconsider whether it represents a logical data member. If not, use a method.
  • Consider using only one index. If the design requires multiple indexes, reconsider whether it represents a logical data member. If not, use a method.
  • Use only one indexed property per class, and make it the default indexed property for that class. This rule is enforced by indexer support in the C# programming language.
  • Do not use nondefault indexed properties. C# does not allow this.
  • Name an indexed property Item. For example, see the DataGrid.Item Property. Follow this rule, unless there is a name that is more obvious to users, such as the Chars property on the String class. In C#, indexers are always named Item.
  • Do not provide an indexed property and a method that are semantically equivalent to two or more overloaded methods.

And don’t forget the property naming guidelines: http://msdn.microsoft.com/en-us/library/fzcth91k(v=vs.71).aspx

  • Use a noun or noun phrase to name properties.
  • Use Pascal case.

Powershell & SMO–Copy and attach database

Mission: Copy mdf and ldf files from a source location to a destination computer and then attach them to the destination computer:

Script:

#### Variables that need to be specified....

##variables needed for copy: source
$mdfSourcePath = "\\SourceServer\backup\myDb.mdf";
$ldfSourcePath = "\\SourceServer\backup\myDb.ldf";

##variables needed for copy: destination
$mdfCopyToDestinationPath ="\\DestinationServer\d$\MSSQLData";
$ldfCopyToDestinationPath ="\\DestinationServer\l$\MSSQLLog";

##variables regarding the destination database
$databaseServer = "DestinationSqlServer";
$databaseName = "databaseName";
$mdfDestinationFolderForAttach = "d:\MsSqlData\";
$ldfDestinationFolderForAttach = "l:\MsSqlLog\"

##### end of variables that need to be specified


$mdfFileName = [System.IO.Path]::GetFileName($mdfSourcePath);
$ldfFileName = [System.IO.Path]::GetFileName($ldfSourcePath);

cls;


####### Drop the destination database if it already exists

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$sqlServerSmo = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server ($databaseServer)

Write-Host "Checking to see if $databaseName needs to be dropped....";
if ($sqlServerSmo.databases[$databaseName] -ne $null)
{
  Write-Host "Dropping database $databaseName on server $databaseServer"
  $sqlServerSmo.KillAllProcesses($databaseName)
  $sqlServerSmo.databases[$databaseName].drop()
  Write-Host "Database $databaseName on server $databaseServer has been dropped"
}
else
{
    Write-Host "Database $databaseName does not exist on server $databaseServer"
}
Write-Host "";
######### Copy files from source to destination

Write-Host "Copying mdf $mdfSourcePath to $mdfCopyToDestinationPath...."
Copy-Item $mdfSourcePath $mdfCopyToDestinationPath -Force
Write-Host "Copy complete!"

Write-Host "Copying mdf $ldfSourcePath to $ldfCopyToDestinationPath...."
Copy-Item $ldfSourcePath $ldfCopyToDestinationPath -Force
Write-Host "Copy complete!"
Write-Host "";
#######  Attach the database to detsination server


$datafile = [System.IO.Path]::Combine($mdfDestinationFolderForAttach, $mdfFileName);
$logfile = [System.IO.Path]::Combine($ldfDestinationFolderForAttach, $ldfFileName);

$sc = new-object System.Collections.Specialized.StringCollection;
$sc.Add($datafile) | Out-Null;
$sc.Add($logfile) | Out-Null;

Write-Host "Attaching $datafile and $logfile to $databaseServer....";
$Error.Clear();
try
{
    $sqlServerSmo.AttachDatabase($databaseName, $sc);
}
catch
{
    Write-Host $_.Exception;
    if ($Error.Count -gt 0)
    {
        Write-Host "Error Information" -BackgroundColor Red;
        $error[0] | fl -force ;
    }
}

Write-Host "Completed!!!" -BackgroundColor DarkGreen;

Read-Host "Press any key to continue....";

Saturday, February 25, 2012

SetDpmServer error logs

Could not find this information anywhere on the Internet and I just happened upon the file.

When running SetDPMServer, a log is created in your %windir%\temp and the file is called MSDPMAgentBootstrap0Curr

Trying to debug a weird error where SetDPMServer works when I am logged in locally on the protected client machine, but fails when I try and run it via power-shell from a remote computer.

Thursday, February 23, 2012

Powershell–calling from command line with arguments

Here is how you can create a batch file that allows you to call a powershell script and pass parameters to it:

powershell.exe -Command "& 'c:\scriptName.ps1' -argument1 '%1' -argument2 '%2' -argument3 '%3' –argument4 %4"

And you would call the batch file like so:

"HelloWorld" "Hello World 2012" "" $true

Things to note:

The script name is quoted.

The first 3 arguments are passed in as a quoted string. This is because you may be passing in the strings with spaces in them. (Note while calling your batch file you need to use double quotes around your string to pass it to powershell.

The last argument is not being passed in as a quoted string. This is because in my case I am passing a boolean value and need it to be interpreted as such.

The above format works perfectly with Windows Task Scheduler (where your task calls the batch file and you setup the arguments in the task-action.

Bing! Weather Page

I really like the Bing weather page compared to Google’s as you get all the information you need in one page and you also get to compare the forecasts from the big 3 (Weather.com, AccuWeather and Weather Underground) all in one page without ever having to navigate away from that one page.

image

Compare this to the Weather page on Google, where you do get your weather at a glance, but to see the weather from the other providers, you have to navigate away from the search page.

image

The nice thing is that both Google and Bing bring up the weather page based on a search for weather.

Wednesday, February 22, 2012

WCF Tracing–Message Logging and Tracing

Note: this is an update to my previous post: http://blog.aggregatedintelligence.com/2011/09/wcfsetting-up-tracing.html

Tracing is a useful way to determine problems with WCF. You can enable them through your config file.

Here is how you can enable both message logging (which logs the messages being sent to the WCF service) and tracing (which allows you to see all the steps through which WCF is going in servicing your request):

Under <configuration> add System.Diagnostics as shown below:

<system.diagnostics>
  <sources>
   
    <!—tracing is enabled through this section—>

    <source propagateActivity="true" name="System.ServiceModel"
    switchValue="Information, ActivityTracing">
      <listeners>
        <add type="System.Diagnostics.DefaultTraceListener"
        name="Default">
          <filter type="" />
        </add>
        <add name="sdt">
          <filter type="" />
        </add>
      </listeners>
    </source>

    <!—message logging is enabled through this section—>
    <source name="System.ServiceModel.MessageLogging"
    switchValue="Information, ActivityTracing">
      <listeners>
        <add type="System.Diagnostics.DefaultTraceListener"
        name="Default">
          <filter type="" />
        </add>
        <add name="ServiceModelMessageLoggingListener">
          <filter type="" />
        </add>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add initializeData="web_messages.svclog"
    type="System.Diagnostics.XmlWriterTraceListener"
    name="ServiceModelMessageLoggingListener"
    traceOutputOptions="Timestamp">
      <filter type="" />
    </add>
    <add initializeData="traceLog.svclog"
    type="System.Diagnostics.XmlWriterTraceListener" name="sdt"
    traceOutputOptions="DateTime, Timestamp">
      <filter type="" />
    </add>
  </sharedListeners>
  <trace autoflush="true" />
</system.diagnostics>

Under <system.serviceModel> add the diagnostics node as shown below:


<diagnostics>
  <messageLogging logEntireMessage="true"
  logMalformedMessages="true" logMessagesAtTransportLevel="true" />
</diagnostics>

Tuesday, February 21, 2012

WP7 #30tolaunch–Nokia Lumia 800

I found a brown package waiting at my door when I returned home yesterday and upon opening it I was surprised to find that Microsoft had sent me my Nokia Lumia 800 as part of the “30 to launch” program.

wp7-nokiaLumia

Here are some of my thoughts upon unboxing it:

  1. It needs a micros-SIM card. I have a normal SIM card – so I am going to have to wait to try out all the phone features. (Note: My current contract is with AT&T and all I had to do was to go into the store and they swapped out my SIM card for free. If you are adventurous, you can cut your existing SIM card to the micro SIM card factor, see “How to convert a SIM to a micro SIM with a meat cleaver!”)
  2. There was no getting started pamphlet in the box. So it took me a while to figure out where the USB cord and the SIM card go. Hint: they go in on the top side. (Press the button labeled (1) and the USB door will pop open. Slide the piece labeled (2) and the SIM card holder should pop out) (see: Nokia user guide)
     image
  3. The phone was heavier than I expected it to be. (this is subjective, as I havent checked out its actual weight, but compared to my Samsung Focus, it definitely feels heavier). But, I am still figuring out if the feeling of heft in my hand is a good or bad thing, as the heft definitely makes the phone feel substantial in my hand (and not like a plastic toy).
  4. The screen is beautiful. Even compared to the Samsung’s AMOLED screen, this one is definitely more vibrant. The touch screen also feels a lot more responsive.
  5. Oddly, I got a USB charger that had the round UK plug prongs instead of the flat prongs that are used in the US. I think that is because these are units made for sale in UK (or Europe) and were brought here especially for the #30ToLaunch program. Luckily it uses the MicroUSB cable, so I already have many chargers sitting around and didn’t need the packaged USB charger.
    image

 

This is definitely a nice phone!

Wednesday, February 15, 2012

Bing Route Service Reference errors in Visual Studio

When I was trying to reference the Bing Route service in a WP7 app (http://dev.virtualearth.net/webservices/v1/routeservice/routeservice.svc), I kept getting errors from SvcUtil that the service could not be referenced properly. Some of the error messages looked like the following:

Custom tool warning: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='http://dev.virtualearth.net/webservices/v1/route/contracts']/wsdl:portType[@name='IRouteService']
XPath to Error Source: //wsdl:definitions[@targetNamespace='http://dev.virtualearth.net/webservices/v1/route']/wsdl:binding[@name='BasicHttpBinding_IRouteService']

Not sure why the errors were being raised, but what I found was that if I deleted the existing service reference and then restarted Visual Studio and then re-added the service reference, the errors went away. WEIRD! but it works now.

SqlServer SMO–Truncating logs

The TruncateLogs method (Database class) is not supported on SqlServer 2008 (and above).

Here is how you do it in SqlServer 2008 using PowerShell

$serverName = "server"
$databaseName = "database"

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$sqlServerSmo = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server ($serverName )
if ($sqlServerSmo.databases[$databaseName] -ne $null)
{
     $database = $sqlServerSmo.databases[$databaseName];
     if ($database)
    {
         $database.RecoveryModel = [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple;
         $database.Alter();
         $database.LogFiles | ForEach-Object {
                $_.Shrink(2, [Microsoft.SqlServer.Management.Smo.ShrinkMethod]::Default);
         }

    }
}

And here is how you change the database owner (where $database is retrieved as shown in the snippet above).:

$database.SetOwner("SA");
$database.Alter();

Dynamics CRM– Listing javascript used by forms

The javascript used in forms is stored in the table “OrganizationUIBase” in the CRM database for your organization [Organization_MSCRM].

Here is a quick query to list the entities and the script that is being used (the script is stored in FormXML field):

SELECT [Name] as EntityName
      ,[PhysicalName] as EntityPhysicalName
      ,[FormXml]
  FROM [Organization_MSCRM].[dbo].[OrganizationUIBase] o
  Join [Organization_MSCRM].[MetadataSchema].[Entity] e ON e.ObjectTypeCode = o.ObjectTypeCode
  where o.version = (SELECT max(oi.Version)
  FROM [Organization_MSCRM].[dbo].[OrganizationUIBase] oi
  WHERE oi.FormId = o.FormId)
  and o.formXml like '%<event%active="true">%'
 

The scripts finds those scripts that have been set to active. The script itself appears within the Event tag. (important: never attempt to manipulate the data in the CRM database directly – bad things will happen to you!).

Saturday, February 11, 2012

WP7–Your Last About Diaglog

Came across “Your Last About Dialog” (YLAD) project for Windows Phone 7. It makes it extremely easy to build an About page for your WP7 application (About pages are a requirement for WP7 apps, without which you will fail certification).

Using YLAD is as simple as installing it as a NuGet package for your phone project, configuring a few values in a XML file and setting up the link to bring up the page.

In less than 10 minutes I had the following Pivot pages created:

image  image

Install YLAD via NuGet or by downloading it from CodePlex: http://ylad.codeplex.com/

In addition, check out the one page documentation that goes into the configuration of the About page: http://ylad.codeplex.com/documentation

Nuget package manager does not update in Visual Studio Ultimate

I kept getting notified that there was an update for Nuget, but everytime I tried to install the update, the installation would fail with the following message:

The signature on the update version of 'NuGet Package Manager' does not match the signature on the installed version. Therefore, Extension Manager cannot install the update.

And when I tried to uninstall the Nuget package manager manually, the uninstall button would appear greyed out.

The solution I found was to right click on the Visual Studio shortcut and open it up in Administrative mode. In admin mode, I was able to uninstall Nuget and then was successfully able to install the newest version of Nuget.

Now you know!

Friday, February 10, 2012

Windows Phone 7–Application Lifecycle

MSDN reference on the WP7 application lifecycle: http://msdn.microsoft.com/en-us/library/ff817008(VS.92).aspx

Execution Model Diagram for Windows Phone 7.5

And remember to enable “Fast Application Switching” (FAS) in your app, all you need to do is to check the IsApplicationStatePreserved property and perform state loading only if the property is false.

private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            if (!e.IsApplicationInstancePreserved)
            {
                LoadStateFromStorage();
            }
        }

Wednesday, February 08, 2012

SqlServer–getting only the date part of DateTime field

One method is to use the DatePart method.

But here is a much nicer way to get the Date Portion:

CAST(FLOOR( CAST( GETDATE() AS FLOAT ) )AS DATETIME)

Monday, February 06, 2012

WP7–using Application.Resources to define string resources

Scenario: You need to define a string value that needs to be reused across your application (eg: Application Title)

One way the above scenario can be implemented is by using the “Application.Resources” in the App.Xaml file.

The first step is to define the string resource. This is done by defining the type (clr:String) and a key that will be used to access the string. The value is also defined here:

<Application.Resources>
        <clr:String x:Key="ApplicationTitle">OptiRoute</clr:String>
</Application.Resources>

The above resource can then be accessed in your XAML markup using StaticResource markup extension:

<TextBlock x:Name="ApplicationTitle" Text="{StaticResource ApplicationTitle}" Style="{StaticResource PhoneTextNormalStyle}"/>

Saturday, February 04, 2012

Windows Phone 7–Reoderable list box

I needed a list box that would allow users to reorder items in the box by clicking and dragging a handle. Weirdly, the SDK does not support this kind of behavior (I would have thought that something like this would be part of the standard behavior).

My next step was to see if there was an existing control built by someone else on CodePlex and I had no luck there either. I finally, came across Jason Ginchereau’s blog on the “ReorderListBox” that he wrote. And its an awesome implementation of a re-orderable list.

Check out his blog-post for more details on the capabilities of his control. I have been trying it out and its exactly what I wanted.

http://blogs.msdn.com/b/jasongin/archive/2011/01/03/wp7-reorderlistbox-improvements-rearrange-animations-and-more.aspx

Below is a screen of the reorderable list in-action: I am moving the 2nd item to the first place.

image

Friday, February 03, 2012

Powershell and calling commands

Some tips I gathered while working on invoking commands from Powershell. (an example would be calling iisreset from Powershell).

1. The Call (or invocation) Operator “&”

The call operator is used to run a command or even a script block. Here is an example:

$cmd = "systeminfo" #where systeminfo is a dos-command
& $cmd

2. Passing parameters to the command:

If you try:

$cmd = "ping www.google.com"
& $cmd

You will find that an error will be thrown. To pass parameters to the call-operator, you need to send them as separate strings:"

$cmd = "ping"
& $cmd "www.google.com"

In addition, if you need to pass separate arguments, each one should be sent as a separate string.

$cmd = "ping"
& $cmd "www.google.com" "-n" "2"

One nice little work-around to passing each argument as a separate quoted string is to use the split command:

$cmd = "ping"
& $cmd "www.google.com -n 2".split()

3. Use the automatic variable $LastExitCode to determine the exit code of the command you just ran using the call-operator:

It’s a contrived example, but its just so that I can illustrate how to use $LastExitCode:

$LASTEXITCODE = 0;
$cmd = "cmd.exe"
$result = & $cmd '/c copy z:\txt.txt m:\txt.txt';
Write-Host $LASTEXITCODE;
if ($LASTEXITCODE -ne 0)
{
    Write-Host "Error" -ForegroundColor DarkRed
    $result
}

In the above example, the copy command will fail and because of that the “Error” message will be printed to the screen.

4. Capturing error messages:

One problem with the above example is that, you don’t get to capture the error message reported by the copy (although it gets printed to the screen, its not in the $result object). If you want to be able to log all the error messages, you should redirect StdErr to StdOutput and this is done by appending “2>&1” to command above:

$LASTEXITCODE = 0; #reset the value of the lastexitcode. done so that you can be sure that lastexitcode was set by your call
$cmd = "cmd.exe"
$result = & $cmd '/c copy z:\txt.txt m:\txt.txt 2>&1';
Write-Host $LASTEXITCODE;
if ($LASTEXITCODE -ne 0)
{
    Write-Host "Error" -ForegroundColor DarkRed
    $result
}

Tip:

The PowerShell Community Extensions projects has a command-line tool called “EchoArgs”. It is a useful tool for the purpose of determining how powershell will pass along arguments to a command.

More Info:

Call operator: http://technet.microsoft.com/en-us/library/dd347588.aspx
LastExitCode: http://technet.microsoft.com/en-us/library/dd347675.aspx
EchoArgs: http://stackoverflow.com/questions/8905232/powershells-call-operator-syntax-and-double-quotes

Test post–Google+ integration

Post to test integration with Google+

Thursday, February 02, 2012

Powershell–Convert a SecureString to plain text

How do you go about converting a SecureString object to plain text in powershell? Turns out its not through the Convert-SecureString method.

Instead, you need to perform some interop to get the plain text string.

$Pwd = read-host -assecurestring "Password:"; #returns a SecureString object

#convert the SecureString object to plain text using PtrToString and SecureStringToBSTR

$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd)
$Pwd = [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr) #$Pwd now has the secure-string contents in plain text
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) #this is an important step to keep things secure

More info:

http://blogs.msdn.com/b/shawnfa/archive/2004/05/27/143254.aspx

Hype Cycle–the technology adoption curve

The Hype Cycle is a graph used by the Gartner group to show the typical stages through which technology innovation gets adopted. It provides insight into the typical cycles that any new technology goes through.

File:Gartner Hype Cycle.svg

Another graph that maps to the hype-cycle is the “">Market Life Cycle” graph:

Figure 1.Market Life Cycle

And finally, there is the Magic Quadrant graph that allows one to figure out where their company/technology is positioned in terms of other competitors.

Figure 2.The Magic Quadrant

More info:

http://en.wikipedia.org/wiki/Hype_cycle

Gartner.com: Magic Quadrants

Wednesday, February 01, 2012

Splitting User Stories: Useful resources

Pointed out to me by Mike Schmidt, these are 2 useful documents on Richard Lawrence’s site that show different strategies that can be used to split user stores:

1. Story splitting cheat sheet: http://www.richardlawrence.info/wp-content/uploads/2009/10/Story-Splitting-Cheat-Sheet.pdf

2. Flow chart to aid in splitting of user-stories: http://www.richardlawrence.info/wp-content/uploads/2012/01/Story-Splitting-Flowchart.pdf

image