Skip to main content

Featured post

XM Cloud content sync from prod to uat or UAT to prod step by step

When working with Sitecore, it’s common to need content synchronization across environments. Today, I’ll walk you through the steps to sync content from Production to UAT/TEST and vice versa. Steps to Follow 1. Set Up Your Workspace Create a folder on your computer where you will manage the script files and exported data. Open the folder path in PowerShell to begin scripting. We need to run some scripts in PowerShell to update the folder with the basic requirements for syncing content. PS C:\Soft\ContentSync> dotnet new tool-manifest PS C:\Soft\ContentSync> dotnet nuget add source -n Sitecore https://nuget.sitecore.com/resources/v3/index.json PS C:\Soft\ContentSync> dotnet tool install Sitecore.CLI PS C:\Soft\ContentSync> dotnet sitecore cloud login If the above error occurs, you will need to run a different command to resolve the issue. PS C:\Soft\ContentSync> dotnet sitecore init now, Again run above command to open and authenticate with XM Cloud. It will be there a...

CRUD operation using MongoDB with asp.net mvc project


Insert, Delete and Update using MongoDB with ap.net mvc project.

In this article i am going to explain with example for user registration and login step by step.

Open your Visual Studio and create a project.

Add MongoDB driver in your project by using the following process.

Go to Tools > Library Package Manage > Manage Nugget manager for sultion.

It will open new window , search online MongoDB and install it in your project.

Now create a class in Model folder of project . Here , I have created User Class and added some properties.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Bson.Serialization.Attributes;

namespace M101DotNet.WebApp.Models
{
    public class User
    {

        [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
        public string Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }
          }
}

Now adding another class in this project which can connect with MongoDB

Here, I have created mongodbcontext  class to perform operation with MongoDB.

          using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using MongoDB.Driver;

namespace M101DotNet.WebApp.Models
{
    public class BlogContext
    {
        public const string CONNECTION_STRING_NAME = "Blog";
        public const string DATABASE_NAME = "blog";
        public const string POSTS_COLLECTION_NAME = "posts";
        public const string USERS_COLLECTION_NAME = "users";

        private static readonly IMongoClient _client;
        private static readonly IMongoDatabase _database;

        static BlogContext()
        {
            var connectionString = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_NAME].ConnectionString;
            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(DATABASE_NAME);
        }

        public IMongoClient Client
        {
            get { return _client; }
        }

        public IMongoCollection<User> Users
        {
            get { return _database.GetCollection<User>(USERS_COLLECTION_NAME); }
        }
    }
}

and finally, I have created AccountController in project please see below code which help you more understand  .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using MongoDB.Driver;
using M101DotNet.WebApp.Models;
using M101DotNet.WebApp.Models.Account;

namespace M101DotNet.WebApp.Controllers
{
    [AllowAnonymous]
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            var model = new LoginModel
            {
                ReturnUrl = returnUrl
            };

            return View(model);
        }

        [HttpPost]
        public async Task<ActionResult> Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var blogContext = new BlogContext();
            // XXX WORK HERE
            var user = await blogContext.Users.Find(x => x.Email == model.Email).SingleOrDefaultAsync();
            // fetch a user by the email in model.Email

            if (user == null)
            {
                ModelState.AddModelError("Email", "Email address has not been registered.");
                return View(model);
            }

            var identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, user.Name),
                    new Claim(ClaimTypes.Email, user.Email)
                },
                "ApplicationCookie");

            var context = Request.GetOwinContext();
            var authManager = context.Authentication;

            authManager.SignIn(identity);

            return Redirect(GetRedirectUrl(model.ReturnUrl));
        }

        [HttpPost]
        public ActionResult Logout()
        {
            var context = Request.GetOwinContext();
            var authManager = context.Authentication;

            authManager.SignOut("ApplicationCookie");
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult Register()
        {
            return View(new RegisterModel());
        }

        [HttpPost]
        public async Task<ActionResult> Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var blogContext = new BlogContext();
          
            var user = new User
            {
                Name = model.Name,
                Email = model.Email
            };
            await blogContext.Users.InsertOneAsync(user);
            // create a new user and insert it into the database

            return RedirectToAction("Index", "Home");
        }

        private string GetRedirectUrl(string returnUrl)
        {
            if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
            {
                return Url.Action("index", "home");
            }

            return returnUrl;
        }
    }
}





Comments

Popular posts from this blog

Socket Programming in Python

  Example of socket programing in python. Here's a simple example of socket programming in Python: Server Side Code import socket # Create a socket object serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Get local machine name host = socket.gethostname()                            port = 9999 # Bind to a port serversocket.bind((host, port))                                   # Listen to at most 1 connection at a time serversocket.listen(1) print("Server is ready to receive") while True:     # Establish a connection     clientsocket,addr = serversocket.accept()           print("Got a connection from", addr)     clientsocket.send(b"Thank you for connecting")     clientsocket.close() Client Side Code import socket # Create a socket obje...

Homework 3.3 MongoDB for DBAs

MongoDB Homework 3.3 for DBAs. She below image for the answer of homework 3.3.

How do I start learning on AI

To start learning AI, you can follow these steps: Choose a programming language: Python is the most popular language for AI and machine learning, but you can also use R or other languages. Get familiar with basic mathematics and statistics: You should have a basic understanding of linear algebra, calculus, and probability. Learn about artificial neural networks: Neural networks are the building blocks of deep learning and are essential to understanding AI. Get hands-on experience: The best way to learn AI is by working on projects. There are many online resources with tutorials and open-source projects to get you started. Participate in online communities: AI has a thriving online community where you can ask questions, share your work, and connect with others. Keep up with the latest developments: AI is a rapidly advancing field, and it's important to stay up-to-date with the latest developments and trends. Remember, learning AI requires time, effort, and practice, but it is a valu...

AngularJS Best Practice

Best Practice to write AngularJS Program code. This is very useful code to communicate with webApi or other any any services. You may learn here more about different services. var commonModule = angular.module('common', ['ngRoute']); var mainModule = angular.module('main', ['common']); commonModule.factory('viewModelHelper', function ($http, $q, $window, $location) { return MyApp.viewModelHelper($http, $q, $window, $location); }); commonModule.factory('validator', function () { return valJs.validator(); }); mainModule.controller("indexViewModel", function ($scope, $http, $q, $routeParams, $window, $location, viewModelHelper) { var self = this; $scope.sessionName = "ASP.NET MVC with Angular JS"; $scope.speakerName = "Shashi Keshar"; }); (function (myApp) { var viewModelHelper = function ($http, $q, $window, $location) { var self = this; self.modelIsValid = true...