Dailycode.info

Short solution for short problems

AngularJS and .Net WEB.API: 405 (Method Not Allowed) for PUT and DELETE

I was having some problems with put and deletes. When I ran the code on the localhost, no problem, but after installing on the servers, delete calls were giving CORS errors. I tried to figure out what was going on, but I lost some time. First I rewrote the methods to POST methods, this worked. But when a new occasion came to look for a better solution I found it here.

The thing is that DELETE and PUT are sending a OPTION request first to the API on the server. If this method is not there, then it will not work. The error message will not really point you into the right direction. 

But instead of adding the OPTION methods foreach DELETE or PUT you could also disable WebDAV in IIS. That really does the trick. No code changes needed, just a simple configuration.

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule"/>
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

And thatis it.

No more of these now:



AngularJS and Windows authentication

We are starting up several Anguar JS (in typescript) projects with an .Net WebAPI2 background. This is really an pleasure to work with, it's like playing with lego when you're 10 years old. Keep building and inventing new things.

One of the things that all applications require is security. Inside our application we can use windows authentication. To set this up was really easy, that is, to set it up for simple GET requests. But with POSTS it gets more tricky. Ruben Biesemans from SPIKES explains this in details here: 

How to implement Windows Authentication in an AngularJS application with a stand-alone Web API

Hope this will help solving this nasty preflight errors. 


Tech: My Techorama 2015 review

1.           ASP.NET 5

1.           ASP.NET 5

A session on the new ASP.NET 5. A lot of overlapping information. New features of visual studio 2015. This session also confirms that WEB API is the way to go in the future.

Here is a summary of the foundational improvements:

  • New light-weight and modular HTTP request pipeline
  • Ability to host on IIS or self-host in your own process
    • Showed in the session, you can host is from command line on USB stick.
  • Built on .NET Core, which supports true side-by-side app versioning
  • Ships entirely as NuGet packages
    • Not part of the System.Web.dll anymore.
  • Integrated support for creating and using NuGet packages
  • Single aligned web stack for Web UI and Web APIs
  • Cloud-ready environment-based configuration
  • Built-in support for dependency injection
  • New tooling that simplifies modern Web development
  • Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
  • Open source and community focused

 

2.           The internet of your things (Iot)

Mainly about Azure and the capabilities to host applications on Azure. Interesting was the table storage. You can create a table service where different types of data can be stored in 1 table. It’s a no SQL datastore. This is ideal for storing structured non relational data.

Link to this:

https://azure.microsoft.com/en-gb/documentation/articles/storage-dotnet-how-to-use-tables/

 

3.           How to live longer and happier with Visual Studio 2015

This session was about the new features of Visual Studio 2015.

You can see that a lot of resharper functionality is now default in VS 2015.

Also integration with a BOWER, Gulp and Grunt are used very frequenly. For packages like AngularJS, bower is better than NuGet.

http://www.dotnetcurry.com/visualstudio/1096/using-grunt-gulp-bower-visual-studio-2013-2015

 

 

4.           EF7, Who are You and What Have You Done With My ORM?

Julie Lerman who gave the session is an expert on EF. She wrote books and gives trainings about it. Her conclusion in regard with the silver bullet key note is that the best way to go for the future is:

-       Keep using EF 6.0 in existing projects.

-       Start using EF 7.0 in new projects.

EF7 is a complete makeover of the entity framework. Since the start of EF they continued on the same code base. For EF7 they restarted completely from the beginning, to make it more light weight and also to tackle some challenges that were not possible to take with the old code base.

 

5.           "Write once, run anywhere”: Can AngularJS & Cordova do it?

This was definitely my favorite session. Christian Weyer explained in 1 hour and 30 min the complete lifecycle of a modern app that has 1 code base but can be published in any device!

 

He is co-owner of thinktecture that tackle very large implementations using .Net back-end, HTML5 and Javascript to code once, deploy anywhere.

 

Their code base is EF --> .Net WEB API --> AngularJS.

Using Cordova they can deploy the code to native iOS, Android and Windows Phone.

Then the AngularJS is also available in any browser and can even be build to native Apps for Windows and Mac OS.

 

6.           "It's alive!": Real-time applications with ASP.NET SignalR and AngularJS

Again a great session by Christian Weyer. SignalR is definitely something to look into. Very brief it’s a way to let the server communicate to the clients. E.g. when some data is updated and the clients need to refresh without the user having to click on a refresh button.

More info:

http://signalr.net/

 

7.           HTML 5 Security

This session was mainly about CORS and ways that javascript could inject bad code. If setup the code in the correct way, you could prevent this.

 

8.           Aurelia Deep Dive

This session was about an alternative to AngularJS. Another javascript framework. The demo were not impressive, some failed. I do not believe in Aurelia, since the community behind it is not comparable with AngularJS.

 

9.           Domain Driven Design for the Database Driven-Mind

Another view on application architecture. This looks promising, but at the moment not feasible because lack of knowledge and high impact on development. Also we are in a process of change that first need to be advanced.

 

10.        The Engaging User Experience & the Natural User Interface

Key note about user experience. Not very interesting. Talking a lot about xbox Kinect and face recognition.

 

11.        Chrome developer tools

Here is a good summery made by one of the attendees:

The Console tab

It’s probably safe to assume that you all know and use the Console Tab of Google Chrome to write your debug statements and evaluate JavaScript expressions. Most of the time we do that by using “console.log” statement which writes your logging messages to the console. If you are using a lot of those “console.log” statements in your code then things can quickly get messy and it will become difficult to work through your logs to find the one line you actually need.

