February02

Is this .Net Type Assignable from another Type?

I have run into this a few times and always have to go to the MSDN to find the answer.  I have a situation where I needed to determine if a given type can be treated as a base type in an object factory.  I wanted to be able to create my concrete classes without having to do a switch statement for each type.

First I had to determine if the types were assignable to each other, then find the type to implement.  I will cover that in another article.  In this one I just want to cover the assignment test.

Can this type be assigned?

There is a function IsAssignableFrom that you can call on a System.Type. 

if( ParentType is ChildType )

It actually has to be written the other way around.

if( ChildType.IsAssignableFrom(ParentType) )

Quick Extension Method

So instead of having to do that all over my code, I wrote an extension method to allow me to do it following a different ordering.  I actually got this basic idea from one of the comments on the MSDN page.

if( parentType.CanBeTreatedAsType(childType) )

As you can see the extension method lets you write the syntax in a more natural manner.  Your preference may differ, but this makes more sense to me.

Example Code

public static class DataExtensionMethods
{
public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
{
if (CurrentType == null || TypeToCompareWith == null)
return false;

return TypeToCompareWith.IsAssignableFrom(CurrentType);
}
}

void Main()
{
System.Type parentType = typeof(ParentClass);
System.Type childType = typeof(ChildClass);

bool ChildToParent = childType.CanBeTreatedAsType(parentType);
Console.WriteLine("Child can be treated as parent: " + ChildToParent );

bool ParentAsChild = parentType.CanBeTreatedAsType(childType);
Console.WriteLine("Parent can be treated as child: " + ParentAsChild );
}

public class ParentClass
{
public ParentClass()
{
}
}

public class ChildClass : ParentClass
{
public ChildClass() : base()
{

}
}

January04

Debug Secondary Tiles

This is another of those posts for my future self, because I know I won’t remember this little tip.

Set startup through app manifest

The WMAppManifest.xml has a property that tells it where to send the default launch of the application.

    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
    </Tasks>

So the normal launch page is MainPage.xaml. But you can change it to another page, and include your parameters just like from a secondary tile!

    <Tasks>
      <DefaultTask Name="_default" NavigationPage="/TileDetails.xaml?myid=2" />
    </Tasks>

Now you can just press F5 and debug just as if that secondary tile had been clicked.

January03

Coding 4 Fun Phone Toolkit updated

If you have not looked at the toolkit before you seriously owe it to yourself, go get it now!

Coding 4 Fun Phone Toolkit

Windows Phone Geek has also done a great intro post on one of the new controls (the MetroFlow control).  Getting started with MetroFlow Control is a great read, even just to get up to speed with the overall concepts of the toolkit.

December09

Click back twice to exit app?

I have been adding animations to a Windows Phone 7 app that has a panorama control and ran into a problem I have seen others post online.  I figured it out, so I thought I would take a minute to explain how.

Get ready to add transitions

The Silverlight Toolkit is the way you want to go about adding quick and easy animations when a page loads and navigates away from the current page.

If you are not familiar with the basics visit the link above, or read this really good tutorial about wp7 page transitions on Windows Phone Geek.

The basics are that you have to include the toolkit, and you have to modify the root frame of your application to be a transition page instead of a normal phone page.

In a typical application you have the RootFrame declared in your App.xaml.cs like this:

    public partial class App : Application
    {
        /// <summary>
        /// Provides easy access to the root frame of the Phone Application.
        /// </summary>
        /// <returns>The root frame of the Phone Application.</returns>
        public PhoneApplicationFrame RootFrame { get; private set; }
    }

But for transitions to happen you need to change the object to a TransitionFrame when your InitializePhoneApplication is called.

            // REPLACE THE FIRST LINE WITH THE SECOND
            // RootFrame = new PhoneApplicationFrame();
            RootFrame = new TransitionFrame();

This will give you the ability to add transitions to your page.

I prefer to define my transition style at the application level, rather than the page level.  Usually I want all the pages to behave the same, so this gives a nice central point for all of them to reference it.

More...

November16

Async Data Flow Block in TPL

Check out the new System.Threading.Tasks.Dataflow.dll for processing blocks of data in an asynchronous manner.  I watched this video on Channel 9 and it blew me away.  I hope this goes into .Net 4.5 by default.

Intro to TPL Dataflow

Very easy to control things like a data pump where you want to process the data as it comes into a queue.  You can even let the ActionBlock run in and just have it call you back when it is done.

 

Sample code

// Setup an action block - nothing is happening here 
// until we post something to this block
var ab = new ActionBlock<int>( i =>
{
// Wait without blocking the thread
await TaskEx.Delay(1000);
Console.WriteLine(i);
}
, new DataFlowBlockOptions(TaskScheduler.Default, 4));


// Now post 10 items to the block
for(int i = 0; i < 10; i++)
{
ab.Post(i);
}

// Tell the action block we are done and it should stop
ab.DeclinePermanently();

// Wait for it to done processing
ab.CompletionTask.Wait();

More information

Visual Studio Aync Website

October19

Windows Runtime Information Links

WINRT (as the Windows Runtime as been dubbed) was announced a while back at BUILD in California.  I was super busy at the time and didn’t get to read or watch any of the sessions online.  Check out the WinRT Wikipedia page for more information.

