by Andreas

Define a #Region in javascript files (Visual Studio 2010 / 2012)

In these times of super responsive client side processing mega javascript extravaganza web applications  you’re more than likely to end up with fairly large .js files in your projects. The standard code file in Visual Studio allows you to define collapsible sections by wrapping them with the #region / #endregion blocks. In javascript files however, you are restricted to collapsible functions only (“#region” is not recognized as anything valid):

image

Well, I just found out that that’s not entirely true. By marking a section of code (regardless of any logical blocks) and hitting CTRL + M + H you’ll define the selection as a region which is collapsible and expandable

image

by Andreas

Visual Studio 2010 – alternatives to ReSharper

imageJetBrains ReSharper is without a doubt an extremely powerful tool for developers. If you’ve never heard about it or given it a go, I strongly recommend you go ahead and try it out.

That said, there are two camps when it comes to ReSharper: the lovers and the haters. The lovers have become so dependent on it that they claim “Visual Studio feels broken without it” (a quote from my colleague). The haters will spend time out of their day to slam it because it’s not true to “old school programming” and simply does too much for you. Not surprisingly, a lot of them (including me) started their programming careers back when C++ was considered state of the art and intellisense was a word only used by dyslexics.

When I first tried it a few years ago I ended up in the haters camp, although not spending time telling others that they should hate it too. And I have to admit after recently giving it another go with their latest release (which at the time of writing is ReSharper 7) I’m still not entirely convinced. I find it to be just too much, too visually noisy, too “let me do this automatically for you” – simply too annoying. Which sucks, because after installing it I ended up turning off one great feature after another until I was left with some simple code editor improvements, the HTML and Javascript editor improvements and their absolutely brilliant lambda expression converter.

Anyway, the aim of this post is to suggest an alternative for the ones of us that find ReSharper to be too intrusive. The Visual Studio Gallery is a great place to start, and you will find a great selection of plugins that offer you single, isolated features rather than a massive package containing 95% of stuff you simply don’t want. As an example, check these two out:

Productivity Power Tools
http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef

JScript Editor Extensions:
http://visualstudiogallery.msdn.microsoft.com/872d27ee-38c7-4a97-98dc-0d8a431cc2ed

There are also quite a few plugins for the (at the time of writing) new Visual Studio 2012, and more are added every week.

by Joakim

Automatic Config Transformations

My fellow blogger here on the Degree Blog, Thor Halvor, had a blog post not too long ago titled “Don’t let the Configuration transform your Configs” where he recommends that people don’t transform their config files based on the solution configuration, and he points out a lot of things which is important to keep in mind. I, however, think that using the solution configurations to control which transformation files are applied to your config files works quite well.

As Thor Halvor points out in his blog post, you get a few extra config files when you create a web application in Visual Studio, namely Web.Debug.config, and Web.Release.config. These files are the XML transform files for Web.config, and when you build you application locally, they do exactly nothing (no matter if you have selected the debug or release solution configuration). If you use the “Build Deployment Package” or the “Publish” functionality in Visual Studio however, they are applied to your web.config file based on the currently selected solution configuration. Now this might work fine for a small personal project like your own homepage etc., but I doubt many people use this on large work projects. Another problem with this functionality (as Thor Halvor points out), is that it only works for Web.config, and in larger projects you often have more than one config-file (connection strings in a separate file, etc.).

So how can we use xml transform files for more than Web.config, and have the transformation be performed as part of an automated build on a build server? By adding a new target to the Web Application’s project file (.csproj) which will run as a part of the build (You need to right click on the project and choose “Edit project file”).

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  .
  .
  .
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target> -->
  <Target Name="TransformConfigFiles" AfterTargets="AfterBuild" Condition="'$(TransformConfigFiles)'=='true'">
    <ItemGroup>
      <DeleteAfterBuild Include="$(WebProjectOutputDir)Web.*.config" />
      <DeleteAfterBuild Include="$(WebProjectOutputDir)ConnectionStrings.*.config" />
    </ItemGroup>
    <TransformXml Source="Web.config" Transform="$(ProjectConfigTransformFileName)" Destination="$(WebProjectOutputDir)Web.config" />
    <TransformXml Source="ConnectionStrings.config" Transform="ConnectionStrings.$(Configuration).config" Destination="$(WebProjectOutputDir)ConnectionStrings.config" />
    <Delete Files="@(DeleteAfterBuild)" />
  </Target>
  .
  .
  .
