Dan Rigsby - Coding Up Style

.Net, C#, & Wcf Development

Archive for April, 2008

Have you tried Community-Credit.com?

Posted by Dan Rigsby on 30th April 2008

logosmall5 I am probably the last person to discover this site (I always seem to be the last to know a lot of stuff), but www.Community-Credit.com is a site where you can record your contributions to the development community. "Stupid prizes" are given to the people who record the most community points for a given month.  Some of these prizes are actually quite nice and all of them are very geeky. If you do any kind work with the community or even just attend user group meetings, I encourage you to check it out.

What is Community Credit?
Community Credit is a way of showing your contribution to the technology community.  Community Credit helps show off the enthusiasm and passion you have for the success of our industry.

How do I actually get points?
You can submit points on our Point Submission page. Simply type your name, email address, date you earned the points and point category and they will instantly be added to your total. The points that you earn can be seen on our Community Leaders.

The site was created by David Silverlight back in 2005.  David has been a great community contributor and Microsoft Mvp for many years.  Microsoft honored him last year when they named Silverlight after him.  After reading so much about him, I hope I have the chance to meet him some day.  Not only is has he done a lot to promote the community, but he also does a lot of work for non-for-profits through his sites.

So why record your community credit?  Well for one, it helps you keep track of everything you have been doing in the community.  It can be easy to forget something you have done many months ago.  You may use the site to show off to potential employers or friends.  Mostly its just fun to compete with your community friends to see who can help out others the most.

When you submit your contributions, you must provide a Url which can be checked to validate your submission.  Each Url can only be submitted once.  So if a single Url could relate to multiple point credit areas, then you will want to pick the one with the highest total.  There is room for this system to be abused, but there is a certain amount of honesty that must be assumed with a site like this.  I’m sure if someone is caught abusing the system, then they would be banned or at least deducted a certain amount of points.

communitycredit1

The point ranges don’t always make sense.  Like a response on a discussion board that is marked as an answer is only worth 150 points, while a blog entry can be worth around 3000.  Sometimes an answer on the forums can be longer than a blog post.  Writing a book is only 30000 points.  I think most books are bigger than 10 blog posts.  You can even get points for posting articles to DotNetKicks. But then again, you are probably getting some kind of commission from a blog post too.  However, I think the point ranges have been fairly well thought out and are at least level among all of the contributors.  They have also added in "curves" so that people who have won prizes in previous months, don’t get as much credit in future months.  For example, the top winner in April, may get a 95% curve placed on them such that if they enter something that is normally worth 1000, they will only be awarded 50 points.  These curves normally expire after a few months, however certain "Hall of Famers" of the have been slapped with a 50% curve making it harder for them to come out on top in a given month.

The site is so great at recording points, that the INETA Community Champions Program even uses the community-credit.com website to log contributions for their own award system.  This program offers its own set of awards that are given to contributions to the development community.  However, the points from community-credit don’t automatically cross over to the INTEA program.  INETA has their own set of Activities and Activity Types.  So if you wish to contribute to INETA and community-credit, then you will have to do a fair bit of dual entry.

Check out my community-credit profile here: http://www.community-credit.com/Portfolios/ShowPortfolio.aspx?UserID=119bae28-46ed-491d-8243-94c452dc1991.

I also created a blog badge (80×15) image that links to my community-credit account.  Feel free to download this badge and use it on your own blog, if you want:  http://www.danrigsby.com/Files/Images/communitycredit.png.

communitycredit

kick it on DotNetKicks.com

Posted in Community | 12 Comments »

Sexagesimal Conversions in .Net

Posted by Dan Rigsby on 30th April 2008

No, that is not a dirty word, and yes, it is fun to say. [sek-suh-jes-uh-muhl]

7520012074151Sexagesimal is a base-60 number system much like our own base-10 decimal system.  Throughout history different cultures have chosen different base numbering systems based on things they considered common or sacred.  Many people today recognize numbers as always being base-10, and it can be quite difficult to explain a different numbering system to a child.  Those of us in computer science are quite use to a base-2 (binary) system.  Some of the more common historic number systems are:

  1. Base-5 (quinary): This system has been popular because five can easily be represented by the five fingers on one hand
  2. Base-8 (octal): Some cultures used only their fingers to count and used the thumbs as place holders.  While other cultures, such as the Yuki Native American tribe of Northern California , counted the spaces between the fingers.  The Yuki actually started counting with 0 as well (much like C based languages).  So the numbers 0-7 were counted on their fingers.
  3. Base-10 (decimal): We are all familiar with the base-10 system which is almost universally used around the world.  Historical this is based on the fact that humans have ten fingers on which to count.
  4. Base-12 (duodecimal):  This system is based on the knuckles of the four fingers.  Each finger has 3 knuckles and the thumb is used as the place holder.  Twelve is also an important unit in British measurement such as 12 inches in a foot, 12 pennies to a shilling, 12 numbers used in our time units, etc.
  5. Base-20 (vigesimal): The base-20 system originates from the combination of ten fingers and ten toes on which to count.  This is most widely known to be used by the Mayan civilization.
  6. Base-60 (sexigesimal): The base-60 system dates back to the Sumerians and the early cultures of Mesopotamia.  It’s hard to say where this system originated from, but common belief is that it is a combination of the base-10 and base-12 systems.

