Friday, August 15, 2025

How to open binary file from database on browser- only display

 byte[] bytes =   file.FileData;

Response.Clear();

    Response.ContentType = file.ContentType;

Response.BinaryWrite(bytes);


https://www.aspsnippets.com/questions/206135/Open-Show-Base64-PDF-data-in-new-window-Tab-using-C-and-VBNet-in-ASPNet/

How to open new window with width and height - using window.open

  <a href="#" onclick="MyWindow=window.open('https://www.aspsnippets.com/Articles/660/Display-image-from-database-in-Image-control-without-using-Generic-Handler-in-ASPNet/','MyWindow','width=600,height=300'); ">click to open new window</a>

How to view the image in browser from database - binary image from database - asp.net

  string alert1 = "var image = new Image();";

        alert1+= "image.src='data:image/jpg;base64,"+ Convert.ToBase64String(bytes)+"';";

        alert1 += "var w = window.open('');";

              alert1+= "w.document.write(image.outerHTML);";


           ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenNewTabScript", alert1, true);


ref:-https://stackoverflow.com/questions/27798126/how-to-open-the-newly-created-image-in-a-new-tab

Thursday, August 14, 2025

System.InvalidOperationException: ExecuteScalar: Connection property has not been initialized.

 This error comes when you write below code:-


using (SqlCommand cmd=new SqlCommand("SELECT TOP 1 [FileID]  FROM [UploadFiles] order by Fileid desc"))


and not passed con as second parameter in SqlCommand. Use below code

using (SqlCommand cmd=new SqlCommand("SELECT TOP 1 [FileID]  FROM [UploadFiles] order by Fileid desc", con))


also you have to add below line

cmd.CommandType = System.Data.CommandType.Text;

How to display binary images from database - How to view images from database - view binary images - asp.net c# - How to download file from database

protected void FetchImage(object sender, EventArgs e)

{

    string id = ddlImages.SelectedItem.Value;

    Image1.Visible = id != "0";

    if (id != "0")

    {

        byte[] bytes = (byte[])GetData("SELECT Data FROM tblFiles WHERE Id =" + id).Rows[0]["Data"];

        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);

        Image1.ImageUrl = "data:image/png;base64," + base64String;

    }

}


ref:- https://www.aspsnippets.com/Articles/660/Display-image-from-database-in-Image-control-without-using-Generic-Handler-in-ASPNet/ 

How to run background music in website - HTML

 https://www.tutorialspoint.com/how-to-add-background-music-to-your-web-page

Tuesday, August 12, 2025

How to download file using binarywrite function and download file from url link - using webclient function

  protected void btnClickMe_Click(object sender, EventArgs e)

    {

                WebClient client = new WebClient();

        byte[] bytes = client.DownloadData("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgahqj6mU5OTtB-PLGl36tvYYv02OuXuR__pTakG-Y8dBc36TZaSboLga6RwM8DJUQKAwJ_sSjkp-4nhW1udweEejazbrZ50z2cb1ynJgIaZNBlrSIy827bc_5iY6UesB4/s220/WIN_20220808_12_53_18_Pro.jpg");

        Response.Clear(); //This must be add ,without this the file that you save will not be open

        Response.AddHeader("content-disposition", "attachment; filename=1.jpg"); 

         


 //Response.ContentType = System.Net.Mime.MediaTypeNames.Image.Jpeg; 


        //"application/octet-stream"; 


        Response.BinaryWrite(bytes);

        Response.Flush();

        Response.End();

    }


Note:-         Response.Clear(); //This must be add ,without this the file that you save will not be open

Friday, August 8, 2025

How to t change text font background of Menu Under Header of Blogger - Tabs of blogger - pages gadget of blogger

> Click on theme

>Click on Customize

>Click on advance

>Select tabs from dropdown list

> And you can change font size, font , background

>and click on save


Also you can change font size and font of other gadgets

Thursday, August 7, 2025

How to convert div to pdf using itextsharp asp.net - C# - Simplest and less code

First you have to download itextsharp.dll and itextsharp.pdfa.dll files and  you have to give the font size as below because in some case it will give error that font size is small.

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

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

    <div id="mainDiv" runat="server">

        

        <asp:Label runat="server" Text="Test" Font-Bold="true" Font-Size="13px" />

        <br />


        <asp:Label runat="server" Text="E-Admit Card" Font-Bold="true" Font-Size="13px" />

        <br />


        <table border="1">

            <tr>

                <td>

                    <asp:Label runat="server" Text="Date Of Test:" Font-Size="13px" />

                </td>

                <td>

                    <asp:Label runat="server" Text="20/11/2024" Font-Size="13px" />

                </td>

            </tr>

        </table>

        

    </div>

        <asp:Button ID="Button1" runat="server" Text="Print" OnClick="Button1_Click" />