</Project>

This new target will run after the “AfterBuild”-target, and it will transform both Web.config and ConnectionStrings.config, given that you specify the property “TransformConfigFiles” to be “true” (because we don’t want this be be done when we’re developing the application and building it in Visual Studio. As you can see above it uses the “Configuration”-property to decide which xml transform file to use (this property will contain the name of the selected solution configuration). After performing the transformation, it will clean-up/delete the xml transform files.

ConfigTransform1As you can see, I have created an additional config file, namely ConnectionStrings.config, as well as xml transform files for it (ConnectionStrings.Debug.config and ConnectionStrings.Release.config). The transformation files I’ve created aren’t group under the actual config file like Web.config’’s xml transformation files are, but if you wanted to you could edit the project file to do this.

You need to have xml transformation files for each solution configuration for those config files you want to transform, and they must all be named as <ConfigFileName>.<SolutionConfigurationName.config. I.e. if you create a new solution configuration called “Production” you would need to create a xml transform file called ConnectionString.Production.config (for Web.config you would just need to right click on it and select “Add Config Transforms”.

 

 

 

Inside my transformation files I’ve just put some simple transformations that will allow me to see that the config files are actually being transformed.

Web.config:
<configuration>
  <connectionStrings configSource="ConnectionStrings.config" />
  <appSettings>
    <add key="Configuration" value="" />
    ...
  </appSettings>
  ...
</configuration>

Web.Release.config:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <appSettings>
    <add key="Configuration" value="Release" xdt:Transform="Replace" xdt:Locator="Match(key)" />
  </appSettings>
  </system.web>
</configuration>

ConnectionStrings.config:
<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=(local);Initial Catalog=dbMVC4;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

ConnectionStrings.Release.config:
<connectionStrings xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <add name="DefaultConnection" connectionString="Data Source=PreProdDatabaseServer;Initial Catalog=dbMVC4;Integrated Security=True" providerName="System.Data.SqlClient" xdt:Transform="Replace" xdt:Locator="Match(name)" />
</connectionStrings>

In order to build the Web Application and have the config transformations take place we must run msbuild and specify the solution configuration we want to use, and that TransformConfigFiles should be true.

Running msbuild manually from the Visual Studio command prompt:

msbuild "C:...Testing.sln" /p:Configuration=Release /p:TransformConfigFiles=true /p:OutDir=C:TempTesting_Release

Under “C:TempTesting_Release_PublishedWebsitesMVC4” one should be able to find the Web Application with transformed config-files.

Now for the cool part, this approach will also work on your TFS build server, in your build definition just specify the build configuration and add TransformConfigFiles=true to the MSBuild Arguments.

ConfigTransformTFS

On the project I’m currently working on, we have successfully been using this solution with TFS 2010 to automatically build and deploy our web application to the different testing environments for the better part of a year now! Smile

by Andreas

Visual Studio 2010 – how to Add Existing Folder

Have you ever wanted to include an entire existing folder to your project, and not just files?

I used to do this the stupid way. Right click the project, choose Add New Folder, give it a reasonable name, open up the folder in Windows Explorer, copy my files into the folder, go back to Visual Studio, right click the folder, choose Add Existing Item and then finally include the files in the project. The stupid way.

imageYou can add an entire folders to your project directly, by first turning on “Show All Files” (tiny icon at the top of the Solution Navigator). Your folder will now be displayed as existing (e.g. my Scripts folder), but not part of your project. Right click the folder, choose “Include In Project” and not only will the folder and its containing files be added, but all subfolders as well. This was particularly neat in my case since the Scripts folder contained a jQuery component with corresponding library files stored in several sub folders.

by Andreas

Sharepoint 2010 – programmatically import and use web parts from site gallery

I recently discovered that when I export webparts with custom settings (like a CQWP with styling, filter values etc) and stored them in the site collection gallery, the configuration values were lost when programmatically importing them in a Visual Studio 2010 solution. The .webpart file created upon export contains all the custom settings, but this was ignored when using the standard add method ( SPLimitedWebPartManager.AddWebPart(…) ). All I got was a standard clean out-of-the box instance of the CQWP, which meant manual configuration was required.

To overcome this limitation there is another available method in the SPLimitedWebPartManager class: SPLimitedWebPartManager.ImportWebPart(…). This method takes an XmlReader parameter, which should get its data feed from the .webpart file stored in the gallery. The trick is to find the path to this file, but when you’ve got that it is simple to import it to your current page and then add it a web part zone. Here’s a snippet to help you get started:

    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    {
        SPList list = site.RootWeb.Lists["Web Part Gallery"];

        for (int i = 0; i < list.ItemCount; i++)
        {
            if (list.Items[i].Title.Contains("The title of my custom webpart"))
            {

... // you can figure out the rest

The following code is in the context of a newly created sub site, and I access the SPLimitedWebPartManager for a publishing page like this:

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    {
        // get reference to newly created sub site
        using (SPWeb web = site.AllWebs[_NewSiteGuid])
        {

            PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);

            PublishingPage page = pWeb.GetPublishingPage(_NewSiteUri);
            // check out page before making changes
            page.CheckOut();

            // access webparts
            SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(page.Uri.ToString(), PersonalizationScope.Shared);

...

A bit further down the actual import and adding occurs:

...

    string error = ""; // holds the potential error message
    // bit of ugly coding here, Robert C. Martin will shoot you if you use this!
    string exportedWebPartXml = new StringReader(site.RootWeb.GetFileAsString(site.RootWeb.Url + "/_catalogs/wp/SomeCustomFancyComponent.webpart")).ReadToEnd();
    // alter contents
    exportedWebPartXml = exportedWebPartXml.Replace("SomeValueThatShouldBeGeneric", "ThisOtherValueThatIsPageDependant");

    // create a reader
    XmlTextReader reader = new XmlTextReader(new StringReader(exportedWebPartXml));

    // wpMgr is an instance of SPLimitedWebPartManager
    System.Web.UI.WebControls.WebParts.WebPart importedWp = wpMgr.ImportWebPart(reader, out error);

    // make some other alterations if applicable
    importedWp.Title = "New title";

    // add the web part to the publishing page
    wpMgr.AddWebPart(importedWp, "TopBarLeftZone", 0);

...

Note: I have removed validation for increased readability, but before someone gets on my back for possible null pointer exception traps I just wanted to say it was deliberate!

If you expect to get anything out of this post, I assume you already know enough basic coding to see what’s going on. Basically, using the path pointing to the .webpart file the contents are read into the XmlTextReader and passed on to the ImportWebPart() method. The return parameter is an instance of your webpart (if you got the path correct…) which can then be added to a web part zone on your page.

Your custom settings are now preserved, and as you see in this code I also do some runtime alterations of the .webpart file contents which practically removes any boundries to what you can do.

by Stian

WP7: Application launch failed

When you try to deploy your WP7 applications from Visual Studio to your phone, you might get the message: “Application launch failed. Ensure that the device screen is unlocked and device is developer unlocked. For details on developer unlock, visit http://go.microsoft.com/fwlink/?LinkId=195284

The link you get is only a link to create.msdn.com, which does not actually help you solve the problem.

Very often we find that the reason for this error message is the device screen is unlocked, but it is also necessary to register your device on your developer account to be able to deploy. You already have the tools you need on your computer, just follow these instructions:

Developer Phone Registration

  1. Go to “All Programs” on your start menu and find “Windows Phone Developer Tools
  2. Start “Windows Phone Developer Registration
  3. Fill inn Windows Live ID and password.
  4. Click “Register

devregwp7

by Andreas

Visual Studio 2008 tip: how to get public key token for assembly

Simple trick for generating public key token from the Tools menu (for example when deploying Sharepoint 2007 webparts):

1. In Visual Studio, choose Tools –> External tools…

2. Click Add, enter
* Title = Get public key
* Command = C:Program Files (x86)Microsoft Visual Studio 8SDKv2.0Binsn.exe
* Arguments = -Tp “$(TargetPath)”
* Ensure that just “Use Output window” is checked, none of the others

image

3. Click OK and you now have a new entry under the Tools meny

image

This will give you the public key token in the output window.

by Andreas

Windows Phone

Sannsynligvis en gang før jul lanseres den nye Marketplace, Microsofts alternativ til Apples gigantsuksess App Store. Dette skjer naturligvis i sammenheng med lansering av det nye OS’et for mobil, Windows Phone.

Windows Phone er bygget helt fra grunnen og har lite eller ingenting til felles med det gamle Windows Mobile 6.x. Microsoft har tydelig beveget seg mer mot en lukket plattform, men i motsetning til Apple som selv produserer hardwaren skal Phone kunne kjøre på et utall enheter fra forskjellige produsenter som HTC, Motorola, LG osv. Det har derfor blitt definert en del krav som stilles før en produsent kan stemple sin enhet som “Windows Phone”-godkjent. Disse innebærer minimumskrav til CPU, minne, kamera, skjermkort og andre komponenter (komplett liste: http://www.techautos.com/2010/03/17/windows-phone-7-series-hardware-requirements/ ). På denne måten forsikrer de seg om at brukeropplevelsen holder en viss standard (WM 6.x hadde ikke disse kravene, og resultatet av det kjenner mange til..).

Marketplace er som sagt Microsofts alternativ til App Store. Marketplace eksisterer allerede i dag og er en kanal for salg av applikasjoner til WM, men utvalget av applikasjoner er svært begrenset og helt i skyggen av Apples pengemaskin. Måten Microsoft skal ta sin del av dette markedet på er å tilby mye av det samme konseptet, men gjøre verktøyene mer tilgjengelige og fleksible. Pr i dag må en applikasjon for iPhone utvikles på en Mac, mens de fleste utviklere (den får skyte meg den som mener det motsatte) fortsatt sitter på en Windows-maskin. I tillegg kommer integreringen med Visual Studio, Expression Blend og de andre verktøyene til Microsoft gjøre det enkelt for de aller fleste med litt bakgrunn i enten koding eller design å lage sin første applikasjon for Phone-plattformen. Om dette er nok til å ta igjen forspranget til Apple vil tiden vise, men for oss som har begynt å se litt på denne teknologien er det ikke tvil om at Steve Jobs bør legge noen strategier for at ikke “menigheten” hans skal begynne å miste alt for mange medlemmer fra 2011 og utover.

Microsoft har i år sendt sine “evangelister” rundt omkring i verden for å promotere Phone for utviklere for på denne måten sørge for at Marketplace skal ha et rikt innhold av applikasjoner den dagen Phone lanseres. De har derfor lagt ut en toolkit som kan lastes ned gratis (desverre fungerer dette ikke med Visual Studio 2010 enda, men installeres som en egen Visual Studio Express For Windows Phone), pluss en del eksempelkode og et forum for å skape en community på et så tidlig statium som mulig. Developer tools kan lastes ned her: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=cabcd5ed-7dfc-4731-9d7e-3220603cad14 mens hjelp til å komme i gang finnes her: http://msdn.microsoft.com/en-us/library/ff402535%28VS.92%29.aspx

Oppdatering: Nå har den endelige versjonen av Developer Tools blitt sluppet!

For de som lurer på den økonomiske siden ved Marketplace så melder Microsoft at det blir i henhold til “industry standard” (jepp.. styrt av Apple): 70/30, hvor brorparten går til utvikler. På spørsmål fra salen om hvordan fordelingen ser ut for applikasjoner som er gratis (folk spør om det mest utrolige) sjekket foredragsholder dette opp nøye og svarte tilbake at “joda, samme gjelder for gratis-applikasjoner”…

I VG kan du lese om hvordan Steve Ballmer skal bekjempe iPhone med Windows Phone. Se vg.no

http://blog.degree.no/2010/09/windows-phone-7-developer-tools-released/