So why is the base-60 system still important to us today?  Well for one, there are 60 seconds in a minute and 60 minutes in an hour.  This measurement one of the Sumerian’s lasting impressions today.  Their calendar and type systems have been adopted and modified throughout the Asia and Europe.  We can blame the Sumerian’s for not having enough time in the day.

180px-Geographic_coordinates_sphere.svg Another popular use for the base-60 system is in angular measure in our spherical coordinate system of the Earth.  A degree is divided into 60 minutes and a minute is divided into 60 seconds.  Our system of Latitudes and Longitudes is expressed in these terms.  With the popularity of geo-spatial and mapping tools such as Google Maps and Microsoft Live Maps, it has become important to be able to convert from degrees/minutes/seconds into a decimal notation and vice versa.

Example:

(49°30′02"N, 123°30′30")

 

49 degrees, 30 minutes, and 2 seconds by 123 degrees, 30 minutes, and 30 seconds

Below is a utilities class that I originally wrote for an astronomical observatory simulation application called StellarResults (which is available on codeplex).  This program would simulate observatories around the world and what astronomical objects they could see at a give time of day.  I soon realized that I needed to push this library down to a more basic level so that I could use it for other geo-spatial calculations such as working with geo-coded locations, or entering locations into a database.  Libraries like this will also be useful when working with the new spatial database features in Microsoft SQL Server 2008.

public static class GISUtilities
{
    #region Sexagesimal
    /// <summary>
    /// Converts from degrees, minues, seconds to a double.
    /// </summary>
    /// <param name="degrees">The degrees.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static double ConvertSexagesimalToDouble(
        int degrees,
        int minutes,
        int seconds)
    {
        return ((double)degrees % 360) + ((double)minutes / 60) + ((double)seconds / 3600);
    }

    /// <summary>
    /// Converts from degrees, minues, seconds to a string.
    /// </summary>
    /// <param name="degrees">The degrees.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static string ConvertSexagesimalToString(
        int degrees,
        int minutes,
        int seconds)
    {
        return String.Format(
            "{0}° {1}’ {2}”",
            degrees.ToString(),
            minutes.ToString(),
            seconds.ToString());
    }

    /// <summary>
    /// Converts from a double to degrees, minues, seconds.
    /// </summary>
    /// <param name="value">The value to convert.</param>
    /// <param name="degrees">The degrees.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    public static void ConvertDoubleToSexagesimal(
        double value,
        out int degrees,
        out int minutes,
        out int seconds)
    {
        degrees = (int)value;
        minutes = (int)((value - degrees) * 60);
        seconds = (int)((value - degrees - (minutes / 60)) * 3600);
    }
    #endregion Sexagesimal

    #region HMS
    /// <summary>
    /// Converts from hours, minues, seconds to a double.
    /// </summary>
    /// <param name="hours">The hours.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static double ConvertHMSToDouble(
        int hours,
        int minutes,
        int seconds)
    {
        return ((double)hours % 360) * 15 + ((double)minutes / 60) * 15 + ((double)seconds / 3600) * 15;
    }

    /// <summary>
    /// Converts from hours, minues, seconds to a string.
    /// </summary>
    /// <param name="hours">The hours.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    /// <returns></returns>
    public static string ConvertHMSToString(
        int hours,
        int minutes,
        int seconds)
    {
        return String.Format(
            "{0}h {1}m {2}s",
            hours.ToString(),
            minutes.ToString(),
            seconds.ToString());
    }

    /// <summary>
    /// Converts from a double to hours, minues, seconds.
    /// </summary>
    /// <param name="value">The value to convert.</param>
    /// <param name="hours">The hours.</param>
    /// <param name="minutes">The minutes.</param>
    /// <param name="seconds">The seconds.</param>
    public static void ConvertDoubleToHMS(
        double value,
        out int hours,
        out int minutes,
        out int seconds)
    {
        double totalseconds = value / 15 * 3600;

        hours = (int)Math.Truncate(totalseconds / 3600);
        minutes = (int)Math.Truncate((totalseconds - hours * 3600) / 60);
        seconds = (int)Math.Truncate(totalseconds - (hours * 3600) - (minutes * 60));
    }
    #endregion HMS
}
 