To organize your statements you can use “console.groupCollapsed” and “console.groupEnd”. These functions will create a collapsable group in the log window so you can find your debug lines faster.


If you want to measure how fast your code is executing you can use “console.time” and “console.timeEnd”. This can also prove quite handy when you want to benchmark certain functions.


Device Emulation

The Device Emulator enables you to test out your website on several devices (phones, tablets, computers…) and on different network speeds (4G, 3G, GPRS…). This makes it very easy to test out your responsive design. The emulator even supports touch events!

You can enable/disable it by toggling the device icon Chrome Dev Tools - Mobile Iconin your Dev Tools.


The Network tab

The Network tab is used to monitor the performance of your application and helps you identify slow loading resources. It includes detailed timing data, HTTP request and response headers, cookies…

A very useful feature of the Network tab is that you can download its contents to a .HAR file. This could help us debug the “unreproducible bugs” reported by a QA Engineer. If he’s doing his tests with the Network tab opened he can just send the failed requests to a developer to investigate. All he has to do is right-click the network table and select “Save as HAR with Content”. This will download a .HAR-file that can be read using a tool called Chrome HAR Viewer.

Quick tips

Inline editing

To enable inline editing just open up the console and type “document.body.contentEditable = true” and press ENTER. You can now modify any text on your page by just typing into the browser window. If you have to build a multilingual application you can use this to easily test what would happen if the text in your title or menu items would be translated (and thus be longer or shorter than intended by the designer).

Blackbox scripting

You all know that you can debug javascript code by adding breakpoints to your code in the “sources tab”. Very often this tab includes a lot of scripts that you don’t care about (external libraries etc.). You can prevent the debugger from breaking in those scripts by “blackboxing” them. Just right-click on the file and select “Blackbox Script”. You can stop blackboxing a script by right-clicking the same file and selecting “stop blackboxing”.

Styling log statements

You can add CSS styling to your “console.log” statements. This can prove useful if you want something to stand out if it occurs.


Conclusion

Please note that this blogpost is just a high level overview of useful and time saving features that were presented by Shay Friedman (@ironshay) at Techorama. The Google Chrome dev tools contain a lot more functionality than what can be covered here. If you are curious to learn more or want to read on about the topics covered in this post you can visit https://developer.chrome.com/devtools.

 

12.        Decomposing AngularJS

This was an interesting session that gave a deeper view of how the AngularJS binding works. He actually created a fresh JavaScript Framework from scratch (using code blocks and copy paste) that bound model to the view.

 

13.        EF7 demo demo demo

This was a replacing session were Julie showed EF 7 in combination with ASP.NET 5 in action.


.Net WebAPI: add time zone suffix to datetime in JSON

On iOS, my JSON formatter needed to have the UTC format for date times. But My .Net WebAPI by default just formatted the date like this:

"timeStamp":"2015-01-04T00:00:00"

now just by adding these lines to the WebApiConfig.cs:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;

the date times got the correct format:

"timeStamp":"2015-01-04T00:00:00Z"


.Net WebAPI: A potentially dangerous Request.Path value was detected from the client (:).

Ever got this error?

A potentially dangerous Request.Path value was detected from the client (:).

I was trying to give a datetime in the url as parameter to a REST service. but when I used data time, the following error occurred.

http://localhost/Users/GetPlanForDate/2015-1-5%2008:00

First I changed the route, making the date a querystring.

http://localhost/Users/GetPlanForDate?date=2015-1-5%2008:00

This worked fine, but then I would have to change to many routes. So finally the solution came up.

I could just remove the ':' as potentially dangerous sign. The can be done in the web.config of your project:

Change this line:

<httpRuntime targetFramework="4.5" />

into this:

<httpRuntime targetFramework="4.5" requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,\,?" />

Now the time using the ':' will be passed to your web api.

Some functions have the datetime as first parameter, but have more following, like this:

http://localhost/Users/GetPlanForDate/2015-1-5%2008:00/1

So in this case it's nice that you can use the Route parameters for datetime.

[Route("Users/GetPlanForDate/{date}/{shift}")]

public GalvaSFIMobileDataLayer.GP_MES_ShiftPlans GetPlanForDate(DateTime date, int shift)

{

            //GetMESHeaders(OperationContext.Current);

            return PL.GetPlanForDate(date, shift);

}


AngularJS - WebAPI: No 'Access-Control-Allow-Origin'

Got this error: XMLHttpRequest cannot load http://localhost:777/api/products/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:777' is therefore not allowed access. The response had HTTP status code 405.

It was not so easy to sfind out what the problem was, but then it had something to do with enabling cross origin requests. When you are developing WebAPI back end that is not on the same uri as the front end angular JS site, it could be that you have this error. I even got it on my local host, using different ports for the 2 sites. Simple solution, which will help to secure the WebAPI.

You will first have to allow the cros origin requests in your WebApiconfig.cs:

config.EnableCors();

If VS gives problems, then use the nuget package manager to add this


Then first add this code to the WebApiConfig:

config.EnableCors();

And then you will have to allow ip to connect to your webapi in your controllers like this:

// GET: api/Products/Mark  
[EnableCors("http://localhost:778","*","*")] 
public List<Product> GetProduct()
You can also allow all methods in your API by putting the EnableCors attribute above the class:

using System.Web.Http.Cors;

namespace MyProject.Controllers

{

    [EnableCors("http://localhost:778", "*", "*")]

    public class UsersController : ApiController