What is an Array


A array is a special variable which holds multiple values.
Like if we have more that  2 times of same variety name and we want it be in a single variable we have to use array.

eg;

var fruit1="Mango"
var fruit2="Banana"
var fruit3="Orange"

Here we have  3 fruits in  different variable to merge this in a single variable we have to use an array

So an array be like
var fruits=[];

var fruits=["Mango","Banana","Orange"]
now we have all fruit items in single variable called fruit.

How to get value from the array?

So get value from the array we need index of the value like

var fruit1=fruits[0];
var fruit2=fruits[1];
var fruit3=fruits[2];

With the help of indexing we will get the value of the fruits;

How to get length of the array?

To get length of the we have to use length property

like var arraylength=fruits.length;
arraylength=3;





Concate two or more Array

 To concate or Add two or more Array value  we will use concate method.

concate return a new array consisting the values of all the array which is used to concate.

concate();


Here we have 3 arrays

var Animal=["Lion","Tiger","Leopard"]

var Fruit=["banana","mango"]

var Name=["John","Maya"]


How to concate two or more arrays?

var NewArray=Animal.concate(Fruit,Name)

now in the NewArray we will get value ="Lion","Tiger"."Leopard", "banana","mango","John","Maya"


How to use SessionStorage

 What is SessionStorage?


Basically SessionStorage is a property which is use to save value and use it accordingly from one page to other in the same Project.

It  stores data only for one session and the data get deleted when the browser closed.'


How to Store data in sessionStorage?

sessionStorage.setItem("key", "value");

Here we will set the value in key and will get it accordingly with the same key.


How to retrieve data  from sessionStorage?

var Anyvariable = sessionStorage.getItem("key");

Here in var we will get the data with that key which was used to set the value .


How to remove data  from sessionStorage?

sessionStorage.removeItem("key");

This will remove the data that is stored in the key.


How to clear  sessionStorage?

sessionStorage.clear();

It will clear all the data which is stored in session.




What is Ajax in Jquery

 Ajax Stands for AJAX = Asynchronous JavaScript and XML.


How Ajax works?

In simple words It Loads Data in background and Display in Web page.


Why Ajax?

There are Several method used in Ajax like get ,post to fetch data like HTML,XML or JSON.


Why Jquery For Ajax?

There is Something that we need to understand that there are different syntax for ajax for different browser without JQuery.With the help of Jquery we will complete ajax in sing bit of Lines.So it makes easier for developer to write less codes.



Method of Ajax

Get:-Basically Get method is used to fetch data from server 

Post:-Post method is also used to fetch data from server and also used to send parameters along with it.


Difference between Get and Post Method

Retrieved data though Get method may have cached data while in Post method it does not have Cache.


