Category: NuGet

Azure Blobs from C# and Visual Studio – C# Advent Calendar

This blog post is part of the The Second Annual C# Advent by Matthew Groves which is a C# advent calendar of blog posts by the community which uses C# to cover a topic of your choosing – I chose to show how to use Azure Blob Storage from C# and created a simple console application to upload images from a folder on your local computer and push the images into Azure Blob Storage.

To see all of the other blog posts for the C# advent calendar take a look here

The sample code for this blog post can be found on github

The following will show you how to create and access blobs using C#

  • Log into your Azure account or create a free one
  • Create a new Resource Group and call it something like BlobStorageCSharp
  • Next Add a new Resource, and search for Storage and then select the following highlighted Storage account – blob, file, table, queue)

The code example will show how to create a container which will upload the images into a container in blob storage up into your Azure storage account.

The code makes use of Azure Blob Storage from C# to create a public blob storage container called xmasimages-container if it doesn’t exist already making use of the following:-

And then upload images found in a folder on your local machine and stores the images into the public blob storage container.

You can read more on blob storage container’s and using C# to work with Azure storage

Once the images have been uploaded you could use Azure Storage explorer to view them.

Once you have downloaded and ran the code from my repo above, open up storage explorer and follow the steps below:-

  • Sign into your Azure Subscription
  • Expand Storage Account
  • Expand Blob Containers
  • Locate your container (xmasimages-container)
  • Highlight an image on the right hand side
  • Click Download or double-click and open it using any image viewer.
  • Viola – you’ve uploaded images and now you can view them

It’s a simple demo and there is a lot more you could continue with, so go grab the code, modify and extend it by doing some of the following: –

  • Change the code to make use of Azure Key Vault to store the connection string to your blob storage container
  • Extend the code to list the files within your container

Thanks to Matt Groves for doing the C# advent calendar, mind and check all the other great content here.

Merry Christmas and enjoy!
Gregor

 


Tags:


MSWebDay – What I took away from it

Today, Feb 16th, I attended MSWebdevday ran by Microsoft in Glasgow which was an event covering all things web related from Microsoft, the speakers were @christosmatskas, @thebeebs and @martinkearn and was an all day event.

The Schedule for the day covered various topics and it was great to learn so many new things and get my first glimpse at some new technologies, I always love learning something new, and I even sat next to the illustrious Gary Ewan Park, someone who I have chatted to a few times on twitter but not every managed to meet.

Ok so lets cover the actual event:-

The first talk was by on What’s New in ASP.Net Core 1.0 and was a tour of the new features, how to get it, how to use it, whats new, whats no longer there and he also talked about how you can just take the files and drop them into a folder when deploying, there’s no gac, you can just deploy the Core files in a folder alongside your code, this is very neat, its cross-platform, and it means you could have the same site running under different version of Core going forward should you choose to or need to have this.

The second Talk was Building with JavaScript Task Runners, this was mainly about how to get gulp, how to set it up and how to run some tasks to minify your css, javascript files and all that good stuff, how to add it into Visual Studio as a build step after you compile your code, showed an example gulp file and lots more.

The third talk was Entity Framework Core 1.0, and covered EF and how to use it, how to use code first and also mentioned EF6 how its improved greatly from previous versions and why you should choose this version at the moment whilst EF Core 1.0 is still being worked on and has the tooling added to it for the Core 1.0 release.

The fourth talk was APIs: the cogs behind the machine and this talk was about api’s and mainly web api and how in Core 1.0 there is no MVC and WebAPI its just one thing now and your controller is an API controller, so no need for MVC and WebAPI there is just the controllers now which kind of merge both together.

The fifth talk was Dev Ops in Azure and this covered deploying your website to Azure, making changes, showing the changes, getting the publisher file for using in side Visual Studio and publishing your changes from Visual Studio using Git int his example to deploy your changes from within VS up to the new Azure portal.

The sixth talk was Hitchhikers Guide to JavaScript, this talk focused on ECMAScript and the future of JavaScript and basically how a lot more code that we write will be JavaScript and we saw examples of the features coming in the next few years etc.

The seventh talk was Web Performance and how to check your websites performance using tools like YSlow and Google Page Speed etc and then how to go about making it make far less requests, cache JavaScript, enable IIS features and how to optimise images etc to make your website perform much faster that it currently does.

The eight talk was Single Page Applications and was about KnockoutJS and Angular, talking about Angular 2 and how it makes use of TypeScript and showed code covering KnockoutJS and AngularJS.

