Sunday, February 2, 2020

Forms Authentication in MVC

index.cshtml

@using (Html.BeginForm("index","home",FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <span>Enter Name</span>
    <input type="text" name="name"  required />

    <input type="submit"  value="Submit" />

}

HomeController.cs
        

        using System.Web.Security;

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(FormCollection formCollection)
        {

            if (ModelState.IsValid)
            {
                  var authTicket = new FormsAuthenticationTicket(
                    1,// version
                    formCollection["name"].ToString(), // user name
                    DateTime.Now, // created
                    DateTime.Now.AddMinutes(20), // expires
                    false,  // persistent?
                    "User"  // can be used to store roles
                    );

                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);         

                return RedirectToAction("about");

            }
            else
            {
                return View();
            }
        }

      
 [Authorize(Roles ="User")]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

       
[Authorize]
        public ActionResult logout()
        {

            FormsAuthentication.SignOut();
            return RedirectToAction("index");      
       
        }


Inside the Global.asax.cs


using System.Security.Principal;
using System.Web.Security;

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie == null || authCookie.Value == "")
                return;

            FormsAuthenticationTicket authTicket;

            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch
            {
                return;
            }

            // retrieve roles from UserData
            string[] roles = authTicket.UserData.Split(';');

            if (Context.User != null)
                Context.User = new GenericPrincipal(Context.User.Identity, roles);

        }




Inside the web.config


  <authentication mode="Forms" >
    <forms defaultUrl="home/index" loginUrl="home/index"  protection="All"></forms>
  </authentication>

  <authorization>
    <allow users="*"/>
    <deny users="?"/>
  </authorization>

Saturday, December 7, 2019

Deploy Django application on XAMPP apache Server (Windows)

Below are the steps to deploy the Django application on XAMPP apache server.

Assuming that you have already downloaded and installed the following.




  • After copying the file from the folder rename it with mod_wsgi.so and paste the file where the XAMPP server is installed on your system inside the modules.


  • Make change in the httpd.conf file



  • Add the below line in httpd.conf


  • Create a Django project inside the htdocs folder.

  • After completion of the project when ready to deploy once again open the httpd.conf and add few more lines of code.




  • After add the above lines of code then restart the system and run the XAMPP server to check 



Sunday, November 17, 2019

Excluding fields in MongoDB using Asp.net



using MongoDB.Bson;
using MongoDB.Driver;                             
          
static MongoClient client = new MongoClient("mongodb://localhost:27017"); //Set the connection string

static IMongoDatabase db = client.GetDatabase("test"); //Database name

public void Exclude()
{
   IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("user");

   var filter = Builders<BsonDocument>.Filter.Empty;   

 // uncomment the below two lines to exclude the required things

// var project = Builders<BsonDocument>.Projection.Exclude("_id"); //replace the field which you want to exclude in place of _id and it must match the field name in the MongoDB document

//var res = collection.Find<BsonDocument>(filter).Project(project).ToList();

    var res = collection.Find(filter).ToList(); //Comment this after un commenting the above two line

}

Before excluding _id field

After 



Saturday, November 16, 2019

Delete record from MongoDB using Asp.net



using MongoDB.Bson;
using MongoDB.Driver;   
                                    
static MongoClient client = new MongoClient("mongodb://localhost:27017"); //Set the connection string

static IMongoDatabase db = client.GetDatabase("test"); //Database name

public void DeleteOne(string id)
{
   IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("user"); //table name

   var filter = Builders<BsonDocument>.Filter.Eq("_id",  BsonObjectId.Parse(id)); //Need to parse else you will get the error

   var res = collection.Find(filter).ToList();
 
   collection.DeleteOne(filter);
}

Filter record in MongoDB using Asp.net


using MongoDB.Bson;
using MongoDB.Driver;              
                         
static MongoClient client = new MongoClient("mongodb://localhost:27017"); //Set the connection string

static IMongoDatabase db = client.GetDatabase("test"); //Database name

public void ListOne(string age)
 {
    IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("user");

    var filter = Builders<BsonDocument>.Filter.Eq("age", age);

    var res = collection.Find(filter).ToList();

 }

Get records from MongoDB using Asp.net.

To get the records from MongoDB using Asp.net.

using MongoDB.Bson;
using MongoDB.Driver;         
                              
static MongoClient client = new MongoClient("mongodb://localhost:27017"); //Set the connection string

static IMongoDatabase db = client.GetDatabase("test"); //Database name
     
 public void List()
  {

    IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("user"); //table name

    var filter = Builders<BsonDocument>.Filter.Empty; //It behaves like select * from user

    var res = collection.Find(filter).ToList();
              
 }

Insert a record into MongoDB using Asp.net.


Below code shows how to insert a record into MongoDB using Asp.net.

First install the MongoDB driver from the nuget package manager.



using MongoDB.Bson;

using MongoDB.Driver; 

static MongoClient client = new MongoClient("mongodb://localhost:27017");//Set the connection string

        
static IMongoDatabase db = client.GetDatabase("test"); //Database name 


        public void InsertCollection()
        {
            BsonDocument doc = new BsonDocument  //Create BSON document object
            {
            { "name" , "me" },
            {"age" , "99"},
            {"addr" , new BsonDocument { {"pin" , "1234"} , {"state","unknown"} }}
            };

          IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("user"); //Table name

            collection.InsertOne(doc);

        }

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...