Tagged: C# RSS Toggle Comment Threads | Keyboard Shortcuts

  • John 11:57 pm on January 8, 2012 Permalink | Reply
    Tags: Amazon, Backup, C#, , S3   

    Backup IIS Server Package to Amazon S3 using C# 

    I recently updated our backup process at work to store our backups on Amazon S3. I wanted a simple process to that would backup the IIS server configuration and website files that can be easily be restored on a new server in case of a major problem. Luckily Microsoft have release MSDeploy which can be installed using the Web Platform Installer.

    Within IIS you can backup everything to a server package by opening the context menu selecting depoy, then “Export Server Package”. This will create the server package containing the IIS configuration along with all the sites and their files. This is all good however it is still a manual process that is likely to be forgotten about after a while. Likely there are a series of libraries we can use to automate this process.

    The namespace Microsoft.Web.Deployment provide the functionality we need to backup IIS, this is provided by Microsoft.Web.Deployment.dll. To backup the server we need to use the DeploymentManager to create an object use to create the package, we can then use this to “sync” the server setting to a package.

    After we have backed up the site package we need to upload it to Amazon S3. To do this we can use the AWSSDK .NET library. The library can be installed via NuGet by searching for “AWS SDK”. This will install the required assemblies.

    We can use the AWS SDK to upload our server package zip to S3 using the TransferUtilityUploadRequest to create our request to use with the TransferUtility to upload our file.

    When this is all tied together we have an app that will backup and upload the server package to S3.

    I have attached a sample app that can be configured using the App.config

    Download yeticode-utility.zip

     
  • John 1:03 am on January 4, 2012 Permalink | Reply
    Tags: , C#, , MVC3   

    MVC Update User Online via Action Filter 

    Action filter to update the currently logged in users last online time to allow you to identify which of your users are online

    /// <summary>
    /// User Online Action Filter Attribute
    /// </summary>
    public class UserOnlineActionFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Called by the ASP.NET MVC framework after the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            try
            {
                if (filterContext.HttpContext != null && filterContext.HttpContext.User != null && filterContext.HttpContext.User.Identity != null)
                {
                    Membership.Provider.GetUser(filterContext.HttpContext.User.Identity.Name, true);
                }
            }
            catch
            {
                // BAD: Swallow the exception to prevent it messing with the users action
            }
    
            base.OnActionExecuted(filterContext);
        }
    }
    

    Add the action filter to the global list inside the global.asax Application_Start.

    GlobalFilters.Filters.Add(new UserOnlineActionFilterAttribute());
    
     
  • John 11:05 am on March 10, 2011 Permalink | Reply
    Tags: C#, IIS Express, ,   

    IIS7 & IIS Express 401 Access is denied due to invalid credentials Issue 

    I have been working on a large web application using MVC3, NHibernate using IIS Express to debug and IIS7 to stage. I’m using the membership services provided by ASP.NET to handle user authentication and provide security to the system. However I kept running across an issue, when accessing remotely, that was preventing me from logging in. Whenever I tried to view a page as a non logged in user I was returned a 404 Unauthorized error.

    401 - Unauthorized: Access is denied due to invalid credentials.

    401 - Unauthorized: Access is denied due to invalid credentials.

    After searching around for a solution to why this was not displaying the correct page, even if it was redirecting to the login page I decided to try to set the error displaying to return more information. After adding <httpErrors errorMode=”Details” /> to try and get a detail output from IIS the page started to work as expected.

    With this option enabled the login page was now correctly displayed. This can be set without having to edit the web.config on IIS7 by editing the “Error Pages” features settings for your site in IIS. Set the Error Response to “Detailed errors”

    Related Reading


     
    • John 3:53 pm on March 22, 2011 Permalink | Reply

      Thanks for this post! I ran into the same problem. This seems a little odd to me, have you figured out why MVC3 is exhibiting this behavior?

      • John 4:13 pm on March 22, 2011 Permalink | Reply

        Figured out what is going on… this serverfault answer is the perfect explanation:

        http://serverfault.com/questions/137073/401-unauthorized-on-server-2008-r2-iis-7-5

        In my case, I had a logon page calling Html.RenderAction(), and that action had an [Authorization] attribute.

        Cheers.

        • John 4:17 pm on March 22, 2011 Permalink | Reply

          Sorry… [Authorize] :-)

          • John 8:24 pm on March 22, 2011 Permalink | Reply

            Cheers for the update, I’ll have to take a closer look I also have numerous Html.RenderAction() that properly implemnt the [Authorize] attribute.

            However I only noticed it since MVC3 RC, I don’t think it was in either of the previous of the beta versions.

    • erick 3:31 am on August 22, 2011 Permalink | Reply

      thx alot, it help me alot..i try to figure this out for 6 days :(

    • Ryan Faricy 5:44 am on December 14, 2011 Permalink | Reply

      I can confirm that a path leading to an eventual [Authorize] attribute causes this – removing the RenderAction or allowing that action to render without [Authorize] fixes it.

  • John 12:34 am on March 28, 2010 Permalink | Reply
    Tags: C#, Castle, Medium Trust, NHibernate   

    Running NHibernate in Medium Trust 

    After deploying a NHibernate to a shared host I started running into a number of issues. Whilst developing we were running in full trust not in medium trust whilst the majority of shared hosts use. After hours and hours of searching I finally come across a post on the Castle Project mailing list which detailed how to get a nhibernate working under medium trust. Here is the steps I followed to get it working.

    I am using NHibernate 2.1.2 and C# .NET 3.5 in Visual Studio 2008.

    Step 1

    Download Castle.Core from gitbhub
    git://github.com/castleproject/Castle.Core.git

    Step 2

    Enable Castle to allow partially trusted callers.
    Open buildscripts/CommonAssemblyInfo.cs and enable the library to enable partially trusted callers

    Step 3

    Disable generation of debug information for the projects Castle.Core and Castle.DynamicProxy.

    Step 4

    Build the projects

    Step 5

    Download Nhibernate source code from source forge.

    http://sourceforge.net/projects/nhibernate/files/

    Step 6

    Open Nhibernate.Everything.sln and update the references for the NHibernate.ByteCode.Castle project so that the references for Castle.Core and Castle.DynamicProxy2 are the libraries build in step 4. Disable generation of debug information for the projects NHibernate, Iesi.Collections and NHibernate.ByteCode.Castle, similar to what was done in step 3.

    Step 7

    Copy the outputted library files from NHibernate.ByteCode/bin/Release to your shared libs folder of your project.

    Step 8

    Update the references in your project to point to the new libraries. Next turn off reflection optimization. This needs to be done in code before you create the configuration object. Configuring this in the hibernate.cfg.xml does not work. Update all your projects assemblies to set allow partially trusted callers, similar to step 2. Update your web.config to set requirePermission=”false” in the nhibernate section delceration

    NHibernate.Cfg.Environment.UseReflectionOptimizer = false;
    Configuration = new Configuration();
    Configuration.Configure();
    
    
    

    You can now run your site in medium trust using lay loading.

    Links

    Related Reading

     
    • Curtis Gulick 4:45 am on June 17, 2010 Permalink | Reply

      Can you post a full zip of your solution for both castle and NHibernate with the changes applied? I cannot seem to find the same version of castle.core that you used. I got a vs2008 and vs2010 version, but both have significant changes that do not work with nHibernate directly. Thank you!!

    • John 2:36 pm on June 20, 2010 Permalink | Reply

      Here is a version that I compiled to work view .NET 2.0

      http://blog.yeticode.co.uk/wp-content/plugins/download-monitor/download.php?id=4

    • Bri Manning 8:49 pm on September 5, 2010 Permalink | Reply

      Hey John,

      Having the same issue as Curtis and that download link appears to not be working. I’d be awesome if you could put them in another location. All I’ve been able to find are the 2010 files. Thanks!

    • John 10:56 pm on September 5, 2010 Permalink | Reply

      They should be accessible from here, the plugin was using to sort out downloads broke.

      http://blog.yeticode.co.uk/wp-content/uploads/downloads/2010/06/libs.zip

    • Bri Manning 8:07 pm on September 8, 2010 Permalink | Reply

      Awesome! Thanks, John.

    • Sara 7:41 am on September 24, 2010 Permalink | Reply

      John on behalf of everyone out there who read your post and DID NOT want to do all of that…..thank you, thank you, thank you and THANK YOU!!!

    • Dejan.s 4:14 am on September 30, 2010 Permalink | Reply

      Thanks. I don’t get the last part of it.. where should I put the Nhibernate.Cfg…… and the web.config section where should it go? I really dont got anything in my web.config for my nhibernate. I use fluent nhibernate and dont got no xml files at all its all classes..

    • Lakshmish 7:34 am on November 16, 2010 Permalink | Reply

      I tried using the library provided, but still issue persists

      have this in web.config

      and following in hibernate.cfg.xml….

      Exception Details: System.Security.SecurityException: Request for the permission of type ‘System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.

    • Lakshmish 7:36 am on November 16, 2010 Permalink | Reply

      tags made content not to appear….

      hibernate.cfg.xml ……….. have ……. reflection-optimizer use=”false”
      web.config ………… section name=”hibernate-configuration” type=”NHibernate.Cfg.ConfigurationSectionHandler, NHibernate” requirePermission=”false”

  • John 8:02 pm on January 1, 2010 Permalink | Reply
    Tags: C#, , NAnt   

    NAnt.ToDo a NAnt Plugin 

    This simple plugin for NAnt parses your source code and creates a report of all the TODO and comment tags in your source code. The code is hosted over at google code.

    Comments

    The task automatically identify comments in the following style

    //TODO: First Test to do Item
    //FIXME: First Fix me Item
    //HACK: First Hack Item
    

    Additional matches can be made by adding in Token elements to the NAnt task.

    Sample

    <ToDo source="path/to/source" output="report.xml" searchpattern="*.cs;*.txt">
     <Tokens>
     <Tokens Value="BUGFIX" />
     </Tokens>
    </ToDo>
    

    Output

    <ToDo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
     <Items>
     <Item>
     <Message>First Test to do Item</Message>
     <File>NAnt.ToDo\ToDoTask.cs</File>
     <Line>0</Line>
     <Type>TODO</Type>
     </Item>
     <Item>
     <Message>First Hack Item</Message>
     <File>NAnt.ToDo\ToDoTask.cs</File>
     <Line>0</Line>
     <Type>HACK</Type>
     </Item>
     <Item>
     <Message>First Fix me Item</Message>
     <File>NAnt.ToDo\ToDoTask.cs</File>
     <Line>0</Line>
     <Type>FIXME</Type>
     </Item>
     </Items>
    </ToDo>
    

    Cruise Control Xsl

    Below is a basic xsl style sheet that can be used with CruiseControl.NET to display the output from NAnt.ToDo.

    <?xml version="1.0"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
     <xsl:output method="html"/>
     <xsl:param name="applicationPath"/>
     <xsl:template match="/">
     <div id="ToDo">
     <h1>ToDo List</h1>
     <div id="Summary">
     <h3>To Do</h3>
     <table>
     <tbody>
     <xsl:for-each select="//ToDo/Items/Item">
     <tr>
     <td>
     <xsl:value-of select="Type/text()"/>
     </td>
     <td>
     <xsl:value-of select="Message/text()"/>
     </td>
     <td>
     <xsl:value-of select="File/text()"/>
     </td>
     </tr>
     </xsl:for-each>
     </tbody>
     </table>
     </div>    
     </div>
     </xsl:template>
    </xsl:stylesheet>
    
     
  • John 10:06 pm on September 26, 2009 Permalink | Reply
    Tags: C#, , , , ,   

    jqRunner Snapshot – Running Javascript Unit test with NUnit 

    One of the nice things about unit tests is that you can use continuous integration so that you don’t have to run them yourself. At work we use CruiseControl.NET to automate our builds and run our unit tests. Now as a number of our projects are web based we use a fair amount of javascript, mainly jQuery, though in-house plugins. In order to test these we use jqunit, this works great and allows us to use TDD when writing javascript. However as development goes on the unit tests get forgotten about as they are not automatically ran.

    In order so solve this I decided to experiment to find a method of getting cruise control to run our jqunit tests for me. To run the tests I looked at wrapping the jqunit tests with nunit tests.

    jqRunner

    jqRunner is designed so that you can us your existing jqunit tests in their existing location without changing them. jqRunner required that all the scripts that are needed to run are registered. The full path to the file is required. jqRunner then executes the tests and returns the results, which are then parsed by nunit as tests using the TestCaseSource attribute.

    var sampleTestCase = new jqUnit.TestCase('Sample Test Case', function() {
        /*setup*/
        // this.yep(1);
    }, function() {
        /*teardown*/
        // this.ok(1)
    });
    sampleTestCase.test('Sample Test 1', function() {
        this.ok(1);
    });
    sampleTestCase.test('Sample Test 2', function() {
        this.ok(0);
    });
    
    using System;
    using System.Collections.Generic;
    using NUnit.Framework;
    using jqRunner;
    using System.IO;
    using System.Reflection;
    
    namespace jqRunner.Tests
    {
        [TestFixture,RequiresSTA]
        public class TestCaseSourceTests
        {
            [Test, TestCaseSource("GetTestResults"), RequiresSTA]
            public void CheckTest(ITestResult result)
            {
                Assert.IsTrue(result.Pass, result.Name);
            }
    
            private static ITestResult[] GetTestResults()
            {
                string jsFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) + @"\jqUnitTests\SampleUnitTest.js";
                TestBed target = new TestBed();
                target.RegisterScript(jsFile);
                return target.Execute().ToArray();
            }
        }
    }
    

    This is an initial development snapshot and is bound to have plenty of problems.

    Download
    http://static.yeticode.co.uk/blog/downloads/jqRunner-snapshot.zip

    Related Reading

     
  • John 8:34 pm on August 24, 2009 Permalink | Reply
    Tags: C#, , , ,   

    More Django Plugin Stuff 

    MonoDevelop Django

    So I’ve been working more on the support for django within monodevelop. Heres some screenshots of it.

    MonoDevelop Django

    MonoDevelop Django

     
    • Aledr 8:47 pm on December 16, 2009 Permalink | Reply

      I’ve just installed MonoDevelop 2.2 and started a new Django project but is no option to create a new App there. Is your code already integrated?

      Thanks.

      • John 11:11 am on December 17, 2009 Permalink | Reply

        I never got round to getting the code into a stable state, and submittting a patch. However I have a couple of weeks of work so I’ll see if have anytime to look at it again.

  • John 7:21 pm on June 28, 2009 Permalink | Reply
    Tags: , C#, ,   

    Professional ASP.NET MVC 1.0 

    At work we have been looking at the ASP.NET MVC, model-view-controller, framework. After looking around at various different tutorials and articles we found a sample chapter from the wrox book Professional ASP.NET MVC 1.0. The sample chapter took the hello world example and create a full application. The application, NerdDinner is an application that allows you to create dinner parties and RSPV to them. The sample covers a lot of the functionality that is within ASP.NET MVC. The sample chapter can be found online at Wrox’s website with the source code hosted at codeplex.


    Professional ASP.NET MVC 1.0

    Reading though the sample chapter is a good way to get started with ASP.NET MVC as the chapter explains what it is doing in a easy to understand manor, but more importantly it explains why they are being done. The chapter is a comprehensive walk through of how to create the NerdDinner application. Throughout the chapter the authors provide titbits of useful information, for example the use of the repository pattern and dependency injection. Throughout the chapter the authors trying to enforce good coding practice and often make reference to test driven development which in a later chapter they go into more detail about, discussing different development techniques.

    The sample chapter is more than enough to get anyone started with ASP.NET MVC and follows the development process from start to finish including a section on unit testing the application. The following chapters delve into more detail about specific areas of the ASP.NET MVC framework. The second and third chapters go into detail about the MVC pattern, detailing its background and its use on the web. The chapter also provides an overview, albeit brief, of other frameworks that are available. Although their coverage was brief they were not mentioned as either superior or inferior rather just as alternatives to the ASP.NET MVC framework. This tone was subsequently repeated in the third chapter when the authors compare ASP.NET with WebForms to ASP.NET MVC. They often mention that MVC is not a replacement for WebForms rather it is a different approach. These two chapters are extremely useful as they allow you to make an informed decision whether ASP.NET MVC is the right choice for you.

    I’ve still to finish reading the rest of this book so I’ll update this post the more I read of it.

     
  • John 8:14 pm on May 24, 2009 Permalink | Reply
    Tags: C#, nmock, nunit   

    NUnit and NMock 

    Whist working on a piece of course work for uni I started using NMock as part of some unit tests written using nunit. Having mainly used MSTests for unit tests at work I decided to use nunit as everyone has said that they are very similar. I’m extremely impressed with the potential power that NMock has given me during testing. For the assignment I wrote a small spider application that crawly a site and stores all the link. Using NMock it allowed me to test the structure of the site without requiring internet access. During this assignment I also tried to use the test driven development approach, opposed to my normal sit down and hack away. Not only were there less bugs at the end, the overall quality of my code was noticeable higher. This was largely due to the fact that I had tests already created for what it was meant to do, which required me to put more effort into the implementation. Hopefully I’ll keep this style of programming up, and not just forget it as soon as I get back to work.

    Here’s a sample nunit test that uses nmock. The nmock object mocks the calls that request specific urls and loads the data for local files.

    [Test()]
    public void MockLinkFinderTest()
    {
    	IMock mockWebClient = new DynamicMock(typeof(IWebClient));
    	mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/1.htm"),new object[]{"http://domain.example/1.htm"});
    	mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/2.htm"),new object[]{"http://domain.example/2.htm"});
    	mockWebClient.ExpectAndReturn("GetPage",File.ReadAllText("HTML/3.htm"),new object[]{"http://domain.example/3.htm"});
    
    	string domain = "domain.example";
    	string url = "http://domain.example/1.htm";
    
    	LinkFinder linkFinder = new LinkFinder();
    	LinkItemCollection linkCollection = linkFinder.Find(url,domain,(IWebClient)mockWebClient.MockInstance);
    
    	int expected = 3;
    	Assert.AreEqual(expected,linkCollection.Count);
    }
    
     
  • John 1:59 am on May 13, 2009 Permalink | Reply
    Tags: C#, , ,   

    New GTK# Project 

    I’ve started a new project, RssNotify, to try and learn more about developing applications using GTK. I’ll still be developing cctray-gtk as this project is useful, but the RssNotify is more of a project to satisfy my curiosity.

    The RssNotify project aims to provide an easy way for a user to receive notifications when an rss feed has been updated. the idea is to use notify-sharp to display the new news items. The rest of the interface will be used to try to explore the features widgets that GTK# offers.

     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel