PureSourceCode.com - JavaScriptAll technologies, only pure source codehttp://puresourcecode.com/
http://www.rssboard.org/rss-specificationBlogEngine.NET 3.3.6.0en-GBhttp://puresourcecode.com/opml.axdhttp://www.dotnetblogengine.net/syndication.axdEnrico RossiniPureSourceCode.com0.0000000.000000$.ajax No 'Access-Control-Allow-Origin' header is present on the requested resource with WebAPI<p>I want to get data from a WebAPI with jquery </p> <pre class="brush: js;"> $(&quot;#btnSend&quot;).click(function () {
$(&quot;#sending&quot;).show();
$.ajax({
type: 'GET',
url: '/Report/SendEmail?quote=18',
crossDomain: true,
success: function (msg) {
if (msg == 'True') {
alert('Email sent to the client');
}
$(&quot;#sending&quot;).hide();
},
error: function (request, status, error) {
$(&quot;#sending&quot;).hide();
}
});
});</pre>
<p>and it produce </p>
<blockquote>
<p>‘No Access-Control-Allow-Origin' header is present on the requested resource error.</p>
</blockquote>
<p>The solution is to add in the result of the WebAPI the following code:</p>
<pre class="brush: csharp;">
Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST");
Response.Headers.Add("Access-Control-Allow-Headers", "accept, authority");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
</pre>
<p>
Happy coding!
</p>http://puresourcecode.com/dotnet/dotnet/post/2016/10/06/$ajax-No-Access-Control-Allow-Origin-header-is-present-on-the-requested-resource-with-WebAPI
enrico.rossini.uk@live.comhttp://puresourcecode.com/dotnet/dotnet/post/2016/10/06/$ajax-No-Access-Control-Allow-Origin-header-is-present-on-the-requested-resource-with-WebAPI#commenthttp://puresourcecode.com/dotnet/post.aspx?id=be9519ba-343b-4d82-a036-228727304a84Thu, 6 Oct 2016 10:24:49 -0800WebAPIC#AjaxJavaScriptaccessalloworiginjqueryhenryhttp://puresourcecode.com/dotnet/pingback.axdhttp://puresourcecode.com/dotnet/post.aspx?id=be9519ba-343b-4d82-a036-228727304a840http://puresourcecode.com/dotnet/trackback.axd?id=be9519ba-343b-4d82-a036-228727304a84http://puresourcecode.com/dotnet/dotnet/post/2016/10/06/$ajax-No-Access-Control-Allow-Origin-header-is-present-on-the-requested-resource-with-WebAPI#commenthttp://puresourcecode.com/dotnet/syndication.axd?post=be9519ba-343b-4d82-a036-228727304a84C# and HTML5: drag and Drop elements<p>HTML5 API includes <strong>Drag and Drop</strong> (DnD) native functionality.</p> <p>The event listener methods for all the drag and drop events accept Event object which has a readonly attribute called dataTransfer. The <em>event.dataTransfer</em> returns <strong>DataTransfer</strong> object associated with the event </p> <p>This is the list of events fired during the different stages:</p> <table cellspacing="3" cellpadding="3" border="0"><tbody> <tr style="background-color: #ccc"> <th style="width: 15%">Event</th> <th>Description</th> </tr> <tr> <td>dragstart</td> <td>Fires when the user starts dragging of the object.</td> </tr> <tr> <td>dragenter</td> <td>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.</td> </tr> <tr style="border-top: #ddd 1px solid; border-right: #ddd 1px solid; border-bottom: #ddd 1px solid; border-left: #ddd 1px solid"> <td>dragover</td> <td>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.</td> </tr> <tr style="border-top: #ddd 1px solid; border-right: #ddd 1px solid; border-bottom: #ddd 1px solid; border-left: #ddd 1px solid"> <td>dragleave</td> <td>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.</td> </tr> <tr> <td>drag</td> <td>Fires every time the mouse is moved while the object is being dragged.</td> </tr> <tr> <td>drop</td> <td>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.</td> </tr> <tr> <td>dragend</td> <td>Fires when the user releases the mouse button while dragging an object.</td> </tr> </tbody></table> <p>&#160;</p> <p>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. </p> <p>First of all we create an MVC project in C#. Under Controller folder in the HomeController we add this code: </p> <pre class="brush: csharp;">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 = &quot;Your application description page.&quot;;
return View();
}
public ActionResult Contact() {
ViewBag.Message = &quot;Your contact page.&quot;;
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);
}
}
}</pre>
<p>Now we create a folder in the root of the project called <b>Code</b>. Under this folder we create two new files: </p>
<h3>ITestDatabase.cs</h3>
<pre class="brush: csharp;">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);
}
</pre>
<h3>TestDatabase.cs</h3>
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class TestDatabase : ITestDatabase {
/// &lt;summary&gt;
/// Save an element in the database and return the new ID
/// &lt;/summary&gt;
/// &lt;param name=&quot;symbol&quot;&gt;&lt;/param&gt;
/// &lt;param name=&quot;name&quot;&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
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;
}
}</pre>
<p>The first step is the definition of the <strong>UXinterface</strong>, in sequence the display is this </p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=DragAndDrop_App_1.png"><img title="DragAndDrop_App" style="float: none; margin: 0px auto; display: block" alt="DragAndDrop_App" src="http://puresourcecode.com/dotnet/image.axd?picture=DragAndDrop_App_thumb_1.png" width="616" height="480" /></a></p>
<p>We are adding h5utils.js file, with an implementation of <strong>AddEvent</strong> function to simplify our code:</p>
<h3>h5utils.js</h3>
<pre class="brush: js;">var AddEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el &amp;&amp; el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el &amp;&amp; el.length) {
for (var i = 0; i &lt; el.length; i++) {
AddEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el &amp;&amp; el.nodeName || el === window) {
el.attachEvent('on' + type, function ()
{
return fn.call(el, window.event);
});
} else if (el &amp;&amp; el.length) {
for (var i = 0; i &lt; el.length; i++) {
AddEvent(el[i], type, fn);
}
}
};
}
})();
var pDragElement = document.createElement('p');
var chemicalElements = document.querySelectorAll('div &gt; p'), el = null;
for (var i = 0; i &lt; 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 = &quot;#ffa31a&quot;;
}
function dragEndElement(e) {
this.style.backgroundColor = &quot;#fff9f0&quot;;
}
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 = &quot;Adding &quot; + element + &quot; element&quot;;
var pClone = pDragElement.cloneNode(true);
var newDiv = document.createElement(&quot;div&quot;);
newDiv.appendChild(pClone);
divBoxElements.appendChild(newDiv);
InsertTestElement(element);
return false;
});</pre>
<p>In the Index.cshtml we change as following code: </p>
<h3>Index.cshtml</h3>
<pre class="brush: csharp;">@{
ViewBag.Title = &quot;Home Page&quot;;
}
&lt;div class=&quot;jumbotron&quot;&gt;
&lt;h1&gt;Drag and drop example&lt;/h1&gt;
&lt;p class=&quot;lead&quot;&gt;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.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://puresourcecode.com&quot;
class=&quot;btn btn-primary btn-lg&quot;&gt;Learn more »&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;p id=&quot;1A&quot;&gt;1: A&lt;/p&gt;
&lt;p id=&quot;2B&quot;&gt;2: B&lt;/p&gt;
&lt;p id=&quot;3C&quot;&gt;3: C&lt;/p&gt;
&lt;p id=&quot;4D&quot;&gt;4: D&lt;/p&gt;
&lt;p id=&quot;5E&quot;&gt;5: E&lt;/p&gt;
&lt;div id=&quot;divBoxElements
style=&quot;border: 1px solid #dcdcdc; width: 300px; height: 300px;&quot;
&gt;&lt;/div&gt;
&lt;/div&gt;
@section scripts {
&lt;script src=&quot;~/Scripts/html5utils.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
&lt;!--
function InsertTestElement(element) {
var url = '@Url.Action(&quot;InsertTestElements&quot;, &quot;Home&quot;)';
$.post(url, { testElement: element }, function (data) {
switch (data) {
case 1:
divBoxElements.innerHTML =
element + &quot; inserted OK&quot;;
setTimeout(function () {
divBoxElements.innerHTML = &quot;&quot;; }, 2000);
break;
default:
alert(&quot;Error inserting the element&quot;);
}
});
}
//--&gt;
&lt;/script&gt;
}</pre>
<p>Download or fork tthis code on <a href="https://github.com/erossini/HTML5DragAndDrop/?utm_source=puresourcecode.com" target="_blank">Github</a>. </p>
<p>Happy coding! </p>http://puresourcecode.com/dotnet/dotnet/post/2016/03/28/C-and-HTML5-drag-and-Drop-elements
enrico.rossini.uk@live.comhttp://puresourcecode.com/dotnet/dotnet/post/2016/03/28/C-and-HTML5-drag-and-Drop-elements#commenthttp://puresourcecode.com/dotnet/post.aspx?id=ade16c55-76c7-4f64-aa81-323c241c41e1Mon, 28 Mar 2016 22:19:05 -0800C#HTMLJavaScriptMVCdatatransferhtml5listenerhenryhttp://puresourcecode.com/dotnet/pingback.axdhttp://puresourcecode.com/dotnet/post.aspx?id=ade16c55-76c7-4f64-aa81-323c241c41e10http://puresourcecode.com/dotnet/trackback.axd?id=ade16c55-76c7-4f64-aa81-323c241c41e1http://puresourcecode.com/dotnet/dotnet/post/2016/03/28/C-and-HTML5-drag-and-Drop-elements#commenthttp://puresourcecode.com/dotnet/syndication.axd?post=ade16c55-76c7-4f64-aa81-323c241c41e1Creating a URL shortener using ASP.NET WepAPI and MVC<p>In this tutorial, I use several techniques and tools. I use Microsoft Visual Studio 2015 and the latest version of all components.</p> <ul> <li><strong>ASP.NET MVC</strong>: Microsoft’s modern web application framework. As the name says, it pushes you to use the MVC (<strong>model view controller</strong>) software design principle. </li> <li><strong>ASP.NET Web API</strong>: 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. </li> <li><strong>Microsoft SQL</strong>: this is my primary database choice. </li> <li><strong>Entity Framework</strong>: 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. </li> <li><strong>Unity</strong>: Unity is a dependency injection framework. You can read more on dependency injection and inversion of control later in this tutorial. </li> </ul> <h2>Basic project structure</h2> <p>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).</p> <p>Once you’ve started Visual Studio, go to <em>File</em> | <em>New</em> | <em>Project</em>. 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.</p> <p>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.</p> <p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_FirstStart.png"><img width="644" height="440" title="ASPNET_MVC_FirstStart" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ASPNET_MVC_FirstStart" src="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_FirstStart_thumb.png" border="0"></a></p> <p>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.</p> <p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_Solution.png"><img width="359" height="434" title="ASPNET_MVC_Solution" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ASPNET_MVC_Solution" src="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_Solution_thumb.png" border="0"></a></p> <ul> <li><strong>App_Data</strong>: 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. </li> <li><strong>App_Start</strong>: 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. </li> <li><strong>Content</strong>: this folder contains your CSS files and images. </li> <li><strong>Controllers</strong>: this folder contains the controller classes of the MVC application. </li> <li><strong>fonts</strong>: as the name says, this folder contains fonts. </li> <li><strong>Models</strong>: this folder contains models which will be used to pass data from the controllers to the views. </li> <li><strong>Scripts</strong>: this folder contains (Java)script files. </li> <li><strong>Views</strong>: this folder contains the views for the MVC application. </li> <li><strong>Global.asax</strong>: this file is loaded when the application is started. In this file, the classes in the “<strong>App_Start</strong>” folder are called. </li> <li><strong>packages.config</strong>: 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). </li> <li><strong>Web.config</strong>: this file contains general configuration for your application. Think of database connection strings, SMTP server settings etc. </li> </ul> <p>First, let’s open HomeController.cs in the folder Controllers. You’ll see this code:</p> <pre class="brush: csharp;">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();
}
}
}</pre>
<p>&nbsp;</p>
<p>This method contains three methods. When the application is started, <strong>RouteConfig</strong> (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 <strong>HomeController</strong> will be executed. This is called <strong>convention over configuration</strong>; 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. </p>
<p>You also see that the methods in this class return a <strong>View()</strong>. 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”.</p>
<p>Every method in this controller returns an <strong>ActionResult</strong>. An ActionResult can be a view, but can also be a redirect (which we’ll use later when redirecting a short URL).</p>
<p>This default behaviour can be fine tuned, but I think that’s not necessary for now; I think it works fine this way.</p>
<p>Now that’s explained, let’s create a new controller. Right click the <strong>Controllers</strong> folder and create a new controller (MVC 5 Controller – Empty). I call it UrlController.</p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_AddController1.png"><img width="644" height="438" title="ASPNET_MVC_AddController1" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ASPNET_MVC_AddController1" src="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_AddController1_thumb.png" border="0"></a></p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_AddController2.png"><img width="644" height="448" title="ASPNET_MVC_AddController2" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ASPNET_MVC_AddController2" src="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_AddController2_thumb.png" border="0"></a></p>
<p>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:</p>
<pre class="brush: csharp;">@{
ViewBag.Title = "Index";
}
&lt;h2&gt;Index&lt;/h2&gt;
This is the main URL shortening view. Here, we'll show our form later on.</pre>
<p>&nbsp;</p>
<p>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 “<strong>ViewBag</strong>” 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. </p>
<p>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 <strong>RouteConfig.cs</strong>), 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. </p>
<pre class="brush: csharp;">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 }
);
}
}
}</pre>
<p>&nbsp;</p>
<p>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.</p>
<p>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:</p>
<pre class="brush: csharp;">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; }
}
}</pre>
<p>&nbsp;</p>
<p>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. </p>
<p>Now, let’s add a form to Index.cshtml.</p>
<pre class="brush: csharp;">@model PSC.Shorturl.Web.Models.Url
@{
ViewBag.Title = "URL shortener";
}
&lt;h2&gt;Shorten a URL&lt;/h2&gt;
@using (Html.BeginForm())
{
&lt;div class="form-group"&gt;
@Html.TextBoxFor(model =&gt; model.LongURL,
new { placeholder = "URL you would like to have shortened",
@class = "form-control" })
&lt;/div&gt;
&lt;input type="submit" class="btn btn-primary" value="Shorten" /&gt;
}</pre>
<p>&nbsp;</p>
<p>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. </p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_FirstScreen.png"><img width="644" height="421" title="ASPNET_MVC_FirstScreen" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ASPNET_MVC_FirstScreen" src="http://puresourcecode.com/dotnet/image.axd?picture=ASPNET_MVC_FirstScreen_thumb.png" border="0"></a></p>
<p>All very nice, but there is no logic at all at the moment. Let’s go back to UrlController.cs.</p>
<pre class="brush: csharp;">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);
}
}
}</pre>
<p>&nbsp;</p>
<p>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. </p>
<pre class="brush: csharp;">if (!string.IsNullOrEmpty(Model.ShortURL))
{
&lt;div&gt;
lt;a href="@Model.ShortURL" target="_blank"&gt;@Model.ShortURL&lt;/a&gt;
&lt;/div&gt;
}</pre>
<p>&nbsp;</p>
<p>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: </p>
<pre class="brush: csharp;">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; }
}
}</pre>
<p>&nbsp;</p>
<p>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: </p>
<pre class="brush: csharp;">public ActionResult Index(Url url)
{
if (ModelState.IsValid)
{
url.ShortURL = "http://www.puresourcecode.com";
}
return View(url);
}</pre>
<p>&nbsp;</p>
<p>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): </p>
<pre class="brush: csharp;">@Html.ValidationSummary()</pre>
<p>At this point, I deleted the HomeController and Home folder in the Views folder; we don’t need it for the now. </p>
<p>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”. </p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_NewProject.png"><img width="695" height="531" title="ShortUrl_NewProject" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_NewProject" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_NewProject_thumb.png" border="0"></a></p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_ClassLibrary.png"><img width="644" height="448" title="ShortUrl_ClassLibrary" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_ClassLibrary" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_ClassLibrary_thumb.png" border="0"></a></p>
<ul>
<li><strong>PSC.Shorturl.Web.Business</strong>: 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. </li>
<li><strong><strong>PSC.Shorturl</strong>.Web.Data</strong>: this project will contain our data context for Entity Framework and the migrations will be saved in this project. </li>
<li><strong><strong>PSC.Shorturl</strong>.Web.Entities</strong>: this project will contain the entities (plain old classes) for our data structure. </li>
<li><strong><strong>PSC.Shorturl</strong>.Web.Exceptions</strong>: 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. </li>
</ul>
<p>So, now we’ve created all project we’re going to need to add several NuGet packages to the projects.</p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_NuGet.png"><img width="569" height="565" title="ShortUrl_NuGet" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_NuGet" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_NuGet_thumb.png" border="0"></a></p>
<p>Search and install the following packages. I’m going to describe in which projects every package has to be installed to.</p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=Shorturl_Nuget_packages.png"><img width="644" height="381" title="Shorturl_Nuget_packages" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="Shorturl_Nuget_packages" src="http://puresourcecode.com/dotnet/image.axd?picture=Shorturl_Nuget_packages_thumb.png" border="0"></a></p>
<ul>
<li><strong>EntityFramework</strong>: the ORM which we’re going to use.
<ul>
<li>Business </li>
<li>Data </li>
<li>Entities </li>
<li>Web </li>
</ul>
</li>
<li><strong>Newtonsoft.Json</strong>: a nice Json serializer for ASP.NET. This will be needed by Web API later on.
<ul>
<li>Business </li>
<li>Data </li>
<li>Entities </li>
<li>Web </li>
</ul>
</li>
<li><strong>Unity</strong>, <strong>Unity bootstrapper for ASP.NET MVC</strong> &amp; <strong>Unity.WebAPI</strong>: this is an inversion of control (IoC) for ASP.NET. It is used for loose coupled web applications. I will explain this later on.
<ul>
<li>Web </li>
</ul>
</li>
</ul>
<p>The solution should be able to build now. If not, please leave a comment and maybe I can help you.</p>
<h3>Dependency injection</h3>
<p>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. </p>
<p>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 <strong>Unity</strong>. It might all sound a bit vague. Let’s try to setup Unity.</p>
<h4>1. The web project should reference all other projects</h4>
<p>Right click the web project and add a new reference.</p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_ReferencesMenu.png"><img width="685" height="751" title="ShortUrl_ReferencesMenu" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_ReferencesMenu" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_ReferencesMenu_thumb.png" border="0"></a></p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_References.png"><img width="644" height="446" title="ShortUrl_References" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_References" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_References_thumb.png" border="0"></a></p>
<h4>2. Add an interface IUrlManager and a class UrlManager (which implements IUrlManager)</h4>
<h5>IUrlManager</h5>
<pre class="brush: csharp;">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&lt;string&gt; ShortenUrl(string longUrl);
}
}</pre>
<h5>UrlManager</h5>
<p>Create a folder named Implementations and under this folder create the following interface:</p>
<pre class="brush: csharp;">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&lt;string&gt; ShortenUrl(string longUrl)
{
return Task.Run(() =&gt;
{
return "http://www.puresourcecode.com";
});
}
}
}</pre>
<p>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: </p>
<pre class="brush: csharp;">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
{
/// &lt;summary&gt;
/// Specifies the Unity configuration for the main container.
/// &lt;/summary&gt;
public class UnityConfig
{
#region Unity Container
private static Lazy&lt;iunitycontainer&gt; container = new Lazy&lt;iunitycontainer&gt;(() =&gt;
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// &lt;summary&gt;
/// Gets the configured Unity container.
/// &lt;/summary&gt;
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// &lt;summary&gt;Registers the type mappings with the Unity container.&lt;/summary&gt;
/// &lt;param name="container" /&gt;The unity container to configure.&lt;/param&gt;
/// &lt;remarks&gt;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.&lt;/remarks&gt;
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&lt;iproductrepository productrepository ,&gt;();
container.RegisterType&lt;iurlmanager urlmanager ,&gt;();
}
}
}</pre>
<h4>3. Update the existing UrlController</h4>
<p>Let’s take a look at the new UrlController:</p>
<pre class="brush: csharp;">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&lt;actionresult&gt; Index(Url url)
{
if (ModelState.IsValid)
{
url.ShortURL = await
this._urlManager.ShortenUrl(url.LongURL);
}
return View(url);
}
}
}</pre>
<p>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. </p>
<p>Every new business manager you’re going to add, can be injected using Unity. </p>
<h3>Entity Framework</h3>
<p>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: </p>
<pre class="brush: xml;"> &lt;connectionStrings&gt;
&lt;add name="Shorturl"
connectionString="Server=YourServer;Database=PSCShortUrl;Uid=youruser;Pwd=yourpassword;"
providerName="System.Data.SqlClient" /&gt;
&lt;/connectionStrings&gt;</pre>
<p>Make sure you put in the correct server, username and password.</p>
<p>Let’s add two entities (so two tables) for the URL shortener application to the Entities project. These are just plain classes. </p>
<h5>ShortUrl.cs</h5>
<pre class="brush: csharp;">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; }
}
}</pre>
<h5>Stat.cs</h5>
<pre class="brush: csharp;">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; }
}
}</pre>
<p>This is a very basic entity setup.</p>
<ul>
<li><strong>Table</strong> tells Entity Framework what the actual table name should be. </li>
<li><strong>Key</strong> tells Entity Framework that this property is the primary key. </li>
<li><strong>Column</strong> tells Entity Framework what the columns name is in the database. </li>
<li><strong>StringLength</strong> tells Entity Framework what the maximum string length of a property is (only if the type is “string”). </li>
</ul>
<p>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.</p>
<pre class="brush: csharp;">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&lt;stat&gt;()
.HasRequired(s =&gt; s.ShortUrl)
.WithMany(u =&gt; u.Stats)
.Map(m =&gt; m.MapKey("shortUrl_id"));
}
public virtual DbSet&lt;shorturl&gt; ShortUrls { get; set; }
public virtual DbSet&lt;stat&gt; Stats { get; set; }
}
}</pre>
<p>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.</p>
<p>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. </p>
<p>First, we have to open the package manager console. </p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_PackageConsole.png"><img width="644" height="144" title="ShortUrl_PackageConsole" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_PackageConsole" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_PackageConsole_thumb.png" border="0"></a></p>
<p>Make sure the default project is “PSC.Shorturl.Web.Data”.</p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_PackageConsole_Data.png"><img width="644" height="144" title="ShortUrl_PackageConsole_Data" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_PackageConsole_Data" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_PackageConsole_Data_thumb.png" border="0"></a></p>
<p>Next, execute the command “enable-migrations”.</p>
<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_PackageConsole_EnableMigration.png"><u></u><img width="644" height="144" title="ShortUrl_PackageConsole_EnableMigration" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" alt="ShortUrl_PackageConsole_EnableMigration" src="http://puresourcecode.com/dotnet/image.axd?picture=ShortUrl_PackageConsole_EnableMigration_thumb.png" border="0"></a></p>
<blockquote>
<p>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 <a title="http://stackoverflow.com/questions/35060821/visual-studio-2015-entity-framework-and-enable-migrations-error" href="http://stackoverflow.com/questions/35060821/visual-studio-2015-entity-framework-and-enable-migrations-error">http://stackoverflow.com/questions/35060821/visual-studio-2015-entity-framework-and-enable-migrations-error</a></p>
</blockquote>
<p>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:</p>
<p><code>add-migration "InitialCreate"</code></p>
<p>This will add an initial migration to your Data project. When you execute the following command:</p>
<p><code>update-database</code></p>
<p>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.</p>
<p>Next step is the <a href="http://puresourcecode.com/dotnet/post/Creating-a-URL-shortener-using-ASPNET-WepAPI-and-MVC-implementing-the-business-layer" target="_blank">implementation on business layer</a>.</p>http://puresourcecode.com/dotnet/dotnet/post/2016/01/28/Creating-a-URL-shortener-using-ASPNET-WepAPI-and-MVC
enrico.rossini.uk@live.comhttp://puresourcecode.com/dotnet/dotnet/post/2016/01/28/Creating-a-URL-shortener-using-ASPNET-WepAPI-and-MVC#commenthttp://puresourcecode.com/dotnet/post.aspx?id=e9fbad2a-87a9-40c3-82eb-b41c1e6dd1afThu, 28 Jan 2016 12:28:00 -0800ASP.NETC#JavaScriptMVCWebAPIshorturlunityentity frameworkjsonormhenryhttp://puresourcecode.com/dotnet/pingback.axdhttp://puresourcecode.com/dotnet/post.aspx?id=e9fbad2a-87a9-40c3-82eb-b41c1e6dd1af1http://puresourcecode.com/dotnet/trackback.axd?id=e9fbad2a-87a9-40c3-82eb-b41c1e6dd1afhttp://puresourcecode.com/dotnet/dotnet/post/2016/01/28/Creating-a-URL-shortener-using-ASPNET-WepAPI-and-MVC#commenthttp://puresourcecode.com/dotnet/syndication.axd?post=e9fbad2a-87a9-40c3-82eb-b41c1e6dd1afAutomatic Table of Contents<p>Any long page of content with distinct and well marked up content can benefit from a table to contents. A table of contents provides a quick way to jump down the page to the desired section. Of course you can create a table of contents manually, but it may be smart to build it dynamically on-the-fly with JavaScript. This is true for several reasons:</p> <ul> <li><strong>It's easier</strong> - write the JavaScript once and it can create the Table on Contents on every page you need it. </li> <li><strong>It's more reliable</strong> - the JavaScript isn't subject to authoring errors. </li> <li><strong>It's still accessible</strong> - A table of contents is good for the general concept of accessibility, but it is a bonus (not having it doesn't ruin the page) and nearly all screen readers run JavaScript. </li> </ul> <p>This kind of thing has been done many times and many ways. But this time is ours! Plus it makes for a good tutorial.</p> <h2>HTML: Headers and IDs</h2> <p>A long page of different parts you wish to link to could be marked up a bunch of ways. Perhaps a FAQ page could be a <code>&lt;dl&gt;</code>. It could literally be <code>&lt;section&gt;</code> after <code>&lt;section&gt;</code>. In our case, we'll assume this structure:</p> <pre class="brush: html;">&lt;article&gt;
&lt;h3 id=&quot;question-one&quot;&gt;Title of Question&lt;/h3&gt;
&lt;!-- whatever other content, probably some paragraphs and stuff. --&gt;
&lt;h3 id=&quot;question-two&quot;&gt;Another Question&lt;/h3&gt;
&lt;!-- whatever other content, probably some paragraphs and stuff. --&gt;
&lt;!-- etc --&gt;
&lt;/article&gt;</pre>
<br />
<p>A perfectly legit page full of headers with IDs and the content between them. Note the ID's. They are unique, as any good ID ought to be. This is required because it gives us a link target. </p>
<p>A link like this: </p>
<pre class="brush: html;">&lt;a href=&quot;#question-one&quot;&gt;Link to Question One&lt;/a&gt;</pre>
<br />
<p>Will jump down the page when clicked until the element with the ID &quot;question-one&quot; is in view. </p>
<h2>Building the Table of Contents with jQuery</h2>
<p>Our goal is to inject HTML on the page in the form of a table of contents. Like this: </p>
<pre class="brush: html;">&lt;nav role=&quot;navigation&quot; class=&quot;table-of-contents&quot;&gt;
&lt;h2&gt;On this page:&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#question-one&quot;&gt;Question One&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/nav&gt;</pre>
<br />
<h3>Step 1: A string of HTML</h3>
<p>We'll build this entirely dynamically. Perhaps it would be smart to use some kind of JavaScript templating for this. But hey, this is so simple, let's just build a big string and append that. </p>
<pre class="brush: js;">var ToC =
&quot;&lt;nav role='navigation' class='table-of-contents'&gt;&quot; +
&quot;&lt;h2&gt;On this page:&lt;/h2&gt;&quot; +
&quot;&lt;ul&gt;&quot;;</pre>
<br />
<h3>Step 2: Loop through the headers</h3>
<p>The &lt;h3&gt;'s on our page indicate each section we wish to link to, so we'll find them all with a jQuery selector, then loop through each of them. </p>
<pre class="brush: js;">$(&quot;article h3&quot;).each(function() {
// loop
});</pre>
<br />
<h3>Step 3: Get the bits of data we need</h3>
<p>We need 1) the text of each header, which we will turn into a link and 2) the ID of each header which we can turn into a href attribute for that link.</p>
<pre class="brush: js;">var el, title, link;
$(&quot;article h3&quot;).each(function() {
el = $(this);
title = el.text();
link = &quot;#&quot; + el.attr(&quot;id&quot;);
});</pre>
<p>Inside of that loop, &quot;this&quot; refers to the header element currently targeted, so to speak. we set &quot;el&quot; to a jQuery version of it, so we can use jQuery methods on it to extract that text and ID. </p>
<br />
<h3>Step 4: Create a new list item and append to string</h3>
<pre class="brush: js;">var newLine, el, title, link;
$(&quot;article h3&quot;).each(function() {
el = $(this);
title = el.text();
link = &quot;#&quot; + el.attr(&quot;id&quot;);
newLine =
&quot;&lt;li&gt;&quot; +
&quot;&lt;a href='&quot; + link + &quot;'&gt;&quot; +
title +
&quot;&lt;/a&gt;&quot; +
&quot;&lt;/li&gt;&quot;;
ToC += newLine;
});</pre>
<p>The &quot;+=&quot; there means &quot;append this new string to the already existing string stored in this variable.</p>
<br />
<h3>Step 5: Close the &quot;template&quot;</h3>
<pre class="brush: js;">ToC +=
&quot;&lt;/ul&gt;&quot; +
&quot;&lt;/nav&gt;&quot;;</pre>
<br />
<h3>Step 6: Inject HTML onto page</h3>
<p>Now you'll need to decide just exactly where you want this newly formed table to contents to be injected onto the page. Putting at the top of the page is probably smart. </p>
<p>Our example uses &lt;article&gt; to wrap everything, so to inject at the top of that, we would do: </p>
<pre class="brush: js;">$(&quot;article&quot;).prepend(ToC);</pre>
<br />
<p>In &quot;real life&quot;, perhaps you'd target a header and use insertAfter or another of jQuery's fancy DOM insertion methods. </p>
<p class="codepen" data-user="erossini" data-default-tab="result" data-slug-hash="RrPxqO" data-theme-id="0" data-height="268">See the Pen <a href="http://codepen.io/erossini/pen/RrPxqO/">Automatic Table of Contents</a> by Enrico (<a href="http://codepen.io/erossini">@erossini</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="//assets.codepen.io/assets/embed/ei.js"></script>http://puresourcecode.com/dotnet/dotnet/post/2015/12/10/Automatic-Table-of-Contents
enrico.rossini.uk@live.comhttp://puresourcecode.com/dotnet/dotnet/post/2015/12/10/Automatic-Table-of-Contents#commenthttp://puresourcecode.com/dotnet/post.aspx?id=c63fe156-eece-41a1-b3e9-6320102e6143Thu, 10 Dec 2015 11:46:41 -0800JavaScriptmenutochenryhttp://puresourcecode.com/dotnet/pingback.axdhttp://puresourcecode.com/dotnet/post.aspx?id=c63fe156-eece-41a1-b3e9-6320102e61430http://puresourcecode.com/dotnet/trackback.axd?id=c63fe156-eece-41a1-b3e9-6320102e6143http://puresourcecode.com/dotnet/dotnet/post/2015/12/10/Automatic-Table-of-Contents#commenthttp://puresourcecode.com/dotnet/syndication.axd?post=c63fe156-eece-41a1-b3e9-6320102e6143Write C#. Run JavaScript.<p><a href="http://puresourcecode.com/dotnet/image.axd?picture=BridgeNet.png"><img title="BridgeNet" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; float: none; padding-top: 0px; padding-left: 0px; margin: 0px auto; display: block; padding-right: 0px; border-top-width: 0px" border="0" alt="BridgeNet" src="http://puresourcecode.com/dotnet/image.axd?picture=BridgeNet_thumb.png" width="644" height="417" /></a></p> <p>Open Source C# to JavaScript Compiler and Frameworks. Run Your App On Any Device Using JavaScript.</p> <p>Use Bridge.NET to build platform independent applications for mobile, web and desktop. Run on <strong>iOS</strong>, <strong>Windows</strong>, <strong>Mac</strong>, <strong>Linux</strong> and billions of other devices with JavaScript support. Compile your C# code into native JavaScript and deploy on Billions of devices. </p> <p>Try it on <a href="http://bridge.net/">bridge.net</a> or fork it on <a href="https://github.com/bridgedotnet/Bridge">GitHub</a></p>http://puresourcecode.com/dotnet/dotnet/post/2015/10/20/Write-C-Run-JavaScript
enrico.rossini.uk@live.comhttp://puresourcecode.com/dotnet/dotnet/post/2015/10/20/Write-C-Run-JavaScript#commenthttp://puresourcecode.com/dotnet/post.aspx?id=77ff690c-3158-4364-8be8-f173f4fe40c2Tue, 20 Oct 2015 12:23:22 -0800C#JavaScriptframeworkiOSMacLinuxwindows10henryhttp://puresourcecode.com/dotnet/pingback.axdhttp://puresourcecode.com/dotnet/post.aspx?id=77ff690c-3158-4364-8be8-f173f4fe40c20http://puresourcecode.com/dotnet/trackback.axd?id=77ff690c-3158-4364-8be8-f173f4fe40c2http://puresourcecode.com/dotnet/dotnet/post/2015/10/20/Write-C-Run-JavaScript#commenthttp://puresourcecode.com/dotnet/syndication.axd?post=77ff690c-3158-4364-8be8-f173f4fe40c2