Tagged: .Net RSS

  • Steve Lydford 12:51 pm on February 11, 2011 Permalink | Reply
    Tags: .Net, , ,   

    Fun With WebMatrix Helpers in ASP.NET MVC 3 

    It’s nearly the weekend, and it’s been long week, so let’s have a bit of fun…

    So I take it you’ve all had a chance to look at WebMatrix? If you haven’t then you should really make the effort to have a play around with it. I will admit that I was a bit snobby about it when I first read about it, but it is actually a really great way to build small, simple web sites. For the uninitiated, here are a few useful links:

    You can install WebMatrix through the Web Platform Installer. It has loads of really great features, which are much better explained in the links above than I could ever do, but the one that hit me immediately as being really fun was the WebMatrix Helpers feature and I wondered if there was a way to use them in MVC.

    Well, WebMatrix is built on ASP.NET, so it is actually a trivial task to add them to an ASP.NET MVC application.

    Getting Going

    There are loads of helpers available, today we are going to look at the Microsoft Web Helpers. This package gives you the ability to quickly and easily add basic functionality for services such as Twitter, Bing, Gravatar, Facebook, Google Analytics and XBox Live to your site. The awesomeness of NuGet makes it easy to add the Microsoft Web Helpers package to our project by typing:

    Install-Package microsoft-web-helpers

    into the the Package Manager Console.

    Next you will need to add references to WebMatrix.Data and WebMatrix.WebData and set the “Copy Local” property to true for both of them. If you fail to do this step you will receive a compilation error, “The type or namespace name ‘SimpleMembershipProvider’ could not be found” in App_Code\Facebook.cshtml.

    And that’s it! You are now ready to start using the Web Helpers in your Views. So let’s have a look at a few of them…

    Gravatar

    You can add a Gravatar image to your page by simply using the Gravatar.GetHtml() method in your Razor view. For example:

    @Gravatar.GetHtml("stevelydford@gmail.com")


    displays this handsome chap (and no the glasses and bandito moustache are not real!):

    gravatar

    If the email address supplied to the method doesn’t have a corresponding Gravatar account the default Gravatar image will be returned, i.e.

    But you can also set the default image to be the URL of any image you desire. For example, the following code:

    @Gravatar.GetHtml
        ("you@me.com", defaultImage: "http://blog.stevelydford.com/content/noGrav.jpg")
      

    Returns this stunning example of programmer art:

    noGrav


    Optional parameters allow you to set the size of the image, the Gravatar rating and a couple of other attributes.

     

    XBox Live GamerCard

    This is a very simple method which returns an XBox Live GamerCard. It has one parameter which is a string containing the required XBox Live GameTag. For example:

    @GamerCard.GetHtml("stinky53")


    returns this:

    gamercard

    which does nothing if not prove that I don’t get enough time to work on my GamerScore!

     

    Microsoft Bing

    Web Helpers has a Bing class that enables you to easily let users Google your site with Bing.

    First, we need to add the following code to our Razor view:

    @{
        Bing.SiteTitle = ".NET Web Stuff, Mostly";
        Bing.SiteUrl = "http://blog.stevelydford.com";
    }


    We can then use either the Bing.SearchBox() or Bing.AdvancedSearchBox() methods to display a Bing search box in our View.

    @Bing.SearchBox()


    displays a Bing search box which takes the user to Bing.com to displays it’s results:


    bingSearch

    @Bing.AdvancedSearchBox()


    displays a Bing search box which renders a <div> on your page containing the search results:

    bingAdvSearch

     

    Analytics

    The Analytics class of Microsoft.Web.Helpers contains methods which generate scripts that enable a page to be tracked by Google Analytics, Yahoo Marketing Solutions and/or StatCounter.

    They all work in a very similar way and just require you to pass the method the relevant account details. For example:

    @Analytics.GetGoogleHtml({your-analytics-webPropertyId-here})
    @Analytics.GetYahooHtml({your-yahoo-accountId-here})


    This will inject the necessary JavaScript into your view at runtime to enable tracking by the relevant service.

     

    Twitter

    The Microsoft.Web.Helpers namespace contains a Twitter class with two methods – Twitter.Profile() and Twitter.Search().

    Twitter.Profile() injects some JavaScript into your view which displays the feed for the Twitter user specified in the userName parameter:

    @Twitter.Profile("stevelydford")


    twitterProfile


    There are a whole raft of parameters, which allow you to customise the output in various ways, such as setting the width and height, colors, number of tweets returned, etc. A full list of these parameters can be found here.

    Twitter.Search() displays the Twitter search results for the search string specified in the searchQuery parameter:

    @Twitter.Search("London 2012")


    twitterSearch


    Again, there are a bunch of optional parameters to allow you to customize the output to your requirements.

    When you use NuGet to install the microsoft-web-helpers package a TwitterGoodies Razor file is added to your App_Code folder. This class contains helpers which provide additional Twitter functionality. These helpers include TwitterGoodies.TweetButton(), TwitterGoodies.FollowButton(), TwitterGoodies.Faves() and TwitterGoodies.List(), all of which can have their outputs customised using various optional parameters:

    @TwitterGoodies.TweetButton
        (tweetText: "I'm reading Steve Lydford's blog", url:"http://blog.stevelydford.com")


    displays a Tweet Button which opens a new window to allow the user to send a Tweet about your site. The URL passed to the helper is automatically shortened using the Twitter t.co URL shortner:

    tweetButton

    @TwitterGoodies.FollowButton("stevelydford")


    displays a button which redirects them to Twitter:

    followButton

     

    @TwitterGoodies.List("stevelydford", "f1-4")


    displays a form which shows a public Twitter list:

    twitterList

     

    There are a few other methods in the TwitterGoodies Razor file, which you can view in App_Code/TwitterGoodies.cshtml.

     

    Facebook

    As well as the TwitterGoodies.cshtml page, the microsoft-web-helpers package also installs Facebook.cshtml to your App_Code directory. This file contains many useful Facebook helpers. I will look at a couple here, a full list can be found on the facebookhelper codeplex site.

    One of the easiest to use out of the box is the Facebook.LikeButton() helper, which displays a ‘Like’ button that either automatically ‘likes’ the URL supplied, or opens a new Facebook window ’on click’ if the user is not currently signed in:

     

    @Facebook.LikeButton("http://blog.stevelydford.com")

     

    likeButton

     

    Next up is Facebook.ActivityFeed() which displays stories when users ‘like’ content on a site or share content from a site on Facebook.

    @Facebook.ActivityFeed("http://www.bbc.co.uk")


    activityFeed

     

    Most of the rest of the Facebook helpers require initialization. In order to do this you will require a Facebook Application ID. You can get one by browsing to http://www.facebook.com/developers/createapp.php and creating a new Facebook Application:

    facebookCreateApp

     

    When you are setting up your app ensure that you enter the URL of your site, including the correct port number if you are working on localhost:

     

    facebookCreateApp2

     

    You can then add the following code to your Razor view to initialize:

    @{
        Facebook.Initialize("{your-application-id-here}", "{your-application-secret-here}");
    }


    Then it’s just a matter of adding a couple of lines of code to the view to add Facebook Comments to the page:

    @Facebook.GetInitializationScripts()
    @Facebook.Comments()

    fbComments

     

    Or, to show a Facebook LiveStream to allow users of your site to communicate in real time:

    @Facebook.LiveStream()

    fbLiveStream

     

    Conclusion

    This post shows just a small fraction of what can be achieved very quickly and very easily using WebMatrix Web Helpers in an MVC application. The Microsoft Web Helpers package makes it incredibly easy to add a whole load of functionality to you site for very little effort.

    Have fun! Let me know how you get on.

    Go play….

    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)
     
    • William 10:01 am on April 17, 2011 Permalink

      Hello, Guys!
      I have a question that I wonder if anyone can answer!
      I have just started using M-Soft WebMatrix … very nice; however!
      I am not sure if this is a bug, or, I am doing something wrong!
      Quite simply, it is this: …
      I have down-loaded WebMatrix on to my new Pc … no problems.
      I load a ‘new’ WordPress site to my Pc … no problems.
      When I click on ‘Run’, the site appears in a browser, and runs very nicely. And, at the top of the site screen, there are the options to go back to “Dashboard”, and do whatever that I want to with this site … no problems.
      So, quite simply, I can ‘up-an-run’ the site, and get back to Dashboard to do whatever I want, as many times as I want … no problems.
      However, and this is a ‘big’ however: …
      Whilst I have the site ‘up-an-running’; if I close the browser, WITHOUT GOING BACK TO DASHBOARD, (and at this moment in time, I have no other browser up-on-screen), and that just leaves the WebMatrix control window (if you will) up and running; if I then click on ‘Run’ to bring the site back … yes it appears, ”’however”’ there are now; ”’NO”’ options at the top of the browser screen for me to get back into ‘Dashboard’. Quite simply, guys, I cannot get back to Dashboard at all. I have to delete the whole site and start again … wow!
      What happens if you have built; and taken many hours, to build the site of your dreams, only to find that, if you close the browser, deliberately or by mistake, or by having to reboot your machine, you then cannot get back to Dashboard, and your site is completely lost!!! Wow, scary!
      Or, guys, am I doing something wrong?

      Desperately need some help from you, most learned, and qualified guys.

      Best wishes…
      Kind regards…

      William (Hampshire UK)

    • Green coffee bean storage 4:46 am on April 10, 2013 Permalink

      hmoejcmph, Meta gen pure green coffee bean extract with svetol, jCdnPKV, [url=http://greencoffeewarning.ca/]Green coffee bean extract for weight loss[/url], NryFhYK, http://greencoffeewarning.ca/ Green coffee bean extract leave a comment website, PNtjIwi.

    • Xanax online overnight shipping 5:02 am on April 10, 2013 Permalink

      ijhajcmph, Xanax, JrrvkPA, [url=http://www.xanaxblog2013.com/]Buy cheap xanax[/url], EpRYArk, http://www.xanaxblog2013.com/ Xanax, lgIZStK.

    • pure green coffee extract 6:03 am on April 27, 2013 Permalink

      This way, once you have started taking up these elements.
      Clinacallix contains three separate compounds
      that are 25 to 100 times the antioxidant power of vitamins C and E.
      People are buying it online then make sure that
      you will be slim in a natural manner is possible with the help of pure green coffee extract
      the oral medications. Most green pure green coffee extracts are
      standardized to their EGCG content.

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

    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 4:02 pm on January 31, 2011 Permalink | Reply
    Tags: .Net,   

    My Developer Toolbox 

    I guess the title of my blog is a giveaway to the fact that I am primarily an ASP.NET developer; at the moment mostly MVC 3, which is all kinds of awesome, for all kinds of reasons.

    So here is a list of the tools that I can’t do without and that I think would be useful for anyone else out there who is wanting to build web apps on the Microsoft stack. This is the stuff that I would automatically install onto a new machine before I started development work on it.

    Post any tools you love in the comments and I will check them out. I’ll keep the list updated as I find new cool stuff ™, so keep checking back. So here they are, in the order that my mind blurted them out:

     

    Microsoft Visual Studio 2010

    http://www.microsoft.com/visualstudio/en-us

    It’s Visual Studio. If you can afford it get it – it’s the best. If not, have a look at BizSpark, WebsiteSpark or Visual Web Developer 2010 Express (below).


    Microsoft Visual Web Developer 2010 Express

    http://www.microsoft.com/express/Downloads/

    The Microsoft Express products are basically FREE cut-down versions of full applications (in this case Visual Studio 2010). It is not as feature-rich as Visual Studio, but has all the tools necessary to develop ASP.NET applications. Ideal if you are a hobbyist programmer or a student. All projects created in Visual Web Developer Express 2010 are compatible with Visual Studio 2010. And did I mention it’s FREE?


    Notepad++

    http://notepad-plus-plus.org/

    Notepad++ is a free code editor, designed as a replacement for Windows Notepad with code syntax highlighting. Ideal for those times when you just want to edit a bit of source code, some HTML, or some CSS without having to fire up the whole of Visual Studio.


    NuGet

    http://nuget.codeplex.com/

    NuGet is a free open-source package manager for Visual Studio and Visual Web Developer Express that just makes it so ridiculously easy to integrate third-party libraries and tools into your projects it is untrue. Truly brilliant, I can’t recommend this enough.

    Take a look at this brief introduction to NuGet by Phil Haack (note that this is for an older version)

    Firebug and IE8 Developer Tools

    http://getfirebug.com/ or press F12 in IE8

    Firebug and the IE8 Developer Tools both do essentially the same job, although each has it’s own strengths – they both let you inspect the source code, CSS and Scripts of any web page and any element within it. This is a fantastic way to learn how other developers have achieved a certain CSS effect or to inspect your output at runtime to find out what is really going on.


    .NET Reflector

    http://www.red-gate.com/products/dotnet-development/reflector/

    Another tool aimed at helping you to find out what is really going on. Reflector enables you to analyse compiled .NET assemblies in C#, Visual Basic and MSIL and is an invaluable learning and debugging tool.


    Ninject

    http://ninject.org/

    I love Ninject. It is a Dependency Injection container which makes it possible to achieve real separation of concerns between your applications components. Ninject is very easy to use and does a good job of all the usual dependency chain resolution and object lifetime management stuff that you would expect from a DI container. Also very simple to install, thanks to NuGet!


    NUnit

    http://www.nunit.org/

    NUnit is a unit-testing framework for .NET, ported from JUnit – the popular Java based framework. This is a completely standalone product, which is particularly useful if you are using Visual Web Developer 2010 Express which has no built in unit-testing.


    Moq

    http://code.google.com/p/moq/

    If you are doing Test Driven Development then life is going to be even harder without a good mocking library. Moq is one.


    Fiddler

    http://www.fiddler2.com/fiddler2/

    Fiddler allows you to inspect all incoming and outgoing HTTP traffic. I find this particularly useful for debugging ASP.NET applications on your local machine by inspecting the HTTP requests and responses to localhost to look at cookies, header information, etc.


    ELMAH

    http://code.google.com/p/elmah/

    ELMAH stands for Error Logging Modules and Handlers and is an open-source error logging facility for ASP.NET. It will log almost any unhandled exceptions and display them back to you via the web. In many cases you can look back to see the original "Yellow Screen of Death", even if you have customErrors turned off. If you have NuGet installed (which you really should), just type “install-package elmah” into the Package Manager Console” and browse to elmah.axd to see the error logs. It really is that easy.


    FileZilla

    http://filezilla-project.org/

    At some point you gotta ship stuff right? And to the web developer that means uploading it. Well there are loads of free FTP solutions out there, but my favourite at the moment is FileZilla.


    SketchFlow

    http://www.microsoft.com/expression/products/SketchFlow_OverView.aspx

    SketchFlow is a prototyping tool released by Microsoft as part of Expression Studio. It gives you the ability to quickly map out workflow and basic functionality to show end users, without having them concentrate on the UI. For once you may get some useful feedback instead of, "Can we try that in green?".


    XMind

    http://www.xmind.net/

    I was never a fan of mind-mapping, but I sat at in a meeting with an avid user of XMind and was very impressed. I have used it a few times since just to blurt out all my "neat ideas" about an application before I start a more formal design.


    Ultramon

    http://www.realtimesoft.com/ultramon/

    If you are a real hardcore developer you will run at least two monitors. I run three and I don’t think I could go back to anything less than that now. Windows can handle all this extended desktop goodness for you, but Ultramon just does a far, far better job. Go and download the free trial and you’ll see what I mean.

    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 9:56 pm on January 25, 2011 Permalink | Reply
    Tags: .Net, , , 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 2:38 pm on October 22, 2010 Permalink | Reply
    Tags: .Net, , ,   

    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:21 am on August 4, 2010 Permalink | Reply
    Tags: .Net, , ,   

    “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: .Net, ,   

    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: .Net,   

    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