Contents tagged with .NET 3.5

  • SharePoint 2010 Sandboxed solution SPGridView

    Tags: SharePoint, .NET 3.5

    If you didn’t know, you probably will soon, the SPGridView is not available in Sandboxed solutions.

    To be honest there doesn’t seem to be a great deal of information out there about the whys and what nots, basically its not part of the Sandbox SharePoint API.

    Of course the error message from SharePoint is about as useful as punch in the face…

    An unexpected error has been encountered in this Web Part.  Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. You don't have Add and Customize Pages permissions required to perform this action

    …that’s if you have debug=true set, if not the classic “This webpart cannot be added” !! Love that one!

    but will a little digging you should find something like this…

    [TypeLoadException: Could not load  type Microsoft.SharePoint.WebControls.SPGridView from assembly 'Microsoft.SharePoint, Version=14.900.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'.]

    Depending on what you want to do with the SPGridView, this may not help at all.  But I’m looking to inherit the theme of the site and style it accordingly.

    After spending a bit of time with Chrome’s FireBug I was able to get the required CSS classes.  I created my own class inheriting from GridView (note the lack of a preceding SP!) and simply set the styles in there.

    Inherit from the standard GridView

    1. public class PSGridView : GridView

    Set the styles in the contructor…

    1. public PSGridView()
    2. {
    3.     this.CellPadding = 2;
    4.     this.CellSpacing = 0;
    5.     this.GridLines = GridLines.None;
    6.     this.CssClass = "ms-listviewtable";
    7.     this.Attributes.Add("style", "border-bottom-style: none; border-right-style: none; width: 100%; border-collapse: collapse; border-top-style: none; border-left-style: none;");
    9.     this.HeaderStyle.CssClass = "ms-viewheadertr";
    11.     this.RowStyle.CssClass = "ms-itmhover";
    12.     this.SelectedRowStyle.CssClass = "s4-itm-selected";
    13.     this.RowStyle.Height = new Unit(25);
    14. }

    Then as you cant override the Columns property setter, a custom method to add the column and set the style…

    1. public void AddColumn(DataControlField field)
    2. {
    3.     if (field == null) return;
    5.     field.ItemStyle.CssClass = "ms-vb2";
    6.     field.HeaderStyle.CssClass = "ms-vh2-nofilter ms-vh2-gridview";
    7.     this.Columns.Add(field);
    8. }

    And that should be enough to get the nicely styled SPGridView without the need for the SPGridView, but seriously….get the SPGridView in the SandBox!!!


  • Gotcha | Installing .net 4.0 and IIS 6

    Tags: MVC, .NET 3.5

    Just a quick one, seems pretty weird to me.

    I installed .net 4.0 on an old IIS6 box, ready to deploy a mvc app targeting .net 4.0.  I thought, which to me seems logical, that I install .net 4.0, setup a new web site, new app pool, set the web site to 4.0 (other configuration also needed to run MVC on IIS6 here and here) and it would just work.

    Errr… No.  The page cannot be displayed!  Nothing to do with MVC.

    Apparently just because you have installed .net 4 and the option is available in IIS, it’s not enabled.  I’m not going to repeat anything here…take a look at this post – clear, easy steps on exactly what you need to do and how to check if this is the problem.


  • Dynamic connection for LINQ to SQL DataContext

    Tags: .NET 3.5, LINQ, Visual Studio, .NET

    If for some reason you need to specify a specific connection string for a DataContext, you can of course pass the connection string when you initialise you DataContext object.  A common scenario could be a dev/test/stage/live connection string, but in my case its for either a live or archive database.

    I however want the connection string to be handled by the DataContext, there are probably lots of different reasons someone would want to do this…but here are mine.

    • I want the same connection string for all instances of DataContext, but I don’t know what it is yet!
    • I prefer the clean code and ease of not using a constructor parameter.
    • The refactoring of using a constructor parameter could be a nightmare.


    So my approach is to create a new partial class for the DataContext and handle empty constructor in there.

    First from within the LINQ to SQL designer I changed the connection property to None.  This will remove the empty constructor code from the auto generated designer.cs file.


    Right click on the .dbml file, click View Code and a file and class is created for you!


    You’ll see the new class created in solutions explorer and the file will open.

    We are going to be playing with constructors so you need to add the inheritance from System.Data.Linq.DataContext

    1. public partial class DataClasses1DataContext : System.Data.Linq.DataContext
    2.    {
    3.    }

    Add the empty constructor and I have added a property that will get my connection string, you will have whatever logic you need to decide and get the connection string you require.  In my case I will be hitting a database, but I have omitted that code.

    1. public partial class DataClasses1DataContext : System.Data.Linq.DataContext
    2. {
    3.    // Connection String Keys - stored in web.config
    4.    static string LiveConnectionStringKey = "LiveConnectionString";
    5.    static string ArchiveConnectionStringKey = "ArchiveConnectionString";
    7.    protected static string ConnectionString
    8.    {
    9.       get
    10.       {
    11.          if (DoIWantToUseTheLiveConnection) {
    12.             return global::System.Configuration.ConfigurationManager.ConnectionStrings[LiveConnectionStringKey].ConnectionString;
    13.          }
    14.          else {
    15.             return global::System.Configuration.ConfigurationManager.ConnectionStrings[ArchiveConnectionStringKey].ConnectionString;
    16.          }
    17.       }
    18.    }
    20.    public DataClasses1DataContext() :
    21.       base(ConnectionString, mappingSource)
    22.    {
    23.       OnCreated();
    24.    }
    25. }

    Now when I new up my DataContext, I can just leave the constructor empty and my partial class will decide which one i need to use.

    Nice, clean code that can be easily refractored and tested.

    Share this post :


  • Sharepoint | Silverlight video player web part

    Tags: .NET 3.5,, SharePoint, Silverlight

    Silverlight makes working with videos pretty straight forward, Microsoft makes Silverlight pretty straight forward with and sharepoint is written in, so match made in tech heaven!!

    I wanted a video player web part for sharepoint, that had some simple functionality like play, pause and volume.  I started with expression encoder which output a nice media player interface...this is OK, but has a couple of restrictions; 1, its far to rich for what I wanted, animations all over the place and 2, its JavaScript with Silverlight 1.  So, using blend I opened one of the exported files to rip out a few features of the player.

    Play / Pause button, volume control and some associated storyboards for some nice animations... visible = true; visible = false is so last year!!!

    I copied the xaml into my own Silverlight 2 app, that already had the media player element.  A little positioning in blend and we're off.  Right that's far too much waffle lets get to it!


    I wont paste the xaml here as it basically only a media element, the play/pause button and volume control copied from Expression Encoder. OK, well maybe a little...

    <MediaElement HorizontalAlignment="Stretch" Margin="0,0,0,0" x:Name="MediaMain" VerticalAlignment="Stretch" Source="" Stretch="Fill" AutoPlay="False"/>

    What I did add was handlers for all of the events e.g. Play, pause, volume (actually all the code to do the slider) and hide/show events for the play button.  More on that in a mo.

    Of course for this to be a web part, the movie file at least has to be a variable that's changeable in the properties of the web part.  To do this I am going to use Silverlight's InitParams property.  Its worth mentioning that the movies are nothing to do with me...they are going to live in a sharepoint library, they are encoded into wmv format using another app.

    In the App.xaml file within your Silverlight project you will find an OnStartUp method, this is where I handle the InitParams.

            private void OnStartup(object sender, StartupEventArgs e) 
                this.VideoUrl = string.Empty;
                if (e.InitParams["videoUrl"] != null) {
                    this.VideoUrl = e.InitParams["videoUrl"];
                if (e.InitParams["AutoPlay"] != null) {
                    this.AutoPlay = Convert.ToBoolean(e.InitParams["AutoPlay"]);
                else {
                    this.AutoPlay = false;
                if (e.InitParams["Loop"] != null) {
                    this.Loop = Convert.ToBoolean(e.InitParams["Loop"]);
                else {
                    this.Loop = false;
                // Load the main control here
                this.RootVisual = new Page();

    As you can see I am expecting 3 params and set class level properties for later use. AutoPlay(play the video on page load) and Loop play(to obvious to describe!!), VideoUrl (the url of the video to show).

    public string VideoUrl { get; private set; }
    public bool AutoPlay { get; private set; }
    public bool Loop { get; private set; }

    In the Silverlight class (Page) constructor I get the values like this...

            App currApp;
            public Page()
                // Required to initialize variables
                currApp = Application.Current as App;
                VideoMain.Source = new Uri(currApp.VideoUrl);
                VideoMain.AutoPlay = currApp.AutoPlay;
                if (currApp.AutoPlay) {
                    ControlsPlayPause.Opacity = 0;
                    PlaySymbol.Opacity = 0;
                    PauseSymbol.Opacity = 1;

    Here you can see I get the current application, cast it as App (insert whatever the name of your own application class is...App is default) and access the properties.  I am setting the source of the video and deciding whether to play or not, setting the UI to suit.

    I have a couple of handlers on the UserControl to show the play/pause button.  Basically when the mouse hovers over the control show the button (begin the StoryBoard that animates it in)

            private void UserControl_MouseEnter(object sender, MouseEventArgs e)
                if (ControlsPlayPause.Opacity < 1)
            private void UserControl_MouseLeave(object sender, MouseEventArgs e)

    In the top one, I check for opacity, as you can see in the class constructor if the video is not set to AutoPlay I show the play button.

    I don't use this, but for reference this is what the markup would look like to use this Silverlight app.

        <div id="silverlightControlHost">
            <object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%">
                <param name="source" value="ClientBin/VideoViewer.xap"/>
                <param name="background" value="white" />
                <param name="initParams" value="videoUrl=http://mossinstance/site/library/movie.wmv,AutoPlay=true,Loop=false" />
                <a href="http://Silverlight.2.0.exe" style="text-decoration: none;">
                     <img src="" alt="Get Microsoft Silverlight" style="border-style: none"/>
            <iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>


    Now onto the web part.  I am going to have the Silverlight app on the Sharepoint server, there are obviously several ways, one that appeals to me most is have a sharepoint library for your Silverlight apps, or it could be as simply as creating a ClientBin folder at the route of the site.  Don't forget you need to set the MIME type up for Silverlight.

    The web part itself is pretty simple, all I need is 3 properties, create the Silverlight control and set the InitParams.

    I do have a custom "NotInstalled" template, but you don't need that.  I didn't want users to have to download the installer from the web, so I have put it on the network. You will also see I have set the source of the Silverlight control to a ClientBin folder at the root of the site.

    Another point to note(!) I have put the dll System.Web.Silverlight in the GAC, there are arguments for and against, I prefer the GAC.

    Now install your web part in whatever method you prefer...

    Some pages/sites/articles that helped.

    I have literally just found this on codeplex, it's a Silverlight 1.0 video player web part for Sharepoint.  Would have been no good for me as I have no interest in Silverlight 1.0, but you might!!


  • MOSS | Custom Field, drop down auto select hell

    Tags: .NET 3.5, SharePoint

    The more I work and develop with SharePoint I am learning that 95% of the task, with a little guidance is a walk in the park, especially when compared to that final 5%, which is either impossible or is the most painfully experience any developer can experience!!

    Take my Friday hell for an example...

    A requirement comes in for custom news item, with a property that is the users department, but could be changed to another. Sure i think, drop down control, bind to all the possible departments, auto select the user department, getting the value from the users profile.

    Converting that into SharePoint, create a custom field, inherit from SPFieldChoice, bind to an SPList with all the groups (add to the base.Choices collection), get the current user from the SPContext, use that to the query the users profile to get the department, set the base.DefaultValue. Cool, now that is sweet, test in a simple column adding to a list, works a treat. The field is wanted for a page content type though so...

    Create a site column, add to content type, create custom page layout, drop on...we are rocking so far.

    Go to create a page and my group is selected, awesome. Change my group just to test, but nope still selects old group...hmmm...iisreset....nope the same. Test with other users, the same!! Just to confirm, its not selecting the first item in the list, its selecting the department of the admin user who deployed the solution, and what it was when they deployed it!!!!! Now that is nuts, go into a standard list, works a treat!! After hours of thrashing, trying to add it directly as a column to the page library and many others i gave up and came up with a far less appealing solution but a solution none the what the feck is going on here???

    Its worth noting that i put some trace code in and found that the correct department was being pulled through, and checking what base.DefaultValue was after setting it showed it was what I expected, but on the page was the admin's original group. If anyone else has experienced similar it would be great to here from you, I can post some code if you like, but its pretty simple stuff and like i said, works in standard items.

    I did actually take the time this weekend to create a custom field rendering my own drop down list, the value is auto selected as I would expect, but I the value doesn't display in the "View Properties" or "Published Page" mode, fine in "List View"....its metal!

    P.S. I have another one to with sub classing the CQWP, that I might post later.


  • Cricket Club Starter Kit CodePlex project

    Tags: .NET 3.5,, Personal

    I mentioned a while back that I had something I was working on that involved a change in language, actually a pretty radical change. I have been working on vocational project written in and made heavy use of LINQ to SQL. I wasn't sure of LINQ to SQL for anything else other than RAD and to be honest I'm still not. Anyway, I'm not getting into that debate. Needless to say I went all the way and don't use a single sproc in this project.

    Some of you will know I play cricket every Saturday for a local club (nothing special, just for fun!), well for a couple of years I have been thinking of putting a website together for the club, just never got round to it. However the other day I was looking at the starter kits on the website and came across The ClubSite v2.0, also hosted on codeplex, basically this is built on top of the original ClubSite, it adds functionality and has layered the code. Problem is, its American and the statistics part of the site relates in no way to cricket, which is a pretty statistics intensive sport.

    I decided to write the cricket stats engine (that sounds fancy!), and take the opportunity to write some real code in and LINQ to SQL. I have pretty much completed this project on my train journey to and from work, which is about 40 mins each way. Working on it not every day, but most for the past month.

    The original ClubSite makes use of submodal for its AJAX functionality and some modal popups, I am not really a fan of these and found them to work erratically so have replaced a few and plan to do the rest, using the AJAX control toolkit modal popup. I have also added update panels to make the UI some what slicker! I code is in no way of a work of art, that's not really been the point of the exercise.

    I haven't finished the project, apart from very limited testing, I plan on using silverlight (to tick another "must learn more about" box) to create some pie charts etc to better represent the data. I have actually found some open source examples i intend to download soon.

    I appreciate that cricket is a pretty captive audience and cricket playing geeks are no doubt even less, but hopefully I will get some downloads and help if finding bugs and enhancing the project. I have actually only found 1 other site that does cricket statistics and that is a national site and every club has a sub-site within the main site. Far to restrictive for my liking.

    Go and check the project out here: Cricket Club Starter Kit

    It's also worth mentioning that I haven't changed any of the original ClubSite v2.0 code, I have simply added on to it, mainly because I don't to miss out on anything that gets released/fixed with that project. Apart from perhaps a link of two in the menu to point to my new CricketStats folder and the graphic from a football (soccer ball) to a cricket related image. I haven't even fixed bugs that I have come across, that isn't the point of this project. On Codeplex I have checked all the code in, including scripts to create the schema in the db, but not all my test data (yet). I'm not sure if this is the best way to go about it, it might be better to simply check in the new code and some scripts to incorporate it in into the clubsite v2.0. That might over complicate the whole development process though.

    A Few screen shots to give you a flavour!

    Games in season overview - (Default.aspx)


    Game Statistics


    Team Statistics for the season


    Player Statistics by season






  • Gotcha | Windows Service reinstall

    Tags: .NET, .NET 3.5

    System.ComponentModel.Win32Exception: The specified service has been marked for deletion.

    This is the first time I have ever seen this error and it may well have been complete luck that I haven't as there seems to be a pretty solid reason why it occurs.

    It popped when I uninstalled a service using InstallUtil.exe, then tried to install again using the same utility.  Because I had the Windows Services window open (apparently it can also happen when you run uninstall without stopping the service as well, but seriously, who would be so reckless! ;-) ) when executing the uninstall there are some registry keys that are not deleted so when you try an install again the error occurs.

    The simple solution was to close the windows services window and run uninstall/install again...Bingo!