Developing a REST Web Service using C# – A walkthrough

REST stands for Representational State Transfer. The term was introduced by Roy Fielding in his doctorial dissertation. REST is an architectural style for designing networked applications. It is an alternate to using complex mechanisms like COBRA, RPC, and SOAP to connect between client and server. REST makes communication between remote computers easy by using the simple HTTP protocol which support for CRUD (Create, Read, Update, and Delete) operations on the server. In a way, our World Wide Web is also based on the REST architecture. In a nutshell, REST is…

Read More

C# Extension Method

An extension method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class. Example First, here is a custom extension method defined in a program written in the C# language. Generally, you will want to store your extension method class in a separate source file, such as “ExtensionMethods.cs” in your project. Note:This file should store a static class with public static extension methods. Then: In the rest of your source code,…

Read More

How create a OFT file for HTML?

OFT file is a Outlook Template of an email. If you need to send a newsletter for example, it’s very useful to create this kind of file. The procedure to make a OFT file is very simple: build html file open the file in Internet Exlorer in IE open the menu (don’t use the icon!) File | Send | Page by e-mail Outlook opens a new email with the page click on File | Save As, click dropdown and select Outlook Template (*.oft), save to desired location

Read More

Reading multiple excel sheets with different worksheet names

I would like to know how I can read multiple excel worksheet with different worksheet name in c# and with the used of oledb. I have this existing way to read multiple sheets (but with fixed worksheet name):             DataSet ds = new DataSet();            var excelConnectionString = string.Format(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0”, path);            OleDbConnection connection = new OleDbConnection();            connection.ConnectionString = excelConnectionString;             var i = 1;            while (i <= 4)            {                string query = “SELECT * FROM [Sheet” + i + “$]”;                ds.Clear();                OleDbDataAdapter data = new OleDbDataAdapter(query, connection);                data.Fill(ds);                …

Read More

Download page from web with encoding

Usually you can use WebClient to download a page from web but no always it’s a good way, sometimes the page encode is different. With this code you can download without problems! #region ” Download page “public static string PageDownload(string url){    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);     using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())    {        byte[] buffer;         using (Stream s = resp.GetResponseStream())        {            buffer = ReadStream(s);        }         string pageEncoding = “”;        Encoding e = Encoding.UTF8;        if (resp.ContentEncoding != “”)            pageEncoding = resp.ContentEncoding;        else if (resp.CharacterSet != “”)            pageEncoding = resp.CharacterSet;        else…

Read More

What is the JavaScript Equivalent of print_r in PHP?

