Monday, 22 July 2019

Simple way to create dropdwon in MVC with EntityFramework.


Step:1  Create  KeyValuePair Class in ModelLayer

namespace Model
{
    public  class KeyValuePair
    {
        public int Val { get; set; }
        public string label { get; set; }
    }
}



Step:2 Create DropDownModel Model in ModelLayer


using System.Collections.Generic;

namespace Model
{
    public  class DropDownModel
    {
        public int RollNo { get; set; }
        public string Name { get; set; }
       public List<KeyValuePair> KeyValuePair { get; set; }
        public List<KeyValuePair> KeyValuePair1 { get; set; }
        public List<KeyValuePair> KeyValuePair2 { get; set; }
        public List<KeyValuePair> KeyValuePair3 { get; set; }
    }
}


Step:3 Create Class StudentManagement in BussinessLayer.

Step:4 Add Entity in dataLayer.


Step:5 Create Method to get Data from Database using Entity.



using DataLayer;
using Model;
using System.Collections.Generic;
using System.Linq;

namespace BussinessLayer
{
    public class StudentManegament
    {

        public List<KeyValuePair> getDropDownData()
        {
            List<KeyValuePair> keyValuePairs = new List<KeyValuePair>();

            using (var Context = new StudentDBEntities())
            {
                keyValuePairs = (from std in Context.getStudentList() select new KeyValuePair
                {
                    label=std.Name,
                    Val=std.Roll
                }).ToList();
            }

                return keyValuePairs;
        }
    }
}

Step:6 Create Home Controller.

Step:7 Create  Action Method DropDown in Home  Controller.


using BussinessLayer;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DotNetByPriyanshu.Controllers
{
    public class HomeController : Controller
    {
      

        public ActionResult DropDown()
       {
            StudentManegament studentManegament = new StudentManegament();
            DropDownModel dropDownModel = new DropDownModel();
            dropDownModel.KeyValuePair1 = studentManegament.getDropDownData();
            dropDownModel.KeyValuePair2 = studentManegament.getDropDownData();
            dropDownModel.KeyValuePair3 = studentManegament.getDropDownData();

            return View(dropDownModel);
        }

      
    }
}

Step:8 Add View with DropDownModel

@model Model.DropDownModel

@{
    ViewBag.Title = "About";
}

<h2>About</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>DropDownModel</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

 
    <div class="form-group">

        <div class="col-md-5">
            @Html.DropDownListFor(x => Model.RollNo, new SelectList(Model.KeyValuePair1, "Val", "label"), "Select1", htmlAttributes: new { @class = "form-control", @id = "DDlRegion" })
            @Html.ValidationMessageFor(x => x.KeyValuePair, "", new { @class = "text-danger" })
        </div>
    </div>   <div class="form-group">

        <div class="col-md-5">
            @Html.DropDownListFor(x => Model.RollNo, new SelectList(Model.KeyValuePair2, "Val", "label"), "Select2", htmlAttributes: new { @class = "form-control", @id = "DDlRegion" })
            @Html.ValidationMessageFor(x => x.KeyValuePair, "", new { @class = "text-danger" })
        </div>
    </div>   <div class="form-group">

        <div class="col-md-5">
            @Html.DropDownListFor(x => Model.RollNo, new SelectList(Model.KeyValuePair3, "Val", "label"), "Select3", htmlAttributes: new { @class = "form-control", @id = "DDlRegion" })
            @Html.ValidationMessageFor(x => x.KeyValuePair, "", new { @class = "text-danger" })
        </div>
    </div>
  
</div>
}



Database

Table StudentInfo:

/****** Object:  Table [dbo].[StudentInfo]    Script Date: 7/23/2019 2:41:02 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[StudentInfo](
[Roll] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NULL,
[Course] [varchar](100) NULL,
[Mobile] [varchar](100) NULL,
[Address] [varchar](100) NULL,
 CONSTRAINT [PK_StudentInfo] PRIMARY KEY CLUSTERED 
(
[Roll] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO



StoredProcedure [dbo].[getStudentList]:

/****** Object:  StoredProcedure [dbo].[getStudentList]    ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Dot Net By Priyanshu
-- Create date: 12-12-2018
-- Description: getStudentList
-- =============================================
ALTER PROCEDURE [dbo].[getStudentList]
AS
BEGIN
SET NOCOUNT ON;
SELECT [Roll]
      ,[Name]
      
  FROM [StudentDB].[dbo].[StudentInfo]
END

Saturday, 20 July 2019

Console Program for finding Nth Large Salary from List. using Lambda expression/Linq.



using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace DotNetByPriyanshu_App

{

    class Program

    {

        static void Main(string[] args)

        {

            List<TestClass> testClasses = new List<TestClass>();

            for (int i = 0; i < 10; i++)

            {

                TestClass testClass = new TestClass();

                testClass.id = 1 + i;

                testClass.EmpName = "Dot Net By Priyanshu" + i;

                testClass.salary = 20000 + i;

                testClasses.Add(testClass);

            }


             int N = 2; //we can change value according to requirement.


            // It will return 2nd Heigest salary.

            var Nth_HieghtSal = testClasses.OrderByDescending(e => e.salary).Skip(N-1).First();


          //Note : if you want to find n salary then you can simply change the value of N 

        }
    }

    public class TestClass

    {

        public int id { get; set; }

        public string EmpName { get; set; }

        public int salary { get; set; }

}

}

Create filter to redirect page to login page on direct hit URL in MVC.



Steps:



1. Add a new folder Name it Filter.

2. Add a new class name it NoDirectAccessAttribute.  

3. Inherit ActionFilterAttribute




using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;



namespace DotNetByPriyanshu.Filter

{

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]

    public class NoDirectAccessAttribute : ActionFilterAttribute

    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)

        {

            if (filterContext.HttpContext.Request.UrlReferrer == null ||

                        filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)

            {

                filterContext.Result = new RedirectToRouteResult(new

                               RouteValueDictionary(new { controller = "Login", action = "Login", area = "" }));

            }

        }

    }

}







Uses:- use as an attribute over all Controller.
like:- [NoDirectAccessAttribute]

Thursday, 10 January 2019

Reverse String with two different logic using C#

               Reverse String with two different logic  using C#


                                                Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculationApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter String For Reverse.");
            string str = Console.ReadLine();
            string rev = Calculation.revString1(str);
            Console.WriteLine("Orignal String = " + str);
            Console.WriteLine("Reversed String1 = " + rev);
            string rev1 = Calculation.revString2(str);
            Console.WriteLine("Reversed String2 = " + rev1);
            Console.ReadLine();
        }
    }

                                              Calculation.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculationApp
{
    public static class Calculation
    {

        public static string revString1(string str)
        {
            char[] charArray = str.ToCharArray();
            char[] rev = new char[charArray.Length];
            int j = 0;
            for (int i = charArray.Length - 1; i >= 0; i--)
            {
                rev[j++] = charArray[i];
            }

            return new string(rev);
        }

        public static string revString2(string Str)
        {
            int L;
            string Revstr = string.Empty;
            L = Str.Length - 1;
            while (L >= 0)
            {

                Revstr = Revstr + Str[L];
                L--;

            }
            return Revstr;
        }

    }
}

HCF Calculation Over integer Array using c#.

HCF Calculation Over integer Array using c#.




                                                       Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculationApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter number");
            int num = int.Parse(Console.ReadLine());
            int[] Arr = new int[num];
            Console.WriteLine("Enter " + num + "number");
            for (int i = 0; i < num; i++)
            {
                Arr[i] = int.Parse(Console.ReadLine());
            }

            Console.WriteLine("HCF Array");

            int result = Arr[0];
            for (int i = 1; i < Arr.Length; i++)
            {
                result = Calculation.Calculate(result, Arr[i]);
            }
            Console.WriteLine(result);



            Console.ReadLine();
        }
    }


                                                   Calculation.cs

                    //HCF Calculation Over integer Array using c#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculationApp
{
    public static class Calculation
    {

        public static int Calculate(int result, int value)
        {
            while (value > 0)
            {
                int temp = value;
               value = result % value;
                result = temp;
            }
            return result;
     }
    }
}

Maximum occurrence of number in an integer Array using C#

Maximum occurrence of number in an integer Array using C#



                                               Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculationApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter number");
            int num = int.Parse(Console.ReadLine());
            int[] Arr = new int[num];
            Console.WriteLine("Enter " + num + "number");
            for (int i = 0; i < num; i++)
            {
                Arr[i] = int.Parse(Console.ReadLine());
            }
            int[] result = new int[2];
            result = Calculation.MaxOccurance(Arr);
            Console.Write("Number:- " + result[0] + " Occurance:- " + result[1]);
            Console.ReadLine();
        }
    }


                                              Calculation.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CalculationApp
{
    public static class Calculation
    {
//Method for Calculating the maximum occurrence of number in array.
        public static int[] MaxOccurance(int[] Arr)
        {
            int Number = 0;
            int MaxOccurance = 0;
            int Search = 0;
            for (int i = 0; i < Arr.Length; i++)
            {
                int count = 0;
                Search = Arr[i];
                for (int j = 0; j < Arr.Length; j++)
                {
                    if (Arr[i] == Arr[j])
                    {
                        count++;
                    }
                }
                if (count > MaxOccurance)
                {
                    MaxOccurance = count;
                    Number = Arr[i];
                }
            }
            int[] result = new int[2];
            result[0] = Number;
            result[1] = MaxOccurance;
            return result;
        }
    }
}