Store Dictionary object in config file

I found lots of solutions to solve this problem but I didn’t like many of them.
In this link I found THE solution:
http://stackoverflow.com/questions/338242/how-do-i-store-a-dictionary-object-in-my-web-config-file

To avoid to lose it in the future I’ve reported it as well:

<configuration>
  <configSections>
    <section 
      name="MyDictionary" 
      type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <MyDictionary>
     <add key="name1" value="value1" />
     <add key="name2" value="value2" />
     <add key="name3" value="value3" />
     <add key="name4" value="value4" />
  </MyDictionary>
</configuration>

How to use it:

using System.Collections.Specialized;
using System.Configuration;

public string GetName1()
{
    NameValueCollection section =
        (NameValueCollection)ConfigurationManager.GetSection("MyDictionary");
    return section["name1"];
}
Pubblicato in c# | Lascia un commento

POST Ajax and redirect file response to the browser

Yesterday a collegue of mine had a problem:
How post an ajax form and redirect the file result to the browser.
If you post a form to an handler that response with a file the result will be downloaded by your browser.
But how can we achive this behaviour via ajax?
We looked for a solution and we found something but not completed.
My collegue worked on this and here his result.
It’s written in javascript and not using jquery because jquery has some problems managing bynary response

function getFileFromHTTPRequest(modelForm, fileGenAction) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', fileGenAction, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            var type = xhr.getResponseHeader('Content-Type');

            var blob = new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location = downloadUrl;
                }

                setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
            }
        } else if (this.status === 400)
            alert("The query returns too many elements, please select some filters.");
        else
            alert("Can’t download the file. Error code: " + this.status);
    };
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(modelForm.serialize());
}

How to use it by javascript

function getScreenElements() {
    getFileFromHTTPRequest($(".form-inline"), '@Url.Action("GetScreenElements")');
}

Here a sample of C# code to handle the request and response an excel file

[HttpPost]
public ActionResult GetScreenElements(SearchModel vm)
{
    using (var db = new EFContext())
    {
        var count = db.GetElementsCount(vm.Parameter1, vm.Parameter2...);
        if (count &gt; 30000)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
        var items = db.GetElements(vm.Parameter1, vm.Parameter2...).ToList();
        using (MemoryStream ms = new MemoryStream())
        {
            var dtt = ConvertToDataTable(items);
            var wb = new XLWorkbook();
            wb.Worksheets.Add(dtt, "Elements");
            wb.SaveAs(ms);
            return File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "Element List.xlsx");
        }
    }
}

#region Helper
private DataTable ConvertToDataTable(IList data)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    foreach (PropertyDescriptor prop in properties)
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    foreach (T item in data)
    {
        DataRow row = table.NewRow();
        foreach (PropertyDescriptor prop in properties)
            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
        table.Rows.Add(row);
    }
    table.AcceptChanges();
    return table;
}
#endregion
Pubblicato in .Net, Asp.Net, c#, MVC | Contrassegnato , , | Lascia un commento

Optimize Entity Framework performance

This wouldn’t be a complete article on how to improve EF performance but only a little reminder.
Every time you have performance problem on updating or adding entity these properties will help you.

public void SetOptimization()
{
    // this flag produce a huge performance change improvement
    this.Configuration.AutoDetectChangesEnabled = false;
    // turn off this flag increase little performance so my suggestion is do not turn it off
    this.Configuration.ValidateOnSaveEnabled = false; // I usually use it turned on
}

You can find a lot of articles about these properties so I suggest reading more in detailed article.
This is only a remind every time I forget the right properties’ names

Pubblicato in .Net, Entity Framework | Lascia un commento

Bootstrap tools

I’m working with boostrap and before doing my work I usually create mockups about what I would realyze.
In the past I used pencil and paper, after that I bought a laptop with touchscreen, so now I use one note do draw and share my mockups.
When everything is ok I create a mockup for customers, and if have to work with bootstrap I found a great tool to achieve that:
Pingendo

It’s free and it works very well! It permits to create sample sites wasting little time.
The only drawback is that I can’t extend the tool by adding custom components. As workaround you can use some txt files with the html code of your custom components.
Currently they are working on the version compatible with bootstrap 4.

In addition, I suggest having a look to this site:
bootsnipp.com

There are a lot of code snippets to use in a fast way.
I don’t like the site search beacuse founds too many results, but using google search you can find great example.
To do this you have to write this in google:
WhatYouNeed site:http://bootsnipp.com/

Pubblicato in Bootstrap | Contrassegnato , , , , , | Lascia un commento

Exam Simulator VCE dumps free

I’m currently studying to pass exam certifications and I’ve already read 2 books.
Now the question is: how can I do same exercises to check my level?
In order to do that I have found some sites where you can download .vce file.
A .vce file is a file that contains questions and answers and could be opened from VCE Exam Simulator, a program that to be installed on your local pc.
Here some sites where you can download that file:

After downloading the vce files, how can you use them?
You can buy VCE Exam Simulator or you can use A+ VCE Player for Android.

But if you would like to use vce files on your PC (without buying VCE Exam Simulator) below you can find the right steps:

  1. Download and install Bluestacks (Android emulator free)
  2. Download and install A+ VCE (after you have installed Bluestacks double click .apk file)
  3. Copy yours .vce files to folder “C:\Users\YOUR_ACCOUNT\Pictures\Saved Pictures”
  4. Open Bluestacks
  5. Open A+ VCE
    1. Click Add File
    2. Go to path “/storage/sdcard/windows/Pictures/Saved Pictures”
    3. Select the file you want to import

Here are some videos I used to write this guide (same videos have more steps like connect with your google account and download other apps from the play store)
https://www.youtube.com/watch?v=zLMLfly3xi8
https://www.youtube.com/watch?v=DG41krt1Fok

Now the only thing i need is to do a lot of tests, hoping to get the exam certification😉

Pubblicato in Uncategorized | Contrassegnato , , , , , , | Lascia un commento

Multiple content type

Today I’ve worked on a generic handler that recovers file from else where, than it sends the file to client browser.

When you write a generic handler it is important to specify the contentType before complete the response.
There are many mime type availables:
image/png, text/plain etc.

But if you don’t know which mime type use I suggest you to use this one:

context.Response.ContentType = "application/octet-stream"
Pubblicato in .Net, HTML5 | Lascia un commento

HTTP Error 404.3-Not Found

Some times ago I got this error using IIS:

HTTP Error 404.3-Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is script, add a handler. If the file should be downloaded, add a MIME map.

I looked for a solution on Internet and I found this:
You should install IIS sub components from
Control Panel -> Programs and Features -> Turn Windows features on or off
Internet Information Services has subsection World Wide Web Services / Application Development Features
There you must check ASP.NET (.NET Extensibility, ISAPI Extensions, ISAPI Filters will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.

This happen when you install Visual Studio before IIS; in this case you need only to run the command regiis

Pubblicato in Uncategorized | Contrassegnato , , | Lascia un commento