Friday, June 6, 2025

Fundamental unit of data

 Fundamental unit of data in computer is bit or binary digit  0, 1

how to convert byte array to image in asp.net

Byte[] bytes =  fileUpload1.FileBytes;

  MemoryStream m = new MemoryStream(bytes);

     System.Drawing.Image MyImage = System.Drawing.Image.FromStream(m);            

            string filepathandname = Server.MapPath(string.Format("~/uploads/{0}-{1}-{2}", DateTime.Now.ToShortDateString(), Guid.NewGuid(), ".png"));

            MyImage.Save(filepathandname);

Thursday, June 5, 2025

How to see or view a base 64 image file or image file in HTML page and how to see image file base 64 with URL

 <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABkAAAAOECAYAAAD5Tf2iAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAP+lSURBVHhe7N0LYFTVuTb+B1AkeIGEm0CABBAiglyD3CINoqJoKRSRNqWtSEUK51NrgVKPHD48LYLHqt8fSvEgtlJaRAqlFouKIAUBCYIXREAggVwAA0lQgQgK//2uvfbMnvueaybx+dld9m1m1r5OZr17rbdOt249LoGIiIiIiIiIiIiIiKgWqav/JSIiIiIiIiIiIiIiqjUYACEiIiIiIiIiIiIiolqHARAiIiIiIiIiIiIiIqp1GAAhIiIiIiIiIiIiIqJahwEQIiIiIiIiIiIiIiKqdep069bjkh4nIiIiIiIiIiKq1erXv0KPEVFtdf78V3qMvu3YAoSIiIiIiIiIiIiIiGodBkCIiIiIiIiIiIiIiKjWqdeixbWz9Hi1qFevHn7zmydwyy1DUFVVhaKiIr2EiIiIiIiIiIgoturVu0yP

Sunday, June 1, 2025

Web api get post delete and put difference in apicontroller class

 public class ValuesController : ApiController

{


  //For get all data

    public IEnumerable<BookMaster> Get()

    {

           }

    

   

//For get by ID

    public void Get(int id)

    {

        }

        


    [HttpPost] // insert or add or create new

    public string Post([FromBody]string value)

    {

        return value;

    }


    // PUT api/<controller>/5    update

        public void Put(BookMaster bookMaster) 

    {    

    }


    // DELETE api/<controller>/5

    [HttpDelete]

    public void Delete(int id)

    {

    }


How to use ObjectDataSource in asp.net with Model or business object and controller or login layer

 >Add object datasource from controls in visual studio

> Add TypeName Property(class name .cs file) where you have get, update and delete methods.

>Click on configure data source and select dataset or typename file and you will get select insert update delete methods and click on finish and use this object datasource id in grid view or other controls. 

bulk insert with single insert query in sql

 INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

Transaction in asp.net c#

 https://learn.microsoft.com/en-us/aspnet/web-forms/overview/data-access/working-with-batched-data/wrapping-database-modifications-within-a-transaction-cs

Friday, May 30, 2025

A network-related or instance-specific error occurred while establishing a connection to SQL Server. Error

>First open services.msc from wondow + r (Window Services)

> Then right click on sql server (SQL express)

>go to Properties

Then go to Log On tab and select Local System account

Click on Ok button and start the service.

Sunday, May 25, 2025

How to call two insert queries on one button in click in asp.net C#

 protected void Unnamed_Click(object sender, EventArgs e)

    {

        //TextBox t = DetailsView1.FindControl("TextBox1") as TextBox;

        string conStr = ConfigurationManager.ConnectionStrings["testdbConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(conStr))

        {

            if (ddlSelect.SelectedValue == "1")

            {

                abc(txt1.Text, con);

            }

            if (ddlSelect.SelectedValue == "2")

            {

                abc(txt1.Text, con);

                abc(TextBox2.Text, con);

            }

}

}


void abc(string value, SqlConnection con)

    {

        SqlCommand cmd = new SqlCommand();

        cmd = new SqlCommand("INSERT INTO BookMaster(BookName) VALUES (@BookName)", con);

        cmd.CommandType = CommandType.Text;

        cmd.Parameters.AddWithValue("@BookName", value);

        con.Open();

        cmd.ExecuteReader();

        con.Close();

    }

Friday, May 16, 2025

Restore of database failed sql server

>Open sql server

>Right Click on database >click on task>restore>database

>From device >select database bak file

>In option tab > Check overwrite the existing database (with replace)

or > in file tab click on reallocate all files to folder

Tuesday, May 13, 2025

How to collapse and expand functions of class in Visual studio

 Ctrl+M+M


Or in visual studio go to Edit and outlining and there are different shortcuts for more commands.

Saturday, May 3, 2025

How to create webapi in website without MVC Namespace - My First Webapi

 >First you have to add three files in project 1)Global.asax 2) testApiController.cs by adding web api controller class in project(add new item) 3)WebApiConfig.cs file

> Add below code in these files

  Global.asax

void Application_Start(object sender, EventArgs e) 

    {

        // Code that runs on application startup

        YashWebsiteWebForm.WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);

    }


WebApiConfig.cs

 public static class WebApiConfig

    {

      

        public static void Register(HttpConfiguration config)

        {

            

            config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{id}",    

                defaults: new { id = RouteParameter.Optional }

                );

        }

    }

Monday, April 28, 2025

Saturday, April 26, 2025

