Evaluate an mathematical expression

public class MathEvaluator
public static void Run()

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 if (s.Equals("/")) ops.Push(s);
else if (s.Equals("sqrt")) ops.Push(s);
else if (s.Equals(")"))
int count = ops.Count;
while (count > 0)
String op = ops.Pop();
double v = vals.Pop();
if (op.Equals("+")) v = vals.Pop() + v;
else if (op.Equals("-")) v = vals.Pop() - v;
else if (op.Equals("*")) v = vals.Pop()*v;
else if (op.Equals("/")) v = vals.Pop()/v;
else if (op.Equals("sqrt")) v = Math.Sqrt(v);

else vals.Push(Double.Parse(s));
return vals.Pop();

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 HTTP methods in combination with the resource URIs:

HTTP Verb Entire Collection (e.g. /customers) Specific Item (e.g. /customers/{id})
GET 200 (OK), list of customers. Use pagination, sorting and filtering to navigate big lists. 200 (OK), single customer. 404 (Not Found), if ID not found or invalid.
PUT 404 (Not Found), unless you want to update/replace every resource in the entire collection. 200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
POST 201 (Created), 'Location' header with link to /customers/{id} containing new ID. 404 (Not Found).
DELETE 404 (Not Found), unless you want to delete the whole collection—not often desirable. 200 (OK). 404 (Not Found), if ID not found or invalid.


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:

Create      POST
Read         GET
Update     PUT
Delete      DELETE

This can be true, with GET and DELETE specifically, but when it comes to which HTTP methods should be associated with create and update, the answer comes down to idempotency.


Idempotence is an important concept in the HTTP specification that states idemptotent HTTP requests will result in the same state on the server no matter how many times that same request is executed. GET, HEAD, PUT, and DELETE all have this attribute, but POST does not.

To help illustrate idempotency, we will use an Account collection (“/accounts) and for brevity we will say that each account resource has three properties called givenName, surname, and status.

Let’s say you submit an update request using the HTTP PUT method. In the body, you set givenName a value of “John” and surname a value of “Smith”. Later, you submit another request HTTP PUT request, this time setting givenName to “Johnny”. Is this idempotent? No. Why? Because other requests might have changed the server state of the account resource in between our two requests. For instance, between the two requests, status could have been changed to “blocked.” Our example request cannot guarantee that the state of the account on the server is identical when it is repeated.


HTTP/1.1 PUT /accounts/abcdef1234
“givenName”: “John”,
“surname”: “Smith”

Possible account state after our two requests (due to side effects from other requests):

“givenName”: “John”,
“surname”: “Smith”,
“status”: “enabled”


“givenName”: “John”,
“surname”: “Smith”,
"status”: “disabled”

To quote Dino Chiesa, “PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing.” With PUT requests you MUST send all the available properties/values, not just the ones you want to change. If we were to send the status of “disabled” in addition to the givenName and surname, the call would be idempotent and eliminate the side effects. Idempotency is a fundamental property of the HTTP specification and must be adhered to to guarantee web interoperability and scale.

Finally, we should point out that HTTP idempotency only applies to server state – not client state.  For example, a client could send a server-idempotent request successfully, and then send that same exact server-idempotent request immediately again and experience an error (e.g. perhaps due to a constraint violation in the server) and this is totally ‘legal’ for HTTP.  As long as the requests result in the same identical state on the server, HTTP idempotency is maintained.


Now that idempotency is clear, which method should you use when performing create and update operations? The following is a quick reference for when it is appropriate to use each method.


Use POST to create resources when you do not know the resource identifier. With POST creates, it is best practice to return the status of “201 Created” and the location of the newly created resource, since its location was unknown at the time of submission.  This allows the client to access the new resource later if they need to.

HTTP/1.1 POST /accounts


201 Created
Location: https://api.puresourcecode.com/accounts/abcdef1234

Use PUT when you allow the client to specify the resource identifier of the newly created resource.  But remember, since PUT is idempotent, you must send all possible values.

HTTP/1.1 PUT /accounts/abcdef1234

“givenName”: “John”,
“surname”: “Smith”,
“status”: “enabled”



You can use POST to send either all available values or just a subset of available values:

HTTP/1.1 POST /accounts/abcdef1234
“status”: “disabled”
Response 200 OK

If you want to use PUT to update a resource, it must be a full resource update; you MUST send all attribute values in a PUT request to guarantee idempotency.

Use PUT when you want or need to send all available values in order to follow idempotency requirements, for instance in the case of a full resource update. I

HTTP/1.1 PUT /accounts/abcdef1234
“givenName”: “J”,
“surname”: “Smith”,
“status”: “Enabled”

You can also use POST to send all values as well and the server state could be the same as a full PUT – it’s just not required to be by the HTTP specification. Note that idempotency has a strong correlation to being cacheable by HTTP caching servers, and therefore POST requests are generally not cached. If you are ok with this caching side effect, you can use POST for both full and partial updates.

POST is currently the only non-idempotent method. The HTTP specification is very generic about it, and basically states it to be a ‘server processing directive’. This means it is ‘safe’ to do whatever you want during a POST request.

Finally, we should note that there is another method that has not been finalized for the HTTP specification yet, called PATCH. PATCH is meant to be used as an alternative to POST for partial updates. However, since POST can already simply handle partial updates, there doesn’t seem to be a strong movement for PATCH to be finalized and approved quickly by the HTTP specification committee. If approved, PATCH would join POST as the only other non-idempotent HTTP method.

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 even after opening up this port some errors can rise to the occasion when using passive ftp.

