Tagged: C# RSS

  • Steve Lydford 11:18 am on February 3, 2011 Permalink | Reply
    Tags: , C#   

    What’s Happening to Reflector? 

    So Red Gate have made the announcement that the next version of their excellent Reflector application will be a “paid for” product. This is OK, I totally understand the reasons for this – they have a business to run and have tried the free model, but it’s just not working out for them.

    Neil Davidson, Co-CEO of Red Gate Software said this in an “Open Letter to the .NET Community“:

    “As many of you know, our original intention was to maintain .NET Reflector as a free tool. But, after two-and-a-half years of providing it without charge, we realized that we could not make the free model work. We know that this will cause pain for some people in the .NET community, and we apologize for the change in policy.”

    So my initial thoughts were, “You know what? It’s only $35 and I have been using it free for a couple of years, so I’ll take the hit if I want to upgrade. No hard feelings.”

    And then I read this in the FAQs:

    “A free version will be available for download until the release of Version 7, scheduled for early March. The free version will continue working until May 30, 2011.”

    So the version I have on my machine will cease to function on the 30th May!

    I will spend $35 on the new version, but I won’t be happy doing it, I have little choice. I like Reflector, a lot of people do. It is a very useful tool for looking behind the scenes of an assembly to see whats going on (both for debugging and educational purposes). I recommended it as an essential .NET development tool in my last blog post.

    In my opinion, disabling the free version of the software on 30th May is not a good way to go. Why not make the new version so awesome that I NEED it? Don’t FORCE me to begrudgingly pay you money – make me WANT to pay you for an even better product. Maybe the new release is going to be that good, but let me decide for myself.

    You have only got to look at Twitter or search around a few blogs to see that this has already annoyed a lot of people. All that Red Gate is doing is giving someone the incentive to start, or improve an existing Open Source project (like Monoflector) to give equivalent functionality because they don’t give out a free version anymore. Someone could make a big name for themselves by writing the new Reflector.

    I hope that Red Gate have a strategy re-think. Reflect on it, if you will.

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • Alex 9:32 pm on February 4, 2011 Permalink

      Well, JetBrains has ‘hinted’ at the fact that they may be including a ‘Reflector’ in ReSharper. It’s also not free, but if you already are using ReSharper (like me), it’s one less thing to buy…

  • Steve Lydford 9:56 pm on January 25, 2011 Permalink | Reply
    Tags: , , C#, Enitity Framework,   

    Entity Framework Mapping Entities To Specific Database Tables 

    I have been playing around with the Entity Framework Code First CTP 4 in ASP.NET MVC 3 for a couple of days and have come across across a need to map an entity to a specific database table.

    Entity Framework Code First automatically pluralizes all entity names when it creates database tables from your domain model. However, I had an entity called Accommodation which I did not want pluralized. It wasn’t really a big deal, just really that Accommodations sounded wrong, but it gnawed at my borderline-OCD perfectionist mind until I was forced to go looking for a solution. And here it is, you simply need to change the name of the DbSet and override the OnModelCreating method like this:

     

    public class AccommodationEntities : DbContext
    {
        public DbSet<Accommodation> Accommodation { get; set; }
        public DbSet<Address> Addresses { get; set; }
    
        protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Accommodation>().MapSingleType().ToTable("Accommodation");
        }
    }
    

     

    While I’m on the subject of the EF Code First CTP 4, here is another thing that caught me out.

    EF Code First creates a table called EdmMetadata which stores a hash of the database schema created by EF. If you change your domain model entities EF Code First will automatically re-create all the tables in the context. I mean re-create as in drop the tables first, then create new. This is fine as long as you haven’t got any data you want to keep hold of, as you get no warning that this is going to happen.

    To stop EF re-creating the tables (and I suppose to bring it out of Code First mode) I dropped the EdmMetadata table and added the following to the Application_Start() method of my global.asax:

    Database.SetInitializer<AccommodationEntities>(null);

    This seems to have done the trick!

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • bioff 3:43 am on February 2, 2012 Permalink

      hi!!!

  • Steve Lydford 10:20 pm on January 22, 2011 Permalink | Reply
    Tags: , C#,   

    ASP.NET MVC 3 Internationalization 

    I have been doing some work with internationalization (globalization, localization, whatever you want to call it, and yes I do know they all mean something slightly different) in ASP.NET MVC 3 and thought I would share a couple of tips.

    The Past

    Internationalization has always been a bit of a pain in the #youknowwhat with ASP.NET MVC up to now. For me it’s always been like, “it’s so close I can smell it, but it’s not quite there yet”. In the past I have created custom HTML Helpers to let me do something like this in the View:

    <%: Html.LabelFor(model => model.Surname, PersonResources.Surname ) %>

    This custom helper allowed me to describe the the property that I wish to associate the label to and the text I wish to display. It turns out that a lot of people must have requested this as this functionality is now provided out-of-the-box in ASP.NET MVC 3.

    I have also heard of people doing all sorts of workarounds, like creating localized copies of each View (surely a maintenance nightmare!), using JavaScript to look up localized versions of UI text in XML files, etc., etc. ….

    But there is now a better way!

    The problem actually all stems from the DisplayNameAttribute, which you can use to decorate the properties in a model with a user-friendly name which is displayed in the UI by default instead of the actual name of the property. For example, if you had a property called ContactEmail and you decorated it with [DisplayName(”Email Address”)], whenever you referred to the ContactEmail property in the UI (maybe using an HTML Helper) the string “Email Address” would be displayed in place of the property name (ContactEmail).

    The problem is DisplayNameAttribute has only one constructor (barring the empty one):

    DisplayNameAttribute(string displayName)

    Since there was no way to pass in a reference to a resource file we could only pass hard-coded strings to the UI – no good for a UI that is supposed to be multi-language.

    The Solution

    This problem has been resolved with ASP.NET MVC 3 which, because it is built on .NET Framework 4, has access to the DisplayAttribute class.

    This class has several properties, including the Name and ResourceType properties to look at a particular resource file and name/value pair within it. For example:

    [Display(Name="Surname", ResourceType=typeof(PersonResources))]
    public string Surname { get; set; }

    This will use the relevant resource file (in this instance called PersonResources.resx), according to the current language, to display the localized value for Surname wherever it is referred to in the UI.

    @Html.LabelFor(model => model.Surname)

    Summary

    I really hope this makes sense. Internationalization is a job that developers often try to avoid, but these improvements in ASP.NET MVC 3 make, at least this bit of the job, much, much easier.

    Leave any questions you may have in the comments and I will do my best to answer them for you.

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • D Clumsy 1:48 pm on January 26, 2011 Permalink

      I usually subclass the attribute to use translations which are stored in a database rather than a .resx text file.

    • Ricardo 4:42 pm on May 17, 2011 Permalink

      Very nice, thank you for sharing. How do you go about getting translated strings from a database? will this approach still work and how does differ from using resource files? Thanks!

    • Nobels 9:20 pm on November 23, 2011 Permalink

      Hello,

      Your example works indeed. But when you forget 1 word in your resourece you get an error. :-(

      Is there a way to catch that problem, and returns the key as value?

      i would like to here an anwser to my question.

      Thanks

  • Steve Lydford 2:38 pm on October 22, 2010 Permalink | Reply
    Tags: , , C#,   

    Unique Key Generator 

    This morning I needed to generate a unique key for an application I am working on. The key needed to be unique within the application, but I didn’t need it to be globally unique and a GUID is just too long.

    I have played in the past with various combinations of DateTime, SessionID and other application specific values to cobble together an application wide unique key but really wanted something much neater, like the unique values created by sites such as TinyUrl.com

    For example: http://tinyurl.com/39gg3es

    So, after a little research and playing around, I came up with this:

    
    static string GenerateKey(int keyLength) {
        char[] maskChars = "1234567890AaBcCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".ToCharArray(); 
    
        RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
        byte[] cryptoBytes = new byte[keyLength];
        crypto.GetNonZeroBytes(cryptoBytes); 
    
        StringBuilder key = new StringBuilder(keyLength);
            foreach(byte b in cryptoBytes)
        key.Append(maskChars[b % 62]);
        return key.ToString();
    }
    

    You will need to import

    System.Security.Cryptography;

    and can create a unique key by using the following code:

    
    string uniqueKey = GenerateKey(6);
    

    specifying the length of the key you require (in this case six). This will generate a key such as: D7D2iU

    Please feel free to use this code as you wish. If you do use it I would love to know where and, of course, any comments or suggestions would be appreciated.

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
    • Softwarepadawan 6:33 pm on February 1, 2011 Permalink

      Although your key generator algorithm is _very_ good it does not produce unique keys. You need to change the title. BUT! It’s still a nice way of generating keys. Keep up the good work!

    • Filip Zawada 7:34 pm on February 1, 2011 Permalink

      Nice code but if you need something shorter than 32 then why not just:
      static string SimpleKey(int keyLength)
      {
      if (keyLength > 32)
      {
      //start yelling
      }
      return Guid.NewGuid().ToString().Replace(“-”, “”).Substring(0, keyLength);
      }

      Faster and easier, unless I’m missing something from your post.

  • Steve Lydford 11:53 am on September 15, 2010 Permalink | Reply
    Tags: C#   

    Dependency Injection Article 

    As well as finding the new MSDN UK design this morning I also stumbled across
    this great article
    on Depending Injection (otherwise known as Inversion of Control).

    “Dependency injection is a technique used in object-oriented programming languages. It promotes loose coupling of components by passing dependencies to an object, rather than having an object instantiate its own dependencies.”

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
  • Steve Lydford 11:21 am on August 4, 2010 Permalink | Reply
    Tags: , , C#,   

    “Works On My Machine” Code Snippet 

    Here’s a ‘useful’ snippet I just wrote for C# ASP.Net in Visual Studio. Type “womm”, hit tab twice and you’ll get this…

    try
    {
    
    }
    catch (Exception)
    {
        Response.Write("That's weird!<br />");
        Response.Write("It works on my machine.");
    }
    

    To use it either download the snippet or copy the code below and save it as womm.snippet, and drop it into:

    My Documents\Visual Studio 2010 (or 2008)\Code Snippets\Visual C#\My Code Snippets

    or add it to Visual Studio using the Code Snippets Manager found in the Tools menu.

    Enjoy! ;)

    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    	<CodeSnippet Format="1.0.0">
    		<Header>
    			<Title>womm</Title>
    			<Shortcut>womm</Shortcut>
    			<Description>Code snippet for WOMM try catch</Description>
    			<Author>Steve Lydford</Author>
    			<SnippetTypes>
    				<SnippetType>Expansion</SnippetType>
    				<SnippetType>SurroundsWith</SnippetType>
    			</SnippetTypes>
    		</Header>
    		<Snippet>
    			<Declarations>
    				<Literal>
    					<ID>expression</ID>
    					<ToolTip>Exception type</ToolTip>
    					<Function>SimpleTypeName(global::System.Exception)</Function>
    				</Literal>
    			</Declarations>
    			<Code Language="csharp"><![CDATA[try
    	{
    		$selected$
    	}
    	catch ($expression$)
    	{
    		$end$
    		Response.Write("That's weird!<br />");
    		Response.Write("It works on my machine.");
    	}]]>
    			</Code>
    		</Snippet>
    	</CodeSnippet>
    </CodeSnippets>
    
    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
  • Steve Lydford 11:47 am on June 30, 2010 Permalink | Reply
    Tags: , , C#   

    C# ASP.Net FileUpload – Stop Files Being Overwritten 

    The following code will stop files being overwritten in the servers upload directory by placing an incrementing number on the end of the file name to make it unique.

    For example:

    • picture.jpg
    • picture1.jpg
    • picture2.jpg
    • picture3.jpg

    It will also cope with mulitple dots (periods) in the filename (ie. filenames that are not in the standard filename.extension format).

    For example:

    • my.new.house.picture.jpg
    • my.new.house.picture1.jpg
    • my.new.house.picture2.jpg
    • my.new.house.picture3.jpg

    The code assumes that the webform has a FileUpload control named FileUpload1 and that the current user (IIS user that is) has rights to the necessary area of the server file system.

    Hopefully you may find it useful. Please leave any comments you may have, or requests for further refinements.

    //File upload code by Steve Lydford 2010
    //www.stevelydford.com
    //www.sixsixtytwo.com
    
    try
    {
        string UpPath = @"C:\Uploads"; //the directory you want the file uploaded to
    
        //create directory if it doesn't already exist
        if (!Directory.Exists(UpPath))
            Directory.CreateDirectory(UpPath.Replace("\\", "\\\\"));
    
        string FileName = FileUpload1.PostedFile.FileName;
        string FileType = FileUpload1.PostedFile.ContentType;
        string FileSize = FileUpload1.PostedFile.ContentLength.ToString();
        string ClientFile = System.IO.Path.GetFileName(FileName);
    
        FileInfo ServerFile = new FileInfo(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile);
        int idx = 1;
    
        //increment a number on the end of the filename until it is unique to stop files being overwritten
        //will cope with filenames with multiple dots (eg. sunset.photo.12.jpg)
        while (ServerFile.Exists)
        {
            string[] filename = ClientFile.Split('.');
            ClientFile = "";
            int prevIdx = idx - 1;
    
            if (idx > 1)
            {
                for (int i = 0; i < filename.GetUpperBound(0); i++)
                {
                    ClientFile += filename[i];
                    if (i < filename.GetUpperBound(0) - 1)
                        ClientFile += ".";
                }
                ClientFile = ClientFile.Substring(0, ClientFile.Length - prevIdx.ToString().Length) + idx.ToString() + "." + filename[filename.GetUpperBound(0)];
            }
            else
            {
                for (int i = 0; i < filename.GetUpperBound(0); i++)
                {
                    ClientFile += filename[i];
                    if (i < filename.GetUpperBound(0) - 1)
                        ClientFile += ".";
                }
                ClientFile += idx.ToString() + "." + filename[filename.GetUpperBound(0)];
            }
            ServerFile = new FileInfo(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile);
            idx++;
        }
    
        //save file to server
        FileUpload1.PostedFile.SaveAs(UpPath.Replace("\\", "\\\\") + "\\" + ClientFile);
    
    }
    catch (Exception ex)
    {
        throw ex;
    }
    
    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
  • Steve Lydford 8:00 am on June 29, 2010 Permalink | Reply
    Tags: , C#   

    C#4.0 Optional Parameters and Named Arguments 

    There are loads of really great new features in C# 4 and the .Net Framework. In my mind, one of the most overdue is the ability to have optional method parameters and default parameter values. VB.Net has had this for many years, so it was obviously available in MSIL, just not implemented in C# for some reason.

    Optional parameters give us the ability to replace all this code:

        public int GetResult(int x, int y)
        {
            return x + y;
        }
    
        public int GetResult(int x)
        {
            int y = 10;
            return x + y;
        }
    
        public int GetResult(int y)
        {
            int x = 5;
            return x + y;
        }
    
        public int GetResult()
        {
            int x = 5;
            int y = 10;
            return x + y;
        }

    with this:

        public int GetResult(int x = 5, int y = 10)
        {
            return x + y;
        }

    This means that all the following are valid calls to the GetResult method:

        int z = GetResult();
        int z = GetResult(30, 20);
        int z = GetResult(x: 15);
        int z = GetResult(y: 20);

    The last two calls here use Named Arguments to explicity identify the argument you are passing.

    You can mix mandatory and optional parameters within a single methods argument list, but you cannot have any mandatory arguments after an optional one. For example:

       public int GetResult(int x, int y = 10)

    is fine, but:

       public int GetResult(int x= 10 , int y)

    returns the error, “Optional parameters must appear after all required parameters”.

    Visual Studio 2010 also has some handy prompts built into Intellisense to let you know that some parameters are optional, along with their default values:

    Digg This
    Reddit This
    Stumble Now!
    Buzz This
    Vote on DZone
    Share on Facebook
    Bookmark this on Delicious
    Kick It on DotNetKicks.com
    Shout it
    Share on LinkedIn
    Bookmark this on Technorati
    Post on Twitter
    Google Buzz (aka. Google Reader)
     
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
esc
cancel