So a conversion from Latitude or Longitude to a double would look something like this:

double latitude = GISUtilities.ConvertSexagesimalToDouble(100, 34, 20);
 
There are also methods in this library to convert between hours/minutes/seconds as well as the degree/minutes/seconds primarily used in geo-spatial calculations.
 

kick it on DotNetKicks.com

 

Posted in .Net | 3 Comments »

IndyCodeCamp

Posted by Dan Rigsby on 27th April 2008

Saturday April 26, 2008 ushered in the first IndyCodeCamp.  This event was designed to be a code camp for all languages, but morphed more into a .Net thing this year.  This may change in future events.  I would love to see the event stay mostly .Net focused, but offer at least one track for other languages such as Ruby, Python, etc.  This year we had over 400 people registered for an event that could only accommodate 250 people.  We had a great line up of speakers as well.  I was very anxious in the days leading up to the event.

On Saturday morning, I arrived at IndyCodeCamp around 7am.  The event started at 8am, but I wanted to be sure to get there early to meet with the staff, speakers, and friends.  Part of my job as Logistics Director of IndyNDA is “speaker support”.  So at events like this, it’s my job to make sure the speakers know what is going on and that they are taken care of.  Personally, I just love being able to hang out with all of these great guys and gals.  Anyway, when I got there, I found the building still locked and a number of people standing around outside.  It had been warm all week, but Mother Nature hit us with a cold front, and it was quite chilly standing outside of the building.  Building staff claimed it was a miscommunication, but were were able to get in the building around 7:30am.  Needless to say, it was a mad house trying to get everything set up.  We had expected to have time to setup sign in booths and tables, but the attendees were right behind us.  Things went a little chaotically up until the first session.

Overall the event went off well.  We had a couple of speakers cancel at the last minute, but we were able to fill in their spots.  Out of the 400 people we had registered, only about 170 showed up.  That is quite a drop off rate, but I think the lack of reminder emails and no iCal files, lead to a lot of people forgetting about the event or not thinking they were registered.  Our local Microsoft representatives Dave Bost and Larry Clarkin had family commitments (we understand guys), but Bill Steele was kind enough to make it down, speak at a couple of sessions, show off his new hud, and buy us pizza for lunch.

There were four rooms setup for sessions and one great room where the sponsers were setup and were the speakers could sit.  It was great meeting up with many of my speaker friends from Indiana, Ohio, Michigan, Kentucky, Tennessee, and Illinois.  It’s nice to see that we had people speaking from all of the surrounding states.  We did have a number of Audio/Video issues in the first couple of sessions, but things got worked out throughout the day and the attendees were patient.

I was fortunate enough to have 3 sessions at IndyCodeCamp.  I was a little worried when I saw that all 3 of them were back to back and that it meant about 4 hours of conversation, but my voice didn’t waver too much and I made it through.  Here are my comment about each session:

  • Agile Project Management with Scrum:  This was my first time performing this session and since this was a code camp, I didn’t think it would be accepted.  However, I had 30 people attend which was a lot more than I expected.  Everyone was very attentive and came with a lot of great questions!  I think the slide deck was good and filled up the time nicely.  I got great comments and some nice laughter at some of the “funnier” slides I put in.  I really hope I get a chance to do this session again in the future.  A couple of people afterwards even asked me about presenting this to people at their places of employment.
  • Introduction to Windows Communication Foundation: I have done this session a few times now, and it always seems to be a hit.  I was fortunate to have over 50 people attend which ended up being the most popular session of at IndyCodeCamp.  The session went off without a hitch and the modifications I made, helped keep the session more introductory for those who may be new to any kind of connected system development.  I do think I am going to add a couple of new slides to this deck over why we need services.
  • Intermediate Windows Communication Foundation: I wanted to discuss the Web Programming Mode, Duplexing, and Asynchronous Operations all in one session.  I hated the name that I gave the session, but I couldn’t think of anything better.  However, I really under estimated how much I can talk about a topic. In the future I will break this up into three self contained sessions.  The talk today went well though. and I had about 28 people attend. But I really had to rush a couple of the topics, and I felt that I lost the audience when I talked about Duplexing.  In my next Duplexing talk, I will have a lot more “lead up” slides to help introduce the topic to the audience.