The ninth talk was about Hybrid Web Apps and how you can create application that can appear as Windows 8/10 tiles, make use of Microsoft Office and showed some very neat stuff using ManifoldJS which is itself very cool stuff.

Other stuff mentioned
I wrote some notes during the talks (should have taken a lot more) but a couple of things I need to look at are listed below:-

Summary
The event was great, full days learning, a lot of content covered, great speakers and good turn out. Spoke to some guys I chat to on twitter and all in all an awesome day spent learning some new stuff. There was a lot of content, I’ve missed half of it I’m sure so take a look at the slides on the site at MSWebdevday.

Dear Microsoft can we have some more of these days please? – especially Azure and Core related content.



Nuget bug I ran into with solution level packages and dependencies

nugetIf your using nuget and have a solution level nuget package you wish to add to a project, install-package will install your package as suggested, however update-package wont work as it wont find the nuget package your trying to update, this is only the case if the solution level package contains any dependencies, remove your dependencies and update-package does work.

This appears to be a bug, the obvious way to get around it is to use uninstall-package then install-package but its a bug none the less, I spent some time trying to get around this.

I was hoping this would have been fixed in nuget version 2.8 but it hasn’t been as yet.



Issue I ran into when using Nuget/SlowCheetah

nugetCannot add part to the package. Part names cannot be derived from another part name by appending segments to it

Last week I ran into an issue where I was using nuget to package a .csproj file.
What I was after was the contents of the nuget package to contain a Content folder and inside this Content folder have one file called app.config.transform, that’s it.

If my .csproj file contained the following:-

[sourcecode language=”xml”] <PropertyGroup Label="SlowCheetah">
<SlowCheetahTargets>..\.shared\SlowCheetah.Transforms.targets</SlowCheetahTargets>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(SlowCheetahTargets)" Condition="Exists(‘$(SlowCheetahTargets)’)" Label="SlowCheetah" />
[/sourcecode]

Then the package contents had a single file called content – which is incorrect.

The way I fixed this was inside the .csproj file I changed the type of the app.config.transform from Content to None. I then changed my .nuspec file to have the following:-

[sourcecode language=”xml”] <files>
<file src="App.config.transform" target="Content" />
</files>
[/sourcecode]

This fixed my issue with the contents of my nuget package, just incase anyone runs into the same issue.




Nuget Packages – solution level versus project level

nugetI’ve recently been working on a number of projects/solutions which contain nuget packages, one of the requirements I had been given was to add a nuget package which I had created at a solution level instead of it being at project level.

This means just that, the package is for the project solution and not for a particular project within the solution. If you’re still not sure what I mean let me explain with an example to better illustrate.

If you create an empty console application and add the nuget package called xunit runners:-

xunit.runners2

This will add the package at the solution level rather than to the consoleapplication1 project as shown below:-

xunit.runners3

Contrast this will a package level nuget package such as NUnit which is a project level nuget package:-

xunit.runners4

If you need to create a solution level nuget package then here is what I have found so far:-

  • Don’t reference a version of the framework within your Nuspec file
  • Don’t reference any dll’s

If you do either then you’ll end up with a project level nuget package.

There is more information on this here.



Small Nuget gotya with our TeamCity builds

At work we use TeamCity from Jetbrains on our build server, the product itself is the best there is out there.

Good products should be talked up more on twitter in my opinion, so that more people learn about what is good out there. If you’re considering software to use for building software then look no further than TeamCity.

We recently created quite a few nuget packages for internal use at work and we have them building as part of our builds on the buildserver using Teamcity. They used to be class libraries used as externals and these were causing us some pain so we decided to make them into Nuget packages and build them as part of our build process.

Our build process at work is pretty neat, I can push a website/windows service to dev, or staging environments with once click and it build the code, runs all the unit tests, check the level of code coverage is above a certain level and then removes the current installation and installs the new version – all in one click (for production we have 3 clicks due to having to log onto production servers and clicking on a batch file to do remove the old code and install the new version)

To set that up took time but worth doing as it means anyone can build and deploy to any environment with 3 clicks or less, thats quite powerful.

Now before going into the issue, let me say that people use TeamCity in different ways, the way people build Nuget packages will also no doubt differ.

Our Issue
As part of the code we were referencing internal and external Nuget packages, the NuSpec files had the following:-

[sourcecode language=”csharp”] <dependency id="ExamplePackage" version="1.3.2" />
[/sourcecode]