I had the following problem:

Response:   227 Entering Passive Mode
Command: LIST
Error: Connection timed out
Error: Failed to retrieve directory listing

When port 21 is configurated in the Firewall, and you have setup the users/groups in the FileZilla Server setup you still can encounter the problem above. By default the FTP client will connect through passive mode, and opens a random port between 1-65535. Now this is a wide range and I do not recommend opening all these ports. Instead you can limit the range of these ports to let's say: 50100-51100.

So lets do this, configure FileZilla Server Passive Port Range:

  1. Open up the FileZilla GUI on your server.
  2. Click on the top menu Edit -> Settings.
  3. From the tree menu click on Passive mode settings.
  4. Now make sure the checkbox Use custom port range is checked and enter 50100 in the first box a and 51100 in the second.
  5. Click OK

Now that you have finished setting up the custom port we can move forward to the Windows Server 2012 Firewall.

Configurating the Firewall

Lets open up the Firewall panel, press the Windows key on your keyboard and start typing firewall. The result should be Windows Firewall with advanced.... Click it or hit enter.
(Pro tip ;-) hit Windows Key + R -> firewall.cpl -> hit enter)

  1. From the tree, select Inbound Rules.
  2. In the right panel, click New Rule.
  3. A windows pops up, select Port and click next.
  4. Make sure TCP is selected, and enter 50100-51100 in the Specific local ports field.
  5. Hit Next and make sure the Allow connection option is selected. Then hit Next again.
  6. Select the zones where this rule need to be applied (in my case I have selected all the zones).
  7. Click Next and give this rule a recognizable name: Passive FTP Ports - FileZilla.
  8. Click on Finish, and your done.

In case you have not yet added port 21 to the Firewall you can use the same steps, but instead of using port 50100-51100 just use port 21.

When connecting to your FTP Server the result now should be:

Response:   227 Entering Passive Mode
Command: LIST
Response: 150 Connection accepted
Response: 226 Transfer OK
Status: Received file listing

PS: this solution is ok such for 425 Can't open data connection for transfer

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:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<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] %-5level %logger [%property{NDC}] - %message%newline" />

3. Use the following code to use the configuration you just added to app.config:

static void Main()

4. To log use the following code:

using log4net;

private static readonly ILog log = LogManager.GetLogger(typeof(YourClassOrApp));
log.Debug("this is the first log message");

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;

// Open a connection
System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

_HttpWebRequest.AllowWriteStreamBuffering = true;

// You can also specify additional header values like the user agent or the referer: (Optional)
_HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
_HttpWebRequest.Referer = "http://www.google.com/";

// set timeout for 20 seconds (Optional)
_HttpWebRequest.Timeout = 20000;

// Request response:
System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

// Open data stream:
System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

// convert webstream to image
_tmpImage = Image.FromStream(_WebStream);

// Cleanup
catch (Exception _Exception)
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
return null;

return _tmpImage;

Here is a simple example showing how to use above function (DownloadImage) to download image and show it in a PictureBox and how to save it on a local disk.

// Download web image
Image _Image = null;
_Image = DownloadImage("http://www.yourdomain.com/sample-image.jpg");

// check for valid image
if (_Image != null)
// show image in picturebox
pictureBox1.Image = _Image;

// lets save image to disk

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.

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.

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

Check whether an IP address is local

The following method checks if a given host name or IP address is local. First, it gets all IP addresses of the given host, then it gets all IP addresses of the local computer and finally it compares both lists. If any host IP equals to any of local IPs, the host is a local IP. It also checks whether the host is a loopback address (localhost /

public static bool IsLocalIpAddress(string host)
{ // get host IP addresses
IPAddress[] hostIPs = Dns.GetHostAddresses(host);
// get local IP addresses
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

// test if any host IP equals to any local IP or to localhost
foreach (IPAddress hostIP in hostIPs)
// is localhost
if (IPAddress.IsLoopback(hostIP)) return true;
// is local address
foreach (IPAddress localIP in localIPs)
if (hostIP.Equals(localIP)) return true;
catch { }
return false;

You can test the method for example like this:

IsLocalIpAddress("localhost");        // true (loopback name)
IsLocalIpAddress(""); // true (loopback IP)
IsLocalIpAddress("MyNotebook"); // true (my computer name)
IsLocalIpAddress(""); // true (my IP)
IsLocalIpAddress("NonExistingName"); // false (non existing computer name)
IsLocalIpAddress(""); // false (non existing IP in my net)

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 this case the WebException is thrown).

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");

Download File Asynchronously

To download file without blocking the main thread use asynchronous method DownloadFileA­sync. You can also set event handlers to show progress and to detect that the file is downloaded.

private void btnDownload_Click(object sender, EventArgs e)
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), @"c:\myfile.txt");

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
progressBar.Value = e.ProgressPercentage;

private void Completed(object sender, AsyncCompletedEventArgs e)
MessageBox.Show("Download completed!");

Note: Although you use asynchronous method, it can block the main thread for a while. It's because before the async download itself, it checks the DNS name (in this case „mysite.com“) and this check is done internally by blocking function. If you use directly IP instead of domain name, the DownloadFileAsync method will be fully asynchronous.