Because my sessions ate up the 2nd half of the day, I didn’t get to attend any of the afternoon sessions. And during the first half of the day, the best I could do was to take a sampling of each of the sessions.  Overall, I think everyone did a good job.  A few sessions had some issues, but I hope that doesn’t scare the speakers away from speaking again in the future.  The comments I heard from the attendees though were all positive.

After the event of a few of the speakers made it down to Champp’s for a little after-party.  Everyone was invited, but only some of the speakers showed up.  I hope in the future, more attendees will make to out.  It’s important to interact with your peers when possible.

I want to thank all of the speakers and staff for making this event a success.  I hope to see many of you again next year!  And to those who read this blog regularly, I apologize for the lack of posts this past week.  I have 4 great Wcf posts in draft state at the moment, but I spent most of time this week preparing my sessions for this event.

The materials from my sessions can be found here:

Posted in Community | 7 Comments »

New Webcast: CSS Support in Visual Studio 2008

Posted by Dan Rigsby on 22nd April 2008

I have a new 7 min 50 sec training webcast out over the CSS Support in Visual Studio 2008.  The video is available through JupiterMedia and can be viewed at http://www.internet.com/video/. Just look for the "Developer Video" titled "CSS in Visual Studio 2008".  Direct links are:

http://www.internet.com/video/?bcpid=1431564240&bclid=1433966034&bctid=1499645387
http://link.brightcove.com/services/link/bcpid1431564240/bclid1433966034/bctid1499645387

Posted in Visual Studio, Webcast | 1 Comment »

Central Ohio Day of Dot Net

Posted by Dan Rigsby on 19th April 2008

Central Ohio Day of .NET

I made it out to Wilmington, Ohio today to attend the Central Ohio Day of .Net (CODoDN).  There hasn’t been much representation of Indianapolis in Ohio thus far. I have session out here on Wcf and no one seems to know any other speakers from Indiana. There must be some magical barrier between Indiana and Ohio (or just miles and miles of open fields).  I am hoping to change that a bit today. I have met a lot of really smart people out here: some speakers and some attendees. (James Bender, Amanda Laucher, Michael Neel, Jay Wren, Jim Holmes, Jeff McWherter, David Redding, Brian Prince, Jeff Blankenburg , Alexei Govorine, Joe Wirtley, Matt Casto, Michael Eaton, etc).  Although I knew no one out here, everyone I met made me feel like I was part of the family.

According to my sources there are 172 people here today (although 300 were registered).  There are 5 sessions rooms each holding around 25-40 people.  Which fortunately means that there is free lunch for everyone!  Some sessions have been pretty packed. While others have had only a handful.  The popular topics so far have been Asp.Net MVC and F#.

Overall the presentations have been going well.  The audience and the speakers have all been light hearted and seem relaxed.  The talks I have attended have been going well.  I think the funniest so far has been Michael Neel’s "Church of the Agile".  He took the approach of making agile seem like a religion.  He came out in full robes and hood with candles lit.  It felt like more of a cult than a church, but definitely fun.

My session ended up being plagued by ghosts.  My slides started moving on their own, and Visual Studio would close windows.  Probably someone in the audience hijacking my bluetooth.  I’ll be sure to turn that off in the future.  Overall, I’m afraid I spoke over people’s heads, but I got a number of good comments afterwards.  Some people actually like a presentation that is chalked full of content I guess.  But realistically, how can you really do Wcf justice in 70 mins?  I did pack the house though.  I had 55+ people in a room that didn’t seat that many.  A few people stood or sat against the wall, but I did see people peak in, see that it was full, and walk away.

I did attend James Bender’s talk over Reliable Messaging in Wcf.  It was a really good introduction to the topic and MSMQ, lots of demos, and lots of pictures.  He was lucky enough to not have the ghosts invade his PC.

I finished the day at Brian Prince’s talk over "Soft Skillz" for the developer.  This talk was more of a set away from the .Net talks that you would expect at a Day of Dot Net event.   This focus was more on skills that developers need to succeed based off his many years in the field and the knowledge he has gained from others.  I ended up getting a copy of Halo 3 at this talk due to my mad photography skills.  The talk ended with a question of creativity: "If you have an infinite supply of bricks, what would you do raise money for you usergroup/church/school".  A number of ideas were thrown out like "Build brick pants", "Pant names on bricks, etc.  Surprising my idea of "Building a space elevator out of bricks" won the sweet prize of a "Heroes Happen {Here}" jacket (see Swag Score picture).  The jacket will go along nicely with all of the "Heroes {Community} Launch" events  that I have left to give.

