24 November 2010

How do I – Use a bitmask enum in C#

In today’s world where processor memory is plentiful, many developers will often times just use a List<bool> for tracking a series of on/off values.  Though the compiler can optimize this code somewhat, the CPU cycles spent managing the List<> structure when super fast bitwise operations could have been done, isn’t really the best way to go.  So when one of my mentees asked about checking values in an enum bitmask, I thought it best to blog the answer for the benefit of others as well.
Let’s assume I’m trying to track the on/off values of say a permissions mask.  I would define my values using the Flags attribute on an enum thus:
[Flags]
public enum Permissions
{
    All = 4,
    Update = 2,
    Read = 1,
    None = 0
}

If I now proceed to define a variable of our enum, I can set some of it’s bit values using the the bitwise AND operator thus:
Permissions perm = Permissions.Read & Permissions.Update;

If I now check for a value in the mask that is NOT turned on, it is done with the bitwise OR operator thus:
if ((perm & Permissions.All) != 0)
{
    //it never gets here
}

The same applies for values that ARE turned on in the mask thus:
if ((perm & Permissions.Update) != 0)
{
    //it gets here
}

In addition, I can turn on more flag altering future check for them thus:
perm = perm & Permissions.All;
if ((perm & Permissions.All) != 0)
{
    //now it gets here
}

The major advantage to using the bitmask enum with bitwise operators is speed.  These operations are done by the processor literally just flipping a single bit.
Happy coding!



Cheers
C

23 November 2010

How do I – Write my own C Sharp IEqualityComparor when System.Collections.Generic.List.Contains(System.Xml.Linq.XNode) fails and does not work as expected

Unfortunately I ran into an issue with the C# List<T> class the other day.  I was in need of checking for a given XML snippet’s existence in an XML document.  I immediately jumped in and tried using Linq2Xml and List<T> to solve the problem.  The way I figured it, I could grab a quick list of XNodes from the XML document and then using the .Contains() method, I could check if the node in the XML snippet exists in the list.  Imagine my surprise when I ran through the code, but for some reason, the .Contains() method did NOT return true even on an identical match.  Weird.  :S
After spending some time trying to figure out why it wasn’t working as advertised (as I’ve mentioned before, 80% of a developer’s time is spent figuring out why something isn’t working as advertised or published) I decided to go the easier route and leverage the .Contains() method’s second overloaded form which takes an IEQualityComparor so all I’d have to do is write my own IEQualityComparor derived class and pass it to the .Contains() method.  Let’s take a look at how we do this.


In this post we’ve shown how to create our very own IEqualityComparor method to use for our purposes since the List<XNode>.Contains() method doesn’t function the way we needed it to.  I would venture to say, that the .Contains() method without our IEqualityComparor is pretty much useless.
Of course, if anyone out there can explain to me why it works the way it does and how the way it works is actually useful, I’m all ears. ðŸ™‚


Cheers
C

18 November 2010

Process Explorer 14 now available!



If you don’t know who Mark Russinovich is, you’ve been living under a rock. Even so, if you spend ANY time in the Windows world, you’d want to get Mark’s latest iteration of Process Explorer, now at version 14!

Come and get it! http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

Cheers
C

17 November 2010

Start thinking in parallel… seriously!

As we move forward with Visual Studio 2010 and the .NET Framework 4.0, it will become more and more important to understand, embrace and implement parallel programming patterns.  Even though SharePoint 2010 still only runs on .NET 3.5, projects and components that doesn’t directly call into SharePoint, can be built upon this framework technology.
With servers now spanning multi proc/multi core (dual proc/hex core for most standard servers today), it means that a traditional single threaded application only leverages 1/24th (12 cores plus hyper-threading) of it’s potential processor power.  Using simple components such as Parallel.For for instance can potentially yield much better performance and throughput to the apps we build.  I’m by no means advocating consuming all 24 cores in your application on the server, but the point is that we should be thinking in parallel mode.
That said, Stephen Toub wrote the nice white paper on the subject.  Yes, it’s 118 pages, but it’s well worth the read, even if just to stimulate peripheral awareness of the parallel shift in coding.  I enjoyed it and I hope you do too! ðŸ™‚
The paper is published here:  http://www.microsoft.com/downloads/en/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&displaylang=en
For my own reference, I’ve also saved it off to my downloads folder just in case the above link isn’t functional some time in the future.
http://www.cjvandyk.com/blog/Downloads/Patterns%20for%20Parallel%20Programming%20-%20Understanding%20and%20Applying%20Parallel%20Patterns%20with%20the%20.NET%20Framework%204.pdf

Cheers
C

10 November 2010

New SharePoint blogger worth following



My friend, Jason Himmelstein, recently setup the SharePointLonghorn blog and I’ve been eagerly waiting for him to start cranking out content. Well the wait is over. He’s launched into the blogosphere with some awesome posts well worth reading. While you’re at it, subscribe to his RSS feed.

Windows with Claims User gets access denied to a site they had access to earlier in the day

Unable to access VMware Workstation Guest after Host Machine crash Random Server hang issues result in a required hard reset SharePoint 2010 Farm Service Account passwords expired?!?!?!? Like I said… great content! Enjoy!