I have been listening to podcasts and trying to catch up today while I am home sick.  Thought I would put some good links up for others looking to catch up also (and hopefully not while sick).

Dot Net Rocks

If you have never listened to Dot Net Rocks you seriously owe it to yourself to check it out.  I don’t listen to every show.  Grab ones you are interested in from their archive.  I have pointed several junior developers to their shows on specific topics and many have come back to tell me that the podcast was just enough to get them unstuck on some concept or idea.

DNR Show 701 has a really good intro where Carl goes through the WINRT and announcements from BUILD.  Listen to the first 15 minutes for the best information I have found anywhere about WINRT and Windows 8.

DNR Show 705 is an entire show about WINRT and WIN8.  It appears they will be starting a new podcast specifically about tablet development.  Rockford Lhotka and Billy Hollis are the guests on the show and talk about how they view WIN8 from a business and development standpoint.  Good information and will give you some insight into how WIN8 might win over the business segment.

Channel 9

Using the Windows Runtime from C# and Visual Basic BUILD session covering the topic at a high level.

Design Details of the Windows Runtime has a good overview slide from BUILD showing how .Net and WinRT all work through the same stack in Windows 8.

WinRT and .NET in Windows 8 a good blog post about the rumors of .Nets death being greatly exaggerated.

.Net 4.5, Async, WinRT with Bart De Smet is a video podcast talking about some topics for all .Net developers in the coming months and years.  Bart is a seriously smart Microsoft engineer working on all sorts of async technologies.

Application Virtualization is a great podcast talking about how apps could be sandboxed in a future OS.

Going Native 2 talks about using C++ in Windows 8 and how the runtime allows C++ to be a first class citizen of the OS again.  If you extrapolate a little you will also see how it was possible for Javascript to become first class as well.

Metro is coming

Of course building Windows Phone 7 apps I have seen the Metro UI for a while now.  But I am amazed at how many people are now jumping on the Metro theme.

imageOne site that really took the look and feel of Metro and went all out is the AfricanGeek.com site.It is written in Silverlight, but he nailed the whole Windows 8 look and feel for his site.

October14

TouchDevelop makes Windows Phone 7 easy to program

I attended a great XAPFest meeting last night about TouchDevelop.  This is an app you can download today for your Windows Phone 7 from the Web Marketplace.

What is it?

Many of us were introduced to programming because we had computers at home (and usually lots of free time).  Most machines had built in BASIC or some other language, and there were lots of magazines and books with code you could type in to make your machine do what you wanted.

 

Today most machines do not have a built in language, or tutorials on how to use the built in tools like Powershell to write programs.  Even then the tools and learning curve is very steep.  Learning to do something like post an image to Facebook means having to learn a LOT of different technologies.

TouchDevelop is a very easy to use programming tool that lets users write applications directly on the phone.  No need to sync to a PC, or learn C# or even know the SDK.  All of the features of the phone are exposed through built in objects in the tool.  The user doesn’t have to know the difference between a JPG and a PNG.  They just say Image.

More...

October05

Create new SQL Azure database as a copy

Did you know you can create a new SQL Azure database as a copy of an existing database?  Yes, you can.  There are some important limitations on how this works which I will cover below.  

Create the new database

-- create a new database as a copy
create database new_database as copy of original_database

In order to do this you must be logged in as the DBO of the original database.  See the NOTE in the article as well.  I think this is important difference for most database apps, the logins that are contained in the database must be updated.

Note After the cross-server copy process is complete, use the DBO login and the ALTER USER statement to map users in the new database to logins on the new SQL Azure server. For example: ALTER USER userName WITH LOGIN='loginName'. For more information, see ALTER USER (SQL Azure Database).

More...

August30

Red Gate Sql Azure Backup using Import Export Service

This is pretty cool news to me. Red Gate has a very good track record of supporting SQL Server products and technologies. Well, they just updated their SQL Backup product to a new beta SKU including SQL Azure Backup that is using the Import Export service built by the DAC team!

Red Gate SQL Azure Backup

This gives us a much better user experience than our own CLI tool, or even the soon to be released Azure Portal update.

Import Export Service?

The I/E Service is a Windows Azure based mid tier service that runs in each Microsoft Datacenter. The user submits jobs to the service, and it takes care of the long running operations.

iediag

More...

August22

SqlBulkCopy Dispose part 2

OK, fair point.  According to a friend I didn’t make my case very well in the previous post on SqlBulkCopy and Dispose.

As he stated, yes, you can put it in a using statement. And it does implement IDisposable explicitly.  Doesn’t that mean that everything is done?

using(SqlBulkCopy bcp = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default))
{
// DO something
}

// OR YOU CAN DO THIS
SqlBulkCopy bcp = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default);

((IDisposable)bcp).Dispose();

Internally the using seems to get converted to call to the virtual IDisposable.Dispose method according to the IL code I have looked at for the code above.

As an alternative, you could cast it to an IDisposable and call Dispose.  The class does have IDisposable, but only exposes Dispose explicitly (through the cast above).  This is a bad practice in my opinion because most developers won’t look for it.  They will try .Dispose through Intellisense.  If it doesn’t work they assume they don’t need to clean it up.

More...