I was pretty pleased with the event.  The talks contained a lot of "meat" and were very knowledgeable.  Sometimes these events have more of what I would call "marketing" slides.  The guys in Ohio really made sure that that wasn’t the case.  I will definitely be attending (and hopefully speaking) next year.

There were about 25 people at the after party (dinner at Max and Erma’s), mostly speakers, but there were a few attendees.  Jeff Blankenburg hosted an after-after party upstairs which was a blast.  There were around 22 people there and Jeff made sure that everyone not only had plenty to eat and drink, but also had a great time.   The party centered around a .Net Poker Tournament (16 members), food, and conversation.  I joined the poker game, lost early, and scored  sweet Visual Studio 2008 backpack (see Swag Score picture).

 

For those who are interested, a zip of all of my Wcf slides, notes, and demos is available here: Materials- IntroductionToWcf.zip.

And if anyone who attended CoCDoDN is not yet following me on twitter, follow me: http://twitter.com/danrigsby.  And subscribe to this blog.

Thank you Ohio!

Edit: A great little video summary of the entire event can be found here: http://cincinnatirecruiter.wordpress.com/2008/04/22/central-ohio-day-of-net-2008/.

Posted in Community | 8 Comments »

Impersonate a Client’s Identity in Wcf

Posted by Dan Rigsby on 17th April 2008

Impersonation is the process of impersonating a user in an application that isn’t necessarily running as that user.  In Wcf, a service may need to impersonate the user of the client in order to access a resource such as a file share, another machine, etc.  The service may even need to call a different Wcf service on the client’s behalf.

First off, you need to be using a binding that supports impersonation. They are:

To setup impersonation you can follow one of two models: Declarative and Imperative.

Declarative Model

The easiest way to setup impersonation is declaratively through a System.ServiceModel.ImpersonationOption.  This is a property of the OperationBehaviorAttribute that indicates the level of impersonation that the operation supports.  There are three options here:
  1. NotAllowed: Impersonation is not performed. If ImpersonateCallerForAllOperations is equal to true, a validation exception occurs at service startup time.
  2. Allowed: Impersonation is performed if credentials are available and ImpersonateCallerForAllOperations is equal to true.
  3. Required: Impersonation is required. This method can’t run unless the user can be impersonated.  The value of ImpersonateCallerForAllOperations doesn’t matter here.  Impersonation always takes place.

The default value is NotAllowed.  So if you are going to use ImpersonateCallerForAllOperations, you will need to make sure to set all of your methods to ImpersonationOption.Allowed.  If you are not using ImpersonateCallerForAllOperations and just want to use a impersonation for a single method, the set ImpersonationOption.Required.

[OperationBehavior(Impersonation=ImpersonationOption.Required)]
public bool MyMethod(string input)
{
    return true;
}

Imperative model

If you chose to setup the impersonation in code, System.ServiceModel.ServiceSerurityContext has everything you need.  But, if the declarative model is so easy to use, why would you want to set this up through code? Well, this model is best used if only a part of your method needs to use impersonation.  The declarative model uses client impersonation for everything in the method.  Depending on what your system is doing, one model may be better than another.

public bool MyMethod(string myParameter)
{
    // Set security context for the current user
    System.ServiceModel.ServiceSecurityContext securityContext =
        System.ServiceModel.ServiceSecurityContext.Current;

    // Make sure there is a windows identity present and impersonate it
    if (securityContext != null
        && securityContext.WindowsIdentity != null)
    {
        // Can check the securityContext.WindowsIdentity.ImpersonationLevel
        // here to make sure we are allowed to impersonate before
        // actually creating the impersonation context

        using (securityContext.WindowsIdentity.Impersonate())
        {
            // TODO: Perform operations here as the impersonated user
        }
    }

    return false;
}
 
Seems easy enough right?  You just grab the current windows identity and create a WindowsImpersonationContext
 

Impersonation for all Methods

If you need to use impersonation for all methods on a service. You can use the ServiceAuthorizationBehavior and set the ImpersonateCallerForAllOperations property to true.  This can be done programmatically on the servicehost like so:

ServiceAuthorizationBehavior serviceAuthoriationBehavior =
    serviceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
serviceAuthoriationBehavior.ImpersonateCallerForAllOperations = true;

Or through the application configuration as such:

