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





Friday 23 November 2018

how to implement NLog in webapi



https://www.c-sharpcorner.com/article/how-to-implement-nlog-in-webapi/

In this topic I will cover the following things
1-    Definition
3-    Log Level
4-    Implementation
After reading this article I hope you will be able to use easily.
Definition :
NLog is a flexible and free logging platform for various .NET platforms, including .NET standard. NLog makes it easy to write to several targets. (database, file, eventviewer)
Log levels
The log levels, in sliding request, are as per the following:
 S.N Level Use
 1 Fatal Something terrible occurred; application is going down
 2 Error Something fizzled; application might possibly proceed
 3 Warn Something surprising; application will proceed
 4 Info Normal conduct like mail sent, client refreshed profile and so on.
 5 Debug For troubleshooting; executed question, client confirmed, session terminated
 6 Trace  For follow troubleshooting; start technique X, end strategy X


Implementation
Step 1
Click Visual studio> Select File>New>Project
 
Step 2
Select Web> Asp.net Web Application > Give your project name, for me I have given NLogTest then click on Ok
 
Step 3
Select WebApi then click on OK
 
Step 4
Now you have to add NLog to your project.
So follow the steps Right click on your project solution then click on Manage NugGet Packeses
And then install.
 
After click on install you will get following window.
 
Click OK on this pop up windo, after successful installed you will get dll in your project reference
 
Now your half part of configuration is done!
Let go to next level
Step 5
Now add following code in your config file
  1. <configSections>  
  2.   
  3. <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />  
  4.   
  5. </configSections>  
  6.   
  7. <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  8.   
  9. <targets>  
  10.   
  11. <target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" />  
  12.   
  13. <target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" My Custom Api Services" />  
  14.   
  15. <target name="database" type="Database" connectionString="Data Source=your sql source;initial catalog=YourDbNameDb;user id=u1;password=p1;MultipleActiveResultSets=True;">  
  16.   
  17. <commandText>  
  18.   
  19. insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message,  
  20.   
  21. case when len(@UserID) = 0 then null  
  22.   
  23. else @UserId  
  24.   
  25. end,  
  26.   
  27. @Exception, @StackTrace);  
  28.   
  29. </commandText>  
  30.   
  31. <parameter name="@TimeStamp" layout="${date}"/>  
  32.   
  33. <parameter name="@Level" layout="${level}"/>  
  34.   
  35. <parameter name="@Logger" layout="${logger}"/>  
  36.   
  37. <parameter name="@Message" layout="${message}"/>  
  38.   
  39. <parameter name="@UserId" layout="${mdc:user_id}"/>  
  40.   
  41. <parameter name="@Exception" layout="${exception}"/>  
  42.   
  43. <parameter name="@StackTrace" layout="${stacktrace}"/>  
  44.   
  45. <dbProvider>System.Data.SqlClient</dbProvider>  
  46.   
  47. </target>  
  48.   
  49. </targets>  
  50.   
  51. <rules>  
  52.   
  53. <!-- add your logging rules here -->  
  54.   
  55. <logger name="*" minlevel="Debug" writeTo="database" />  
  56.   
  57. <logger name="*" minlevel="Trace" writeTo="logfile" />  
  58.   
  59. <logger name="*" minlevel="Trace" writeTo="eventlog" />  
  60.   
  61. </rules>  
  62.   
  63. </nlog>  


Please refer below screen
 
Step 6
Create your db Script
  1. CREATE TABLE [dbo].[ExceptionLog](  
  2.   
  3. [Id] [int] IDENTITY(1,1) NOT NULL,  
  4.   
  5. [TimeStamp] [datetime] NOT NULL,  
  6.   
  7. [Level] [varchar](100) NOT NULL,  
  8.   
  9. [Logger] [varchar](1000) NOT NULL,  
  10.   
  11. [Message] [varchar](3600) NOT NULL,  
  12.   
  13. [UserId] [intNULL,  
  14.   
  15. [Exception] [varchar](3600) NULL,  
  16.   
  17. [StackTrace] [varchar](3600) NULL,  
  18.   
  19. CONSTRAINT [PK_ExceptionLog] PRIMARY KEY CLUSTERED  
  20.   
  21. (  
  22.   
  23. [Id] ASC  
  24.   
  25. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  26.   
  27. ON [PRIMARY]  
Step 7
Go to your home controller
And add following code
  1. using NLog;  
  2.   
  3. using System;  
  4.   
  5. using System.Web.Mvc;  
  6.   
  7. namespace NLogTest.Controllers  
  8.   
  9. {  
  10.   
  11. public class HomeController : Controller  
  12.   
  13. {  
  14.   
  15. private static Logger logger = LogManager.GetCurrentClassLogger();  
  16.   
  17. public ActionResult Index()  
  18.   
  19. {  
  20.   
  21. ViewBag.Title = "Home Page";  
  22.   
  23. logger.Info("Hell You have visited the Index view" + Environment.NewLine + DateTime.Now);  
  24.   
  25. return View();  
  26.   
  27. }  
  28.   
  29. public ActionResult About()  
  30.   
  31. {  
  32.   
  33. ViewBag.Message = "Your app description page.";  
  34.   
  35. logger.Info("hello now You have visited the About view" + Environment.NewLine + DateTime.Now);  
  36.   
  37. return View();  
  38.   
  39. }  
  40.   
  41. }  
  42.   
  43. }  


Now run the application
And open your sql you will see following logs inserted in your dB
 
You can see in your event viewer
 
You can see in your txt file
 
Now your can open your event viewer in following ways
To access the Event Viewer
1. Right click on the Start button and select Control Panel > System & Security and double-click Administrative tools.
2. Double-click Event Viewer.
3. Select the type of logs that you wish to review (error, information etc..)
Or
Press Windows+R to open the Run dialog, enter eventvwr