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();