<behaviors>
    <serviceBehaviors>
        <behavior name="myBehavior">
            <serviceAuthorization impersonateCallerForAllOperations="true" />
        </behavior>
    </serviceBehaviors>
</behaviors>

Client Configuration

There is a bit more to this story.  The default ImpersonationLevel of the client is set to Identification which doesn’t allow impersonation.  You must setup the client connection to allow impersonation.  Here is a list of the impersonation levels you can use:
  1. None: An impersonation level is not assigned.
  2. Anonymous: The server process cannot obtain identification information about the client, and it cannot impersonate the client.
  3. Identification: The server process can obtain information about the client, such as security identifiers and privileges, but it cannot impersonate the client. This is useful for servers that export their own objects, for example, database products that export tables and views. Using the retrieved client-security information, the server can make access-validation decisions without being able to use other services that are using the client’s security context.
  4. Impersonation: The server process can impersonate the client’s security context on its local system. The server cannot impersonate the client on remote systems.
  5. Delegation: The server process can impersonate the client’s security context on remote systems.

If you need impersonation, you will have to choose between Impersonation or Delegation depending on your needs. 

If you are using a proxy client to connect to the service, you could setup the impersonation level like so:

// Create a new client and set the impersonation level
MyServiceClient client = new MyServiceClient();
client.ClientCredentials.Windows.AllowedImpersonationLevel =
     System.Security.Principal.TokenImpersonationLevel.Impersonation;
 
Using a ChannelFactory is very similar:
 
// Create a new channel factory and set the impersonation level
ChannelFactory<IMyService> channelFactory =
    new ChannelFactory<IMyService>();
channelFactory.Credentials.Windows.AllowedImpersonationLevel =
     System.Security.Principal.TokenImpersonationLevel.Impersonation;
 

Impersonate a totally different Windows User in a client

There may also be times when on the client you want to impersonate a different user than what is currently being used. To do this, you must know the domain, username, and password for that user. You then just use these values to set the client credential for the client:

MyServiceClient client = new MyServiceClient();
client.ClientCredentials.Windows.ClientCredential.Domain = domain;
client.ClientCredentials.Windows.ClientCredential.UserName = username;
client.ClientCredentials.Windows.ClientCredential.Password = password;
client.ClientCredentials.Windows.AllowedImpersonationLevel =
     System.Security.Principal.TokenImpersonationLevel.Impersonation;
 

Or through a ChannelFactory as such:

ChannelFactory<IMyService> channelFactory =
    new ChannelFactory<IMyService>();
channelFactory.Credentials.Windows.ClientCredential.Domain = domain;
channelFactory.Credentials.Windows.ClientCredential.UserName = username;
channelFactory.Credentials.Windows.ClientCredential.Password = password;
channelFactory.Credentials.Windows.AllowedImpersonationLevel =
     System.Security.Principal.TokenImpersonationLevel.Impersonation;
 
You can read more about impersonation here: http://msdn2.microsoft.com/en-us/library/ms730088.aspx

kick it on DotNetKicks.com

 

Posted in Wcf | 2 Comments »

Visual Studio 2008 & ClickOnce Warning

Posted by Dan Rigsby on 16th April 2008

Visual Studio 2008 added a new feature to easily embed a manifest.  This is available right from the project properties page. It can be used to embed UAC data for Vista or other things.

ClickOnceManifest

By default each project is selected to use the embedded manifest.  This doesn’t sound too harmful, right?

Well, ClickOnce and Registration-Free COM applications require an external manifest.  So, if you use ClickOnce, it will try to create it own external application manifest which could cause a conflict with the embedded one. Here is the error you might get when you try to install the ClickOnce application:

ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of \\MyShare\MyApplication.application resulted in exception. Following failure messages were detected:
        + Reference in the manifest does not match the identity of the downloaded assembly MyApplication.exe.

This error seems a bit cryptic at first.  Especially if you don’t know that Visual Studio is embedding a manifest for. Fortunately, this error is easy to get around.  You simple just set this option to “Create application without a manifest”.  Or manually add “<NoWin32Manifest>true</NoWin32Manifest> ” to your project file like so:

<PropertyGroup>
    <Configuration Condition=” ‘$(Configuration)’ == ” “>Debug</Configuration>
    <Platform Condition=” ‘$(Platform)’ == ” “>AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <OutputType>WinExe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>MyApplication</RootNamespace>
    <AssemblyName>MyApplication</AssemblyName>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
    <NoWin32Manifest>true</NoWin32Manifest>
  </PropertyGroup>
 
 

