0%

I’ve created a MVC 4 Web API Application inside my solution, but I changed nuget package default location. So I’m getting 2 errors right now.

‘System.Web.Http.HttpConfiguration’ does not contain a definition for ‘MapHttpAttributeRoutes’ and no extension method ‘MapHttpAttributeRoutes’ accepting a first argument of type ‘System.Web.Http.HttpConfiguration’ could be found (are you missing a using directive or an assembly reference?)

A forced reinstall of WebAPI could do the job:

update-package microsoft.aspnet.webapi -reinstall -project yourProject

The following example demonstrates the use Strong type, JObject, Dynamic different approaches to deal with JSON serialization / deserialization.

1
2
3
4
5
6
7
public class Food
{
public DateTime d { get; set; }
public int n { get; set; }
public string s { get; set; }
public int[] a { get; set; }
}

Lab1:Using Strong Type to deserialize

1
Food f = JsonConvert.DeserializeObject<Food>(jsonString);

Lab2:Using JObject to deserialize

1
2
3
4
5
6
JObject jo = JObject.Parse(jsonString);
DateTime d = jo.Property("d").Value.Value<DateTime>();
int n = jo["n"].Value<int>();
string s = jo["s"].Value<string>();
int[] ary = jo["a"].Value<JArray>()
.Select(o => o.Value<int>()).ToArray();

Lab3:Using Dynamic to deserialize

1
2
3
4
5
6
7
JObject jo = JObject.Parse(jsonString);
dynamic dyna = jo as dynamic;

DateTime d = dyna.d;
int n = dyna.n;
string s = dyna.s;
var ary = ((JArray)jo["a"]).Cast<dynamic>().ToArray();

Deserialize Performance: Lab2 > Lab1 ~= Lab2

Lab4:Using Strong Type to serialize

1
2
3
4
5
6
7
8
Food f = new Food()
{
d = new DateTime(2015, 1, 1),
n = 12345,
s = "MR-Brain",
a = new int[] { 1, 2, 3, 4, 5 }
};
string json = JsonConvert.SerializeObject(f);

Lab5:Using JObject to serialize

1
2
3
4
5
6
JObject jo = new JObject();
jo.Add(new JProperty("d", new DateTime(2015, 1, 1)));
jo.Add(new JProperty("n", 12345));
jo.Add(new JProperty("s", "MR-Brain"));
jo.Add(new JProperty("a", new JArray(1, 2, 3, 4, 5)));
string json = jo.ToString(Formatting.None);

Lab6:Using Dynamic to serialize

1
2
3
4
5
6
dynamic dyna = new JObject();
dyna.d = new DateTime(2015, 1, 1);
dyna.n = 12345;
dyna.s = "MR-Brain";
dyna.a = new JArray(1, 2, 3, 4, 5);
string json = dyna.ToString(Formatting.None);

Serialize Performance: Lab5 > Lab4 > Lab6

Nuget version 2.1

There is now official documentation on how to control the package locations. The release notes for 2.1 specifies the following configuration in a nuget.config file.

Please modify NuGet.config file in

1
C:\Users\MrBrain\AppData\Roaming\NuGet\NuGet.Config

and add following

1
2
3
4
5
6
<configuration>
<config>
<add key="repositoryPath" value="C:\thePathToMyPackagesFolder" ></add>
</config>
...
</configuration>

Restart VS.NET 2013, NuGet will place packages in the new location.

PowerShell says “execution of scripts is disabled on this system.”

Jenkins powershell plugin is running 32 bit Powershell

1
2
64-bit:  C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
32-bit: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

you can run following

1
2
3
4
5
6
7
> C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
PS C:\hoge > Set-ExecutionPolicy RemoteSigned
PS C:\hoge > exit

> C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
PS C:\hoge > Set-ExecutionPolicy RemoteSigned
PS C:\hoge > exit

Or you can

1
2
3
set-executionpolicy -executionpolicy unrestricted
set-executionpolicy -executionpolicy -Scope LocalMachine unrestricted
get-executionpolicy -list

Other Information

powershell.exe -executionpolicy unrestricted -command .\test.ps1

You can’t really do EnableInterfaceInterceptors globally.

But you can add the interceptors dynamically and it requires a little work. The way to go is to create a custom Autofac.Module that attaches to all component registrations. I’ll show it to you in an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class InterceptorModule : Autofac.Module
{
// This is a private constant from the Autofac.Extras.DynamicProxy2 assembly
// that is needed to "poke" interceptors into registrations.
const string InterceptorsPropertyName = "Autofac.Extras.DynamicProxy2.RegistrationExtensions.InterceptorsPropertyName";

protected override void Load(ContainerBuilder builder)
{
// Register global interceptors here.
builder.Register(c => new CallLogger(Console.Out));
}

protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
{
// Here is where you define your "global interceptor list"
var interceptorServices = new Service[] {
new TypedService(typeof(CallLogger))
};

// Append the global interceptors to any existing list, or create a new interceptor
// list if none are specified. Note this info will only be used by registrations
// that are set to have interceptors enabled. It'll be ignored by others.
object existing;
if (registration.Metadata.TryGetValue(InterceptorsPropertyName, out existing))
{
registration.Metadata[InterceptorsPropertyName] =
((IEnumerable<Service>)existing).Concat(interceptorServices).Distinct();
}
else
{
registration.Metadata.Add(InterceptorsPropertyName, interceptorServices);
}
}
}

