17 December 2021

JSON format data responce from webmethod to jquery AJAX and display in asp.net controls

 

Step 1: Create asp.net Project

Step 2: Create "jsonFile.json" file and add below code

{

  "status": "success",

  "status_code": 200,

  "product_name": "oneplus nord",

  "product_details": {

    "amount": 20000,

    "manufacturing_year": 2020,

    "manufacturing_month": "Jun",

    "color": "Blue"

  }

}


Step 3:  create "WebForm1.aspx" page and add below code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="JSON_Responce_from_Webmethod_To_Jquery_AJAX.WebForm1" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="Jquery/jquery-3.6.0.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:Button ID="btnGetDetails" runat="server" Text="Get Details" />

            <table>

                <tr>

                    <td>Product Name:</td>

                    <td>

                        <asp:DropDownList ID="ddlProductName" runat="server">

                            <asp:ListItem Text="Select" Value="Select"></asp:ListItem>

                            <asp:ListItem Text="oneplus nord" Value="oneplus nord"></asp:ListItem>

                            <asp:ListItem Text="Vivo" Value="Vivo"></asp:ListItem>

                            <asp:ListItem Text="Moto" Value="Moto"></asp:ListItem>

                        </asp:DropDownList>

                    </td>

                </tr>

                <tr>

                    <td>Amount:</td>

                    <td>

                        <input id="txtAmount" runat="server" type="text" />

                    </td>

                </tr>

                <tr>

                    <td>Manufacturing Year:</td>

                    <td>

                        <asp:TextBox ID="txtManufacturing_year" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Manufacturing Month:</td>

                    <td>

                        <asp:TextBox ID="txtManufacturing_month" runat="server"></asp:TextBox>

                    </td>

                </tr>

                <tr>

                    <td>Color:</td>

                    <td>

                        <asp:TextBox ID="txtColor" runat="server"></asp:TextBox>

                    </td>

                </tr>

            </table>


            <script type="text/javascript">

                $('#btnGetDetails').click(function (e) {

                    e.preventDefault();

                    //alert($("#DropDownList1 option:selected").text());

                    //var postData = {

                    //    'selectedData': $("#DropDownList1 option:selected").text()

                    //};

                    $.ajax({

                        type: "POST",

                        url: "/WebForm1.aspx/getProductDetails",

                        // data: JSON.stringify(postData),

                        contentType: "application/json; charset=utf-8",

                        dataType: "json",

                        success: function (r) {

                            $("#ddlProductName").val(r.d.product_name);

                            $('#txtAmount').val(r.d.product_details.amount);

                            $('#txtManufacturing_year').val(r.d.product_details.manufacturing_year);

                            $('#txtManufacturing_month').val(r.d.product_details.manufacturing_month);

                            $('#txtColor').val(r.d.product_details.color);

                            console.log(r.d.product_details);

                        }

                    });

                });

            </script>

        </div>

    </form>

</body>

</html>


Step 4: go to "WebForm1.aspx.cs" and update code.

using Newtonsoft.Json;

using System;

using System.IO;

using System.Web.Hosting;

using System.Web.Services;


namespace JSON_Responce_from_Webmethod_To_Jquery_AJAX

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            // JsonResponce();

        }

        [WebMethod]

        public static ProductRoot getProductDetails()

        {

            string jsonString = File.ReadAllText(HostingEnvironment.MapPath("~/jsonFile.json"));

            var content = jsonString;

            var jsonResult = JsonConvert.DeserializeObject(content).ToString();

            var result = JsonConvert.DeserializeObject<ProductRoot>(jsonResult);

            return result;

        }

    }

    public class ProductDetails

    {

        public int amount;

        public int manufacturing_year;

        public string manufacturing_month;

        public string color;

    }

    public class ProductRoot

    {

        public string status;

        public int  status_code;

        public string product_name;

        public ProductDetails product_details;

    }

}


Step 5: Now go and run the application it will display like below.



Step 6: Then click on "Get Details" button. it will hi the web method then it will read .json file and it will send response to jQuery. there we are assigning data to page controls.  as below image.



Github Link: https://github.com/adi501/JSON-Response-from-Webmethod-To-Jquery-AJAX

10 December 2021

Call a SQL function in Entity Framework Core

Step 1: Create .net core MVC project with Entity framework

Step 2:  Create Function in SQL Server

create function funFullName(@firstName varchar(10),@lastName varchar(10))

RETURNS varchar(25)

AS

BEGIN

RETURN @firstName+' '+@lastName

