Archive for category .net

Import & Export break points in Visual Studio 2010

“This will change your life”

… reassured my colleague Mr Carmicheal.

Basically it’s possible in VS2010 (Pro, Premium or Ultimate) to Import & Export sets of break points for projects, handy if you have pieces of code you often have to step through for some reason or another.

The original article can be found here: http://msdn.microsoft.com/en-us/library/dd293657.aspx

In case that page goes AWOL as MSDN pages often do, this is what it said;

To export all breakpoints that match the current search criteria

  1. In the Breakpoints window toolbar, click the Export all breakpoints matching current search criteria icon.

    The Save As dialog box appears.

  2. In the Save As dialog box, type a name in the File name box.

    This is the name of the XML file that will contain the exported breakpoints.

  3. Note the folder path shown at the top of the dialog box. To save the XML file to a different location, change the folder path shown in that box, or click Browse Folders to browse for a new location.
  4. Click Save.

To export selected breakpoints

  1. In the Breakpoints window, select the breakpoints you want to export.

    To select multiple breakpoints, hold down the CTRL key and click additional breakpoints.

  2. Right-click in the breakpoints list, and choose Export selected.

    The Save As dialog box appears.

  3. In the Save As dialog box, type a name in the File name box.

    This is the name of the XML file that will contain the exported breakpoints.

  4. The folder path is shown at the top of the dialog box. To save the XML file to a different location, change the folder path shown in that box, or click Browse Folders to browse for a new location.
  5. Click Save.

To import breakpoints

  1. In the Breakpoints window toolbar, click the Import breakpoints from a file icon.

    The Open dialog box appears.

  2. In the Open dialog box, browse to the directory where your file is located, and then type the file name or select the file from the file list.
  3. Click OK.

No Comments

Conditional logic in ListView ItemTemplate with DataBinder.Eval

Embarrasingly simple, but something I always seem to forget, and then never blog! I needed to show a tick in a repeater when a row value was -1: Simple! In MVC, with the razor syntax and strongly typed views I’ve grown to love, this is a pinch o’ the proverbial piss- In WebForms rreviously I often resort to setting up an ItemDataBound event handler which hides or shows an image, but to be honest I could not be bothered- this seems such overkill for something as simple as this. Anyway, after some faffing I reminded myself the easiest method is to use an ‘in-line if’ in the ItemTemplate, like so;

<ItemTemplate>
        <tr>
            <td><%# Eval("CarReg") %></td>
            ...
            <td>
                <%# (DataBinder.Eval(Container.DataItem, "NewRepeat") != null && DataBinder.Eval(Container.DataItem, "NewRepeat").Equals(-1) ? "<img src=\"../images/tick.png\" alt=\"tick\" />" : "<img src=\"../images/cross.png\" alt=\"cross\" /")%>
            </td>

No Comments

Grabbing data from the registry on a remote machine using dot net and WMI