How to create unique key in SQL server management studio

 >First Open Visual Studio

>Right Click on table and click on Design

>Right Click on column name left side

>Click on Indexes/Key

>Select Unique key in 'Type' Filed


Note:- Sometime unique key option is not visible

Saturday, April 19, 2025

asp.net button pass value to url in grid view

    <asp:Button ID="Button1" runat="server"

            PostBackUrl='<%# Eval("Id","~/Employee/Update/{0}") %>'

            Text="Save" Width="75px" />

Friday, April 18, 2025

how to use webclient class uploadstring - For webapi, webservice, handler - For post and for get

webclient in asp.net 


for get

 string handlerUrl = String.Format(Request.Url.Scheme+"://" +Request.Url.Authority+"{0}","/api/values");

        string response = (new WebClient()).DownloadString(handlerUrl);


for post

   using (var client = new WebClient())

        {

            string handlerUrl = String.Format(Request.Url.Scheme + "://" + Request.Url.Authority + "{0}", "/api/values");

            client.Headers[HttpRequestHeader.ContentType] =  "application/x-www-form-urlencoded";

            var data = "=Short test...";

            string result = client.UploadString(handlerUrl, "POST", data);

            

            Response.Write(result);

        }


 https://www.aspsnippets.com/Articles/2149/Call-Consume-Web-API-using-WebClient-in-ASPNet-C/

How to use object as list of object - Array of object - How to create object in C#

   object input = new { Name ="yash"};

        input = 6;

        List<object> a = new List<object>();

        a.Add(5);

        a.Add( "ere");


object[] jji=new object[2]{ new {s = "df"}, new {s= "df"}};

some times we can use 

dr.ItemArray = new Object[] {new {    AgentName = "dfdf"}, new {AgentName = "df"} };

How to view a json file in web browser using asp.net webclient

 string json = (new WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");

 

        //Return the JSON string.

        return Content(json);

Thursday, April 17, 2025

How to create model or business object from database in visual studio asp.net - How to create Entity Data Model - DbContext class

 > Add new item in visual studio

> Add ADO.net entity data model

>Click generate from database

>Set connection string Yes or no

> Select table

>Click finish

> Click on ok when says it can harm computer

> Go to model.tt

> You can copy entity model

Note:- When creating a Entity Data Model> In the EDMX file > Goto properties and Code generation Stratigy to Default > you will see the code in the designer file(if it is showing blank file)

In web.config file connection string name will store as (use dbcontext) for remeber.

we have to use context.cs class for CRUD operation

example

//create 

using (EmployeeDBContext dbContext = new EmployeeDBContext())

        {

            dbContext.Employees.Add(employee);

            dbContext.SaveChanges();

        }

===============

//update

using (EmployeeDBContext dbContext = new EmployeeDBContext())

        {

            var entity = dbContext.Employees.FirstOrDefault(e => e.ID == id);

            entity.FirstName = employee.FirstName;

            entity.LastName = employee.LastName;

            entity.Gender = employee.Gender;

            entity.Salary = employee.Salary;

            dbContext.SaveChanges();

        }

==============

//Delete

using (EmployeeDBContext dbContext = new EmployeeDBContext())

        {

            dbContext.Employees.Remove(dbContext.Employees.FirstOrDefault(e => e.ID == id));

            dbContext.SaveChanges();

        }

============

//Getall

  using (BookMasterdbEntities db=new BookMasterdbEntities())

        {

           return db.BookMasters.ToList();

        }

==============

//Getbyid

  using (BookMasterdbEntities dbContext = new BookMasterdbEntities())

        {

            dbContext.BookMasters.add(dbContext.BookMasters.FirstOrDefault(a => a.BookID == id));

            dbContext.SaveChanges();

        }


ref:- https://dotnettutorials.net/lesson/web-api-with-sql-server/


Friday, March 28, 2025

How to add string of array to data source of grid

 public class File1

{

    public string FileName { get; set; }

}


  List<File1> Files = new List<File1>();


if (Directory.GetFiles(Server.MapPath("/uploads/")).Count() > 0)

        {

            foreach (var item in Directory.GetFiles(Server.MapPath("/uploads/")))

            {

                

                Files.Add(new File1 { FileName = item });

                Response.Write(item);

                

                grdTest.DataSource = Files;


                grdTest.DataBind();

            }


        }

How to find the dicrectory path of website

 Response.Write(Request.PhysicalApplicationPath );   //output C:\Users\Yash User\Documents\Visual Studio 2012\WebSites\YashWebsiteWebForm\

        Response.Write(Request.PhysicalPath + Environment.NewLine); // output C:\Users\Yash User\Documents\Visual Studio 2012\WebSites\YashWebsiteWebForm\Default3.aspx


        Response.Write(Request.RawUrl );  //output  /Default3.aspx

        Response.Write(Request.Url); // output http://localhost:49730/Default3.aspx


Server.MapPath ("");   //output C:\Users\Yash User\Documents\Visual Studio 2012\WebSites\YashWebsiteWebForm


Wednesday, March 26, 2025

How to write query with query builder in SQL server

 > Open Sql server management studio

> Right click on editor and click on "Design query in editor"

> And right click in that to change insert update or delete query.

How to create a new table with select query in SQL

 SELECT   [Date]

      ,[SchemeNo] ,[Commission]

INTO        test3

FROM     PolicyDetails

Wednesday, March 12, 2025