Archive

Posts Tagged ‘asp.net’

Debug Aspnet Core HTTP Error 502.5 – Process Failure


Today after upgrading an aspnet core 1.0 to 1.1 I was getting HTTP Error 502.5 – Process Failure

In your project web.config:

  • Enable stdoutLogEnabled (set it to true)
  • Set full path for stdoutLogFile and make sure that the “logs” folder already exists
  • Then hit F5

<aspNetCore
processPath="%LAUNCHER_PATH%"
arguments="%LAUNCHER_ARGS%"
stdoutLogEnabled="true"
stdoutLogFile="C:\logs\stdout"
forwardWindowsAuthToken="false"/>

In my stdout file I got the following error:

The specified framework ‘Microsoft.NETCore.App’, version ‘1.1.0’ was not found.

– Check application dependencies and target a framework version installed at:

C:\Program Files\dotnet\shared\Microsoft.NETCore.App

– The following versions are installed:

1.0.0-rc2-3002702

1.0.1

1.0.3

– Alternatively, install the framework version ‘1.1.0’.

I was under the impression that I had already installed version 1.1.0. But it seems that I installed 1.0.3 instead J It was 1:00 AM LOL

Here is the trick part. When you go to https://www.microsoft.com/net/download/core to download .NET Core, the default selected tab is LTS instead of Current

Select Current and download the latest version of .NET Core SDK

 

Categories: asp.net Tags: ,

Performance tip – Caching expiry in web applications


Caching data that rarely change can give you a big performance boost especially if it takes time to fetch and/or calculate that data. In .NET 4.0, Microsoft introduced the .NET Memory Cache which is a thread safe cache that can be used Windows and Web applications. For more information about the MemoryCache class you can visit https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx

While I was doing a load test for web application for one of my clients, I noticed that the Queued Requests performance counter goes up every five minutes. By using a code profiler, it showed that there were many calls to refresh some of the cached data. Taking a closer look at the code below, if user 1 executing line (value = service.GetStreets();) while the other users are checking if value is cached, there is a potential of thousands of requests to fetch the same data especially if that data is frequently used.

We were using a CacheWrapper that applies a cache policy based on the cache name. With the CacheWrapper we can write the code to cache the Street Streets as follows:


public List<Street> GetStreets()
{

var value = CacheWrapper.Get(CacheNames.Streets) as List<Street>;

if (value == null)
{

    value = service.GetStreet();
    CacheWrapper.Set(CacheNames.Streets, value);

}

return value;

}

My first approach was to use a lock and double check the value


bool StreetsDataInitialized = false;
Object StreetsLock = new Object();

public List<Street> GetStreets()
{

var value = CacheWrapper.Get(CacheNames.Streets) as List<Street>;

if (value == null)
{
StreetsDataInitialized = false;

lock (StreetsLock)
 {
 if (StreetsDataInitialized)
 {
    return CacheWrapper.Get(CacheNames.Streets) as List<Street>;
 }

 value = service.GetStreets();
 CacheWrapper.Set(CacheNames.Streets, value);
 StreetsDataInitialized = true;

}

}

return value;

}

But there were many values that need to be cached and refreshed and I didn’t want to create two variables per cached value. I came up with a more generic way to achieve my goal. I started with the CacheLock Class

 public class CacheLock
  {
     public bool Initialized { get; set; }
     public object LockObject = new object();

 }

I used the ConcurrentDictionary to store the locks. I also created a generic GetOrSetCacheValue function which gets or creates a CacheLock for each cached data and invoke “function” if the data is not cached.


Public class CacheableLookupProvider
{
private static ConcurrentDictionary<string, CacheLock> LockDictionary = new ConcurrentDictionary<string, CacheLock>();
private readonly IStreetsService service;

Public CacheableStreetsProvider(IStreetsService service)
{
    this.service = service;
}

 private T GetOrSetCachedValue<T>(string cacheName, Func<T> function) where T : class
 {
    var value = CacheWrapper.Get(cacheName) as T;
    if (value == null)
     {
       var lockObject = LockDictionary.GetOrAdd(cacheName, new CacheLock());
       lockObject.Initialized = false;
      
      lock (lockObject.LockObject)
       {
         if (lockObject.Initialized)
         {
           return CacheWrapper.Get(cacheName) as T;
         }
         value = function();
         CacheWrapper.Set(cacheName, value);
         lockObject.Initialized = true;
       }
    }
    return value;
 }

 public List<Street> GetStreets ()
 {
    return GetOrSetCachedValue(CacheNames.Streets, () => service.GetStreets());
 }

 public List<Province> GetProvinces ()
 {
   return GetOrSetCachedValue(CacheNames.Provinces, () => service. GetProvinces());
 }

}

Categories: asp.net Tags: , , ,

Replace JavaScript serializer in Kendo controls with NewtonSoft