END

Step 3:  Add Connection in "appsettings.json" file 

 "ConnectionStrings": {

    "SQLDB": "Server=.;Database=Dotnet_Core_MVC;Trusted_Connection=True;"

  },

Step 4:  Create Model class in "FuntionOutput.cs" under DBContext/Models folder

namespace Dotnet_Core_MVC.DBContext.Models

{

    public class FuntionOutput

    {

        public string FullName { get; set; }

    }

}

Step 5:  Create class in "DatabaseContext.cs" under DBContext folder

using Dotnet_Core_MVC.DBContext.Models;

using Microsoft.EntityFrameworkCore;


namespace Dotnet_Core_MVC.DBContext

{

    public class DatabaseContext : DbContext

    {

        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)

        {


        }

        //Funtion Call

        public virtual DbSet<FuntionOutput> funFullName { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)

        {

            modelBuilder.Entity<FuntionOutput>(e => e.HasNoKey());

        }

    }

}

Step 6:  Create Controller "Call_A_SQL_FunctionController.cs"  and call the SQL Function ass below code.

using Dotnet_Core_MVC.DBContext;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace Dotnet_Core_MVC.Controllers
{
    public class Call_A_SQL_FunctionController : Controller
    {
        private readonly DatabaseContext _databaseContext;
        public Call_A_SQL_FunctionController(DatabaseContext databaseContext)
        {
            this._databaseContext = databaseContext;
        }
        public IActionResult Index()
        {
          ViewBag.functionOutput= _databaseContext.funFullName.FromSqlInterpolated($"select dbo.funFullName('adi','jc') as FullName").FirstOrDefault().FullName;
            return View();
        }
    }
}


Step 7:  Create View and add below code.

<h5>Function Output:</h5>@ViewBag.functionOutput

Step 8:  Open "Startup.cs" class and update "ConfigureServices" method as below.

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            var ConnectionString = Configuration.GetConnectionString("SQLDB");
            //Entity Framework  
            services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(ConnectionString));
        }

Output:

.net core WebAPI methods testing with xUnit

In this Article we can see .net core WebAPI methods testing with xUnit

Step 1: Create .net core WebAPI project 

Step 2: Create Model with below code

using System;

namespace WebAPI.Models

{

    public class Student

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

    }

}

Step 3: Create WebAPI Control with below code 

using Microsoft.AspNetCore.Mvc;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController : ControllerBase
    {
        [HttpPost]
        public ActionResult<string> CreateStudent(Student obj)
        {
            // you code here
            return "Data inserted successfully";
        }
        
    }
}

Step 4: Build the WebApi Project

Step 5: Create .net core xUnit Project.

Step 6: Create UnitTest class and add below code 

using Microsoft.AspNetCore.Mvc;
using WebAPI.Controllers;
using WebAPI.Models;
using Xunit;

namespace XUnitProject
{
    public class UnitTest1
    {
        [Theory]
        [InlineData(1, "Student 1", "Email1", "Data inserted successfully")]
        [InlineData(2, "Student 2", "Email2", "Data inserted successfully")]
        [InlineData(3, "Student 3", "Email3", "Data inserted successfully")]
        [InlineData(4, "Student 4", "Email4", "Data inserted successfully")]
        public void Test1(int Id, string Name, string Email, string ExpectedResult)
        {
            Student objStudent = new Student();
            objStudent.Id = Id;
            objStudent.Name = Name;
            objStudent.Email = Email;

            StudentController objStudentController = new StudentController();

            ActionResult<string> actionResult = objStudentController.CreateStudent(objStudent);
            string result = actionResult.Value;
            Assert.Equal(ExpectedResult, result);

        }
    }
}


Step 7: Right click on Test Method and select "Run Test(s)"

Output:



Github Code: https://github.com/adi501/xunit_on_dotnet_core_web_api
 

6 December 2021

