How to Restrict Method to particular User and class in c#

How to Restrict Method to particular User and class in c#


How to Restrict Method to particular User in c#





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

namespace Inheritancet
{
    public class Person
    {
        [System.Security.Permissions.PrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Role = "DoDelete")] // or "PowerUser" etc.
        public void DoDelete()
        {
            // Delete User Infor
            Console.WriteLine("gggg");         
        }
        public void click(string username)
        {

            // authenticate user here
            if (username != null)
            {
                GenericIdentity id = new GenericIdentity(username); // username of the current login

                Thread.CurrentPrincipal = new GenericPrincipal(id, new string[] { "Admin", "PowerUser", "DoDelete" }); // the roles the user has usually from a database
                DoDelete();
            }

        }
    }
     
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.click("Admin");
            Console.Read();
        }
    }
}

Multicaste delecate in c#

Multicaste delecate in c#

Multicaste delecate in c#

Here our code

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

namespace multicastedelegate
{
    class Program
    {

        public delegate void GetResult(int x, int y);

        public void Sum(int x, int y)
        {
            int Z = x + y;
            Console.Write(Z +""+ Environment.NewLine) ;
           
        }

        public void Sub(int x, int y)
        {
            int Z = x - y;
            Console.Write(Z);
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            GetResult d = p.Sum;
             d(1,2);
            d = p.Sub;
            d(8, 6);

            Console.Read();

        }
    }
}


Output
3
2
Ajax with Model base httppost in mvc?

Ajax with Model base httppost in mvc?


Ajax with Model base httppost in mvc?


1. create model
public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
2. create controller


  [HttpPost]
        public ActionResult Emp(Employee emp)
        {
            return View("Emp",emp);


        }

3.Create view with ajax

@html.texboxfor(r=>r.Id,new{@Id=in})
@html.texboxfor(r=>r.Name,new{@Id=nm})

<script>
  
    $(document).ready(function() {
        $("#click").click(function () {
            var viewModel = { Id: $("#in").val(), Name: $("#nm").val() };
            $.ajax({
                type: "POST",
                url: 'http://localhost:11685/Home/Emp',     //your action
             data: viewModel,//or{Id:$("#in").val(),Name:$("#nm").val()}; model              
                dataType: 'json',
                success: function (result) {
                    console.log(result);
                }
            })
            return false;
        });
    });
</script>

Count highest element sequnce for the digit 1 in Arraylist in C#

Count highest element sequnce for the digit 1 in Arraylist in C#

Count highest element sequnce for the digit 1 in Arraylist in C#


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

namespace Algorithm
{
    class Program
    {

        ArrayList arr = new ArrayList() {1,0,0,0,1,1,1,0,0,0,0,0,1,1};
        List<object> n = new List<object>();
        public void Arrcheck()
        {
            foreach (var i in arr)
            {
                n.Add(i);
            }
            var a = "";
            for (int i = 0; i < n.Count(); i++)
            {
               
                if ((int)n[i] == 0)
                {
                    a += " ";                   
                }
                else if((int)n[i] == 1)
                {
                    a += n[i] + "";
                }
               
                   
               

            }

            var jsplit = a.Split(' ');
            List<count> l = new List<count>();
            foreach (var j in jsplit)
            {
                if(j.Length >0)
                Console.Write(j+"  "+ j.Length+"\n");
            }
           
         
                 
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Arrcheck();
            Console.Read();
        }
    }
}

Output:-

1     1
111  3
11    2
Fetch Web Api data to Console Application in C#

Fetch Web Api data to Console Application in C#

Fetch the Data from web ai to console screen.

Let's go-to application

In NuGet solution:- Install

PM> install-package Microsoft.AspNet.WebApi.Client



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace ConsoleApp1
{

    public class Employee
    {
        public int id { get; set; }
        public int empid { get; set; }
        public string name { get; set; }
        public string address { get; set; }
        
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://employees/list");
                //HTTP GET
                var responseTask = client.GetAsync("employees");
                responseTask.Wait();

                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {

                    var readTask = result.Content.ReadAsAsync<Employee[]>();
                    readTask.Wait();

                    var emps = readTask.Result;

                    foreach (var emp in emps)
                    {
                        Console.WriteLine(emp.empid + emp.name);
                    }
                }
            }
            Console.ReadLine();
           

        }
    }

}