I recently had to write an app which, given a computer name, would grab their telephone extension from a registry key (For the purpose of the code example below, I just grab the CommonFilesDir key from the windows node. There’s a couple of ways you can achieve this- either using RegistryKey.OpenRemoteBaseKey which gave me a whole bunch of permissions issues, plus you need the remote registry and remote administration services active on the server/client OR you can use the Windows Management Instrumentation (WMI) service. I took this route, as it’s a service which is active by default on all of our machines on the domain, and it was easier to get the permissions right.

Before I paste the code, a GOTCHA to beware of, straight from the MSDN here;

The registry provider is hosted in LocalService—not the LocalSystem. Therefore, obtaining information remotely from the subtree HKEY_CURRENT_USER is not possible

ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
options.Username = "<domain_admin_username>";
options.Password = "<domain_admin_password>";

// http://msdn.microsoft.com/en-us/library/system.management.managementscope.aspx
ManagementScope ms = new ManagementScope("\\\\<computer name>\\root\\default", options);          

ms.Connect();

// http://msdn.microsoft.com/en-us/library/windows/desktop/aa390788(v=vs.85).aspx
ManagementClass mc = new ManagementClass("stdRegProv");
mc.Scope = ms;

ManagementBaseObject inParams = mc.GetMethodParameters("GetStringValue");
// there are other methods for grabbing other reg types- see
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa393664(v=VS.85).aspx

inParams["hDefKey"] = RegHive.HKEY_LOCAL_MACHINE;
inParams["sSubKeyName"] = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion";
inParams["sValueName"] = "CommonFilesDir";

ManagementBaseObject outParams =
        mc.InvokeMethod("GetStringValue", inParams, null);

if (outParams["ReturnValue"].ToString() == "0")
{
    Console.WriteLine(outParams["sValue"]);
}
else
{
    Console.WriteLine("Error " + outParams["ReturnValue"] + " please refer to http://msdn.microsoft.com/en-us/library/ms681382%28v=3Dvs.85%29.aspx");
}

Console.ReadLine();

This code requires this enum..

public enum RegHive : uint
{
  HKEY_CLASSES_ROOT = 0x80000000,
  HKEY_CURRENT_USER = 0x80000001,
  HKEY_LOCAL_MACHINE = 0x80000002,
  HKEY_USERS = 0x80000003,
  HKEY_CURRENT_CONFIG = 0x80000005
}

If you receive a COM error back “The RPC server is unavailable”, make sure the target machine’s firewall isn’t blocking the call- this will open the port;
netsh firewall set service RemoteAdmin

No Comments

IIS Express hanging when launched from visual studio

I recently built up a new machine at work and grabbed all my latest projects out of SVN only to find that one of them no longer seemed to start.

Since checkout I hadn’t changed any code, got a clean build, but when the browser window opened it just hung, with no error.

I eventually found this was because I was using the UrlRewrite module on the site (with the rules in the web.config file) but had forgotten to install this component on my IIS on the new machine. An error message would have been nice!

No Comments

Ninject + WCF Docs

I’ve recently started using Ninject, having previously only used Unity as my IoC container, but it seems the internet is scarce of any documentation. I’ve employed the WCF extension, and found this handy guide on how to get up and going with it. www.aaronstannard.com/post/2011/08/16/dependency-injection-ninject-wcf-service.aspx

ps- This is my 200th blog post! Woohoo!

No Comments

Conditional DataAnnotations in c#

This is something a bit weird, which maybe even, dare I say, a bug in the .net DataAnnotationsExtensions pack (Installable via NuGet). I decorated one of my class properties with an Email data annotation, because If the class had an email set, I wanted to ensure it was valid. I didn’t, however, decorate it with a Required attribute. However it seems the Email attribute will return false if no value is passed, ensuring that it is infact required? (Please leave a comment if there is some really obvious built in way around this!)

To get around this I created a simple “IfPresent” data annotation which you can chain another validation onto; This basically returns a true if the value is null, otherwise it will pass it on to the real ValidationAttribute to work it”s magic. It can be implemented like this;

[DataMember]
[IfPresent(typeof(EmailAttribute), ErrorMessage = "Must be a valid email address")]
public string EmailAddress { get; set; }

The code is;

namespace Chinook.Model.ValidationAttributes
{
    public class IfPresent : ValidationAttribute
    {
        private ValidationAttribute attr;

        public IfPresent(Type attr)
        {
            this.attr = (ValidationAttribute)Activator.CreateInstance(attr);
        }

        public override bool IsValid(object value)
        {
            if (value == null)
                return true;

            return attr.IsValid(value);
        }
    }
}

8 Comments

WCF Services with both JSON and SOAP endpoints

A quick example of how to set this up in the web.config.

Services, in this example, can be accessed

  • using JSON via localhost/Services/MyService.svc/HelloWorld or..
  • using SOAP on localhost/Services/MyService.svc/soap/HelloWorld
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />

    <services>
      <service behaviorConfiguration="WebServiceBehavior" name="Demo.Web.Services.MyService">
        <endpoint address="" binding="webHttpBinding" contract="Demo.Web.Services.IMyService" behaviorConfiguration="jsonBehavior" />
        <endpoint address="soap" binding="basicHttpBinding" contract="Demo.Web.Services.IMyService"/>
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="WebServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <bindings>
      <webHttpBinding>
        <binding crossDomainScriptAccessEnabled="false" name="httpBinding" />
      </webHttpBinding>
    </bindings>

  </system.serviceModel>

No Comments

MVC Razor Syntax – Web forms “Master Page” content area equivalent

In razor instead Web Forms ContentArea’s in Master Pages you have @sections within your _Layout.cshtml file. In the _layout file you have a declaration such as;

@RenderSection("JavaScript", required: false)

Then in your content pages;

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")" />;
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")" />;
}