How to call web method in asp.net using jquery

 ASP.Net Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="How_to_call_web_method_in_asp_net_using_jquery.aspx.cs" Inherits="WebApplication1.How_to_call_web_method_in_asp_net_using_jquery" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="Jquery/jquery-3.6.0.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:DropDownList ID="DropDownList1" CssClass="DropDownList1" runat="server">

                <asp:ListItem Text="Select" Value="0"></asp:ListItem>

                <asp:ListItem Text="asp.net" Value="1"></asp:ListItem>

                <asp:ListItem Text="c#" Value="2"></asp:ListItem>

                <asp:ListItem Text="ado.net" Value="3"></asp:ListItem>

                <asp:ListItem Text="SQL Server" Value="4"></asp:ListItem>

            </asp:DropDownList>

            <script type="text/javascript">

                $('#DropDownList1').change(function () {


                    alert($("#DropDownList1 option:selected").text());

                    var postData = {

                        'selectedData': $("#DropDownList1 option:selected").text()

                    };

                    $.ajax({

                        type: "POST",

                        url: "/How_to_call_web_method_in_asp_net_using_jquery.aspx/GetDropDownSelectedData",

                        data: JSON.stringify(postData),

                        contentType: "application/json; charset=utf-8",

                        dataType: "json",

                        success: function (r) {

                            alert(r.d);

                        }

                    });

                });

            </script>

        </div>

    </form>

</body>

</html>



C# Code:

using System;
using System.Web.Services;

namespace WebApplication1
{
    public partial class How_to_call_web_method_in_asp_net_using_jquery : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static string GetDropDownSelectedData(string selectedData)
        {
            //you can write you code here
            return selectedData;
        }
    }
}

5 December 2021

DropDownList change event using jQuery class selector in ASP.net

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DropDownList_change_event_using_jQuery_class_selector_in_ASP_net.aspx.cs" Inherits="WebApplication1.DropDownList_change_event_using_jQuery_class_selector_in_ASP_net" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="Jquery/jquery-3.6.0.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <div>

            <asp:DropDownList ID="DropDownList1" CssClass="DropDownListcss" runat="server">

                <asp:ListItem Text="Select" Value="0"></asp:ListItem>

                <asp:ListItem Text="asp.net" Value="1"></asp:ListItem>

                <asp:ListItem Text="c#" Value="2"></asp:ListItem>

                <asp:ListItem Text="ado.net" Value="3"></asp:ListItem>

                <asp:ListItem Text="SQL Server" Value="4"></asp:ListItem>

            </asp:DropDownList>

            <script type="text/javascript">

                $('.DropDownListcss').change(function () {

                    alert("DropDownList change() event.");

                    alert($(".DropDownListcss option:selected").text());

                    alert($(".DropDownListcss option:selected").val());

                });

            </script>

        </div>

        </div>

    </form>

</body>

</html>



DropDownList change event using jQuery in ASP.net

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DropDownList_Change_Event_Using_JQuery_in_ASP_net.aspx.cs" Inherits="WebApplication1.DropDownList_Change_Event_Using_JQuery_in_ASP_net" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="Jquery/jquery-3.6.0.js"></script>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <asp:DropDownList ID="DropDownList1" CssClass="DropDownList1" runat="server">

                <asp:ListItem Text="Select" Value="0"></asp:ListItem>

                <asp:ListItem Text="asp.net" Value="1"></asp:ListItem>

                <asp:ListItem Text="c#" Value="2"></asp:ListItem>

                <asp:ListItem Text="ado.net" Value="3"></asp:ListItem>

                <asp:ListItem Text="SQL Server" Value="4"></asp:ListItem>

            </asp:DropDownList>

            <script type="text/javascript">

                $('#DropDownList1').change(function () {

                    alert("DropDownList change() event.");

                    alert($("#DropDownList1 option:selected").text());

                    alert($("#DropDownList1 option:selected").val());

                });

            </script>

        </div>

    </form>

</body>

</html>

3 December 2021

Ternary operator example in react js

import React from "react";

function TernaryOperatorEXP2(props) {
    const status=1
  return (
    <div>
      <div>
        <h1>Ternary operator example in react js</h1>
      </div>
      <button> {status === 1 ? "Active" : "DeActive"} </button>
    </div>
  );
}
export default TernaryOperatorEXP2;

 Github link: https://github.com/adi501/react-js-example

substring function in react js

import React from 'react';

function SubstringEXP(props) {
    var str = "Hello world, react js SubString example";
    return (
        <div>
            <div><h1>SubString example</h1></div>
            {str.substring(0,10)}
        </div>
    );
}

export default SubstringEXP;

Github link: https://github.com/adi501/react-js-example

Reactjs code snippets

 Reactjs code snippets

How to install: https://marketplace.visualstudio.com/items?itemName=xabikos.ReactSnippets

Below is a list of all available snippets and the triggers of each one. The  means the TAB key.

Trigger

Content

rcc→

class component skeleton

rrc→

class component skeleton with react-redux connect

rrdc→

class component skeleton with react-redux connect and dispatch

rccp→