Wasnt till I suddenly realised that this means go get the latest version of the example package from Nuget if one is available, which wasnt really what we wanted in this scenario.

Versioning packages within Nuget is covered here Versioning Nuget packages and was just what I needed.

Once I updated the Nuspec files to have:-

[sourcecode language=”csharp”] <dependency id="ExamplePackage" version="[1.3.2]" />
[/sourcecode]

This square brackets around the version number means that instead of going off to Nuget to get the latest version, go off and get this version (if not installed already).

Now when i do a build it wont try and pull down the latest version of Nuget goodies such as AutoMapper and StructureMap.

Feel free to ask any questions or leave a comment on this post.




AspConf – My Review

Last week we had AspConf – “aspConf is a virtual conference focused on one thing: showcasing the ASP.NET stack as the platform for great web applications.

Over 2 days they had 5 virtual rooms used to present lots of fascinating stuff on .Net, including talks about all manner of things in the Asp.Net world.

The sessions on both days covered topics such as, Async in .Net 4.5, Glimpse, TDD, Azure and Cloud Computing and lots lots more, you can read more about the sessions here.

Although it had some technical difficulties, due to its popularity I may add, the conference is an awesome way to learn for free – and free is always good. It’s a superb way to learn about content you havent had time to look at it, or new technologies you havent heard of. Hopefully next year they might try to use something different from livemeeting.

If you missed any of the session then fret not, most of them if not all of them were recorded and put up on Channel 9 here

I only managed to see sessions from day 2 so I am off to go watch more content on Channel 9 – a great resource for free learning.



Scott Hanselman’s Scotland Tour – Glasgow Talk

Scott Hanselman was touring Scotland and taking in some of our country as well as some talks in Edinburgh, Dundee, Aberdeen and finally Glasgow. You can read more about the event on his site Scott’s tour of Scotland. The following is my review of his talk in Glasgow which was on Friday 13th of July.

Scott was delivering his – One ASP.NET (super everything talk) covering almost everything going on that Microsoft are working on/have to offer for developers within Asp.Net

The talk covered the following areas – Visual Studio 2012, SignalR, WebAPI, Webform improvements, Azure and also what to look forward to when .Net 4.5 is released.

Visual Studio 2012

Visual Studio 2012 – Scott was kind enough to demo a build newer than the RC which had some unseen bits.

CSS improvements – Scott demoed some of the new features when you have a .css file open in the VS 2012 editor, actual colour pickers where you can choose the colour, including a droplet for choosing a colour out with Visual Studio which will be picked up when selected. Styles are also indented so for example you can have an .li tag and a .li a tag nicely formatted and indented below the .li tag.

Browse with option – you can now select from any browser which you have installed on your pc as well as iphone and ipad and this will display your website rendered in which ever browser you wish, you can also mark several of these as default, this means that when you run your site in VS 2012 and say you have selected FireFox, IE and Ipad as your default browsers the site will open up in all 3.

Javascript improvements – VS 2012 has much better intellisense and by this I mean true intellisense, if you define a new function within your javascript file or webpage and then call it elsewhere you’ll get full intellisense for the function your calling – impressive stuff indeed.

WebAPI – Scott demoed WebAPI as there were quite a few people myself included who hadn’t really looked into this as yet, it looks cool though and a lot easier than WCF, also if you’re using MVC seems very easy to pick up. Scott demoed just how easy it was to create a class and change the response from a method to return XML or JSON just by changing the content-type from within Fiddler, this means that you can have your methods returned using XML or JSON as well as other formats and then send this data off to whatever system requires data in whatever format it requires – nice!.

Find more info about WebAPI on the Asp.Net website here.

SignalR – and the SignalR demo Scott showed are both available on Nuget using the following command from the package manager console:-

SignalR

and the demo Stock Sample application

SignalR Demo Application

Azure – Scott talked about the hard work Scott Guthrie and his team had recently put into Azure and showed the latest release of Azure and it all looked pretty impressive stuff, you can create up to 10 websites and have them deployed and hosted on Azure for free. Also available is VM’s with different operating systems such as Windows Server and Linux.

Within a couple of minutes Scott had created a website and added it to Git and deployed to Azure, then made an update and deployed the change, he then rolled the deployment back to a previous version of the website all in seconds – cool stuff indeed.

Azure

You can get a free trial of Azure by following this link here.