</form>


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

 protected void Button1_Click(object sender, EventArgs e)

    {

        Response.ContentType = "application/pdf";

        Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        StringWriter stringWriter = new StringWriter();

        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

        

        mainDiv.RenderControl(htmlTextWriter);

        StringReader stringReader = new StringReader(stringWriter.ToString());

        Document Doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

        HTMLWorker htmlparser = new HTMLWorker(Doc);

        PdfWriter.GetInstance(Doc, Response.OutputStream);


        Doc.Open();

        htmlparser.Parse(stringReader);

        Doc.Close();

        Response.Write(Doc);

        Response.End();

    }

Tuesday, July 29, 2025

Nupkg extension file from nuget package

 Convert nupkg file to zip file and you will get dll files in it. 


On the right hand side of nuget website you will get "download package" option.

Monday, July 28, 2025

How to print a print statement of sql in asp.net c# - how to call a another event in asp.net event

 using System;

using System.Data.SqlClient;


public class SqlPrintExample

{

    public static void Main(string[] args)

    {

        string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";

        string sqlQuery = "PRINT 'This message comes from SQL.'; SELECT GETDATE() AS CurrentDateTime;";


        using (SqlConnection connection = new SqlConnection(connectionString))

        {

            // Attach an event handler to capture InfoMessage events (including PRINT statements)

            connection.InfoMessage += Connection_InfoMessage;

or// conn.InfoMessage += new SqlInfoMessageEventHandler( Connection_InfoMessage);

            try

            {

                connection.Open();

                using (SqlCommand command = new SqlCommand(sqlQuery, connection))

                {

                    using (SqlDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            Console.WriteLine($"Current Date Time from SQL: {reader["CurrentDateTime"]}");

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine($"Error: {ex.Message}");

            }

        }

    }


    private static void Connection_InfoMessage(object sender, SqlInfoMessageEventArgs e)

    {

        // Display the message from the SQL PRINT statement

        Console.WriteLine($"SQL InfoMessage: {e.Message}");

    }

}

do while loop in sql server - Cursor in Sql Server

For data looping in sql Server, we use While loop  or cursor


 DECLARE @cnt INT = 0;


WHILE @cnt < 10

BEGIN

   PRINT 'Inside simulated FOR LOOP on TechOnTheNet.com';

   SET @cnt = @cnt + 1;

END;


PRINT 'Done simulated FOR LOOP on TechOnTheNet.com';

GO


For cursor:-


https://www.c-sharpcorner.com/blogs/how-to-use-cursors-and-while-loop-in-sql-server

Thursday, July 17, 2025

How to download the file secretly using webclient class -asp.net c#

  using (WebClient client = new WebClient())

        {

            


            string url = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiOJA1ZDa4CQ6OwLx-iL10cLEXpzoJZmZUVLHjJqHBr3-Q9TBEBpjD_ZZgtNGMj59CXGWtZ1yu-CfUoyuU8I7nGjgpwk0wCal_oGSPZNREQssIHeC5PFC10v8YdEIe5ie2wLyfGsrHSBR213ATgNXPyotNs66AoYF2CWPfAx9gu2cgYKw/s1600/Screenshot%202025-05-14%20184428.png";

            

            string savePath = "D:/image1212.jpg";

            client.DownloadFile(url, savePath);


        }


How to call a http handler in web form - asp.net c#

 <script type="text/javascript" src="http://localhost:49183/AsyncHTTPModuleHandler/MyHandler.ashx?url=<%= Request.Path%>">

</script>


public override ProcessRequestAsync(HttpContext context)
{

    string targetUrl = context.Request.QueryString["url"];
}

Thursday, July 10, 2025

How to create and download txt file programaticaly with asp.net c# and write content in it

   Response.Clear();

        Response.Write("This is an HttpHandler Test.");

        Response.Write("<p>Your Browser:</p>");


        Response.AddHeader("content-disposition", "attachment; filename=t.txt");

        Response.End(); 

How to download pdf file from server not on database only on server - Simplest way

//only two lines code is required that is uncommented

//Response.Clear(); // This is i am not using because response.clear is used for clearing http response (like text) but this is a file that is presently on server. Also when we create pdf of text file than we use clear function and we are getting pdf file from database (binary fromat) Response.buffer is default true so we don't need.

 Response.AddHeader("content-disposition", "attachment; filename=t.pdf"); 

 //Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf; 

        //"application/octet-stream"; 

        Response.WriteFile(Server.MapPath("~/App_Data/Annexure.pdf")); // File must be there on server otherwise it will give error


//Response.end is also we are not using because we are not creating pdf file , if we create pdf file or we are getting from database than we use Response.End and Response.Clear() functions.

Response.WriteFile or Response.TransmitFile use in asp.net c# - how to view pdf or text file in web browser

 It is used to show the content of any file in web browser.  This  is same as response.write but it will write the content of the file to web page. Mainly it is used to view the file content not to download the file.  Both Response.WriteFile or Response.TransmitFile  are same

example if text file than use code below

For PDF file

Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;

Response.WriteFile(Server.MapPath("~/App_Data/Annexure.pdf"));


For txt file

Response.Clear(); 

     

        Response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain;  and use Text.html

        //"application/octet-stream"; 

        Response.WriteFile(Server.MapPath("~/App_Data/yash.txt"));

        Response.End(); 



or on page load, simply we can show the content of text file

Response.WriteFile("~/App_Data/" + fileName);

Friday, June 20, 2025

Website admin tool - access rules for files and folders

Access rules are store in web.config for each folder

example like below:-

<?xml version="1.0" encoding="utf-8"?>

<configuration>

    <system.web>

        <authorization>

            <allow roles="Administrator" />

          <deny users="*" />

        </authorization>

    </system.web>

</configuration>

How to download the file using handler in asp.net c# of any format or extension - using anchor tag

  public void ProcessRequest(HttpContext context)

  {

    if (context.User.Identity.IsAuthenticated)

    {

      string filename = context.Request.QueryString["File"];

      //Validate the file name and make sure it is one that the user may access

      context.Response.Buffer = true;

      context.Response.Clear();

      context.Response.AddHeader("content-disposition", "attachment; filename=" + filename);

      context.Response.ContentType = "application/octet-stream";

//File(HelloWorld.txt) should be present on server in App_Data folder , otherwise it will show error

      context.Response.WriteFile("~/App_Data/" + filename);

    }

  }

aspx page

<a href="MyFileHandler.ashx?File=HelloWorld.txt">Click Here to Get File</a>


or 

 string fileName = context.Request.Params["File"];

 context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf; //"application/pdf"

//File(HelloWorld.txt) should be present on server in App_Data folder , otherwise it will show error

 context.Response.WriteFile("~/App_Data/" + fileName);

How to download the file using transmitfile function in asp.net c#

 Response.ContentType = "application/pdf";

Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");

//MyFile.pdf should be present in Files folder on server. other wise it will show error file not found.

Response.TransmitFile(Server.MapPath("~/Files/MyFile.pdf"));

Response.End();


reference:-https://www.c-sharpcorner.com/UploadFile/afenster/how-to-download-a-file-in-Asp-Net/

why Http Handler are used - Introduction to handler

 Http handlers are used for


Binary files

Dynamic image views

Performance-critical web pages

XML files

Minimal web pages


and these are fast and it only gives minimum response. example when you write  

Response.ContentType = "text/plain";

         //MediaTypeNames.Text.Plain

in aspx page it will give lot of information.

and when you write this in handler it will give only specific information that you want.


Also no return type of processrequest funtion in http handler

you can create other return type function in handler and also create model in handler.

Thursday, June 19, 2025

Computer vs television - difference between computer and television

 Computer is having data and english hindi lanuguage all time. and text is very small


but in television we have visual things , and text is very large if it had

Tuesday, June 17, 2025

How to split the comma separated string to list of array in C#

string tags = "9,3,12,43,2"


 tags.Split(',').Select(int.Parse).ToList();

How to convert bytes to string and string to bytes in c#

 


        string author = "Mahesh Chand";

        // Convert a C# string to a byte array

        byte[] bytes = Encoding.ASCII.GetBytes(author);

        foreach (byte b in bytes)

        {

            Response.Write(b );

            Response.Write(Environment.NewLine);                       

        }


bytes to string

string myString = Encoding.ASCII.GetString(bytes);

Response.Write(str);

How to convert bytes to base64string in c#

using fileupload control

 Convert.ToBase64String(fileUpload1.FileBytes);


using memory stream

 Stream fs = fileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        

        Byte[] bytes = br.ReadBytes((int)fs.Length);

 Convert.ToBase64String(bytes );



base64 string meaning

the upper- and lower-case Roman alphabet characters (A–Z, a–z), the numerals (0–9), and the "+" and "/" symbols, with the "=" symbol as a special suffix code



How to save bytes data to image

using memory stream

MemoryStream m = new MemoryStream(bytes); 

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

MyImage.Save(filepathandname)

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

using fileupload control

fileUpload1.FileBytes;

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

MyImage.Save(filepathandname)

How to save a file to binary data to varbinary sql server in asp.net c# - How to save file to database with varbinary(max) datatype

Using fileupload field

byte[] bb = fileUpload1.FileBytes;

  SqlConnection con = new SqlConnection(ConnectionString.ConString);


            con.Open();

            SqlCommand cmd = new SqlCommand("INSERT INTO UploadFiles (FileData, ContentType) VALUES (@filedata, @ContentType)", con);

            cmd.CommandType = System.Data.CommandType.Text;

            

            

            cmd.Parameters.AddWithValue("@FileData", fileUpload1.FileBytes);

            cmd.Parameters.AddWithValue("@ContentType", fileUpload1.PostedFile.ContentType);


            cmd.ExecuteNonQuery();

            con.Close();

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

using binary reader

 Stream fs = fileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        

        Byte[] bytes = br.ReadBytes((int)fs.Length);

  Stream fs = fileUpload1.PostedFile.InputStream;

 Byte[] bytes = br.ReadBytes((int)fs.Length);

object vs instance - object instance - instance vs object in c#

 object are also called instance.

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 - How to view image in html page

 <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();

    }