Render in MVC a link with image and text

Hi guys, I want in MVC to render a text with an image as an ActionLink. For creating a simple anchor tag, we use Html.ActionLink() helper which generates anchor tag for us.

If you want to create something a bit more complicated, you must create you own component. For this reason, I created the following code. It allows you to create an anchor with an image and a text.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PSC.MVC.Helpers
{
    public static class CustomHtmlHelpers
    {
        /// 
        /// Enum ImageAndText
        /// 
        public enum ImageAndText
        {
            /// 
            /// Image on the left, text on the right
            /// 
            ImageOnTheLeft,

            /// 
            /// Text on the left, image on the right
            /// 
            ImageOnTheRight
        }

        /// 
        /// Images the action link.
        /// 
        /// The HTML helper.
        /// The link text.
        /// The action.
        /// The controller.
        /// The route values.
        /// The HTML attributes.
        /// The image source.
        /// The alternate text.
        /// The text style.
        /// The image style.
        /// The image position.
        /// IHtmlString.
        public static IHtmlString ImageActionLink(
               this HtmlHelper htmlHelper, string linkText, string action, 
               string controller, object routeValues, object htmlAttributes, 
               string imageSrc, string alternateText = "", 
               string textStyle = "", string imageStyle = "", 
               ImageAndText imagePosition = ImageAndText.ImageOnTheLeft)
        {
            var urlHelper = new UrlHelper(
                    htmlHelper.ViewContext.RequestContext);

            // create the image
            var img = new TagBuilder("img");
            img.Attributes.Add("src", 
                    VirtualPathUtility.ToAbsolute(imageSrc));
            if (!string.IsNullOrEmpty(alternateText))
                img.Attributes.Add("alt", alternateText.Trim());
            if (!string.IsNullOrEmpty(imageStyle))
                img.Attributes.Add("style", imageStyle);

            // create a render for the image and the text
            string render = "";
            if (imagePosition == ImageAndText.ImageOnTheLeft)
                render = img.ToString(TagRenderMode.SelfClosing) + linkText;
            else
                render = linkText + img.ToString(TagRenderMode.SelfClosing);

            // create the anchor with image and text
            var anchor = new TagBuilder("a") {
                InnerHtml = render
            };
            if (!string.IsNullOrEmpty(textStyle))
                anchor.AddCssClass(textStyle);

            // add reference to the anchor
            anchor.Attributes["href"] = urlHelper.Action(action, 
                                                         controller, 
                                                         routeValues);
            anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            return MvcHtmlString.Create(anchor.ToString());
        }
    }
}

In your MVC code you have to add:

@using PSC.MVC.Helpers;

and then you can call your component:
@Html.ImageActionLink("Your text", "Index", "Home", null, null, 
                      "~/Content/images/img.png", "Logo", "navbar-brand", 
                      "width: 40px;")

C# and HTML5: drag and Drop elements

HTML5 API includes Drag and Drop (DnD) native functionality.

The event listener methods for all the drag and drop events accept Event object which has a readonly attribute called dataTransfer. The event.dataTransfer returns DataTransfer object associated with the event

This is the list of events fired during the different stages:

Event Description
dragstart Fires when the user starts dragging of the object.
dragenter Fired when the mouse is first moved over the target element while a drag is occuring. A listener for this event should indicate whether a drop is allowed over this location. If there are no listeners, or the listeners perform no operations, then a drop is not allowed by default.
dragover This event is fired as the mouse is moved over an element when a drag is occuring. Much of the time, the operation that occurs during a listener will be the same as the dragenter event.
dragleave This event is fired when the mouse leaves an element while a drag is occuring. Listeners should remove any highlighting or insertion markers used for drop feedback.
drag Fires every time the mouse is moved while the object is being dragged.
drop The drop event is fired on the element where the drop was occured at the end of the drag operation. A listener would be responsible for retrieving the data being dragged and inserting it at the drop location.
dragend Fires when the user releases the mouse button while dragging an object.

 

In this post we develop an application to handle the drag and drop events between two elements, and launch a HttpPost method in the server which will ends inserting the dragged value in database.

First of all we create an MVC project in C#. Under Controller folder in the HomeController we add this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HTML5DragAndDrop.Controllers {
   public class HomeController : Controller {
      ITestDatabase _testDatabase = new TestDatabase();

      public ActionResult Index() {
         return View();
      }

      public ActionResult About() {
         ViewBag.Message = "Your application description page.";

         return View();
      }

      public ActionResult Contact() {
         ViewBag.Message = "Your contact page.";

         return View();
      }

      [HttpPost]
      public JsonResult InsertTestElements(string testElement) {
         int? insertResult = null;

         if (!string.IsNullOrEmpty(testElement)) {
            string[] elementData = testElement.Split(':');

            string symbol = elementData[0].Trim();
            string name = elementData[1].Trim();

            insertResult = _testDatabase.InsertElement(symbol, name);
         }

         return Json(insertResult);
      }
   }
}

Now we create a folder in the root of the project called Code. Under this folder we create two new files:

ITestDatabase.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public interface ITestDatabase {
   int InsertElement(string symbol, string name);
}   
 

TestDatabase.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class TestDatabase : ITestDatabase {
   /// <summary>
   /// Save an element in the database and return the new ID
   /// </summary>
   /// <param name="symbol"></param>
   /// <param name="name"></param>
   /// <returns></returns>
   public int InsertElement(string symbol, string name) {
      // save the element in database
      // now it returns just a number: it will be the Id of the record
      return 1;
   }
}

The first step is the definition of the UXinterface, in sequence the display is this

DragAndDrop_App

We are adding h5utils.js file, with an implementation of AddEvent function to simplify our code:

h5utils.js

var AddEvent = (function () {
   if (document.addEventListener) {
      return function (el, type, fn) {
         if (el && el.nodeName || el === window) {
            el.addEventListener(type, fn, false);
         } else if (el && el.length) {
            for (var i = 0; i < el.length; i++) {
               AddEvent(el[i], type, fn);
            }
         }
      };
   } else {
      return function (el, type, fn) {
         if (el && el.nodeName || el === window) {
            el.attachEvent('on' + type, function () 
                  { 
                    return fn.call(el, window.event); 
                  });
         } else if (el && el.length) {
            for (var i = 0; i < el.length; i++) {
               AddEvent(el[i], type, fn);
            }
         }
      };
   }
})();

var pDragElement = document.createElement('p');
var chemicalElements = document.querySelectorAll('div > p'), el = null;
for (var i = 0; i < chemicalElements.length; i++) {
   el = chemicalElements[i];
   el.setAttribute('draggable', 'true');
   AddEvent(el, 'dragstart', dragStartElement);
   AddEvent(el, 'dragend', dragEndElement);
}

function dragStartElement(e) {
   e.dataTransfer.effectAllowed = 'copy';
   e.dataTransfer.setData('Text', this.id);
   e.dataTransfer.setData('Type', this.innerHTML);

   this.style.backgroundColor = "#ffa31a";
}

function dragEndElement(e) {
   this.style.backgroundColor = "#fff9f0";
}

var divBoxElements = document.querySelector('#divBoxElements');

AddEvent(divBoxElements, 'dragover', function (e) {
   if (e.preventDefault) e.preventDefault();
   e.dataTransfer.dropEffect = 'copy';
   return false;
});

AddEvent(divBoxElements, 'drop', function (e) {
   if (e.stopPropagation) e.stopPropagation();

   var element = e.dataTransfer.getData('Type');
   pDragElement.innerHTML = "Adding " + element + " element";

   var pClone = pDragElement.cloneNode(true);
   var newDiv = document.createElement("div");
   newDiv.appendChild(pClone);
   divBoxElements.appendChild(newDiv);
   InsertTestElement(element);

   return false;
});

In the Index.cshtml we change as following code:

Index.cshtml

@{
   ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Drag and drop example</h1>
    <p class="lead">HTML5 API includes Drag and Drop (DnD) 
    native functionality. The event listener methods for all the drag and 
    drop events accept Event object which has a readonly attribute called 
    dataTransfer. The event.dataTransfer returns DataTransfer object 
    associated with the event.</p>
    <p><a href="http://puresourcecode.com" 
    class="btn btn-primary btn-lg">Learn more »</a></p>
</div>

<div class="row">
    <p id="1A">1: A</p>
    <p id="2B">2: B</p>
    <p id="3C">3: C</p>
    <p id="4D">4: D</p>
    <p id="5E">5: E</p>
    <div id="divBoxElements 
       style="border: 1px solid #dcdcdc; width: 300px; height: 300px;"
    ></div>
</div>

@section scripts {
    <script src="~/Scripts/html5utils.js"></script>
    <script>
        <!--
        function InsertTestElement(element) {
            var url = '@Url.Action("InsertTestElements", "Home")';

            $.post(url, { testElement: element }, function (data) {
                switch (data) {
                    case 1:
                        divBoxElements.innerHTML = 
                             element + " inserted OK";
                        setTimeout(function () { 
                             divBoxElements.innerHTML = ""; }, 2000);
                        break;

                    default:
                        alert("Error inserting the element");
                }
            });
        }
        //-->
    </script>
}

Download or fork tthis code on Github.

Happy coding!

C# MVC: HttpContextBase from HttpContext.Current

It's easy by using the HttpContextWrapper

HttpContextBase basecontext = (new HttpContextWrapper(HttpContext.Current));
Happy coding!

How to upload a file in an ASP.Net MVC page

For this example, I’m using a controller named “HomeController”, with the view “Index”. When you click the “Submit” button on the view, it will be submitted to the “Save” method of HomeController.

Index.cshtml

@using(Html.BeginForm("Save", "Home", FormMethod.Post, 
               new {enctype = "multipart/form-data"}))
{
    <table>
        <tr>
            <td>File:</td>
            <td>
                <input type="file" name="UploadedFile" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="Submit" value="Submit"/>
            </td>
        </tr>
    </table>
}

Notice the two additional parameters for BeginForm

FormMethod.Post, new {enctype = "multipart/form-data"}

You need those to have the file included in the HTTP Post action to the Save method on the controller. Other than that, you just need a file input control, with a unique name attribute set.

HomeController

using System;
using System.Web;
using System.Web.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Save(FormCollection formCollection)
        {
            if(Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if((file != null) && (file.ContentLength > 0) && 
                   !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    file.InputStream.Read(fileBytes, 0, 
                                       Convert.ToInt32(file.ContentLength));

                    string pth = Path.GetFileName(fileName);
                    // change the folder
                    file.SaveAs(Server.MapPath("~/Uploads") + "/" + pth);
                }
            }

            return View("Index");
        }
    }
}

The Request object is a base object for handling HTTP requests. Since we set the FormMethod and enctype in the view, we have access to the file that was submitted on the page.

If the Request object isn’t null, we can check for the file by getting the HttpPostedFileBase from the Request object’s list of files, using its name (which is why a unique name was required for the file input control on the view).

Then we do some checking, to make sure the file actually has data, and get its information.

If you’re going to save the files somewhere (which is probably why you’re letting people upload files), then you’re going to need a way to display it for them later. To display a file within a browser, you need to know its ContentType. This will let the browser display it in the correct way.

With the byte array of the file’s contents, you can either save it to the database, in a varbinary column [for SQL Server], or write it out to disk, or some other document storage location.