To make it work, you register the module along with the rest of your dependencies.

1
2
3
4
5
6
builder.RegisterType<YourType>()
.As<YourIInterface>()
.EnableInterfaceInterceptors();
// Here's the magic module:
builder.RegisterModule<InterceptorModule>();
var container = builder.Build();

If you run these registrations and resolve, You can see the interceptor works as you’ll see the CallLogger output.

If you’ve worked with ASP.NET for any length of time, you have worried about how to handle the Yellow Screen of Death. You know, the one that says:

1
HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client...

or something similar.

The common refrain is turn off request validation, but there are times when you want to use the built-in validation functions. You just want a friendlier error for your user.

This code could be better thought out, but here it is anyway:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError();
if (ex is HttpRequestValidationException)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
"http://" + Request.Url.Authority + Request.ApplicationPath + "/HttpRequestValidationException.aspx");
HttpWebResponse response = (HttpWebResponse)req.GetResponse();

Response.Clear();
Response.ClearHeaders();
for (int i = 0; i < response.Headers.Count; i++)
Response.AddHeader(response.Headers.GetKey(i), response.Headers.Get(i));
Response.StatusCode = (int)response.StatusCode;

System.IO.Stream src = response.GetResponseStream();
while (true) {
int b = src.ReadByte();
if (b == -1) break;
Response.OutputStream.WriteByte((byte)b);
}

response.Close();
Response.End();
}

We can add the pre-build event for each of the project that require the packages.config

1
2
cd $(ProjectDir)
nuget restore -source http://www.nuget.org/api/v2/ -packagesdirectory ../packages

What if you have custom package sources?
All you need to do is create a NuGet.Config file next to your .sln file, containing:

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />
<add key="aspnetwebstacknightlyrelease" value="https://www.myget.org/f/aspnetwebstacknightlyrelease/" />
</packageSources>
</configuration>

Note that if you have private package sources that you want to keep out of your repo, you can add them to

1
%APPDATA%\NuGet\Nuget.config (see this page) for details.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public static class ControlExtension
{
public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
if (uiElement == null) {
throw new ArgumentNullException("uiElement");
}

if (uiElement.InvokeRequired) {
if (forceSynchronous) {
uiElement.Invoke((Action)delegate
{
SafeInvoke(uiElement, updater, forceSynchronous);
});
}
else {
uiElement.BeginInvoke((Action)delegate
{
SafeInvoke(uiElement, updater, forceSynchronous);
});
}
}
else {
if (uiElement.IsDisposed) {
throw new ObjectDisposedException("Control is already disposed.");
}
updater();
}
}
}

InspectMode

Web Essentials adds a number of other great Browser Link extensions that are available through the Web Essentials toolbar. Download Web Essentials to try out these great new features.

Inspect Mode – Allows you to highlight an element in the browser and the corresponding code will be highlighted in Visual Studio.

Design Mode – Allows you to edit the content of an element in the browser and the corresponding code will be updated in Visual Studio. This even works if the HTML was generated by Razor code!

Track Unused CSS – Enters a CSS tracking mode that helps you find unused CSS.

Enabling Browser Link for Static HTML Files
To enable Browser Link for static HTML files, add the following to your Web.config file.

<configuration>
  <system.webServer>
    <handlers>
      <add name="Browser Link for HTML" path="*.html" verb="*"
           type="System.Web.StaticFileHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
           resourceType="File" preCondition="integratedMode" />
    </handlers>
  </system.webServer>
</configuration>

Document reference url from microsoft

In JavaScript’s Date type, after JSON.stringify() will return ISO-8601 format (yyyy-MM-ddTHH: mm: ss.fffZ); interestingly, the JSON.parse() return a string, and not restored to the original Date type.

ISO-8601 format will revert back to the Date of demand, to achieve through JSON.parse() function of Reviver. Examples are as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var dateReviver = function (key, value) {
var a;
if (typeof value === 'string') {
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
}
a = /^\/Date\((.*?)\)\/$/.exec(value);
if (a) {
return new Date(parseInt(a[1]));
}
}
return value;
};

We can invoke it as following:

1
2
3
4
5
var strJson = "\"2014-12-25T07:27:13.851Z\"";
var result = JSON.parse(strJson, dateReviver);

strJson = "\""/Date(1330444800000)/\"";
result = JSON.parse(strJson, dateReviver);