Posts

Showing posts from March, 2018

How to send an e-mail via Google SMTP using C#

Image
First things first, some useful StackOverflow links: https://stackoverflow.com/questions/9201239/send-e-mail-via-smtp-using-c-sharp https://stackoverflow.com/questions/17462628/the-server-response-was-5-7-0-must-issue-a-starttls-command-first-i16sm1806350 To demonstrate how this is done I first create a new Visual Studio project: Some example code for sending an email via a Google email account (smtp.goolgle.com) - obviously replace this with email / credentials of your own... I put the code within a try-catch block in order to capture any errors that may occur while attempting this. [code language="csharp"] using System; using System.Net; using System.Net.Mail; namespace EmailSmtp { class Program { static void Main(string[] args) { try { // Credentials var credentials = new NetworkCredential("someEmail@gmail.com", "somePassword"); // Mail message var ...

How to enable SSL / Https in a Visual Studio Web Api project

Image
useful link is here: https://dotnetcodr.com/2015/09/18/how-to-enable-ssl-for-a-net-project-in-visual-studio/ Create a new Web Api project in Visual Studio: Select/click on the Web API project name in the solution explorer, and then click on the Properties tab. Set 'SSL Enabled' to true: The same properties window will also show the HTTPS url for the application. In the above example it’s https://localhost:44314/. Copy that URL and go to the project properties window. Navigate to the Web tab and override the Project Url property with the https address that you copied: Build and run the application. The likelihood is that a message appears in the browser saying that the localhost address is not trusted, you can continue to the website at your own risk. Here’s a Firefox example: The problem is that the certificate automatically installed by Visual Studio is untrusted. In the search programs and files, type 'mmc' (Microsoft Management Console):...

Creating a zip archive in C#

Image
StackOverflow link where I got this technique from is here: https://stackoverflow.com/questions/2454956/create-normal-zip-file-programmatically/ First create a new console application: Add references to System.IO.Compression and System.IO.Compression.FileSystem: Select a folder containing a set of files that you would like to archive. You could make this more sophisticated and create your own list of file paths, but I'm just keeping things simple for now: Here is the sample code I use to test the .NET compression library Program.cs [code language="csharp"] using System.IO; using System.IO.Compression; namespace ZipArchive { class Program { static void Main(string[] args) { var zipFile = @"C:\data\myzip.zip"; var files = Directory.GetFiles(@"c:\data"); using (var archive = ZipFile.Open(zipFile, ZipArchiveMode.Create)) { foreach (var fPath in files) ...

How to serialize and deserialize Json objects in C#

Image
A simple console app to demonstrate this. After creating your Visual Studio application, console or otherwise, make sure the System.Web.Extension reference is added: Suppose we have an object we wish to serialize/deserialize, such as an instance of this class: [code language="csharp"] public class Shared { public List<string> Emails { get; set; } public string Message { get; set; } public List<string> Ids { get; set; } } [/code] One possible way is to make use of the JavaScriptSerializer class. By the way, here is a useful StackOverflow link if you are having trouble finding JavaScriptSerializer in .NET 4.0: https://stackoverflow.com/questions/7000811/cannot-find-javascriptserializer-in-net-4-0 So that in this example, we not only instantiate our example class for serialization using JavaScriptSerializer, but deserialize it back into the original object as well: Console application code listing as follows: Program.cs [code language...

How to encrypt basic authentication credentials in a Web Api application

Image
This post shows you how to handle encrypted user credentials in a Web Api application and offer further security by enforcing https for all REST api calls. Step 1: Create a new Web Api application: This is our web service that will need to authenticate encrypted user credentials. Step 2: Add a class for handling encryption and decryption Crypto.cs [code language="csharp"] using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace WebApiEncrypt.Models { public static class Crypto { private const string PrivateKey = "<RSAKeyValue><Modulus>s6lpjspk+3o2GOK5TM7JySARhhxE5gB96e9XLSSRuWY2W9F951MfistKRzVtg0cjJTdSk5mnWAVHLfKOEqp8PszpJx9z4IaRCwQ937KJmn2/2VyjcUsCsor+fdbIHOiJpaxBlsuI9N++4MgF/jb0tOVudiUutDqqDut7rhrB/oc=</Modulus><Exponent>AQAB</Exponent><P>3J2+VWMVWcuLjjnLULe5TmSN7ts0n/TPJqe+bg9avuewu1rDsz+OBfP66/+rpYMs5+JolDceZSiOT+ACW2Neuw==</P><Q>0Ho...

Using basic authentication in a Web API application

Image
Some instructions on how to create implement basic authentication in a Web API application. Just follow what is shown in the steps and screenshots as shown: Step 1: Create a new ASP.NET Web application in Visual Studio: [caption id="attachment_8209" align="alignnone" width="826"] basic authentication in a Web API application[/caption] Step 2: Create a new authentication filter I have created a new folder with which to put any new filter classes: Create a new class called BasicAuthenticationAttribute. This needs to inherit from AuthorizationFilterAttribute. [code language="csharp"] using System; using System.Net; using System.Net.Http; using System.Security.Principal; using System.Text; using System.Threading; using System.Web.Http.Filters; namespace WebApiAuthenticate.Filters { public class BasicAuthenticationAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(HttpActionContext acti...

Using dependency injection in Web API applications using Unity

Image
Step 1: Create a new ASP.NET Web application Step 2: Install Unity through Nuget At the current time of writing the version used in the Package Manager Console was as follows: [code language="text"] PM> Install-Package Unity -Version 5.7.3 [/code] Step 3: Create a new repository We add this to the Model folder. When creating the controller in the constructor, We like to specify that we would like an interface to the repository – eg when we come to specify tests at a later stage, when don’t have to specify a specific repository, we can be much more de-coupled, but mainly to abstract it out for testing. In this example my 'repository' is just a property that returns a list of strings. IRepository.cs [code language="csharp"] using System.Collections.Generic; namespace WebApiDepInject.Models { public interface IRepository { IEnumerable<string> MyValues { get; set; } } } [/code] Repository.cs [code languag...

How to enforce Https in Web Api server applications

Image
See this post for creating simple Web Api application https://www.technical-recipes.com/2018/getting-started-with-creating-asp-net-web-api-services/ Step 1: Create new Web API project Step 2: Modify the Values controller Comment out [Authorize] requirement and add the [RequireHttps] requirement in ValuesController.cs ValuesController.cs. ValuesController.cs [code language="csharp"] using System.Collections.Generic; using System.Web.Http; namespace WebAppHttps.Controllers { [RequireHttps] public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/va...