Posted in ClickOnce, Visual Studio | No Comments »

Internet Explorer 8: Webslices & Activities for Facebook

Posted by Dan Rigsby on 12th April 2008

With the introduction of Internet Explorer 8, Facebook has provided support for both WebSlices and Activities: http://www.microsoft.com/windows/ie/ie8/welcome/en/default.html.  In the article I am going to express my thoughts about these additions to IE 8 and their implementation for Facebook.

webslc_iconWebSlices

WebSlices allow developers to mark parts of webpages as “WebSlices” and enable users to monitor information they rely on as they move about the web. This information can be displayed in the Favorites bar  so that users can stay abreast to the information.

In Facebook, your friend’s status updates are a WebSlices.  To enable this you can go about this in 2 ways:

  1. When IE8 detects a webslice on the page, the RSS feed button is replaced with the webslice button (as shown in item 1 of the following image).  If you select this window then the subscription confirmation box will be displayed.
  2. If you hover over the webslice data area, a webslice button will appear (as shown in item 2 of the following image).  Selecting this will also open the subscription confirmation box.

facebook1

Once you have subscribed to the webslice, a new item in the Favorites bar will appear called “Facebook Status Updates”.  If you drop down this button, the 3 most recent status changes will be displayed.  You could then select to “Open” this list in an RSS like window.

If there are new status updates, the text of the “Facebook Status Updates” button will become bold.  If your friend’s use Twitter and sync it with Facebook, then prepare to have this text almost always be bold.

facebook2

Overall, webslices could have some very cool uses.  Imagine being able to monitor an auction on eBay or prices of items you wish to buy.  This feature would be more useful in Facebook, if you had a way to filter to only show status updates from select friends.  Most users have between 50-100 friends and status updates could be less useful.

activities_iconActivities

Activities give users ready access to the online services they care about most from any page they visit, and developers gain an easy way to extend the reach of their online services. These activities become available when you select text on a page.  The activity icon will appear above the selected text.  Selecting it will display the activities list.

Facebook provides two activities:

  1. Find with Facebook: This option will open up a Facebook search using the selected text.  This could be useful if you want to search for a person or group on Facebook.
  2. Share on Facebook: This lets you send a link to the selected page as a message to friends or a post on your profile.

facebook3 

Overall, activities really don’t provide us with anything new.  They are really just shortcuts between coping something to the clipboard and navigating to some website or application.  I don’t see myself using these much (if at all), unless some more advanced use for them is found.

Posted in Internet Explorer | 1 Comment »

How to open a project file in Visual Studio 2008 for editing

Posted by Dan Rigsby on 11th April 2008

How many times have you opened up a .csproj file and wanted to edit the xml, but it opened up the actual project in Visual Studio instead?  Your only real options have been:

  1. Open the project file in a different text editor
  2. Give the project file a new extensions, then open it in Visual Studio
  3. Use some custom visual studio extension or write your own

Microsoft released a set of PowerCommands for Visual Studio 2008 which provides this functionally.  With this you can just right click on the project and select “Edit Project File”:

PowerCommands1