.Net 4.5 – Scott talked about Tasks and the new asynchrony possibilites coming with it, showing some nice additions you can use to have truelly asynchronous code – you can read more on this on msdn blogs here.

Feedback on his Talk
Scott is obviously a great speaker and a funny guy too and the content of the talk was excellent, I like demos and the content he showed was pretty neat, VS 2012 looks very promising. I liked how he gives his opinion on things that aren’t the Microsoft opinion and will openly slate something he doesn’t like. The questions asked by the attendees were very good too and he covered a fair amount of stuff in the time given – hopefully he will return sometime in the future and I hope he and his dad enjoyed their tour of Scotland.

You can follow Scott Hanselman on Twitter here.

I know i missed some of the content out, forgot to take notes, if anyone wants to ask questions or comment on this post please by all means do – I’ll update this post If i remember anything I missed.




ElmahR – Elmah fused With SignalR

If your using Elmah then you’ll be familiar with most of this blog post, if not then don’t worry Elmah stands for Error Logging Modules and Handlers and is used to log unhandled exceptions to the file system, event log, databases or even have it email you the errors.

ElmahR was created by Roberto Vespa (@wasp_twit) and his blog on ElmahR can be found at:- Roberto’s blog

The basics – ElmahR uses Elmah and SignalR to create a dashboard page where you can monitor any unhandled exceptions in all of the applications you have running which use Elmah, that means if you have 5 websites in production you can have one web page monitor them all.

ElmahR Dashboard

To view an example dashboard running on app harbor.

ElmahR uses SignalR which again you can read more on Scott hanselman’s blog

Now lets see how we go about setting this up to work with a new MVC 3 project – the same steps apply to adding it to an existing web application.

  • Create a brand new web application, mvc or normal web app works fine.
  • Using Nuget add the following packages to your blank MVC solution, so add Elmah and JQuery.
  • Once both added follow the configurations steps here
  • You can install the Nuget Package:- ElmahRSource



RavenDB CRUD – How To

I always wondered how easy it would be to do a RavenDB CRUD (Create, Read, Update, Delete) example, so lets create a simple MVC application which we can use to create, read, update and delete.

The following is some very basic code and yes you guessed it not for production but more of a quick sample to get you on your way with RavenDB and adding, editing and deleting documents.