output:-  1 xyz



Singleton Pattern in c#

Singleton Pattern in c#

Singleton :-

1> Allows only one time object creatation.

lets move to the code.


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

namespace ConsoleApp1
{

    class Singleton
    {
        private Singleton() { }// constructor must be private or protected to avoid calls from  new                                                         //operator
        private static Singleton _initation =null; //To store singleton instance in static field.

        public static Singleton GetInitation()//  static method. to instantiate singleton object.
        {
            if (_initation == null)
            {
                _initation = new Singleton();
            }
            return _initation;

        }
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            Singleton s = Singleton.GetInitation();
            Singleton s1 = Singleton.GetInitation();

            if (s == s1)
            {
                Console.WriteLine("Singleton");
            }

            Console.ReadLine();
        }
    }
}

output:- Singleton
What is CTE "Common table expression"

What is CTE "Common table expression"

Common Table Expression:-

Is a temporary result set where we can use for execution like Insert, Update, Delete and Select.

CTE always begin => ;with

Syntax:-

     ;with                                                        => Start with a with.
     mycteexample(Name, Age)                    =>Coloumn Name reqiured to display
     as                                                         
     (
        select Name, Age from Employee      => SQL STATEMENT
     )
     select * from mycteexample
     

How create Pagination in C#

How to create Pagination Logic in c#.

Code sample..

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

namespace TestInterviewSolution
{
    class Program
    {
        DefaultConnection constring = new DefaultConnection();

        public List<Emp> Getemp()
        {
            List<Emp> d = (from s in constring.emps.ToList() select s).ToList();
            return d;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            IEnumerable<Emp> emplist = p.Getemp();
            int totalitem= emplist.Count();
            int page= 1;
            int pagesize = 5;
         
            Console.WriteLine("Enter the pagination 1  5  10  15 20" );

            var pagenumber = int.Parse(Console.ReadLine());
            if (pagenumber > 0)
            {
             
                foreach (var i in emplist.Skip(page * pagenumber - 1).Take(pagesize))
                {
                    Console.WriteLine(i.Id + "   " + i.Name + "  " + i.Salary);
                }

            }

         
            Console.ReadLine();
        }
    }
}

Output:- enter 10  and row size(pagesize) is 5








How to get duplicate value from the array in C#

How to get duplicate value from the array in C#

How to get duplicate value from the array in C#


Solution:-

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

namespace LogicTest
{
    class Program
    {
        static void Main(string[] args)
        {
         
            int[] arr = new int[] { 1,2,3,1,4};
            int count = 0;
            var num = 0;
            for (int i = 0; i < arr.Length; i++)
            {

                for (int j = i; j < arr.Length-1 ; j++)
                {
                    if (arr[i] == arr[j+1])
                    {
                     
                        Console.WriteLine("duplicate  "+arr[i]);
                        count++;
                        break;
                    }
                }
            }
            Console.WriteLine("duplicate elements found in the array is: {0} {1}", count, num);
            Console.ReadLine();

        }
    }

Output:- duplicate  1
duplicate elements found in the array is: 1 0
What is StoreProcedure in SQL.

What is StoreProcedure in SQL.

Storeprocedure:-

1. It contains group of transaction statement. It reduce creating dml, ddl operation operation if it is in repeated state. execution done by it's name.

Storeprocedure are two type IN and OUT parameters.

sp_helptext spname  it will show the entire logic of storeprocedure you have written for that.
alter spname :-  modify purpose syntax we use.
drop spname:-  remove the storeprocedure.

for an ex:-
if we are using select statement such as

select  empno, ename, deptno from employee.
we are calling  again an again and this is lengthy, So better to wrap in storeprocedure.

program

create procedure getemployeedetail  //  procedure /proc can be call in short
as
begin
select [Empno],[Ename],[Deptno] from [dbo].[Employees]
end


exec  getemployeedetail // called by name only

Output:-

2212 Amit 30
7369 SMITH 20


Parameteric Storeprocedure

ex:-

Create  procedure getemployeedetail(@empno int) // parametric SP
as 
begin   
select [Empno],[Ename],[Deptno] from [dbo].[Employees]  where [Empno]=@empno
end

execution with sp name with exact parameter value  thats why order is impotant.
we can call two ways:-
1. exec  getemployeedetail 7369
2. exec getemployeedetail  Empno = 7369 // here parameter order is not recommended.


Storeprocedure with output parameter.

1. To use Output parameter storeprocedure we use keyword as OUT or OUTPUT.

Example
Here  we have 2 parameter @empno and @count differences is that @empno is input parameter and @count outputs parameter

Create procedure getemployeedetailwithoutputparam 
@empno int ,
@count int output
as 
begin
   select @count = count(*) from  [dbo].[Employees]  where [Empno]=@empno
end

execution in 2 ways

Declare @Totalemp int
exec  getemployeedetailwithoutputparam 7369,@Totalemp out
print @Totalemp
------
Declare @Totalemp int
exec  getemployeedetailwithoutputparam 7369,@count=@Totalemp out
print @Totalemp

Output :- 1



What is the Triggers in SQL and how to utilized the Triggers .

What is the Triggers in SQL and how to utilized the Triggers .

Triggers:- Trigger works like store procedure and function at the point when it is called or fire between    two or multiple tables and it does automatically..

Triggers are 3 types:- DML, DDL & Logon.

1. DML Triggers.