class component skeleton with prop types after the class

rcjc→

class component skeleton without import and default export lines

rcfc→

class component skeleton that contains all the lifecycle methods

rwwd→

class component without import statements

rpc→

class pure component skeleton with prop types after the class

rsc→

stateless component skeleton

rscp→

stateless component with prop types skeleton

rscm→

memoize stateless component skeleton

rscpm→

memoize stateless component with prop types skeleton

rsf→

stateless named function skeleton

rsfp→

stateless named function with prop types skeleton

rsi→

stateless component with prop types and implicit return

fcc→

class component with flow types skeleton

fsf→

stateless named function skeleton with flow types skeleton

fsc→

stateless component with flow types skeleton

rpt→

empty propTypes declaration

rdp→

empty defaultProps declaration

con→

class default constructor with props

conc→

class default constructor with props and context

est→

empty state object

cwm→

componentWillMount method

cdm→

componentDidMount method

cwr→

componentWillReceiveProps method

scu→

shouldComponentUpdate method

cwup→

componentWillUpdate method

cdup→

componentDidUpdate method

cwun→

componentWillUnmount method

gsbu→

getSnapshotBeforeUpdate method

gdsfp→

static getDerivedStateFromProps method

cdc→

componentDidCatch method

ren→

render method

sst→

this.setState with object as parameter

ssf→

this.setState with function as parameter

props→

this.props

state→

this.state

bnd→

binds the this of method inside the constructor

disp→

MapDispatchToProps redux function

 Reference: https://marketplace.visualstudio.com/items?itemName=xabikos.ReactSnippets

Convert String to Number in react js

import React from 'react';

function ConvertStringToNumber(props) {
    const num="2000";
    return (
        <div>
            <div><h1>Convert String to Number</h1></div>
            {Number(num)}
        </div>
    );
}
export default ConvertStringToNumber;

Github link: https://github.com/adi501/react-js-example

19 October 2021

Rearrange an array in order – largest,smallest, 2nd largest , 2nd smallest,... nth largest, nth smallest

Input is Array of integers. task is to check if any duplicates is there need to print like "Invalid Input". if duplicates not there we need to print like.

1st Largest Number, 1st smallest number, 2nd largest number, 2nd smallest number,....nth largest number, nth smallest..

You can see Examples in below:

Example 1: 

 Input: arr[] = [5, 8, 1, 4, 2,2, 9, 3, 7, 6]

 Output: Invalid Input

Example 2: 

Input: arr[] = [1,3,4,2,5,7,9,8,6]

Output:

9

1

8

2

7

3

6

4

5


Solution in C#.net

using System;

using System.Linq;


namespace ConsoleApp4

{

    class Program

    {

        static void Main(string[] args)

        {

            int[] input1 = new int[] { 1, 2, 3, 4, 5, 7, 8, 9, 6 };

            BigAndSmallNumbers(input1);

            Console.ReadKey();

        }

        public static void BigAndSmallNumbers(int[] input1)

        {

            bool duplicate = false;

            for (int i = 0; i < input1.Length; i++)

            {

                for (int j = i + 1; j < input1.Length; j++)

                {

                    if (input1[i] == input1[j])

                    {

                        duplicate = true;

                    }

                }

            }


            if (duplicate == false)

            {

                Array.Sort(input1);

                Array.Reverse(input1);

                int n = input1.Length;

                int ArrIndex = 0;

                int[] output = new int[input1.Length];


                for (int i = 0, j = n - 1; i <= n / 2 || j > n / 2; i++, j--)

                {


                    if (ArrIndex < n)

                    {

                        output[ArrIndex] = input1[i];

                        ArrIndex++;

                    }


                    if (ArrIndex < n)

                    {

                        output[ArrIndex] = input1[j];

                        ArrIndex++;

                    }

                }


                foreach (var a in output)

                {

                    Console.WriteLine(a);

                }

            }

            else

            {

                Console.WriteLine("Invalid Input");

            }

        }

    }

}


Code in Git: 
https://github.com/adi501/Rearrange-an-array-in-order-largest-smallest-2nd-largest-2nd-smallest-...-nth-largest-nth-smal





18 October 2021

How to install missing node modules in react js

npm install 

npm install: it will install all dependencies that are specified in the package.json

14 October 2021

usesqlserver not found .net core

 

First install the Microsoft.EntityFrameworkCore.SqlServer using NuGet Package like below

PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer


Then, import the namespace in file

using Microsoft.EntityFrameworkCore;