Friday 28 December 2018

How to handle multiple submit button in MVC

There are 3 steps to follow for this:

Step1: Create a class in your application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace PocA2019.Attributes
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class MultipleButtonAttribute : ActionNameSelectorAttribute
    {
        public string Name { get; set; }
        public string Argument { get; set; }

        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            var isValidName = false;
            var keyValue = string.Format("{0}:{1}", Name, Argument);
            var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

            if (value != null)
            {
                controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
                isValidName = true;
            }

            return isValidName;
        }
    }
}

Step2: Add 2 method save and cancel
using System.Web.Mvc;

namespace PocA2019.Controllers
{
    public class HomeController : Controller
    {
     
        [HttpPost]
        [MultipleButton(Name = "action", Argument = "Save")]
        public ActionResult Save(MessageModel mm)
        {
            return RedirectToAction("Index");
            //...
        }

        [HttpPost]
        [MultipleButton(Name = "action", Argument = "Cancel")]
        public ActionResult Cancel(MessageModel mm)
        {
            return RedirectToAction("Index");
            // ...
        }
    }
}

Step3 : Add your html form control:
 <form action="" method="post">
        <input type="submit" value="Save" name="action:Save" />
        <input type="submit" value="Cancel" name="action:Cancel" />
    </form>

Now run the application and click on Save and Cancel button. you will as expected behaviour.

Thanks for reading this article............


Monday 17 December 2018

create crud operation step by step

step1 : Create your project with MVC and webapi
       add connection string
     <connectionStrings>
    <add name="OesV1DbContext" connectionString="Data Source=abc;Persist Security Info=true;Initial Catalog=MyTestDb; User ID=sa;Password=pwd; Integrated Security=false;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