   This type of trigger fires automatically in such a events (INSERT, UPDATE & DELETE ).
    DML triggers are two types:-
    1. After of trigger.
    2. Instead of trigger.

After of trigger:- execution happens when primary table statement get executed first and then secondly  triggered  table executed  in concern of (INSERT, UPDATE & DELETE ) operation .
or in other sentances
After trigger fire after the execution query of an action that can be ddl statement or dml statement.

Instead of trigger :- Instead of trigger fire before the execution query of an action that can be ddl statement or dml statement. it will not effect. Through Insteadof trigger we can insert  the data  multiple table views.

Example After trigger.

create trigger EmpAudit 
on [dbo].[Employees]
for insert
as
begin
declare @Empno int
select @Empno = [Empno] from inserted  // inserted is a magic table create by sql to hold the data.
insert into [dbo].[Audit] values('Employee no :-'+Convert(varchar,@Empno) + '.Registered on '+CONVERT(nvarchar,GETDATE()))
end

Now insert the new row Employee table,

insert into   [dbo].[Employees]values( 9999, 'PRANEET', 'MANAGER', 78
Convert(datetime,'1981-05-01'),   2850, null, 30  )

execute and row added to the employee table.
Audit table will look where after trigger had fired.

1Employee no :-9999.Registered on Jan 27 2018  5:26PM.



Same case in delete

create trigger DeleteEmpAudit 
on [dbo].[Employees]
for delete
as
begin
declare @Empno int
select @Empno = [Empno] from deleted
insert into [dbo].[Audit] values('Employee no :-'+Convert(varchar,@Empno) + '.Deleted on '+CONVERT(nvarchar,GETDATE()))
end

delete from [dbo].[Employees] where [Empno] = 9999


2Employee no :-9999.Deleted on Jan 27 2018  5:44PM


Same case in Update

we use  both the operation deleted and inserted
select * from deleted //  it delete the old data
select * from inserted // it contain fresh records.


Instead of Trigger program

>creating the view

Create view [dbo].[CustomerDerpartmentVw]
as

select  Empno,Ename, Dept.Dname from [dbo].[Employees] join Dept on Employees.Deptno=Dept.Deptno

> creating the  Instead of Trigger

  Create trigger InsteadofInsertvw
on [dbo].[CustomerDerpartmentVw]
Instead of Insert
as
begin
declare @Deptno int
select @Deptno = Deptno  from [dbo].[Dept]  join 
            inserted on inserted.Dname=Dept.Dname 

insert into [dbo].[Employees](Empno,Ename,Deptno)
select Empno,Ename, @Deptno from inserted
end

>Execution
insert into 

[dbo].[CustomerDerpartmentVw] values(2212,'Amit','Sales')

Output:- in Emp table
2212AmitNULLNULLNULLNULLNULL30
 View
2212AmitSALES