What is the JavaScript Equivalent of PHP print_r() function? In other words, how you can “print” a javascript object in a way that’s readable by humans? Code You could use JSON.stringify, as following: The HTML part Let’s create two links for demo: <p><a id=”print_demo” href=”javascript:void(0);”>Print object</a></p><p><a id=”pretty_print_demo” href=”javascript:void(0);”>Pretty Print object</a> The JAVASCRIPT part Remark: I use jQuery to handle events, but you can use plain javascript (if you prefer). <script type=”text/javascript”> $(function() { // create an object var person = new Object(); person.firstname = “John”; person.lastname = “Doe”; person.age =…

Read More

How to Detect Browser (and browser version) using JavaScript

Browser (and browser version) detection is an “all time classic” development requirement. jQuery.browser WAS an excellent solution, but it was removed in jQuery 1.9. Actually, it would be better to try to detect a browser feature instead of browser name itself, where possible. An ideal solution for this is Modernizr (a JavaScript library that detects HTML5 and CSS3 features in the user’s browser). But, if you still need to detect browser and browser version (using javascript), I suggest the following solutions (among many others): Bowser – A Browser detector and…

Read More

Render LocalReport using Microsoft ReportViewer DLL Version 11.0.3366.16

I downloaded the latest Microsoft ReportViewer from the link below and installed it. I want to be able to export (render) my Excel files in xlsx format. I’m referencing version 11.0.3366.16 of the following dll’s in my project… Microsoft.ReportViewer.CommonMicrosoft.ReportViewer.ProcessingObjectModelMicrosoft.ReportViewer.WinForms The download linkhttps://www.microsoft.com/en-us/download/details.aspx?id=35747 When specifying what you want your output to be, instead of sending WORD and EXCEL as the parameters for the output, send WORDOPENXML and EXCELOPENXML for the new office version. To verify what output your version of assemblies support, use <ReportObjec>.LocalReport.ListRenderingExtensions For example:RenderingExtension[] r = reportViewer.LocalReport.ListRenderingExtensions(); The complete…

Read More

Mime type for Microsoft Office 2007-2010

.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template.potx application/vnd.openxmlformats-officedocument.presentationml.template.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation.sldx application/vnd.openxmlformats-officedocument.presentationml.slide.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template.xlam application/vnd.ms-excel.addin.macroEnabled.12.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12

Read More

[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to… web.config issue

I have a problem like this on server [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=1.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_1.0.0.0__31bf3856ad364e35\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,…

Read More

IIS rewrite rules

This post describes some of the tips and tricks that one may find useful when solving URL-based problems for their web server or web site. Each tip/trick has a description of a problem and then an example of how it can be solved with IIS 7 URL Rewrite Module. 1. Add or Remove Trailing Slash Many web applications use “virtual URLs” – that is the URLs that do not directly map to the file and directory layout on web server’s file system. An example of such application may be an…

Read More

How to Enable XP_CMDSHELL using SP_CONFIGURE

In this tip we will take a look at the step to follow to enable or disable XP_CMDSHELL using SP_CONFIGURE system stored procedure. In order to use XP_CMDSHELL you need to be a system administrator. Read the following article which explains how to allow non-administrators to use XP_CMDSHELL. Error Message Received when XP_CMDSHELL is disabled You would end up getting the below mentioned error message when XP_CMDSHELL is disabled. Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure ‘sys.xp_cmdshell’ of component ‘xp_cmdshell’ because…

Read More

How to Disable XP_CMDSHELL using SP_CONFIGURE

It is always considered as a best practice to disable XP_CMDSHELL when not in use. A database administrator can disable XP_CMDSHELL using SP_CONFIGURE system stored procedure. To disable XP_CMDSHELL execute the below mentioned script. Use Master GO EXEC master.dbo.sp_configure ‘xp_cmdshell’, 0 RECONFIGURE WITH OVERRIDE GO EXEC master.dbo.sp_configure ‘show advanced options’, 0 RECONFIGURE WITH OVERRIDE GO

Read More

Evaluate an mathematical expression

public class MathEvaluator{ public static void Run() { Eval(“(1+2)”); Eval(“5*4/2”); Eval(“((3+5)-6)”); } public static void Eval(string input) { var ans = Evaluate(input); Console.WriteLine(input + ” = ” + ans); } public static double Evaluate(String input) { String expr = input.Substring(0,1) == “(” ? input : “(” + input + “)”; Stack<String> ops = new Stack<String>(); Stack<Double> vals = new Stack<Double>(); for (int i = 0; i < expr.Length; i++) { String s = expr.Substring(i, 1); if (s.Equals(“(“)){} else if (s.Equals(“+”)) ops.Push(s); else if (s.Equals(“-“)) ops.Push(s); else if (s.Equals(“*”)) ops.Push(s); else…

Read More

Using HTTP Methods for RESTful Services

The HTTP verbs comprise a major portion of our “uniform interface” constraint and provide us the action counterpart to the noun-based resource. The primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently. Of those less-frequent methods, OPTIONS and HEAD are used more often than others. Below is a table summarizing recommended return values of the primary…

Read More

To PUT or POST?

Create, Update and HTTP Idempotence For developers building REST-based APIs, there is a great deal of misinformation and some understandable confusion about when to use HTTP PUT and when to use HTTP POST. Some say, POST should be used to create a resource, and PUT to modify one. Others that PUT should be used to create, and POST to modify one. Neither is quite right. Often, developers think of each HTTP method as a 1:1 relationship with CRUD operations: CRUD       HTTPCreate      POSTRead         GETUpdate     PUTDelete      DELETE This can be true, with…

Read More

Setup FileZilla Server Passive Ports on Windows Server 2012

I prefer to use FileZilla FTP Server above the traditional IIS FTP module. FileZilla comes with a lite and lean GUI, great logging tools, connection (speed)limits and more. If you do not know FileZilla Server or the Filezilla Client I strongly encourage you to try them out at https://filezilla-project.org/ Setting up the FileZilla Server is straightforward, but after configuration the user/groups and directory you can have some trouble setting up the Windows Server 2012 Firewall. Traditional FTP uses port 21, you should open this on your Firewall (see below) but…

Read More

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