Where you should save the files depends on what you’re going to do with them, how large they are, and what type of file they are.

If you see an error like

The SaveAs method is configured to require a rooted path, and the path '~/App_data/Uploads/1.pdf' is not rooted.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path '~/App_data/Uploads/1.pdf' is not rooted.

the problem is in the SaveAs function. You must pass a valid full path such as “C:\Uploads\Test\1.png”. For this reason I created in the root of the project a folder called Uploads and use Server.MapPath to find the full path.

Happy coding!

Creating a URL shortener using ASP.NET WepAPI and MVC: error handling

In the two previous post I discussed about the first step to creare this application and the implementation of the business logic. Now we can implement the error handling.

We have two custom exception classes:

  • ShorturlConflictException (when a segment already exists) and
  • ShorturlNotFoundException (when a segment isn’t found in the database).

There is also a third type: an unexpected exception, for example when there is no database connection. Normally, the user will see these errors. We have to build a mechanism where these exceptions are caught and a nice error page is shown, corresponding to the type of error, with the corresponding HTTP status code.

We need to add a filter to the Web project. Add a new folder called “Filters” and add a “ShorturlExceptionFilter” class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using PSC.Shorturl.Web.Exceptions;

namespace PSC.Shorturl.Web.Filters
{
    public class ShorturlErrorFilter : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            HttpStatusCode code = HttpStatusCode.InternalServerError;
            var ex = filterContext.Exception;
            string viewName = "Error500";

            if (ex is ShorturlNotFoundException)
            {
                code = HttpStatusCode.NotFound;
                viewName = "Error404";
            }
            if (ex is ShorturlConflictException)
            {
                code = HttpStatusCode.Conflict;
                viewName = "Error409";
            }

            filterContext.Result = new ViewResult()
            {
                ViewName = viewName
            };

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = (int)code;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}

This filter extends from the HandleErrorAttribute, and overrides the OnException method. In this method we do our own exception handling. If the exception is one of our own exceptions, a 404 or 409 is returned, else a 500 is returned. At the bottom of the method we tell the context that the exception is handled, and the current response (the ugly error page) will be cleared and our custom views (which are defined below) will be returned.

Add the following views in the “Views\Shared” folder:

Error404.cshtml

@{
    ViewBag.Title = "Not Found";
}

<h2>Not Found</h2>

<p>The resource you've requested isn't found.</p>

Error409.cshtml

@{
    ViewBag.Title = "Conflict";
}

<h2>Conflict</h2>

<p>The name you've chosen already exists.</p>

Error500.cshtml

@{
    ViewBag.Title = "Error";
}

<h2>Error</h2>

<p>An unexpected error occured.</p>

The only thing we have to do now is add the filter to our FilterConfig class (under App_Start). In the FilterConfig class, replace the existing method with this method:

using System.Web;
using System.Web.Mvc;
using PSC.Shorturl.Web.Filters;

namespace PSC.Shorturl.Web
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ShorturlErrorFilter());
            filters.Add(new HandleErrorAttribute());
        }
    }
}

Now, when there is an exception, a nice error page will be shown. Next post about WebApi integration.

Creating a URL shortener using ASP.NET WepAPI and MVC: implementing the business layer

In my previsious post I discussed the first implementation of this application. In this post I’m explained how to implement the business layer.

First of all you make sure the Business project references the Data, Entities and Exceptions projects. In the Exceptions project you add two new classes:

ShorturlConflictException

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Exceptions
{
    public class ShorturlConflictException : Exception	
    {
    }
}

ShorturlNotFoundException

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Exceptions
{
    public class ShorturlNotFoundException : Exception
    {
    }
}

We’ve implemented a stub for a business manager. The manager actually doesn’t do anything, but since we’ve implemented the database layer, it’s now possible to do some advanced stuff. Below you’ll see the new IUrlManager and UrlManager.

IUrlManager

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PSC.Shorturl.Web.Entities;

public interface IUrlManager
{
    Task<ShortUrl> ShortenUrl(string longUrl, string ip, string segment = "");
    Task<Stat> Click(string segment, string referer, string ip);
}

UrlManager

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PSC.Shorturl.Web.Data;
using PSC.Shorturl.Web.Entities;
using PSC.Shorturl.Web.Exceptions;

namespace PSC.Shorturl.Web.Business.Implementations
{
    public class UrlManager : IUrlManager
    {
        public Task<ShortUrl> ShortenUrl(string longUrl, string ip, string segment = "")
        {
            return Task.Run(() =>
            {
                using (var ctx = new ShorturlContext())
                {
                    ShortUrl url;

                    url = ctx.ShortUrls.Where(u => u.LongUrl == longUrl).FirstOrDefault();
                    if (url != null)
                    {
                        return url;
                    }

                    if (!string.IsNullOrEmpty(segment))
                    {
                        if (ctx.ShortUrls.Where(u => u.Segment == segment).Any())
                        {
                            throw new ShorturlConflictException();
                        }
                    }
                    else
                    {
                        segment = this.NewSegment();
                    }

                    if (string.IsNullOrEmpty(segment))
                    {
                        throw new ArgumentException("Segment is empty");
                    }

                    url = new ShortUrl()
                    {
                        Added = DateTime.Now,
                        Ip = ip,
                        LongUrl = longUrl,
                        NumOfClicks = 0,
                        Segment = segment
                    };

                    ctx.ShortUrls.Add(url);
                    ctx.SaveChanges();

                    return url;
                }
            });
        }