----------------------------------------------------------------------------------
 step2 : add class library:
           and 1 class file and add following code:
   public class OesV1DbContext : DbContext
    {
        public OesV1DbContext() : base("OesV1DbContext")
        {
            Database.SetInitializer<OesV1DbContext>(null);
        }

        public DbSet<User> UserEntities { get; set; }
        public DbSet<Student> Students { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
-------------------------------------------------------------------------------
step3 :add one more class and following code
      public class OesV1DbContextInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<OesV1DbContext>
    {
        protected override void Seed(OesV1DbContext context)
        {
            // with empty database
        }
    }
-----------------------------------------------------------------------
step4 : add following class for database

       class0
   public class User
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string DisplayName { get; set; }
    }

        Class1
public class Student
    {
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
        public DateTime EnrollmentDate { get; set; }
        public int Age { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
class 2
public enum Grade { A, B, C, D, F }

    public class Enrollment
    {
        public int EnrollmentID { get; set; }
        public int CourseID { get; set; }
        public int StudentID { get; set; }
        public Grade? Grade { get; set; }
        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
    }

class3
      public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
        public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
-------------------------------------------------------------------
step4 : add folder in class library
        then add interface and its implementation

// interface
public interface IUserRepository
    {
        IQueryable<User> GetAllUsers();
        IQueryable<User> GetUserById(int userId);
        int AddUser(User user);
        int UpdateUser(User user);
        bool DeleteUser(int userId);

    }
-----------------------------------------------------
// implementation
using System;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Infrastructure;

namespace OesRepo1.Reprository
{
    public class UserRepository : IUserRepository
    {
        private OesV1DbContext dbContext = new OesV1DbContext();



        public int AddUser(User user)
        {
            dbContext.UserEntities.Add(user);
            dbContext.SaveChanges();
            return user.UserId;
        }

        public bool DeleteUser(int userId)
        {
            User user = dbContext.UserEntities.Find(userId);
            if (user == null)
            {
                return false;
            }

            dbContext.UserEntities.Remove(user);
            dbContext.SaveChanges();
            return true;
        }

        public IQueryable<User> GetAllUsers()
        {
            var result = dbContext.UserEntities;
            return result;
        }

        public IQueryable<User> GetUserById(int userId)
        {
            var result = dbContext.UserEntities.Where(x => x.UserId == userId);
            return result;
        }

        public int UpdateUser(User user)
        {
            if (UserExists(user.UserId))
            {
                dbContext.Entry(user).State = EntityState.Modified;

                try
                {
                    dbContext.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException ex)
                {

                    throw ex;

                }
            }
            return user.UserId;
        }


        private bool UserExists(int id)
        {
            return dbContext.UserEntities.Count(e => e.UserId == id) > 0;
        }
    }
}


/////////////////////
Create controller and add following code

using OesRepo1;
using OesRepo1.Reprository;
using OesV1.Attributes;
using OesV1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;

namespace OesV1.Controllers
{
    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
       

        private readonly IUserRepository _userRepository;// = new UserRepository();

        // constructor dependency injection
        public UserController(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }



        // GET: api/user/getallusers
        /// <summary>
        /// Get all users from Db
        /// </summary>
        /// <returns>UserApiModel</returns>
        [HttpGet]
        //[APIAuthenticationFilter(true)]
        [ResponseType(typeof(List<UserApiModel>))]
        [Route("getallusers")]
        public async Task<IHttpActionResult> GetUsers()
        {
            var result = _userRepository.GetAllUsers();
            if (result == null)
            {
                return NotFound();

            }
            var userList = MapUser(result);
            return Ok(userList);
        }


        // GET: api/user/1
        /// <summary>
        /// Get User by Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        //[APIAuthenticationFilter(true)]
        [ResponseType(typeof(UserApiModel))]
        [Route("getuserbyid/{id}")]
        public async Task<IHttpActionResult> GetUser(int id)
        {
            var result = _userRepository.GetUserById(id);
            if (result == null)
            {
                return NotFound();
            }

            return Ok(result);
        }

        /// <summary>
        /// Add user in database
        /// </summary>
        /// <param name="userApiModel"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("adduser")]
        public async Task<IHttpActionResult> AddUser(UserApiModel userApiModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            User dbUser = new User
            {
                UserName = userApiModel.UserName,
                Password = userApiModel.Password,
                DisplayName=userApiModel.Name
            };
            var userId = _userRepository.AddUser(dbUser);

            if (userId == 0)
            {
                return NotFound();
            }

            return Ok(userId);
            //return CreatedAtRoute("DefaultApi", new { id = userApiModel.UserId }, userApiModel);
        }

        [HttpPut]
        [Route("updateuser")]
        public async Task<IHttpActionResult> UpdateUser(UserApiModel userApiModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            User dbUser = new User
            {
                UserId=userApiModel.UserId,
                UserName = userApiModel.UserName,
                Password = userApiModel.Password,
                DisplayName = userApiModel.Name
            };
            var userId = _userRepository.UpdateUser(dbUser);

            if (userId == 0)
            {
                return NotFound();
            }

            return Ok(userId);
            //return CreatedAtRoute("DefaultApi", new { id = userApiModel.UserId }, userApiModel);
        }

        /// <summary>
        /// Delete user by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("deleteuser/{id}")]
        public async Task<IHttpActionResult> DeleteStudent(int id)
        {
            var result = _userRepository.DeleteUser(id);
            if (!result)
            {
                return NotFound();
            }

            return Ok(result);


        }
        #region private section
        private List<UserApiModel> MapUser(IQueryable<User> result)
        {
            List<UserApiModel> userList = new List<UserApiModel>();
            foreach (var item in result)
            {
                UserApiModel userObject = new UserApiModel
                {
                    UserId = item.UserId,
                    UserName = item.UserName,
                    Password = item.Password,
                    Name = item.DisplayName
                };
                userList.Add(userObject);
            }

            return userList;

        }
        #endregion
    }
}

/////////////////////////////////
I have implemented structure map dependency injection so you can also add.
and in default registry you can add following code

 //For<IExample>().Use<Example>();
            For<IUserRepository>().Use<UserRepository>();

Thursday 13 December 2018

Self referencing loop detected with type 'System.Data.Entity.DynamicProxies

Add this line of code in Global.asax file
in application start method


// Reference Loop Handling Ignore
            HttpConfiguration config = GlobalConfiguration.Configuration;

            config.Formatters.JsonFormatter
                        .SerializerSettings
                        .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;



json formatting in webapi

Add this code in Global.asax in method
 Application_Start()


var formatters = GlobalConfiguration.Configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;
            var settings = jsonFormatter.SerializerSettings;
            settings.Formatting = Formatting.Indented;



encode and decode string in C#

string authHeaderValue="hamid123456789"
 byte[] byt = System.Text.Encoding.UTF8.GetBytes(authHeaderValue);

            // thenconvert this byte array to a Base64 string

            authHeaderValue = Convert.ToBase64String(byt);
         
now again get it in its original format
            authHeaderValue = Encoding.Default.GetString(Convert.FromBase64String(authHeaderValue));

Tuesday 4 December 2018

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Problem :A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified):


Sol : There is no code error in your project, it is only sql network issue that is not connected
Once your sql will be up. everything will be work as expected.

Thanks