Tuesday, November 7, 2017

Create Log in c#

We can easliy create log by using File.AppendAllText() method because by using this method, it is guaranteed that the file handle will be closed, even if exceptions are raised.
1
2
3
4
5
6
7
public static class Logger
{
    public static void Log(string message)
    {
        File.AppendAllText("C:\\LogFile.txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ":\t" + message + Environment.NewLine);
    }
}

Monday, June 12, 2017

Access control to MongoDB

Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator.
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment.
use test
db.createUser(
  {
    user: "myTester",
    pwd: "xyz123",
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"

Monday, February 27, 2017

ASP.NET Web API Service Cross Domain Using AJAX

JSONP
JSONP is a JSON with padding. While accessing the data, using AJAX call, we cannot access the data cross-domain because of security reasons. JSONP is used to access the data in the cross domain. JSON returns a JSON-formatted object only. JSONP returns a JSON-formatted object, which is wrapped inside a function call. The example given below differentiates it for JSON and JSONP.
JSON format 
  1. {  
  2.     “Id”             :  “1”,  
  3.         “Name”     :  “Vignesh”,  
  4.     “Address”: “India”,  
  5. }   
JSONP format 
  1. callbackFunction ({  
  2.     “Id”             :  “1”,  
  3.         “Name”     :  “Vignesh”,  
  4.     “Address”: “India”,  
  5. })   
Steps to create cross-origin or cross domain
Step 1
This step is a continuation of previous part of the article. Please find the links given below for first part of the article.
Step 2
Remove the HTML page in our solution files. Now, add a new project in the same solution. Right click on the Solution Explorer, go to “Add” and click new project.

Step 3
Now, select The Web. Under Web, select ASP.NET Web Application in Add New Project Windows and give the project name. Finally, click OK.


Now “New ASP.NET Project - Customers” Window will open. Now, select Web Forms and click OK. Afterwards, add the new project in the solution. We can see the two projects in the single solution.


Step 4
Now, right click on Customer project adds “Customer.html” page in Customers project. Now, copy the same code from “WebAPIsameDomain” project “Customers.html” page and paste it to “Customer” project “Customers.html” page.

Step 5
Now, build our solutions and run ASP.NET Web API Service and Customers.html page. We can see the different port number. The screenshot given below shows it differently.
http://localhost:49352/api/Demo - ASP.NET Web API URL.


http://localhost:52273/Customers.html - Web Page URL.


After building our solution and running “http://localhost:49352/api/Demo” for ASP.NET Web API and running “http://localhost:52273/Customers.html” for our Web page, now click Get button but we don't get any result because of the security problem in cross-origin.
ASP.NET Web API Service returns JSON format data. It is not supported in the cross domain because of the security issue. If we go to developer tool, we can see the error. The error is “XMLHttpRequest cannot load http://localhost:49352/api/Demo. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:52273' is therefore not allowed access.”


To fix this security issue, we need to use JSONP in AJAX, so that ASP.NET Web API Service returns JSONP format. First, enable JSONP in our “Customers” project.
Step 6
We need to install JSONP package in our solution. Go TOOLS àNuGet Package Manager à Manage NuGet Packages for Solutions. We can see it looks like the screenshot given below.

Step 7
After opening Manage NuGet Packages Window, type “JSONP” in the search box, search it. Now, we can get the “WebApiContrib.Formatting.Jsonp” package and click the install button. Read the description columns and one can learn about the package.

After clicking install, it will open Select Project Window, which looks, as shown below. Now, click the check box in which the project needs this package and click OK. Afterwards, click OK and then click I accept button and after some moments; it will be installed. Finally, close Manage NuGet Packages Window.

Step 8
Go to the “WebAPIsameDomain” and go to the “App_Start” folder, followed by going to the “WebApiConfig.cs” file. Now, write the code mentioned below to enable JSONP format in Register method. The code given below is used to convert JSON to JSONP format.
We are using “JsonpMediaTypeFormatter” class, which is used to convert JSON to JSONP. It's namespace is “WebApiContrib.Formatting.Jsonp”.

Code to convert JSONP 
  1. Using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using Microsoft.Owin.Security.OAuth;  
  7. using Newtonsoft.Json.Serialization;  
  8. using WebApiContrib.Formatting.Jsonp;  
  9.   
  10. namespace WebAPIsameDomain  
  11. {  
  12.     public static class WebApiConfig  
  13.     {  
  14.         public static void Register(HttpConfiguration config)  
  15.         {  
  16.             // Web API configuration and services  
  17.             // Configure Web API to use only bearer token authentication.  
  18.             config.SuppressDefaultHostAuthentication();  
  19.             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));  
  20.   
  21.             // Web API routes  
  22.             config.MapHttpAttributeRoutes();  
  23.   
  24.             config.Routes.MapHttpRoute(  
  25.                 name: "DefaultApi",  
  26.                 routeTemplate: "api/{controller}/{id}",  
  27.                 defaults: new { id = RouteParameter.Optional }  
  28.             );  
  29.   
  30.             var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);  
  31.             config.Formatters.Insert(0,jsonpFormatter);  
  32.         }  
  33.     }  
  34. }   
Step 9
Now, go to HTML page and change the data type from JSON to JSONP, which looks, as shown below.


Now build and run the project we get the correct output which looks like the below screenshot.

We are calling ASP.NET Web API Service from http://localhost:49352/api/Demo to http://localhost:52273/Customers.html Web Application. Here, we can see the different port numbers in the URL. It is called cross-origin. If it uses a different domain, like calling ASP.NET Web API Service from http://testAPI.com/api/Demo to http://test.com/Customers.html Web Application is called cross domain.
Conclusion
This article explained about calling ASP.NET Web API in the cross-origin, using AJAX by following some steps. This helps new learners and developers. This article and previous parts of the article clearly explain about the same and cross-origin in ASP.NET Web API.