        public Task<Stat> Click(string segment, string referer, string ip)
        {
            return Task.Run(() =>
            {
                using (var ctx = new ShorturlContext())
                {
                    ShortUrl url = ctx.ShortUrls.Where(u => u.Segment == segment).FirstOrDefault();
                    if (url == null)
                    {
                        throw new ShorturlNotFoundException();
                    }

                    url.NumOfClicks = url.NumOfClicks + 1;

                    Stat stat = new Stat()
                    {
                        ClickDate = DateTime.Now,
                        Ip = ip,
                        Referer = referer,
                        ShortUrl = url
                    };

                    ctx.Stats.Add(stat);
                    ctx.SaveChanges();

                    return stat;
                }
            });
        }

        private string NewSegment()
        {
            using (var ctx = new ShorturlContext())
            {
                int i = 0;
                while (true)
                {
                    string segment = Guid.NewGuid().ToString().Substring(0, 6);
                    if (!ctx.ShortUrls.Where(u => u.Segment == segment).Any())
                    {
                        return segment;
                    }
                    if (i > 30)
                    {
                        break;
                    }
                    i++;
                }
                return string.Empty;
            }
        }
    }
}

You’ll see two new methods here: Click and NewSegment. The Click method will be executed any time anyone clicks on a short URL; some data (like the refering website) will be stored in the database. The NewSegment method creates a unique segment for our short URL. If it hasn’t found a valid segment in 30 loops, an empty string will be returned (this situation will be very rare though). The ShortenUrl method now actually shortens a long URL and stores it, together with a generated segment, in the database.

As you can see, any time a database action is executed, a new context object is created. When there are changes to the data, SaveChanges() is executed on the context at the end.

Putting it in the UrlController

Now we have a working business layer, we can call the business methods in the URL controller. Below, you see the updated Index() method:

public async Task<ActionResult> Index(Url url)
{
    if (ModelState.IsValid)
    {
        ShortUrl shortUrl = await this._urlManager.ShortenUrl(url.LongURL, Request.UserHostAddress);
        url.ShortURL = string.Format("{0}://{1}{2}{3}", Request.Url.Scheme, 
                                     Request.Url.Authority, Url.Content("~"), 
                                     shortUrl.Segment);
    }
    return View(url);
}

The controller asks the UrlManager for a new ShortUrl. When all went well, a full URL with the segment at the end will be created. At the moment there is only one problem; when we navigate to that URL, nothing happens, so we have to implement another method in the UrlController which handles the redirects. You’ll see this method below:

public async Task Click(string segment)
{
    string referer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty;
    Stat stat = await this._urlManager.Click(segment, referer, Request.UserHostAddress);
    return this.RedirectPermanent(stat.ShortUrl.LongUrl);
}

The only thing we have to do now is tell MVC that when we go to http://yourapp/segment, we wind up in that specific method. Below, you’ll see the new RegisterRoutes method of the class RouteConfig.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PSC.Shorturl.Web
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Click",
                url: "{segment}",
                defaults: new { controller = "Url", action = "Click" }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Url", action = "Index", 
                                id = UrlParameter.Optional }
            );
        }
    }
}

It’s very important that the “Click” route stands above the “Default” route.

Another nice thing our URL manager supports is adding a custom segment, for example http://yourapp/mysite. We have to modify three things for that:

1. Update the Url model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PSC.Shorturl.Web.Models
{
    public class Url
    {
        [Required]
        public string LongURL { get; set; }

        public string ShortURL { get; set; }

        public string CustomSegment { get; set; }
    }
}

2. Update the Index method

public async Task<ActionResult> Index(Url url)
{
    if (ModelState.IsValid)
    {
        ShortUrl shortUrl = await this._urlManager.ShortenUrl(url.LongURL, 
                                  Request.UserHostAddress, url.CustomSegment);
        url.ShortURL = string.Format("{0}://{1}{2}{3}", Request.Url.Scheme, 
                                     Request.Url.Authority, Url.Content("~"), 
                                     shortUrl.Segment);
    }
    return View(url);
}

3. Update the view

@model PSC.Shorturl.Web.Models.Url
@{
    ViewBag.Title = "URL shortener";
}

<h2>Shorten a URL</h2>

@Html.ValidationSummary()