Cheers
C

07 November 2010

How to deal with orphaned SharePoint sites

Whatever causes it, orphaned sites in SharePoint can be a very painful issue to deal with.  One way in which an orphaned site can occur is when a STSADM command it terminated during execution because of a drop of your remote desktop connection.
If you are working with STSADM, be sure to configure your Remote Desktop settings in order to keep disconnected sessions alive.  Failure to do so, WILL cause problems for you in the future.
The toughest orphaned site I’ve ever had to deal with occurred during such a case.  The site was being restored from a STSADM backup.  The server’s Remote Desktop settings were not set to keep the session alive and when a blip in the wireless network cause the connection to be broken, Windows simply killed the session causing the site collection to become orphaned.  This was evident when the restore command was re-attempted:
stsadm -o restore -url http://server/site -filename site.stsadm.bak -overwrite
Which returned this puzzling message:
Another site already exists at http://server/site. Delete this site before attempting to create a new site with the same URL, choose a new URL, or create a new inclusion at the path you originally specified.
This is a puzzling message because… didn’t we specify the “-overwrite” switch?  Why yes we did!  So what is going on here? OK, OK.  So the site is there and the “-overwrite” switch isn’t working.  Let’s just delete the site.  The following command is issued:
stsadm -o deletesite -url http://server/site
Only thing is, the site collection delete statement failed with the following error:
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)
No problem you say.  Just use the -force switch with the deletesite command.  Doing that, the following command is issued:
stsadm -o deletesite -force -siteid 2a9fbc10-4a60-427b-8e6e-e1565d7e5796 -databaseserver sql -databasename Site_Content
Unfortunately, the response is not what you expected.  This is the error returned:
Database “Site_Content” is not associated with this Web application
Of course, the message would make sense if the database was not associated with the web application, but it was.  It is time for the good old orphan identification and handling swich… databaserepair We begin by identifying the orphaned content.  We issue the following command:
stsadm -o databaserepair -url http://server/site -databasename Site_Content
As expected, the command dumps a bunch of orphaned content.  Time to delete the corrupted content so we can restore the site again.  Simply add the -deletecorruption switch thus:
stsadm -o databaserepair -url http://server/site -databasename Site_Content -deletecorruption
Once the corrupted content has been deleted, rerunning the command without the -deletecorruption switch yields a clean bill of health for our database thus:
<OrphanedObjects Count=”0″ />
Unfortunately, retrying the restore still fails by with the same “site exists” error.  This is where I had the idea to detach and re-attach the database to try and clear up the issue.  Two quick STSADM commands later thus:
stsadm -o deletecontentdb -url http://server/site -databasename Site_Content
and
stsadm -o addcontentdb -url http://server/site -databasename Site_Content
yielded:
Operation completed successfully.
Now retrying the restore thus:
stsadm -o restore -url http://server/site -filename site.stsadm.bak -overwrite
finally yielded the result we were looking for:
Operation completed successfully.
  Hopefully this will help you get sticky orphaned sites handled quickly so you can move on to more important things!

Cheers
C

04 November 2010

How do I – Create a Windows Service application using Visual Studio 2010



We don’t build many Windows Service applications any more these days, but every once in a while, the need for one comes around. With Visual Studio 2010 now the mainstay of our tool set, let’s look at how you accomplish the mission using this tool.

http://www.cjvandyk.com/blog/Articles/How-do-I–Create-a-Windows-Service-application-using-Visual-Studio-2010.aspx



Cheers
C

01 November 2010

Why can’t I use SCRIPT or IFRAME tags in my SharePoint Rich Text fields?

I answered this question and thought it might be good to post for others as well…  The question was: “So before I write a custom field to replace the use of the OOTB multiline text field could anyone tell me a couple things? First, could someone better explain the reason that script and iframe tags were allowed in content editor web parts but not in the multiline text RTE? Second, is there a way to enable the use of unsafe tags within the multiline text field without having to create a custom field?”   The answers to your questions are: 1.  SECURITY. 2.  NO. (See 1 above) So now, let me explain… The use of <script> and <iframe> tags in the Rich Text fields are not allowed, or rather, are not interpreted as their types, but just as text, because it’s a rich TEXT field.  As a rich text field, the content of the field is something that a USER can set.  As such, any web site that would allow a USER to set the content of a field to something that is executable such as SCRIPTS or IFRAMES, would pose a grave security risk.  It’s like telling a hacker… Here’s the keys to my server.  Do your worst. For that reason, all fields that contain content set by users, are configured to NOT allow users to embed scripts etc. into the pages. In the same way, the use of Content Editor web parts is limited to users with DESIGNER or ADMINISTRATOR rights.  The assumption here is that these level users are trusted users that have been vetted and they won’t intentionally embed harmful content into pages. SharePoint isn’t trying to make life hard… it’s just protecting us from ourselves sometimes. ðŸ™‚

Cheers
C

SharePoint Remote Event Receivers are DEAD!!!

 Well, the time has finally come.  It was evident when Microsoft started pushing everyone to WebHooks, but this FAQ and related announcement...