We shall use a product model as our basis for the demo application – let’s get started.

  1. Create a blank MVC solution to begin with
  2. Using Nuget add in the Nuget package called RavenDB
  3. Lets setup RavenDB as we require within the global.asax.cs file as below:-
    [sourcecode language=”csharp”] protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    Store = new DocumentStore { ConnectionStringName = "RavenDB", DefaultDatabase = "Products" };
    Store.Initialize();
    }
    [/sourcecode] Note:- I have added in a DefaultDatabase config value above which means I have created a new Products Raven Database within the RavenDB Management Studio called Products, if you don’t do this and just want to use the default database then remove the part DefaultDatabase = “Products”

  4. Add a class into the Models folder called Product as below:-
    [sourcecode language=”csharp”] public class Product
    {
    public string Id { get; set; }
    public string CategoryId { get; set; }
    public string SupplierId { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public decimal StandardCost { get; set; }
    public decimal ListPrice { get; set; }
    public int UnitsOnStock { get; set; }
    public int UnitsOnOrder { get; set; }
    public bool Discontinued { get; set; }
    }
    [/sourcecode]
  5. Now that we have our Model, let’s go ahead and add in a couple of controllers. We will use a base controller when working with our RavenDB project so firstly create a RavenDB Controller, to do this right-click on controllers folder and then select Add then choose Controller, select Empty Controller.
  6. Paste this code into your RavenController:-
    [sourcecode language=”csharp”] public class RavenController : Controller
    {
    public IDocumentSession _session { get; private set; }

    public const int DefaultPage = 1;
    public const int PageSize = 10;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
    if (filterContext.IsChildAction)
    return;
    _session = MvcApplication.Store.OpenSession();
    base.OnActionExecuting(filterContext);
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
    if (filterContext.IsChildAction)
    return;

    using (_session)
    {
    if (filterContext.Exception != null)
    return;

    if (_session != null)
    _session.SaveChanges();
    }
    }

    protected int CurrentPage
    {
    get
    {
    var s = Request.QueryString["page"];
    int result;
    if (int.TryParse(s, out result))
    return Math.Max(DefaultPage, result);
    return DefaultPage;
    }
    }
    }
    [/sourcecode]

  7. Lets now add a ProductController and this time choose, Controller with empty read/write actions as below:-
    ProductController
  8. We will start off by adding in some code which I have already written for the methods which we will use on the Products Controller, add them into your code:-
    [sourcecode language=”csharp”] public class ProductController : RavenController
    {
    //
    // GET: /Product/

    public ActionResult Index()
    {
    var model = _session.Query<Product>()
    .Paging(CurrentPage, DefaultPage, PageSize)
    .ToList();

    Mapper.Map<List<Product>, List<ProductViewModel>>(model);

    return View(model);
    }

    //
    // GET: /Product/Details/5

    public ActionResult Details(string id)
    {
    var model = _session.Load<Product>(id);
    return View(model);
    }

    //
    // GET: /Product/Create

    public ActionResult Create()
    {
    var model = new Product();
    return View(model);
    }

    //
    // POST: /Product/Create

    [HttpPost] public ActionResult Create(Product product)
    {
    try
    {
    _session.Store(product);
    return RedirectToAction("Index");
    }
    catch
    {
    return View();
    }
    }

    //
    // GET: /Product/Edit/5

    public ActionResult Edit(string id)
    {
    var model = _session.Load<Product>(id);
    return View(model);
    }

    //
    // POST: /Product/Edit/5

    [HttpPost] public ActionResult Edit(Product product)
    {
    try
    {
    _session.Store(product);
    return RedirectToAction("Index");
    }
    catch
    {
    return View();
    }
    }

    //
    // GET: /Product/Delete/5

    public ActionResult Delete(string id)
    {
    var model = _session.Load<Product>(id);
    return View(model);
    }

    //
    // POST: /Product/Delete/5

    [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(string id)
    {
    try
    {
    _session.Advanced.DatabaseCommands.Delete(id, null);
    return RedirectToAction("Index");
    }
    catch
    {
    return View();
    }
    }

    public ActionResult StoreSomeProductInDatabase()
    {
    var product = new Product
    {
    Name = "Product Name",
    CategoryId = "category/1024",
    SupplierId = "supplier/16",
    Code = "H11050",
    StandardCost = 250,
    ListPrice = 189
    };

    _session.Store(product);
    _session.SaveChanges();

    //return Content(product.Id);
    return RedirectToAction("Index");
    }

    public ActionResult InsertSomeMoreProducts()
    {
    for (int i = 0; i < 50; i++)
    {
    var product = new Product
    {
    Name = "Product Name " + i,
    CategoryId = "category/1024",
    SupplierId = "supplier/16",
    Code = "H11050" + i,
    StandardCost = 250 + (i*10),
    ListPrice = 189 + (i*10),
    };
    _session.Store(product);
    }

    _session.SaveChanges();

    //return Content("Products successfully created");
    return RedirectToAction("Index");
    }

    public ActionResult GetProduct(int id)
    {
    Product product = _session.Load<Product>(id);
    return Content(product.Name);
    }

    public ActionResult LoadAndUpdateProduct()
    {
    Product product = _session.Load<Product>("products/5");
    product.ListPrice -= 10;
    _session.SaveChanges();
    return Content("Product 5 successfully updated");
    }

    public ActionResult DeleteProduct(int id)
    {
    Product product = _session.Load<Product>(id);
    if (product == null)
    return HttpNotFound("Product {0} does not exist");
    _session.Delete(product);
    _session.SaveChanges();
    return Content(string.Format("Product {0} successfully deleted", id));
    }

    /// <summary>
    /// Get all the products that are available for sale (discontinued equal to false) ordered by the product’s list price
    /// </summary>
    /// <returns></returns>
    public ActionResult GetDiscontinuedProducts()
    {
    var products = from product in _session.Query<Product>()
    where product.Discontinued == false
    orderby product.ListPrice
    select product;

    return View(products.ToList());
    }
    }
    [/sourcecode]

  9. Ok so above we added a lot of code but this is good as this is the entire product controller and will allow us to add/edit/delete new products into RavenDB.
  10. I also added in a couple of methods for creating some test data, and also a method for returning discontinued products, mainly to show how you can go about doing this.
  11. Some screen shots are below, note they show me using RavenDB Profiler and MiniProfiler:-

    Crud 1

    Crud 2

    Crud 3

The code for this article is up on github here.
For more on RavenDB have a look at my other RavenDB posts here.

Please leave a comment, ask a question, find a bug or anything like that please let me know.