@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.TextBoxFor(model => model.LongURL, new { placeholder = "URL you would like to have shortened", 
                         @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.TextBoxFor(model => model.CustomSegment, new { placeholder = "If you like, fill in a custom word for your short URL", 
                         @class = "form-control" })
    </div>

    if (!string.IsNullOrEmpty(Model.ShortURL))
    {
        <div>
            <h3><a href="@Model.ShortURL" target="_blank">@Model.ShortURL</a></h3>
        </div>
    }

    <input type="submit" class="btn btn-primary" value="Shorten" />
}

After this is done, it looks like we have a basic, and functioning, URL shortener. We still have to add some error handling; when an error is thrown from within the business layer, a big old ugly error page will be shown to the user. This is not something we want, this is what we’re going to fix next. In the next post.

Happy coding!

Creating a URL shortener using ASP.NET WepAPI and MVC

In this tutorial, I use several techniques and tools. I use Microsoft Visual Studio 2015 and the latest version of all components.

  • ASP.NET MVC: Microsoft’s modern web application framework. As the name says, it pushes you to use the MVC (model view controller) software design principle.
  • ASP.NET Web API: Web API and MVC are used together in many applications. With MVC, the HTML of the web pages are rendered on the server, and with Web API you can, like the name says, create an API. Web API also uses the MVC principle, but returns XML (or JSON, or YAML, or … whatever you want) instead of HTML.
  • Microsoft SQL: this is my primary database choice.
  • Entity Framework: this is my favourite ORM (object relational mapping) framework. With Entity Framework, you can create a database “code-first”, meaning that you can create classes (called entities) that represent the database and create the database based on those entities and its relations. When you’ve updated one of these entities, you can add a new migration, which means that the changes to your entities will be written to the database.
  • Unity: Unity is a dependency injection framework. You can read more on dependency injection and inversion of control later in this tutorial.

Basic project structure

If you didn’t know already, Visual Studio works with solutions. A solution can contain multiple projects. When a solution is compiled, a DLL (or EXE if it’s a WPF or Console application) is created. These DLLs, in case of an MVC application, are deployed to the server. A project can reference another project in the same solution, or assemblies compiled from another solution. A third way of adding references is using NuGet; this is a package manager for ASP.NET applications. Using this, you can add a connector to MySQL, Entity Framework, xUnit.net (testing framework) and many, many more to your solution. You can compare it to Composer (PHP) or npm (Node.js).

Once you’ve started Visual Studio, go to File | New | Project. I always select “ASP.NET Web Application”. In the following dialog, select “MVC”, but also select “Web API”. On the right hand, change authentication to “No Authentication”, since we’re not going to use that (not for this tutorial though, maybe later). In the bottom fields, you can fill in the name and location of your solution. I call it “PSC.Shorturl.Web” (but call it anything you want). You can uncheck “Host in the cloud”, although I’m not sure what the difference is (I never hosted anything in Azure). You can now click OK.

A basic MVC site is created now. Once you click the “Run” button at the top, you’ll already be able to browse the basic website. A local IIS web server is launched and your favourite browser will be opened with the MVC website.

ASPNET_MVC_FirstStart

As you can see, there are some files and folders created for you in this project. I’m going to explain what these folders and files are.

ASPNET_MVC_Solution

  • App_Data: This folder is empty for now, but if you ever want to enable uploads on your websites, it’s best if they are placed here.
  • App_Start: this folder contains some classes which are needed to start up MVC and Web API when the application is first run. If you add new frameworks which need something of a setup, this can be placed in this folder.
  • Content: this folder contains your CSS files and images.
  • Controllers: this folder contains the controller classes of the MVC application.
  • fonts: as the name says, this folder contains fonts.
  • Models: this folder contains models which will be used to pass data from the controllers to the views.
  • Scripts: this folder contains (Java)script files.
  • Views: this folder contains the views for the MVC application.
  • Global.asax: this file is loaded when the application is started. In this file, the classes in the “App_Start” folder are called.
  • packages.config: if you’re going to add packages from NuGet to your project, a reference to that project will be added to this file. When someone else receives your code and tries to build our code, Visual Studio first downloads all packages defined in this file (else the build would fail because these DLLs aren’t available).
  • Web.config: this file contains general configuration for your application. Think of database connection strings, SMTP server settings etc.

First, let’s open HomeController.cs in the folder Controllers. You’ll see this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PSC.Shorturl.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

 

This method contains three methods. When the application is started, RouteConfig (which is located in App_Start) is read and mapped to the existing controllers. In this application it means that when you go to http://yourapp/Home/About, the method About in the HomeController will be executed. This is called convention over configuration; you don’t have to explicitly tell the application that you have added a new controller. This means that when you add a new controller, say UrlController with a method Shorten, this will be called when you go to http://yourapp/Url/Shorten.

You also see that the methods in this class return a View(). For example, when you browse to /Home/About, the View() searches in the folder Views to the file About.cshtml (can be another extension, but the file should be called “About”). Again, this is “convention over configuration”.

Every method in this controller returns an ActionResult. An ActionResult can be a view, but can also be a redirect (which we’ll use later when redirecting a short URL).

This default behaviour can be fine tuned, but I think that’s not necessary for now; I think it works fine this way.

Now that’s explained, let’s create a new controller. Right click the Controllers folder and create a new controller (MVC 5 Controller – Empty). I call it UrlController.

ASPNET_MVC_AddController1

ASPNET_MVC_AddController2

By adding a new controller, a new folder is also added in the “Views” folder; “Url”. In this folder, create a new view called “Index.cshtml”. This is the code for the view:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

This is the main URL shortening view. Here, we'll show our form later on.

 

On the top of the view, you see a syntax you may have never seen before. This is MVC’s template syntax: Razor. The property “Title” of “ViewBag” is set to “URL shortener”. ViewBag is used to pass data from one view to another. In this case, the title will be rendered between the title tags of the master layout.

If you start the application now and head to /Url/Index (or just /Url, because Index is assumed if the second part isn’t set; see RouteConfig.cs), you’ll see our newly created view rendered. Later on, this view will contain the form where users can fill in their long URL to be shortened, so when the root URL is reached, we would like the user to see this page, we don’t want them to go to http://yourapp/Url. To accomplish this open RouteConfig.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PSC.Shorturl.Web
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", 
                                id = UrlParameter.Optional }
            );
        }
    }
}

 

This is the default route configuration. You’ll see that by default the HomeController and Index action are selected. Change “Home” to “Url”. Now, when we go to the root URL, we’ll see our newly created view.

This view is a bit empty for now. First, add a new class called “Url” to the folder “Models”. Like I’ve said before, a model is responsible for passing data between a View and a Controller. Below, you’ll see the model I’ve created:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PSC.Shorturl.Web.Models
{
    public class Url
    {
        public string LongURL { get; set; }

        public string ShortURL { get; set; }
    }
}

 

The model will contain the long URL and the short URL for now. When the user has filled in the URL he / she would like to have shortened, the LongURL property will be set and it will be sent to the business layer (which we will create lateron). The business layer will validate the URL and will return a short URL. The short URL will be set and the model will be returned to the view.

Now, let’s add a form to Index.cshtml.

@model PSC.Shorturl.Web.Models.Url
@{
    ViewBag.Title = "URL shortener";
}

<h2>Shorten a URL</h2>

