C# Tutorial for log4net

Here’s a short tutorial on how to use log4net in C# 1. Get log4net from the apache website or use NuGet to include in your project it   2. Add the Appender section to your app.config. The following code uses a file for the logging: <configuration> <configSections> <section name=”log4net” type=”log4net.Config.Log4NetConfigurationSectionHandler,Log4net”/> </configSections> <log4net> <root> <level value=”DEBUG” /> <appender-ref ref=”LogFileAppender” /> </root> <appender name=”LogFileAppender” type=”log4net.Appender.RollingFileAppender” > <param name=”File” value=”log-file.txt” /> <param name=”AppendToFile” value=”true” /> <rollingStyle value=”Size” /> <maxSizeRollBackups value=”10″ /> <maximumFileSize value=”10MB” /> <staticLogFileName value=”true” /> <layout type=”log4net.Layout.PatternLayout”> <param name=”ConversionPattern” value=”%date [%thread]…

Read More

C# Code Snippet – Download Image from URL

This .Net C# code snippet download image from URL. To use this function simply provide the URL of the image you like to download. This function read the image contents using URL and returns downloaded image as an image object. This function download image using web response stream. /// <summary>/// Function to download Image from website/// </summary>/// <param name=”_URL”>URL address to download image</param>/// <returns>Image</returns>public Image DownloadImage(string _URL){ Image _tmpImage = null; try { // Open a connection System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL); _HttpWebRequest.AllowWriteStreamBuffering = true; // You can also specify additional…

Read More

Check Local IP Address