This will open the project file in the visual studio xml editor. This makes it so much better than an external editor because it allows for intellisense through the xsd schema (http://schemas.microsoft.com/developer/msbuild/2003)!

PowerCommands2

Notice though that while you are editing the project, it becomes unavailable in the Solution Explorer.  This is a side affect, because if you are editing the file, Visual Studio can’t yet know what it is going.  So, when you are done editing the file, you have to right click on the project in Solution Explorer and reload, or close the xml editor and reload the project. It would have been nice if it could have just detected when the project file was changed and then asked the user if he/she wanted to reload the project now.  This would be consistent with what you see if you edit the project file in an external editor.

The PowerCommands collection contains a number of other enhancements which you can see on the project website.  Some of my favorites are:

  • Copy and Paste References: Allows you to copy to the clipboard a project reference or set of references and paste them into another project
  • Copy and Paste Class: Allows you to copy a class to the clipboard which renames the class and to paste it into the project again.
  • Open Containing Folder and Open Command Prompt: Allows you to right click on a file and open the folder or a command prompt at that location
  • Remove and Sort Usings: We got this feature in VS 2008 itself, but you can now run this at the project level to affect all files at once.  Now I wish I could do this with “Format Document” too.
  • Close all documents context menu item:  Allows you to close all open documents.  Sometimes when the designer is getting “funky”, I like to close all files, rebuild, and open it again.  Before I could only “Close all but this” and then close that last document.  With this new command, I can close all of them at once finally!
  • Transform Templates: Allows you run execute a “custom tool” with associated text template items.

I highly recommend that you download these free tools from Microsoft.

Download PowerCommands for Visual Studio 2008 here: http://code.msdn.microsoft.com/PowerCommands

kick it on DotNetKicks.com

Posted in Visual Studio | 1 Comment »

Heroes {Community} Launch - Indianapolis, IN (Part 1)

Posted by Dan Rigsby on 11th April 2008

I finished a Heroes {Community} Launch event in Indianapolis, IN for the IndyNDA users group last night. This event was setup with 2 speakers. Paul Hacker covered Windows 2008 for 20 minutes, while I covered both SQL Server 2008 and Visual Studio 2008 for the remaining hour.

There were about a 120 people in attendance and the response and comments from the audience seemed positive.  IndyNDA is now in meeting a new room which can easily seat 200 people, provides tables for all in attendance to write or eat on, and has 7 projectors to display the presentation to instead of just 2.  This location is much improved and will serve the organization well in the future.

My talk over SQL Server 2008 covered:

Top 10 SQL Server 2008 Features for Developers

  1. LINQ
  2. Intellisense for SQL Server Management Studio: T-Sql, database objects, & parameters
  3. FileStream Datatype:
    • Designed to solve unstructured LOB (large object) storage, provides performance of native NTFS with transactional support. Data is stored in NTFS, and SQL Server manages relationship between the columns and files. SQL Server manages the transactional integrity such as backing up and restoring data.
  4. Date & Time Datatypes: Separate data and time types. Time can now go down to hh:mm:ss[.nnnnnnn]
  5. DateTime2 & DateTimeOffset Datatypes: Supports years 0001 to 9999 (much like in .Net); DateTimeOffset is timezone aware, but not daylight savings time!
  6. Hierachical Datatype: Allows storage of hierarchical data such as org charts, etc.
    • Only 1 root per table though
  7. Spatial Datatypes:
    • Geography: Uses a geodetic (round earth) model and stores points, lines, polygons, and collections of Latitude & Longitude coordinates.
    • Geometry: Uses a planar (flat earth) model which stores the same types of data, but is used primarily for navigation and mapping.
  8. T-SQL MERGE Statement: Allows merging of rows from multiple tables. You can choose to update matched rows, insert unmatched rows, or delete unmatched rows from the primary table.
  9. Table-Valued Parameters: Tables can be passed as parameters to sprocs.
  10. Data Change Tracking
    • Change Data Capture (CDC): This allows you to capture all changes to data in a table into a tracking table.
    • Change Data Tracker (CDT): This similar to CDC, but it doesn’t actually capture the changes made, but captures only that some change was made.

The SQL Server 2008 demonstrations included a series of scripts which created a database, turned on CDC , showed off CDC , and created a table.  The table was an Employee table that used some of the new DateTime types, hierachyId as a make-shirt org chart, and a geography field to represent the employee’s location as a latitude and longitude.  I then ran a series of queries to show how you can search the hierachyId and the CDC history.

My talk over Visual Studio 2008 covered:

  1. What are the features in Visual Studio itself targeted to different types of developers: All, Windows Client, Web Client, Office, Mobile, and Server.  I went into highlights in each one of these that people may or may not know about.

The Visual Studio 2008 demonstrations included: 

  1. New project properties
  2. UAC support in application manifests
  3. Refactoring support for "Using" statements
  4. Wpf Editor
  5. New Css Support in web projects
  6. New Web Designer
  7. Javascript Intellisense
  8. Javascript Debugging
  9. WcfSvcHost and WcfTestClient
  10. "Add Service Reference" window and its advanced options

Overall, I think my presentation went pretty well.  We had some issues with the microphones and I ended up having to do the entire presentation with a handheld microphone.  This made it very hard to do code demos and talk at the same time.  I only have 2 hands.  So there were quite a few more "silent moments" than I would have liked, but I kept each of them around 5 seconds so that I didn’t isolate the audience.

Here is the entire presentation including slides, before and after projects, code snippets, notes, etc.: http://www.danrigsby.com/files/Presentations/HeroesCommunityLaunch-Indianapolis1.zip

Part 2 of this event will occur on May 8th, 2008 at the same location (see speaking engagements).  This meeting will continue on with the Visual Studio 2008 launch, but will really be focused for .Net developers.  Topics will include new language features in C# 3.0 and VB 9.0 and .Net Framework additions such as those added to Wcf, WF, System.Addin, etc.

Posted in Community | 2 Comments »