@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.TextBoxFor(model => model.LongURL, 
                         new { placeholder = "URL you would like to have shortened", 
                         @class = "form-control" })
    </div>

    <input type="submit" class="btn btn-primary" value="Shorten" />
}

 

As you can see, I’ve added a “@model” reference at the top. The view now knows that it should use the class we’ve just created (you can call the model anywhere by using @Model in the view). Further on, you see we start a new HTML form. In this form we start a new TextBox, with a reference to the LongURL property in the class “Url”. The second parameter in this method is an anonymous object with several HTML attributes, like placeholder and class (class is prefixed with an “@” because it is a reserved keyword in ASP.NET, the application won’t work otherwise). The last line is a plain old HTML submit button.

ASPNET_MVC_FirstScreen

All very nice, but there is no logic at all at the moment. Let’s go back to UrlController.cs.

using PSC.Shorturl.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PSC.Shorturl.Web.Controllers
{
    public class UrlController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            Url url = new Url();
            return View(url);
        }

        public ActionResult Index(Url url)
        {
            url.ShortURL = "http://www.puresourcecode.com";
            return View(url);
        }
    }
}

 

You now see that I’ve created two methods with the same name. One which doesn’t have any parameters, one with a Url object as parameter. The first method will only be called when the user is first directed to the page. The second method is used when the user has pushed the submit button. MVC will serialize the data filled in on the form, place it in a URL object and pass it to that function. Here, we will be able read the original LongURL property and send it to the business layer. As of now, nothing happens with it and the ShortURL property is set to “http://www.google.com” hard coded. This is fine for now. The object with the ShortURL property set is being passed to the view, so we can read this property in the view now. If you place the snippet below in “Index.cshtml” underneath the textbox, you’ll see the shortened URL when you push the submit button.

if (!string.IsNullOrEmpty(Model.ShortURL))
{
    <div>
        lt;a href="@Model.ShortURL" target="_blank">@Model.ShortURL</a>
    </div>
}

 

It would be nice to have a little validation. For now, it’s enough to validate that the user has actually filled in anything as long URL. So go back to "Url.cs" and change LongURL to this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace PSC.Shorturl.Web.Models
{
    public class Url
    {
        [Required]
        public string LongURL { get; set; }

        public string ShortURL { get; set; }
    }
}

 

By placing this attribute directly above this property, MVC knows that this property should be set. Next, change the second Index method in UrlController.cs to this:

public ActionResult Index(Url url)
{
    if (ModelState.IsValid)
    {
        url.ShortURL = "http://www.puresourcecode.com";
    }
    return View(url);
}

 

ModelState.IsValid checks if all validation requirements are met. If yes, set the ShortURL. Finally, we would like the user to get validation feedback. In “Index.cshtml”, place this piece of code anywhere you’d like (I place it directly beneath the H2 tags):

@Html.ValidationSummary()

At this point, I deleted the HomeController and Home folder in the Views folder; we don’t need it for the now.

Now, it’s time to set up the other projects. Right click the solution and add new projects. The project I’m describing should be of the type “Class Library”.

ShortUrl_NewProject

ShortUrl_ClassLibrary

  • PSC.Shorturl.Web.Business: this project will contain the interfaces and classes needed to execute numerous business actions; for example adding a new short URL to the database, searching a short URL etc.
  • PSC.Shorturl.Web.Data: this project will contain our data context for Entity Framework and the migrations will be saved in this project.
  • PSC.Shorturl.Web.Entities: this project will contain the entities (plain old classes) for our data structure.
  • PSC.Shorturl.Web.Exceptions: this project will contain custom exceptions. For example, when a specific URL isn’t found, an exception will be thrown and it will be caught by the MVC framework to show us a nice custom error page.

So, now we’ve created all project we’re going to need to add several NuGet packages to the projects.

ShortUrl_NuGet

Search and install the following packages. I’m going to describe in which projects every package has to be installed to.

Shorturl_Nuget_packages

  • EntityFramework: the ORM which we’re going to use.
    • Business
    • Data
    • Entities
    • Web
  • Newtonsoft.Json: a nice Json serializer for ASP.NET. This will be needed by Web API later on.
    • Business
    • Data
    • Entities
    • Web
  • Unity, Unity bootstrapper for ASP.NET MVC & Unity.WebAPI: this is an inversion of control (IoC) for ASP.NET. It is used for loose coupled web applications. I will explain this later on.
    • Web

The solution should be able to build now. If not, please leave a comment and maybe I can help you.

Dependency injection

Robust applications don’t have any hard coupling in their code. What I always like to do is constructor injection; whenever a controller (or any other class) is instantiated, you can fill in a few parameters in the constructor. These parameters are interfaces.

Unity, an inversion of control framework, finds out which implementation belongs to this interface, and injects it. With this framework, you don’t have hard coupling; there is only one place in your application where you fill in this interface/implementation mapping. Whenever you need to change the implementation (for example, you used Entity Framework, but want to switch to NHibernate), you just create a new class that implements that specific interface and you change the configuration for Unity. It might all sound a bit vague. Let’s try to setup Unity.

1. The web project should reference all other projects

Right click the web project and add a new reference.

ShortUrl_ReferencesMenu

ShortUrl_References

2. Add an interface IUrlManager and a class UrlManager (which implements IUrlManager)

IUrlManager
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Business
{
    public interface IUrlManager
    {
        Task<string> ShortenUrl(string longUrl);
    }
}
UrlManager

Create a folder named Implementations and under this folder create the following interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Business.Implementations
{
    public class UrlManager : IUrlManager
    {
        public Task<string> ShortenUrl(string longUrl)
        {
            return Task.Run(() =>
            {
                return "http://www.puresourcecode.com";
            });
        }
    }
}