This example shows how to detect whether a host name or IP address belongs to local computer. Get local computer name Get local computer host name using static method Dns.GetHostName. [C#] string localComputerName = Dns.GetHostName(); Get local IP address list Get list of computer IP addresses using static method Dns.GetHostAd­dresses. To get list of local IP addresses pass local computer name as a parameter to the method. [C#] IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName()); Check whether an IP address is local The following method checks if a given host name or IP…

Read More

Download Files from Web

This example shows how to download files from any website to local disk. The simply way how to download file is to use WebClient class and its method DownloadFile. This method has two parameters, first is the url of the file you want to download and the second parameter is path to local disk to which you want to save the file. Download File Synchronously The following code shows how to download file synchronously. This method blocks the main thread until the file is downloaded or an error occur (in…

Read More

ReportViewer: culture, number, color and more

Step 1. Set the “Language” report properties according to your regional requirements. In my case: “es-MX” Step 2. Use the respective Expression, im have: CDbl(Fields!SALE_PRICE.Value).ToString(“C”) When the report running you have before: and after Background Color If you want that the alternate row in a table will be other color, you have to click on the row on Background Color and insert the following expression: =IIF(RowNumber(“Statements”) Mod 2, “White”, “WhiteSmoke”) Change Language If you can change the language of a report it is necessary that you create a parameter (for…

Read More

Anonymous View Models in ASP.NET MVC Using Dynamics

The introduction of the dynamic keyword in C# 4.0 allows you to do a lot of things you couldn’t do otherwise, but it also makes it easy to forget that C# is still not a dynamic language, so there are limitations. Recently I found myself wanting to whip up a quick test page for something, with a very simple controller action and view. It wasn’t meant to be permanent, so creating a dedicated view model class in the project seemed like overkill. I figured I could just return an anonymous…

Read More

Why does Html.ActionLink render “?Length=4”

I’m VERY confused as to why this code Html.ActionLink(“About”, “About”, “Home”, new { hidefocus = “hidefocus” }) results in this link: <a hidefocus=”hidefocus” href=”/Home/About?Length=4″>About</a> The hidefocus part is what I was aiming to achieve, but where does the “?Length=4” come from? Solution The Length=4 is coming from an attempt to serialize a string object. Your code is running this ActionLink method: public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes) This takes a string object “Home” for routeValues, which the MVC plumbing searches for public…

Read More

Globalization and Localization of Model Validation Messages in MVC

In this quick article you will learn how to globalize and localize the model validation messages in MVC Applications. At the end of this article, you will also learn how to display the localized message (greeting) on the page. Here is what we will build.   I will use ASP.NET resource files to define the globalized (default) and localized strings and this string message will be displayed to the user based on the request header language that the client browser sends. Now, follow the steps from here. Step 1 To…

Read More

Export to Excel in Asp.Net MVC

We can render the data as a HTML table and then give the content type as application/excel. Excel renders HTML content in proper format. To convert the Data collection to HTML i’m making use of Asp.Net GridView here. Though this is not very Asp.Net MVC way of doing it this serves the purpose. you could write your own methods to convert the data to html format instead of the gridview here. Code Snippet [HttpGet] public void GetExcel() { reviewDataContext rdc = new reviewDataContext(); //Bind the Data to Asp.Net DataGrid -…

Read More

Writing Custom HTML Helpers for ASP.NET MVC

As a web forms developer, I found the transition to MVC to be a bit of a shock at first. Without fully understanding the nature of MVC, I found the lack of a Toolbox filled with server controls to be confusing. However, once it became clear that the goal of MVC was to expose HTML markup and give developers full control over what is rendered to the browser, I quickly embraced the idea. Transitioning from Web Forms In MVC development, HTML helpers replace the server control, but the similarities aren’t…

Read More

The Difference Between @Helpers and @Functions

This is another post which was inspired by a recent question in the ASP.NET forums, when someone asked what the difference is between @functions and @helpers in ASP.NET Web Pages. Here, I look at both of these contructs and explain what they are, how they are different, and how each should be used appropriately. Both @helpers and @functions do share one thing in common – they make code reuse a possibility within Web Pages. They also share another thing in common – they look the same at first glance, which…

Read More

ASP.NET MVC Controller for Serving Images

Introduction Working with images in a web application can turn from a simple task to a complexity in need of some serious attention as soon as traffic starts to grow or image assets become too vast to reasonably maintain multiple versions of each (large, medium, thumbnail). A general reference to an image in a HTML img tag does not provide a way to control caching or additional headers like the ETag to help site speed performance, nor does it provide a true way to handle resizing (the use of the…

Read More

Close window without the prompt message

If you tried to close a window using javascript window.close() method in IE7, and as you may noticed a message will prompt “The Webpage you are viewing is trying to close the window. Do you want to close this window”. Because of the security enhancements in IE7, you can’t close a window unless it is opened by a script. so the walkaround will be to let the browser thinks that this page is opened using a script then closing the window. below is the implementation. 1- Create a javascript function…

Read More

Creating Wizard in ASP.NET MVC only

At times you want to accept user input in your web applications by presenting them with a wizard driven user interface. A wizard driven user interface allows you to logically divide and group pieces of information so that user can fill them up easily in step-by-step manner. While creating a wizard is easy in ASP.NET Web Forms applications, you need to implement it yourself in ASP.NET MVC applications. There are more than one approaches to creating a wizard in ASP.NET MVC and this article shows one of them. In Part…

Read More

Creating a simple form wizard in ASP.NET MVC

UPDATE: As of jquery.validation version 1.8+ hidden input fields are not validated by default, which means that the wizard form is submitted without client-side validation being performed. The solution is to set the default back to validating everything in the JavaScript section by including the following line; $.validator.setDefaults({ ignore: “” }); I’ve also added a sample project at the bottom of this post.  For small MVC sample application I’m fiddling with on my spare time, I wanted to be able to split my form up in smaller parts, much like…

Read More

Implementing Role Based Menu in ASP.NET MVC

In default template of asp.net mvc 4.0, Layout.cshtml has following code for menu: <nav> <ul id=”menu”> <li>@Html.ActionLink(“Home”, “Index”, “Home”)</li> <li>@Html.ActionLink(“About”, “About”, “Home”)</li> <li>@Html.ActionLink(“Contact”, “Contact”, “Home”)</li> </ul></nav> Which is hard-coded for all users. We’ll create partial view for menu to reduce complexity. Right click on Shared folder in Views > select Add > click ViewEnter Name: _Menu and set “Create as a partial view” option true > click AddIt’ll open blank cshtml page. Define Menu Items: In normal asp.net webforms app, Sitemap file is used to define structure. Here we’ll define…

Read More

Difference Between ViewBag and ViewData in MVC

If you’re new to ASP.NET MVC, you might be wondering what these two things are and when to use each one. If you’ve been using MVC and are just new to version 3 of MVC, you are probably wondering what this new ViewBag is for and if it’s different from the ViewData you’ve been using. In the beginning of the Summer, I had the opportunity to explain this difference to the two NimblePros interns when they started working on ASP.NET MVC 3 for the first time. This post should serve…

Read More

SoapUI

SoapUI is a free and open source cross-platform Functional Testing solution. With an easy-to-use graphical interface, and enterprise-class features, SoapUI allows you to easily and rapidly create and execute automated functional, regression, compliance, and load tests. In a single test environment, SoapUI provides complete test coverage and supports all the standard protocols and technologies. There are simply no limits to what you can do with your tests. Meet SoapUI, the world’s most complete testing tool! Easy from the start Even if you’ve never used SoapUI before, you’ll find that creating…

Read More

Update to MVC 5.2

The error is: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from ‘System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ in the context ‘Default’ at location ‘C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll’. Type B originates from ‘System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ in the context ‘Default’ at location ‘C:\Users\e.rossini\AppData\Local\Temp\Temporary ASP.NET Files\root\55c43b6b\aa340995\assembly\dl3\a83c308f\965a638d_c896cf01\System.Web.WebPages.Razor.dll’. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from ‘System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ in…

Read More

Code First From Database’ Template not showing in Visual Studio Entity Data Model Wizard

According to Microsft in this article is should see an option ‘Code First From Database’ when adding a new item to the project under ‘ADO.NET Entity Data Model’ in step 3. Where is it the component for Code First like following picture? For installing in Visual Studio 2012 or 2013 this functions you can download the install for this link https://www.microsoft.com/en-us/download/details.aspx?id=40762

Read More

Extract detail from barcode on bollettini prefilled (Italy)

  namespace PSC{ public class Bollettini { public bool getCode(string strCode) { bool rtn = true; if (strCode.Length != 50) { return false; } int first = Convert.ToInt16(strCode.Substring(0, 2)); Bollettino = strCode.Substring(2, first); int second = Convert.ToInt16(strCode.Substring(first + 2, 2)); Contocorrente = strCode.Substring(first + 4, second); int third = Convert.ToInt16(strCode.Substring(first + second + 4, 2)); string tmp = strCode.Substring(first + second + 6, third); Importo = Convert.ToDecimal(tmp) / 100; int fouth = Convert.ToInt16(strCode.Substring(first + second + third + 6, 1)); Codice = strCode.Substring(first + second + third + 7, fouth);…

Read More

ASP.NET MVC 4 and Entity Framework Database Migrations

ASP.NET MVC 4 was released in beta by the Microsoft ASP.NET MVC Developer Team and it comes with a number of really cool features: Bundling and Minification Support of CSS and JavaScript, Database Migrations using Entity Framework 4.3, Web APIs, Mobile Web with support for jQuery Mobile, Real Time Communication via SignalR, and Asynchronous Support. The Database Migrations using Entity Framework Code-First is really cool and is very much like Rails where you can change your code and then via Package Manager add migrations and update your database as your…

Read More

How to programmatically hide the keyboard

I have a textbox with a button inside. When the user presses the Action, a progress bas is displayed, the screen goes dark, and some magic happens. My problem is that since the action doesn’t result in the textbox losing focus, the on-screen keyboard is not hidden, and keeps covering half the screen. Just set focus to the main page: this.Focus(); this will focus a control that doesn’t use the keyboard and thus hide the keyboard. Unfortunately there is no API to the keyboard to hide it.

Read More

Blogger C# API

using System;using System.Text;using Google.GData.Client;using System.Net;using System.Xml;using System.Text.RegularExpressions;namespace BloggerDevSample{ class ConsoleSample { /** Lists the user’s blogs. */ static void ListUserBlogs(Service service) { Console.WriteLine(“\nRetrieving a list of blogs”); FeedQuery query = new FeedQuery(); // Retrieving a list of blogs query.Uri = new Uri(“https://www.blogger.com/feeds/default/blogs”); AtomFeed feed = null; feed = service.Query(query); foreach (AtomEntry entry in feed.Entries) { Console.WriteLine(” Blog title: ” + entry.Title.Text); } } /** Lists the user’s blogs and returns the URI for posting new entries * to the blog which the user selected. */ static Uri SelectUserBlog(Service service) {…

Read More

How to add a new Blogger post with labels from C#

First download and install Google API from here:https://code.google.com/p/google-gdata/downloads/list Add a reference to “Google Data API Core Library”,and use the following function: public static bool AddPost(string title, string bodyHTML, string[] labels) {     Service service = new Service(“blogger”, “<program name>”);     service.Credentials = new GDataCredentials(“<username>”, “<password>”);     AtomEntry newPost = new AtomEntry();     newPost.Title.Text = title;     newPost.Content = new AtomContent();     newPost.Content.Content = bodyHTML;     newPost.Content.Type = “html”;     foreach (string label in labels)     {         AtomCategory cat = new AtomCategory();         cat.Scheme = new Uri(“https://www.blogger.com/atom/ns#”);         cat.Term =…

Read More