Source : http://stackoverflow.com/questions/4311783/asp-net-mvc-3-razor-include-js-file-in-head-tag

No Comments

MySQL 5.1 with DotNet claims Procedure or function ‘‘ cannot be found in database ‘

We have some dot net code which uses MySQL- our live setup it thus;

MySQL 5.1.45
MySQL Dot net connector dll version 6.2.2.0

We recently rebuilt our dev server, and installed MySQL 5.1- it turns out the minor revision number was slightly higher, but nothing to set off any alarm bells, or so we thought;

MySQL 5.1.57

With this combination or MySQL connector 6.2.2.0 and MySQL 5.1.57, we couldn’t execute any stored procedures- we would just get;

Procedure or function ‘ ‘ cannot be found in database ‘

Googling turned up lots of suggestions like “make sure your connection string is lower case” etc etc- nothing fixed our issue.

We found the solution was to update our MySQL dot net connector to the latest, which at time of writing was 6.3.7.0.

You can get MySQL here, and the MySQL dot net connector here.

No Comments

Refactoring a web project so you can share user controls across others

I recently built a brand new site, which launched last week and have now been tasked with adding an additional B2B component to it. The B2B site will have all the same styling as the B2C site, and will share a lot of functionality that I’ve already written into User Controls for the main web site. So I was faced with a problem- How can I share these controls across both projects? I don’t want to simply copy and paste, because then I have two controls to maintain, so I took to Google where I found this old article by Scott Guthrie.

I figured I would document the re-factoring exercise I went through.

So I started with my main web project which looked like this;

I shall break down the refactor into some simple steps;

  1. I created a new class library project which could be shared between the two web projects, in this instance I called mine Chinook.Web.Helpers
  2. Create a “Controls” folder and drag all the controls from the original web project, into the new shared projects control folder (Make sure both the ASPX and the code behind parts came across!). Build the new shared project- you will probably find some build errors and will need to add references to some web specific .net dll’s- I needed
    • System.Configuration
    • System.Web
    • System.Web.Extensions
    • System.Web.Extensions.Design
    • System.Web.Services

    As well as these I also had to add references to my .Model and .Interfaces projects, but this will be different depending on how you’ve setup your project. At this stage I had a projects which built and looked like this;

  3. I updated the namespace for each controls code behind and the first line of each ascx to reflect the namespace of the new project;

    //namespace Chinook.Web.Controls
    namespace Chinook.Web.Helpers.Controls
    {
        public partial class QuickContact : System.Web.UI.UserControl
    

    ..and the new inherits parameters in the ascx;

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="QuickContact.ascx.cs"
        Inherits="Chinook.Web.Helpers.Controls.QuickContact" %>
    
  4. Next I added a reference in my web project to the new shared project, then deleted the controls from my controls folder, leaving an empty controls folder. All the references to the controls in your pages remain the same; for example
    <%@ Master Language="C#" AutoEventWireup="True" CodeBehind="Site.master.cs" Inherits="Chinook.Web.SiteMaster" %>
    <%@ Register Src="Controls/RSSLister.ascx" TagName="RSSLister" TagPrefix="uc1" %>
    <!DOCTYPE html>
    <html lang="en">
    <head runat="server">
    ...
    <ul id="rss" class="orange-bullets">
      <uc1:RSSLister ID="BlogRSSFeed" runat="server" />
    </ul>
    
  5. So the project is now happy- we just need to add the pre-build step which will copy the ascx files (but not the code behind) over to each projects control folder on pre-build. So in the original web project, right click the project and go to properties -> Build Events and set the pre-build event so that it copies;

    copy $(SolutionDir)\Chinook.Web.Helpers\Controls\*.ascx $(ProjectDir)\Controls\
    
  6. Build and run your web project!

I also moved over a few other bits. I had an ashx file which handles file uploads- so I moved the code behind to the shared projects and just updated the ashx file to inherit from the same class, but in it’s new namespace. I also had a resx file which contained user friendly error messages which I moved to be central. My final helper looked like this;

Make sure that you don’t edit the ascx files that now exist within your web project, as there will be overwritten by the versions in the shared project everytime you re-build.

If you use the publish option (you probably do!), make sure you “show all files” on your web project after a build include the ascx files into your web project, so it gets copied up.

2 Comments