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 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);
vals.Push(v);

count--;
}
}
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.

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       HTTP
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.

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.

Request:

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”
}

or

{
“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.


HTTP POST vs HTTP PUT


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.


Creates


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
{
…
}

Response:

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”
}

 


Updates


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
{
//FULL RESOURCE UPDATE
“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.

Tre stanze per un delitto: Il ritorno di Poirot

Tre stanze per un delitto - Agatha ChristieDopo l'ennesimo caso risolto, Hercule Poirot ha finalmente deciso di prendersi una vacanza. E visto che viaggiare è molto stancante, quale migliore destinazione di Londra stessa?

Così, senza dire nulla a nessuno, ha affittato una camera in una pensione cittadina, deciso a godersi il meritato riposo, al riparo dagli assalti di chi cerca il parere del detective più famoso del mondo. Ma se, per una volta, Poirot non insegue il mistero, è il mistero a inseguire lui. Una sera, mentre è seduto a un tavolo di un piccolo locale, intento a gustare un delizioso caffè, irrompe una donna, sconvolta.

Poirot le si avvicina, presentandosi come un poliziotto in pensione. La donna sembra spaventarsi ancora di più e gli chiede di assicurarle che non è più in servizio. Quando Poirot glielo conferma, lei gli confessa che sta per essere commesso un omicidio. La vittima è lei, e merita di essere uccisa. Per questo lui deve prometterle che non farà nulla per salvarla e non cercherà, successivamente, di trovare il colpevole. A quel punto la donna corre fuori dal locale e sparisce nella notte. Quanto c'è di vero in quel racconto?

E i tre omicidi commessi a Londra quella stessa sera sono collegati alle parole della donna? A trentanove anni dalla sua ultima apparizione letteraria, Hercule Poirot, il detective più famoso e amato del mondo, ritorna per risolvere tre delitti apparentemente inspiegabili. Per la prima volta gli eredi di Agatha Christie hanno autorizzato che il personaggio inventato dalla scrittrice britannica nel 1920 faccia la sua ricomparsa, interpretato dalla penna di una nuova autrice.

E la scrittrice chiamata a questo compito è Sophie Hannah, maestra inglese del thriller psicologico, i cui romanzi hanno venduto, nel solo Regno Unito, centinaia di migliaia di copie, vincendo numerosi premi e venendo tradotti in più di venti paesi. Il risultato è un romanzo straordinario, capace di dare vita, ancora una volta, al mito di Poirot, con il suo misto di ironia, mistero e strabilianti deduzioni.

Il libro invece lo puoi trovare qui.

Amazon provoca Apple: Kindle smartphone a 99 centesimi

Mentre il mondo freme per l’iPhone6, Jeff Bezos compete con la società di Cupertino a colpi di “sottocosto”. Il nuovo Fire Phone sarà disponibile a prezzo stracciato per chi sottoscrive un abbonamento con l’operatore telefonico AT&T.

Strano ma vero: Amazon provoca Apple e “svende” a 99 centesimi di dollaro il nuovo Fire Phone, prezzo riservato a chi sottoscrive un abbonamento con l’operatore telefonico AT&T. La notizia è arrivata un giorno prima del lancio mondiale di iPhone6, rilanciata da Il Sole 24 Ore.

Bezos, si sa, è noto per scelte radicali e innovative e la sua decisione di ribassare il prezzo di vendita del nuovo smartphone 3D ha suscitato critiche: c’è chi, come International Business Times, definisce la mossa un flop «necessario per spingere le vendite di un dispositivo che sta facendo fatica a trovare spazio sul mercato: poche caratteristiche interessanti per l’utente e disponibilità limitata».

Fire Phone, infatti, ha avuto un’accoglienza fredda nel mercato americano, in trepidante attesa del rivale iPhone6 della Apple. I motivi? il prezzo di vendita di 199 dollari ritenuto eccessivo in un mercato competitivo come quello degli Usa, le funzionalità “noiose” per i consumatori sempre più esigenti e la disponibilità limitata.

Nonostante ciò il nuovo smartphone, capace di riconoscere (e far comprare) oggetti come riviste, film e opere d’arte grazie alla funzionalità Firefly, sarà lanciato nel mercato europeo a prezzi low cost. In Inghilterra, ad esempio, arriverà il 30 settembre a 33 sterline al mese con abbonamento a Telefonica O2, invece in Germania a 49,95 euro mensili con l’abbonamento all’operatore Deutsche Telekom.

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

NuGet-Log4Net 

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] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>



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

static void Main()
{
log4net.Config.XmlConfigurator.Configure();
...
}



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;

try
{
// 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
_WebResponse.Close();
_WebResponse.Close();
}
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
_Image.Save(@"C:\SampleImage.jpg");
}

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 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 / 127.0.0.1).

[C#]
public static bool IsLocalIpAddress(string host)
{
try
{ // 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:

[C#]
IsLocalIpAddress("localhost");        // true (loopback name)
IsLocalIpAddress("127.0.0.1"); // true (loopback IP)
IsLocalIpAddress("MyNotebook"); // true (my computer name)
IsLocalIpAddress("192.168.0.1"); // true (my IP)
IsLocalIpAddress("NonExistingName"); // false (non existing computer name)
IsLocalIpAddress("99.0.0.1"); // 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).

[C#]
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.

[C#]
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.

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  September 2017  >>
MonTueWedThuFriSatSun
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

View posts in large calendar

Month List