I have been doing code optimization for an ASP MVC 5 application that uses the Telerik Kendo controls. Some of the search results may return 7000 records in this project. After I had replaced the serializer, it took 30% less time to load the search results page.

 

The ASP MVC Helpers for Kendo controls by default use the System.Web.Script.Serialization.JavaScriptSerializer which is slow compared to the NewtonSoft Json serializer. Telerik made it easy to replace the default serializer.

Steps:

  • Created a class that implements IJavaScriptSerializer and implement the Serialize method.
    public class CustomKendoJsonSerializer : IJavaScriptSerializer
    {
       public string Serialize(object value)
       {
          return JsonConvert.SerializeObject(value); //use the serializer you want  here
       }
     }
    
  • Create a class that implements JavaScriptInitializer and implement the CreateSerializer method
    
    public class CustomKendoInitializer : JavaScriptInitializer
    
    {
    
    public override IJavaScriptSerializer CreateSerializer()
    
    {
    
    return new CustomKendoJsonSerializer ();
    
    }
    
    }
    
    
  • In the Application_Start event in the Global.asax file, register the new serializer
Kendo.Mvc.Infrastructure.DI.Current.Register<IJavaScriptInitializer>(() => new CustomKendoInitializer());
Categories: .NET, asp.net, C# Tags: , ,

ASP MVC 5: ViewBag does not exist in the current context


After upgrading one of my client’s applications from ASP MVC 4 to ASP MVC 5, We had designers errors related to Html Helpers and ViewBag in cshtml pages.

To fix those issues make sure you do the following:
Install Asp.NET Web Helpers Library from Nuget
Open the Web.config of the project and update the bindings if they haven’t been updated when installing the Nuget packages for example

<dependentAssembly>
<assemblyIdentity name=”System.Web.Mvc” publicKeyToken=”31bf3856ad364e35″ />
<bindingRedirect oldVersion=”0.0.0.0-5.2.2.0″ newVersion=”5.2.2.0” />
</dependentAssembly>

 

Find “webpages:Version” in the appsettings and update it to version 3.0.0.0. My web.config had

<add key=”webpages:Version” value=”2.0.0.0″ />

and I updated it to

<add key=”webpages:Version” value=”3.0.0.0″ />

Restart Visual Studio and rebuild. You may have to delete the bin folder for your project

 

About Lajak Technologies

A consulting firm in Ottawa, Ontario that provides services related to Microsoft technologies, Team Foundation Server, DevOps practices, security and more. Contact us today to help you solving your complex software problems. Visit us at http://www.lajak.com.

Categories: asp.net Tags: ,

Read Authorization section from Web.config


In my current project, I had to read the find the Windows group for the ESB portal which can be found in the authorization section of the web.config for the ESB portal. I used the following code to read it:

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(“/Bam”, “Default web Site”);
var section = config.GetSection(“system.web/authorization”) as AuthorizationSection;

if (section == null)
{
    return string.Empty;
}

foreach (AuthorizationRule rule in section.Rules)
{
     if (rule.Action.ToString().ToLower() == “allow” && rule.Roles.Count > 0)
     {
        foreach (var item in rule.Roles)
        {
            if (item != “*”)
            {
                return rule.Roles[0];
            }
        }
    }
}
return string.Empty;

[/soucecode]

Categories: .NET, asp.net, C#, Tips Tags: , ,

ASP.NET Move Link Elements from the Body Element to Head


ASP.NET: Move Link Elements from the Body Element to Head

Today at a client site, we use a custom asp.net template and some 3rd party custom controls. to build the asp.net pages The custom template is a standard template by the company and we have to use it. Long story short, the template doesn’t initialize the Head property on the page. Hence when 3rd part custom controls finds that page.head ==null, it registers the webresources, as link elements, into the body of the page. Hence, the page fails xhtml strict validation check.

To fix that behaviour I wrote the following code:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim sbPageHtml As New StringBuilder
        'Get the html to be rendered
MyBase.Render(New HtmlTextWriter(New StringWriter(sbPageHtml)))
Dim strPagHtml = sbPageHtml.ToString()
'find the occurences of
Dim matches() As String = (From m As Match In Regex.Matches(strPagHtml, "*") _
Select m.Value).ToArray()
        'matches exist
        If matches.Length > 0 Then
'remove occurances from html
Dim toRenderPageHtml As String = Regex.Replace(strPagHtml, "*", "")
           'Write found link tags into the head tag
toRenderPageHtml = toRenderPageHtml.Replace("", String.Format("{0}", String.Join("", matches)))
            writer.Write(toRenderPageHtml)

        Else 'no matches found, no modifications required
writer.Write(strPagHtml)
        End If
    End Sub

If you can think of other solutions, feel free to post them in the comment section.

Categories: .NET, asp.net, VB Tags: , ,