eg. For Get

    $.ajax({

        type: "Get",

        url: your URL

        cache: false,

        success: function (data) {

     $("#Data").text(data);

});

eg. For Post


  $.ajax({

        type: "Post",

        url: your URL

        success: function (data) {

     $("#Data").text(data);

});


How to Replace Character from a String in Jquery

  To replace a specific Character from String with other character or number in Jquery we have to     use   regular expression.

  Lets See


How?



   
  var data="pqrst$vw"

   Here we have string data in which we have to replace "$" with     Character "u"


  So to do that


  we will write


  var replaceddata = data.replace(/$/g, 'u')






So in return we will get



  
  replaceddata="pqrstuv"


Conclusion 


Basically we use replace in jquery to stop passing any other unwanted  input from keyboard or to filter the data with correct digit or character.






How to reverse a string in C# and Jquery

To reverse  a string in C# we will use while Loop

Lets see how


  C#


    Public dynamic Reversestring(){
      string data="pqrstuvwxyz"    

            string reverse = "";
            int Length = 0;

            Length = EncodedDasboardData.Length - 1;
            while (Length >= 0)
            {
                reverse = reverse + EncodedDasboardData[Length];
                Length--;
               

            }

    return  reverse 
   }


Below in the return we will get



   reverse ="zyxwvutsrqp"


 Jquery

   
   var data='pqrstuvwxyz'
   var reverse=  data.split(' ').reverse().join('')

    reverse ="zyxwvutsrqp"

How to make Password Strong in jquery


The most important thing in a software is the Password which must be strong .To make Password strong we basically use Special Character,

Lets see how to check whether the entered Password by user is Strong or not in jquery.

Below is the span where we check the status of Password whether it is strong or not



 <span id="result"></span>


Below in the Password input Field we will get the value in a function name checkStrength();



 $('#result').html(checkStrength($('#Password').val()))



Below is the Function that give the Status of the Password


   
   function checkStrength(password) {
    var strength = 0
    Pstrength = 0;

   
    if (password.length < 6) {
        $('#result').removeClass()
        $('#result').addClass('short')
        return 'Too short'
    }

 
    if (password.length > 7) strength += 1


    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1


    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 1


    if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 1


    if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,",%,&,@,#,$,^,*,?,_,~])/)) {
        strength += 1

    }



    if (strength < 2) {
        $('#result').removeClass()
        $('#result').addClass('weak')
        return 'Weak'
    } else if (strength == 2) {
        $('#result').removeClass()
        $('#result').addClass('good')
        Pstrength = 1;
        return 'Good'
    } else {
        $('#result').removeClass()
        $('#result').addClass('strong')
        Pstrength = 1;
        return 'Strong'

    }
 }


In Result Span with (id =result) we will get the Status of the Password.

We can use CSS as given below


    <style>

        #register { margin-left:100px; }
        #register label{ margin-right:5px; } 
        #register input { padding:5px 7px; border:1px solid #d5d9da; box-shadow: 0 0 5px #e8e9eb  inset; width:250px; font-size:1em; outline:0; }
        #result{ margin-left:5px; } 
        #register .short{ color:#FF0000; } 
        #register .weak{ color:#E66C2C; }
        #register .good{ color:#2D98F3; } 
        #register .strong{ color:#006400; }


     </style>

How to Generate OTP in Asp.net C#


To Generate One time password (OTP) in Asp.net C# . We have to use  use For Loop with Numbers and need to use random Class.

Lets See how to generate OTP

we have number from 0-9  in string numbers to which we will use Loop.



  string numbers = "1234567890";

  string otp= string.Empty;

  string characters = numbers;
   characters += numbers;




       int length = 6;

 We take length as per number of digit of the OTP requirement.

 Now in For loop we will use the number as per its Length



             for (int i = 0; i < length; i++)
                {
                    string character = string.Empty;
                    do
                    {
                        int index = new Random().Next(0,   characters.Length);
                        character = characters.ToCharArray()     [index].ToString();
                    }
                    while (otp.IndexOf(character) != -1);
                     otp+= character;

                }



we will get the otp in return

Over All Codes below



 public dynamic generateotp()
        {
    string numbers = "1234567890";

                string characters = numbers;
               
                characters += numbers;
                int length = 6;
                string otp = string.Empty;
                for (int i = 0; i < length; i++)
                {
                    string character = string.Empty;
                    do
                    {
                        int index = new Random().Next(0, characters.Length);
                        character = characters.ToCharArray()[index].ToString();
                    } 
while (otp.IndexOf(character) != -1);
                    otp += character;


                }
      return otp 
  }

How to run a method after a specific time interval?

 To Run A method after a specific time interval in C# we have to use Timespan and threading  i.e

using System.Threading.Tasks;

Lets see How we will use it


   Task.Delay(new TimeSpan(hour, min, sec)).ContinueWith(o => { Your method() });


TimeSpan (hour, min, sec) here we will use the time when we supposed to hit the method.

In the Continue with we will add our method with whatever the Parameter we have.

We can also use 



         Task.Factory.StartNew(() =>
                {
                System.Threading.Thread.Sleep(1000);
               Your method()

          });


From both Process we can hit any method after a specific time interval.

How to create Temptable on SQL server

 Basically Temporary table  in SQL server exists Temporary in Database Server.Which is used  to store Subset of Data from other Table.

Mostly Temp table is useful for the store procedure query where we store large amount of record in it and accordingly fetch data from it .
Lets See How to  create Temporary  table  on SQL Server


 
  First We  we will use drop command to delete any table exist from that name it will delete  automatically if SQL  connection breaks

  Drop table if exists  #Temptable


Now we will Create Temporary table  by using the same name i.e use in above query for drop  #Temptable.

Basically we use # as Prefix in the name of Temporary Table


   create Table  #Temptable
   (
   UserID int,
   UserName nvarchar(32),
   Address nvarchar(64),
   )


We will insert any data in that table and use it  accordingly.
Lets See how we will use it in Store Procedure

  
 create proc Sp_GetEmpDetails
  as
  begin
  Drop table if exists  #Temptable
  create Table  #Temptable
   (
   UserID int,
   UserName nvarchar(32),
   Address nvarchar(64),
   PinCode nvarchar(16),
  Designation nvarchar(16),,
   Company nvarchar(16), 
   )
  insert into #Temptable
 select Username,Address,PinCode ,Designation ,Company 
 from yourtablename
  cross join DesignationtableName
  cross join CompanytableName 


  select * from #Temptable
  end


How to select First letter of first name and First letter of Last Name from Name in Sql


To Get First letter of first name and First letter of Last Name from Name  in Sql server we have to use 

PATINDEX and CHARINDEX

let see how I got it.



  
declare
@var varchar(50),
@lastname  varchar(50)
declare @start INT = 1
declare @Last INT = 1
set @var = 'Gunjan Kumar '

SELECT @start = PATINDEX('%[A-Z][a-z]%',@var)
SELECT @lastname = PATINDEX('%[A-Z][a-z]%',@var)

set @lastname= (SELECT  SUBSTRING(@var, CHARINDEX(' ', @var) +1, 20))
select SUBSTRING(@var, @Last, 1)+
 SUBSTRING(@lastname, @Last, 1)splitname


And The Result looks like


   splitname

   GK


Get Id of the row on click of Datatable in Angular

To get id of  each row of  the material Datatable in angular  we need assign id of each row on its (td) or there must be id on the Datasource.

lets see





 <ng-container matColumnDef="name">
                  <th mat-header-cell *matHeaderCellDef>EmployeeID</th> 

        <td mat-cell *matCellDef="let element"> {{element.EmployeeID}} </td>
                </ng-container>




In the above we have give id to all its row of the table
After this we have to add click function on table row i.e like below


   

<tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="getEmployeeID(row.EmployeeID)"></tr>




On Click function we will get the Id of each row and use it accordingly

Run Store Procedure multiple Times With Different parameter


To run Run Store Procedure multiple Times With Different parameter we have To pass dynamic parameter with store procedure

As the parameter  the value will also change .

Lets see eg.


 Create Procedure SP_UpdateRecord --10,2
  (
  @numericvalue1 int,
  @numericvalue2 int
  )
  As
  Begin

  select (@numericvalue1-@numericvalue2) as SubtractionResult,
  (@numericvalue1+@numericvalue2) as AdditionResult,
  (@numericvalue1*@numericvalue2) as  MultiplicationResult,
  (@numericvalue1/@numericvalue2) as  DivisonResult

   end


As the value Change In parameter the result will also Change Accordingly.Here we can use any dynamic value to fetch the result in the addition ,subtraction ,multiplication and division form.

Add, Subtract,multiply,Divide in Store Procedure Sql Server



To Add,Subtract,Divide and Multiply We will use Following operator

Add (+) ,Subtract( -), Multiply (*), Divide (/)

Lets See how we can use it in Store Procedure





 Create Procedure SP_UpdateRecord --10,2
  (
  @numericvalue1 int,
  @numericvalue2 int
  )
  As
  Begin

  select (@numericvalue1-@numericvalue2) as SubtractionResult,
  (@numericvalue1+@numericvalue2) as AdditionResult,
  (@numericvalue1*@numericvalue2) as  MultiplicationResult,
  (@numericvalue1/@numericvalue2) as  DivisonResult

   end


Here We are Using two dynamic value in @numericvalue1 =10 and @numericvalue2=2
that will give us following Record



 SubtractionResult  AdditionResult MultiplicationResult      DivisonResult
           8                         12                             20                          5

Update Two table with Single Store Procedure



To update Two or more Table We can use Single Store Procedure.It can be use as Same as we use a query .the thing only we need to do is to use in Store Procedure ,

Here we are updating two table at a time using Store Procedure.
Lets see how.In the normal update Query in Sql Server Looks like this


  
update Department set DepartmentName='IT ' where DepartmentID=5

  update Designation set DesignationName='Admin' where   DesignationID=3


To use this in Store Procedure we will convert this query in Store procedure Syntax




 Create Procedure  SP_UpdateRecord 

 As
 Begin

 update Department set DepartmentName='IT' where DepartmentID=5
 update Designation set DesignationName='Admin' where DesignationID=3
 end



It will Work as same the single update Query Works.We can also update the Table by passing parameter to it .
Lets See how


Create Procedure  SP_UpdateRecord 
( @DepartmentID int,
@DesignationID int,
@DepartmentName nvarchar(32),
DesignationName nvarchar(32))
 As
 Begin

 update Department set DepartmentName=@DepartmentName where DepartmentID=@DepartmentID
 update Designation set DesignationName=@DesignationNamewhere DesignationID=@DesignationID
 end

Store Data in Dynamic Array C#

         


To Store Multiple Array In a New Array using C# . We have to use ArrayList for it

Lets See How 


         


dynamic arrayList = new ArrayList();

 dynamic FirstArrayRecord = _context.ArrayClass.FromSqlRaw("[dbo].[Sp_getCalenderAttendanceJan] @EmployeeID=" + EmployeeID + ",@year=" + year + " ").AsNoTracking().ToList();


            dynamic SecondArrayRecord = _context.ArrayClass.FromSqlRaw("[dbo].[Sp_getCalenderAttendanceFeb] @EmployeeID=" + EmployeeID + ",@year=" + year + " ").AsNoTracking().ToList();




Above We Have Two Records  i.e FirstArrayRecord  and  SecondArrayRecord  we have to add this record in a new arraylist.



            arrayList.Add(FirstArrayRecord );
           arrayList.Add(SecondArrayRecord );

         return arrayList 


In the Last we will return arrayList .

Convert Row data in column using Sql Server



What is pivot ?

Pivot  is   Relational   operator in SQL server  which is used to convert data from Row to Column view. To convert data from Column to Row we will use Unpivot Operator .Unpivot is opposite to Pivot

So lets See how we will use It.We have Data like this in Table




     
    EmployeeID EmployeeName Country State

         14 John D India Karnataka
         15 John R India Bihar
         16 John G India Maharastra
         17 John P India UP


We will use Pivot For State



   select [Karnataka],[Bihar],[Maharastra],[UP]  from(

   select EmployeeName,state from Tablename
   )t
  pivot( max(EmployeeName)  for state in ( [Karnataka],[Bihar],[Maharastra],[UP])  )st



This will convert Row data in Sates to Column with value EmployeeName
So the Result Will be Like

   
    Karnataka   Bihar   Maharastra    UP

    John D          John R    John G           John P


Get month name from week number in SQL Server


To Get Month name from Week Number we have to execute following query



declare @Year char(4), @Week INT, @month int
select @Year = '2020', @Week = 30
SET @month = month(dateadd(wk,@Week,@Year + '/01/01'))
SELECT DATENAME(month, DATEADD(month, @month, -1 ))as Nameofmonth




Here Week =30 and Year is 2020  

Result:-
Nameofmonth
July

Pass NULL value to stored procedure in C#

        


We can Pass null or String as parameter to store procedure




public dynamic GetEmpdata(int EmployeeID)
        {
            dynamic EmployeeIDs = EmployeeID;

            string Department=null;

            var Getdata = _context.Employee.FromSqlRaw("dbo.SP_
GetEmpdata    @p0 ,@p1 ",      parameters: new[] { EmployeeIDs , Department}).ToList();
            return Getdata ;
        }




We will take string department parameter as null .it will work as empty String and this will return value if store procedure work fine with null data.

String or binary data would be truncated in SQL

Sometimes I faced this issue like string or binary data would be truncated  in SQL database.


The query that is executed by me was..


 

 drop table if exists #Empattendanceday
 create table #Empattendanceday
  (
 Today datetime,

 DayName nvarchar(8)

 )

 insert into #Empattendanceday

 SELECT GETDATE(), 'Wednesday'



The reason Behind this error is the length of datatype(nvarchar) is dayname is 8 character and we are inserting data more than 8 char i.e 9

That's why it gives us  this error


String or binary data would be truncated.

The statement has been terminated.


So try to keep datatype character more than inserting value or DayName nvarchar(max).



Convert DateTime to a specified Format in C#



To Convert Datetime to  a specific format in C# we need to use ParseExtract.

According To Microsoft

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.


Lets see How to use


     

var EventDates = Request.Form["EventDate"];


compEvent.EventDate = DateTime.ParseExact(EventDates, "dd/MM/yyyy", CultureInfo.InvariantCulture ).ToString("MM/dd/yyyy");
           
           




This will convert the Desired DateFormat.

How to convert date in Desired format in angular



To convert date in desired format  like dd-MM-yyyy or  yyyy-MM-dd or other we will use datepipe

Datepipe will provide  date  values in different formats like milliseconds,date object,datetime string etc

Lets see how to use

In component.ts




 import { DatePipe } from '@angular/common';

 constructor( public datepipe: DatePipe) {}

  myDate = new Date();

Gettodaydate = this.datepipe.transform(this.myDate, 'yyyy-MM-dd');

console.log(this.Gettodaydate )





In the above part we have to import datepipe from angular/common and need to define it in constructor and after it we can use easy according to our need.

There are various predefined format



Date FormatDatepipe Value
M/d/yy, h:mm a{{todayDate | date:'short'}}5/19/20, 11:55 PM
MMM d, y, h:mm:ss a{{todayDate | date:'medium'}}May 19, 2020, 11:55:20 PM
MMMM d, y, h:mm:ss a z{{todayDate | date:'long'}}May 19, 2020 at 11:55:20 PM GMT+5
EEEE, MMMM d, y, h:mm:ss a zzzz{{todayDate | date:'full'}}Tuesday, May19, 2020 at 11:55:20 PM GMT+05:30
M/d/yy{{todayDate | date:'shortDate'}}5/19/20
MMM d, y{{todayDate | date:'mediumDate'}}May 19, 2020
MMMM d, y{{todayDate | date:'longDate'}}May 19, 2020
EEEE, MMMM d, y{{todayDate | date:'fullDate'}}Tuesday, May 19, 2020
h:mm a{{todayDate | date:'shortTime'}}11:55 PM
h:mm:ss a{{todayDate | date:'mediumTime'}}11:55:20 PM
h:mm:ss a z{{todayDate | date:'longTime'}}11:55:20 PM GMT+5
h:mm:ss a zzzz{{todayDate | date:'fullTime'}}11:55:20 PM GMT+05:30

Add Dynamic class in Angular 8



We can add dynamic class in Angular using NgClass .It is simple to use in HTML side lets see how

We have three class in the css with different colour


  .pending{

Color:orange;

  }

  .approved{

color:green;

  }

  .disapproved{

color:red;

  }



Above three  class  pending approved and disapproved will be used dynamically in NgClass with conditions




<div [ngClass]="{
                  'pending': element.Status =='Pending',
                  'approved': element.Status =='Approved',
                  'disapproved': element.Status =='Disapproved'
           
                  }">{{element.Status}}</div>



According to the Status the will be dynamically applied.

How to select single column using Linq C#



To select Specific Column using Linq in C# we have write following query base on data.




var Resume = _context.Resume.Where(e => e.EmployeeID ==
               EmployeeID && e.UploadDate == _context.Resume.Max(e => e.UploadDate)).FirstOrDefault();



On the basis of where condition we will get the specific record.

How to find years of experience in SQL

                   



To Find Year of experience in SQL we need to use DATEDIFF

Lets see how




 select (DATEDIFF(Year, DateOfJoining,getdate()))  from   Employee where EmployeeID=@EmployeeID



To get data in months



 select (DATEDIFF(month, DateOfJoining,getdate()))  from   Employee where EmployeeID=@EmployeeID

How to get Day or Weekday name from date in Sql Server


How to get Day or Weekday name from date in Sql Server



To Get Day or weekday from date we need to run below query




    SELECT GETDATE() 'Today', DATENAME(weekday,GETDATE()) ' DayName '



The Result will be like;


       Today                                  DayName 
       2020-05-14 13:14:23.503 Thursday