Archive for category .net

MVC3/Webforms app using forms authentication – CSS & Images folder not accessible before login

This is very usually embarrassingly simple. You have a site which is locked down using forms authentication, but your login page needs the css and images- so you add settings to your web config telling the app only authenticated users can come in, but no one else can- then you add a couple of exceptions for your specific folders- like so;

<configuration>
	<system.web>
		<authentication mode="Forms" >
			<forms loginUrl="login.aspx" name=".ASPNETAUTH" protection="None" path="/" timeout="20" >
			</forms>
		</authentication>
<!-- This section denies access to all files in this application except for those that you have not explicitly specified by using another setting. -->
		<authorization>
			<deny users="?" />
		</authorization>
	</system.web>
<!-- This section gives the unauthenticated user access to the Default1.aspx page only. It is located in the same folder as this configuration file. -->
		<location path="default1.aspx">
		<system.web>
		<authorization>
			<allow users ="*" />
		</authorization>
		</system.web>
		</location>
<!-- This section gives the unauthenticated user access to all of the files that are stored in the Subdir1 folder.  -->
		<location path="subdir1">
		<system.web>
		<authorization>
			<allow users ="*" />
		</authorization>
		</system.web>
		</location>
</configuration>

This is documented on the MSDN on this article.

I just deployed an existing site to a new dev server and found everything ran fine, except the css and images would not load on the login page, despite me having the exception in the web.config.

After lots of Googling (most articles simply explain that you need the above exception’s in your config!) I found this little gem which explained I needed to;

  1. Open the IIS7.5 control panel
  2. Select the application
  3. double-click “Authentication”
  4. select “Anonymous Authentication”, then Edit
  5. change it to use the Application Pool Identity. Make sure that user has permissions on the folder that contains the site

No Comments

Switching from ObjectContext to DbContext in your Entity Framework EDMX File

Tres easy and much cleaner classes turfed out the other end;

http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx

2 Comments

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.

1 Comment

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