We have to tell the application somehow that when an implementation for IUrlManager is desired, a UrlManager should be injected. The method RegisterTypes in the class UnityConfig will look like this now:

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using PSC.Shorturl.Web.Business;
using PSC.Shorturl.Web.Business.Implementations;

namespace PSC.Shorturl.Web.App_Start
{
    /// <summary>
    /// Specifies the Unity configuration for the main container.
    /// </summary>
    public class UnityConfig
    {
        #region Unity Container
        private static Lazy<iunitycontainer> container = new Lazy<iunitycontainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container" />The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your types here
            // container.RegisterType<iproductrepository productrepository ,>();
            container.RegisterType<iurlmanager urlmanager ,>();
        }
    }
}

3. Update the existing UrlController

Let’s take a look at the new UrlController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using PSC.Shorturl.Web.Business;
using PSC.Shorturl.Web.Models;

namespace PSC.Shorturl.Web.Controllers
{
    public class UrlController : Controller
    {
        private IUrlManager _urlManager;

        public UrlController(IUrlManager urlManager)
        {
            this._urlManager = urlManager;
        }

        [HttpGet]
        public ActionResult Index()
        {
            Url url = new Url();
            return View(url);
        }

        public async Task<actionresult> Index(Url url)
        {
            if (ModelState.IsValid)
            {
                url.ShortURL = await 
                    this._urlManager.ShortenUrl(url.LongURL);
            }
            return View(url);
        }
    }
}

As you see here, we’ve added a private field and a constructor. When the controller is selected, Unity knows that it should insert the UrlManager in the IUrlManager. We have no hard coupling on the implementation at the moment. The second Index method is now async, and returns a Task. This is because our final implementation of the UrlManager will call the database and check if the inserted URL actually exists. If this isn’t executed async, it will block the entire application until these actions are done; that’s something you don’t want.

Every new business manager you’re going to add, can be injected using Unity.

Entity Framework

As I’ve explained before, Entity Framework is a object relational mapping framework. You define a few classes with a few properties. These properties match the fields in the database. Before we can do anything with Entity Framework, we have to make set up the MySQL connection in the Web.config file. The code snippet below should be inserted in the configuration tag of Web.config:

  <connectionStrings>
    <add name="Shorturl"
        connectionString="Server=YourServer;Database=PSCShortUrl;Uid=youruser;Pwd=yourpassword;"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

Make sure you put in the correct server, username and password.

Let’s add two entities (so two tables) for the URL shortener application to the Entities project. These are just plain classes.

ShortUrl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Entities
{
    [Table("short_urls")]
    public class ShortUrl
    {
        [Key]
        [Column("id")]
        public int Id { get; set; }

        [Required]
        [Column("long_url")]
        [StringLength(1000)]
        public string LongUrl { get; set; }

        [Required]
        [Column("segment")]
        [StringLength(20)]
        public string Segment { get; set; }

        [Required]
        [Column("added")]
        public DateTime Added { get; set; }

        [Required]
        [Column("ip")]
        [StringLength(50)]
        public string Ip { get; set; }

        [Required]
        [Column("num_of_clicks")]
        public int NumOfClicks { get; set; }

        public Stat[] Stats { get; set; }
    }
}
Stat.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PSC.Shorturl.Web.Entities
{
    [Table("stats")]
    public class Stat
    {
        [Key]
        [Column("id")]
        public int Id { get; set; }

        [Required]
        [Column("click_date")]
        public DateTime ClickDate { get; set; }

        [Required]
        [Column("ip")]
        [StringLength(50)]
        public string Ip { get; set; }

        [Column("referer")]
        [StringLength(500)]
        public string Referer { get; set; }

        public ShortUrl ShortUrl { get; set; }
    }
}

This is a very basic entity setup.

  • Table tells Entity Framework what the actual table name should be.
  • Key tells Entity Framework that this property is the primary key.
  • Column tells Entity Framework what the columns name is in the database.
  • StringLength tells Entity Framework what the maximum string length of a property is (only if the type is “string”).

This actually doesn’t do anything. We have to define a “data context”. The data context is the central piece in Entity Framework: it contains the relations between the different entities and contains the repositories. A repository is a collection of all records in a specific table mapped to a specific entity. Let’s add a ShortUrlContext to the Data project.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PSC.Shorturl.Web.Entities;

namespace PSC.Shorturl.Web.Data
{
    public class ShorturlContext : DbContext
    {
        public ShorturlContext()
            : base("name=Shorturl")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<stat>()
                .HasRequired(s => s.ShortUrl)
                .WithMany(u => u.Stats)
                .Map(m => m.MapKey("shortUrl_id"));
        }

        public virtual DbSet<shorturl> ShortUrls { get; set; }
        public virtual DbSet<stat> Stats { get; set; }
    }
}

The string "name=Shorturl" in the constructor refers to the connection string in the Web.config file. The method OnModelCreating is where all the relations between the entities are configured. At the moment, there is only one relation, so not much going on there. The latest two properties are the repositories. Entity Framework knows that these should be filled with the correct entities.

Now that we have the entities and the database configured, it’s time to set up our first migration. A migration is a change to the database. When you add a migration, Entity Framework compares the database with your current entity configuration and creates a new migration. This new migration can then be pushed to the database.

First, we have to open the package manager console.

ShortUrl_PackageConsole

Make sure the default project is “PSC.Shorturl.Web.Data”.

ShortUrl_PackageConsole_Data

Next, execute the command “enable-migrations”.

ShortUrl_PackageConsole_EnableMigration

If you have a Windows 10 Pro Insider Preview Build 11099, you can’t execute this command or other commands with Entity Framework. For updates see http://stackoverflow.com/questions/35060821/visual-studio-2015-entity-framework-and-enable-migrations-error

A migrations configuration file will be added to the Data project. From now on, it will be possible to add new migrations. Execute the following command:

add-migration "InitialCreate"

This will add an initial migration to your Data project. When you execute the following command:

update-database

The migration will actually be written to the database. If everything went right, you’ll now see the created (but empty) tables in the newly created database.

Next step is the implementation on business layer.

OWIN and Facebook: the developers of this app have not set up this app properly for Facebook Login?

Facebook-error

Did you received this error when you try to login in your Owin app with Facebook?

App Not Set Up: This app is still in development mode, and you don't have access to it. Switch to a registered test user or ask an app admin for permissions.

Solution

  1. Go to https://developers.facebook.com/
  2. Click on the My Apps menu on the top bar and select your appFacebook-DeveloperThe circle next to your app name is not fully green. When you hover mouse on it, you'll see a popup saying, "Not available to all users because your app is not live." So next, you've to make it publicly available. Facebook-Developer_Dashboard
  3. Click on Setting at left panel Facebook-Developer_Settings
  4. In Basic tab add your "Contact Email" (a valid email address - I've added the one which I'm using with developers.facebook.com) and make "Save changes".
  5. Next click "Status & Review" at left panel
  6. Look for this, Do you want to make this app and all its live features available to the general public? and Turn ON the switch next to this. Facebook_Developer_Status_Review
  7. Confirm the question “Are you sure you want to make your app public? It will become available to everyone.”
  8. That's it! - App is now publicly available. See the fully green circle next to the app name.Facebook-Developer_AppPublish

Happy coding!

C# ASP.NET MVC OWIN and Twitter authentication error

We have an MVC project using OWIN Framework to allow our users to authenticate using Twitter.
However starting today, we have been getting this exception when trying to authenticate:

System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

Thanks to the power of open source we can see that the thumbprints for the twitter certificates have been coded in the Katana Project.

Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions

Recently some certificates must have changed and now the thumbprints no longer match.

Please add a new thumb print for the "VeriSign Class 3 Public Primary Certification Authority - G5" Certificate to your Twitter Auth Options in your Startup.Auth.cs (for MVC users).

Change from the default:

app.UseTwitterAuthentication(
    consumerKey: "XXXX",
    consumerSecret: "XXX"
);

with:

app.UseTwitterAuthentication(new TwitterAuthenticationOptions
{
    ConsumerKey = "XXXX",
    ConsumerSecret = "XXXX",
    BackchannelCertificateValidator = 
      new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(
        new[] {
        // VeriSign Class 3 Secure Server CA - G2
        "A5EF0B11CEC04103A34A659048B21CE0572D7D47",
        // VeriSign Class 3 Secure Server CA - G3
        "0D445C165344C1827E1D20AB25F40163D8BE79A5", 
        // VeriSign Class 3 Public Primary Certification Authority - G5
        "7FD365A7C2DDECBBF03009F34339FA02AF333133", 
        // Symantec Class 3 Secure Server CA - G4
        "39A55D933676616E73A761DFA16A7E59CDE66FAD", 
        // Symantec Class 3 EV SSL CA - G3
        "‎add53f6680fe66e383cbac3e60922e3b4c412bed", 
        // VeriSign Class 3 Primary CA - G5
        "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", 
        // DigiCert SHA2 High Assurance Server C‎A 
        "5168FF90AF0207753CCCD9656462A212B859723B",
        // DigiCert High Assurance EV Root CA 
        "B13EC36903F8BF4701D498261A0802EF63642BC3" 
      })
});

Happy coding!

ASP.NET MVC Return image dynamically drawn in controller

If you have problem returning dynamically drawn image from controller below informations may help. The task looks easy and should be achieved with this code:

public ActionResult Image(string text)
{
    //Create new image
    Image img = new Bitmap(100, 50);
    Graphics g = Graphics.FromImage(img);
            
    //Do some drawing
    Font font = new Font("Arial", 24);
    PointF drawingPoint = new PointF(10, 10);
            
    g.DrawString(text, font, Brushes.Black, drawingPoint);

    //Return Image
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);

    return new FileStreamResult(ms, "image/png");
}

 

Unfortunately this won't work. At least not in .NET 4.0. Perceptive person will notice that after writing image to the stream it position property isn't at the beginning and FileStreamResult apparently can't deal with this.

MVCImageDynamically

After reseting stream position everything works well (bold line).

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

...

public ActionResult Hello(string text)
{
    //Create new image
    Image img = new Bitmap(100, 50);
    Graphics g = Graphics.FromImage(img);
            
    //Do some drawing
    Font font = new Font("Arial", 24);
    PointF drawingPoint = new PointF(10, 10);
            
    g.DrawString(text, font, Brushes.Black, drawingPoint);

    //Return Image
    MemoryStream ms = new MemoryStream();
    img.Save(ms, ImageFormat.Png);

    ms.Position = 0;

    return new FileStreamResult(ms, "image/png");
}

 

Additionally the view which asynchronously (but without ajax) retrieve image from our controller:

<div id="divResult"></div>

<input type="text" id="txtText" value="Hello" />

<input type="button" name="submit" onclick="javascript:Hello();" value="Draw" />

<script type="text/javascript">

function Hello()
{
    var link = '@Url.Content("~/Controller/Hello")';

    var txt = document.getElementById('txtText').value;

    link += '?';
    link += 'text=' + txt;

    document.getElementById('divResult').innerHTML = '<img src="' + link + '" alt="' + txt+ '" />';

    return false;
}

</script>

 

or you can you an action like:

<img src="@Url.Action("Hello", new { text = "Hello guys!" })" 
       alt="Image for Hello guys!" style="width: 250px;" />

 

Happy coding!

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  July 2017  >>
MonTueWedThuFriSatSun
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

View posts in large calendar

Month List