#Context menu with Powershell
for ($i = 1; $i -le 500; $i++) {
[System.Windows.Forms.SendKeys]::SendWait("^+{F10}")
Write-Host "Iteration: $i"
}
#Context menu with Powershell
for ($i = 1; $i -le 500; $i++) {
[System.Windows.Forms.SendKeys]::SendWait("^+{F10}")
Write-Host "Iteration: $i"
}
1) Download Node JS in nodejs.org
2) Go to downloads
3) Download msi file
4) At last after finish installation, Click on close while install Additional Tools for Node.js
ref:- https://nodesource.com/blog/installing-nodejs-tutorial-windows
After installing, you can generate subtitles for videos in node js by below link
sample video link, below
ref:-https://storage.googleapis.com/aai-web-samples/aai-overview.mp4
Private Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
' Define the mouse events
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_ABSOLUTE = &H8000
Public Const MOUSEEVENTF_MOVE = &H1
Sub SimulateLeftClick(ByVal x As Long, ByVal y As Long)
' Move the cursor to the specified coordinates (screen coordinates)
SetCursorPos x, y
' Perform the left click (Down and then Up)
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub
Sub TestClick()
' Clicks at screen coordinates X=50, Y=50
Call SimulateLeftClick(40, 200)
End Sub
Enter below text in Chrome URL
data:text/html, <title>Notepad</title><body contenteditable style="font-size:18px;line-height:1.6;font-family:sans-serif;">
>Open Windows Explorer
> Go to View
> Uncheck navigation Pane
<html>
<head>
<link href="https://vjs.zencdn.net/8.23.4/video-js.css" rel="stylesheet" />
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/1.1.2/videojs-ie8.min.js">
function init() {
var url = "https://dash.akamaized.net/akamai/test/caption_test/ElephantsDream/elephants_dream_480p_heaac5_1_https.mpd",
video = video = document.querySelector('video'),
player;
player = dashjs.MediaPlayer({}).create();
player.initialize(video, url, true);
}
</script>
</head>
<body>
<video
id="my-player"
class="video-js"
controls
preload="auto"
poster="//vjs.zencdn.net/v/oceans.png"
data-setup='{}'>
<source src="//vjs.zencdn.net/v/oceans.mp4" type="video/mp4"></source>
<source src="//vjs.zencdn.net/v/oceans.webm" type="video/webm"></source>
<source src="//vjs.zencdn.net/v/oceans.ogv" type="video/ogg"></source>
<p class="vjs-no-js">
To view this video please enable JavaScript, and consider upgrading to a
web browser that
<a href="https://videojs.com/html5-video-support/" target="_blank">
supports HTML5 video
</a>
</p>
</video>
<video
id="my-video"
class="video-js vjs-default-skin"
controls
preload="auto"
width="560"
height="300"
data-setup='{}'>
<source
src="https://vjs.zencdn.net/v/oceans.mp4"
type="video/mp4"
size="1080"
>
<track
kind="subtitles"
src="https://gist.githubusercontent.com/samdutton/ca37f3adaf4e23679957b8083e061177/raw/e19399fbccbc069a2af4266e5120ae6bad62699a/sample.vtt"
srclang="en"
label="English"
>
</video>
</body>
<html>
Start-Sleep -Seconds 3
[System.Windows.Forms.SendKeys]::SendWait("^+{F10}")
[System.Windows.Forms.SendKeys]::SendWait("e")
CTRL + E----- To merge two cells
ALT + H +O +I ----------- Column width Auto size
ALT +H + W or ALT + H + O +A ---------- Auto size column height
#Context menu with Powershell
[System.Windows.Forms.SendKeys]::SendWait("^+{F10}")
Shift + F10
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName Microsoft.VisualBasic
Start-Process -FilePath "explorer.exe"
# Wait for WinWord to open and become active
Start-Sleep -Seconds 1
(New-Object -ComObject "wscript.shell").SendKeys("^{l}")
Start-Sleep -Seconds 1
(New-Object -ComObject "wscript.shell").SendKeys("D:\")
Start-Sleep -Seconds 1
(New-Object -ComObject "wscript.shell").SendKeys("{Enter}")
#Context menu with Powershell
[System.Windows.Forms.SendKeys]::SendWait("^+{F10}")
Start-Sleep -Seconds 1
[System.Windows.Forms.SendKeys]::SendWait("^+n")
Start-Sleep -Seconds 1
(New-Object -ComObject "wscript.shell").SendKeys("{Enter}")
#Note This first line is mandatory
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Start WinWord (if not already running)
Start-Process -FilePath "excel.exe"
# Wait for WinWord to open and become active
Start-Sleep -Seconds 3
# Activate the WinWord window (adjust the title if necessary)
$wshell = New-Object -ComObject wscript.shell
#$wshell.AppActivate("Document1 - Word") # Or the actual document title
Start-Sleep -Seconds 1
for ($i = 1; $i -le 5; $i++) {
$j = [char](65 + $i)
[System.Windows.Forms.SendKeys]::SendWait("$j")
}
or
for ($test = 0; $test -lt 26; $test++)
{
[char](65 + $test)
}
>click on Start button
> Type Printers and scanners
>Select printer(Printer that you work like HP or Other) and Manage
> Click on Open Print Queue
> Click on Printer And Click on pause Printing(Check and Uncheck for Printing)
# Load the necessary assemblies for accessing mouse position information
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
Write-Host "Move your mouse. Press Ctrl+C to stop."
while ($true) {
# Get the current mouse position
$cursorPosition = [System.Windows.Forms.Cursor]::Position
$x = $cursorPosition.X
$y = $cursorPosition.Y
# Print the coordinates. Using Write-Host with -NoNewline and carriage return `r`
# overwrites the previous line in the console for a cleaner continuous update.
Write-Host "`rX: $x | Y: $y" -NoNewline
# Wait for a short period to prevent the loop from consuming too much CPU
Start-Sleep -Milliseconds 100
}
or for single position
Add-Type -AssemblyName System.Windows.Forms
$mousePosition = [System.Windows.Forms.Cursor]::Position
Write-Host "Current mouse position is X: $($mousePosition.X), Y: $($mousePosition.Y)"
for ($i = 100; $i -ge 10; $i--) {
Start-Sleep -Milliseconds 1
Write-Host "Iteration: $i"
[System.Windows.Forms.Cursor]::Position = "$i, $i "
}
or with 10 decrement
for ($i = 1000; $i -ge 10; $i -= 10) {
Start-Sleep -Milliseconds 1
Write-Host "Iteration: $i"
[System.Windows.Forms.Cursor]::Position = "$i, $i "
}
[System.Windows.Forms.Cursor]::Position = "700,700"
Add-Type –AssemblyName UIAutomationClient
Add-Type –AssemblyName UIAutomationTypes
$calc = [Diagnostics.Process]::Start('calc')
#wait for the UI to appear
$null = $calc.WaitForInputIdle(5000)
sleep –s 2
$calcWindowId = ((Get-Process).where{$_.MainWindowTitle -eq 'Calculator'})[0].Id
$root = [Windows.Automation.AutomationElement]::RootElement
$condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ProcessIdProperty, $calcWindowId)
$calcUI = $root.FindFirst([Windows.Automation.TreeScope]::Children, $condition)
function FindAndClickButton($name){
$condition1 = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::ClassNameProperty, "Button")
$condition2 = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::NameProperty, $name)
$condition = New-Object Windows.Automation.AndCondition($condition1, $condition2)
$button = $calcUI.FindFirst([Windows.Automation.TreeScope]::Descendants, $condition)
$button.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern).Invoke()
}
#get and click the buttons for the calculation
FindAndClickButton Five
FindAndClickButton Plus
FindAndClickButton Nine
FindAndClickButton Equals
#get the result
$condition = New-Object Windows.Automation.PropertyCondition([Windows.Automation.AutomationElement]::AutomationIdProperty, "CalculatorResults")
$result = $calcUI.FindFirst([Windows.Automation.TreeScope]::Descendants, $condition)
$result.current.name
Sub CommandButton1_Click()
Shell "Notepad.exe", vbNormalFocus
Dim I As Integer
SendKeys "one"
SendKeys "{Enter}"
Application.Wait (Now + TimeValue("00:00:01"))
SendKeys "^a"
Application.Wait (Now + TimeValue("00:00:01"))
SendKeys "^c"
Application.Wait (Now + TimeValue("00:00:01"))
SendKeys "{right}"
Application.Wait (Now + TimeValue("00:00:01"))
SendKeys "two"
Application.Wait (Now + TimeValue("00:00:01"))
End Sub
Sub SendAlphabet_AtoZ()
Shell "Notepad.exe", vbNormalFocus
Dim i As Integer
Dim char_code As Integer
Dim current_char As String
Dim row_num As Integer
Dim z As Integer
For z = 1 To 50
row_num = 1
' Loop through ASCII codes for lowercase 'a' (97) to 'z' (122)
For char_code = 50 To 122
' Convert the ASCII code to a character
current_char = Chr(char_code)
Application.Wait (Now + TimeValue("00:00:00"))
' Place the character in the active worksheet in column A
SendKeys current_char
' Move to the next row
Next char_code
Next z
End Sub
Start-Sleep -Seconds 5
$wshell = New-Object -ComObject WScript.Shell
$wshell.SendKeys("^{F4}")
or
#Note This first line is mandatory
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Start WinWord (if not already running)
Start-Process -FilePath "explorer.exe"
# Wait for WinWord to open and become active
Start-Sleep -Seconds 3
(New-Object -ComObject "wscript.shell").SendKeys("^{ESC}")
# Activate the WinWord window (adjust the title if necessary)
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
https://stackoverflow.com/questions/19824799/how-can-i-send-ctrl-or-alt-any-other-key
=Countif('SheetName'!I3:I998, "Open")
I3:I998 is range
for ($i = 0; $i -lt 1000; $i++) {
(New-Object -ComObject "wscript.shell").SendKeys("^{ESC}")
# Optional: Add a small delay (e.g., 10 milliseconds) to prevent overwhelming the system
Start-Sleep -Milliseconds 10
}
Note:- Start-Sleep -Milliseconds 10 // Fastest
Start-Sleep -Milliseconds 100 //More Fast
Start-Sleep -Milliseconds 1000 //Slow
(New-Object -ComObject "wscript.shell").SendKeys("^{ESC}")
Start-Sleep -Seconds 3
[System.Windows.Forms.SendKeys]::SendWait("file explorere")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
function Send-MouseClick {
# Define the necessary Win32 API function for mouse events
$signature = @'
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
'@
$mouseEvents = Add-Type -MemberDefinition $signature -Name "Win32MouseEvents" -Namespace "Windows" -PassThru
# Mouse event flags
$MOUSEEVENTF_LEFTDOWN = 0x0002
$MOUSEEVENTF_LEFTUP = 0x0004
# Get current cursor position
$cursorPos = [System.Windows.Forms.Cursor]::Position
$x = $cursorPos.X
$y = $cursorPos.Y
# Perform the left mouse button down and up events
$mouseEvents::mouse_event($MOUSEEVENTF_LEFTDOWN, $x, $y, 0, 0)
$mouseEvents::mouse_event($MOUSEEVENTF_LEFTUP, $x, $y, 0, 0)
}
# Loop 1000 times to perform 1000 clicks
for ($i = 0; $i -lt 1000; $i++) {
Send-MouseClick
# Optional: Add a small delay (e.g., 10 milliseconds) to prevent overwhelming the system
Start-Sleep -Milliseconds 10
}
Write-Host "1000 clicks performed."
Sub Macro2()
Shell "winword", vbNormalFocus
SendKeys "George W. Bush"
SendKeys "%{F4}", True
SendKeys "{ENTER}", True
'SendKeys "George W. Bush.txt", True' 'Comment'
'SendKeys "%S"' 'Comment'
End Sub
Type this below code in URL
file:///C:/
> Open developer tools in chrome
> Go to sources tab and select overrides tab
> Click on "select folder for overrides" and Select the folder where you want to change the overrides
> Right click on element of website and change color of background or style
> Click on sources tab and Page tab and save the css file in folder where you select the folder above.
If you want to delete, goto sources tab and goto overrides tab and delete overrides. And the website will be able to run as it was.
Note:-
After the above steps, For Enable styles that you edit, right click and inspect > Go to Sources> Overrides> Check Enable Local Overrides
For disable styles that you edit, right click and inspect > Go to Sources> Overrides> UnCheck Enable Local Overrides or refresh page will disable style overrides
or you can use stylebot extension in chrome.
Sub CommandButton1_Click()
Shell "Notepad.exe", vbNormalFocus
Dim I As Integer
SendKeys "one"
SendKeys "{Enter}"
SendKeys "two"
End Sub
for ($i = 1; $i -le 5; $i++) {
Write-Host "Iteration: $i"
}
with 10 increments
for ($i = 1; $i -le 50; $i += 10) {
Write-Host "Iteration: $i"
}
#Note This first line is mandatory
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Start WinWord (if not already running)
Start-Process -FilePath "winword.exe"
# Wait for WinWord to open and become active
Start-Sleep -Seconds 3
# Activate the WinWord window (adjust the title if necessary)
$wshell = New-Object -ComObject wscript.shell
#$wshell.AppActivate("Document1 - Word") # Or the actual document title
Start-Sleep -Seconds 1
# Send some text and an Enter key
[System.Windows.Forms.SendKeys]::SendWait("This is a test message.")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
[System.Windows.Forms.SendKeys]::SendWait("Another line of text.")
Application.Wait (Now + TimeValue("00:00:01"))
or
Application.Wait Now + TimeSerial(0, 0, 5)
Note: This is only work in Excel VBA, Not in Word VBA.
Selection.Copy
MsgBox "Copied ---- " & Selection
Note:- Copy Only a single cell , if more than one cell copied, it will give error
> With the help of Action Replay Extension in chrome
> Google chrome recorder can also be used for replay of steps.
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(100, 200)
$wshell = New-Object -ComObject wscript.shell
$wshell.AppActivate("Title of the application window") # Activate the target window
Start-Sleep -Seconds 5 # Give time for the window to activate
$wshell.SendKeys("Hello World{ENTER}")
After 5 seconds, it will paste in the window where cursor is clciked
> First Open chrome
> Click on 3 dots and click on cast, save and share
>Click on create shortcut and a shortcut will be created.
> Go to chrome developer tools
> Go to Network Tab
> Click on CSS, JS, ALL
> Press CTRL + F5 Key and you will see files. You can block that files.
> And you can change slow 4g or fast 4g or you can change agent in Chrome.
>Open developer tools
> Click on Recorder
> Click on Create recording
> Click on Start recording.
> Click on website and when you click on buttons and anywhere it will save.
>You can import, export and delete the recordings.
>It will save as JSON file.
>Click on play recording to play.
select IF(0 > 0, 'True', 'False') as message;
create DATABASE IF not EXISTS test2;
drop DATABASE IF not EXISTS test2;
Select * from table1 t1 inner join table t2 on t1.id = t2.id
Here t1 and t2 are called alias.
DELIMITER $$
CREATE PROCEDURE new_procedure_procedure_name()
BEGIN
SELECT *
FROM test.new_table t1
LEFT JOIN test1.table1 t2 ON t1.id = t2.id;
END $$
DELIMITER ;
===============================
CALL new_procedure_procedure_name();
> First open My SQL workbench
>Than click on Database menu and click on Connect to database
> Than in navigator , Select Schemes tabs
> Right click in navigator and click on Create schema
> and Type name and click on apply and click on apply and click on finish
> First download MySql Workbench
> Than click on Database menu and click on Connect to database.
> Than click on OK button
> Than click on Schemas tab.
> Than write query
For Creating database
Create Schema test or Create Database test;
> Open MSWord
> Go to Insert Menu
> Click on Chart
> Right Click on Char and Click on Edit data to edit the data
>First Click on Draw Menu
>Than Click on Ruler and with Mouse scroll, you can rotate Scale.
Note:-
Scale is also called Ruler.
> Go to File
> Go to Print
> Go to Print What and Select Selection from Radio box
Public Sub test()
MsgBox ("dfdfd")
test1
End Sub
Public Function test1()
MsgBox ("dfdfd")
End Function
Sub mecro1()
Selection.TypeText "www.automateexcel.com"
MsgBox "You need to select some text."
End Sub
> Search for night light (Turn it on)option in search under display settings
> Also you can search for color filter settings in search option
> Also search for "adjust clear text" setting in search option under window button click
>Also you can search for brightness and change the brightness level
> Also you can increase Zoom in Chrome browser (Min 110% is good).
Also you can use apps like eye saver, CareUEyes
Also you can use Magnifier.
Also you can use scale from 100% to 110% from display settings.(Min 110% is good )
Also you can use resolution change. and color in Intel graphics command centre.
Also you can go to text size in scale in system settings and change it to 100% to 110%.(Min 110% is good )
Also you can use visual vibration images, examples :- https://img.freepik.com/free-vector/realistic-optical-illusion-background_52683-54383.jpg?semt=ais_hybrid&w=740&q=80
https://i.pinimg.com/736x/82/b2/5f/82b25fed9db53b364d55bc80f9d76efc.jpg
ref:- https://allthings.how/how-to-change-brightness-on-windows-11/
>You can use color changer app but it needs root permission
2) Display collaboration, blue light filter or sfilter , you can use these apps for android for decreasing color.
>Also simples is the rgb settings app for color changer.
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "Vithal" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
DataTable dt = new DataTable("DummyData");
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("City", typeof(string));
DataTable dt1 = new DataTable("DummyData");
dt1.Columns.AddRange(new DataColumn[] {
new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("City", typeof(string))
});
dt.Rows.Add(1, "John Doe", "New York");
dt.Rows.Add(2, "Jane Smith", "London");
dt.Rows.Add(3, "Peter Jones", "Paris");
//or
// DataRow newRow = dt.NewRow();
newRow["Id"] = 4;
// newRow["Name"] = "Alice Brown";
//newRow["City"] = "Tokyo";
//dt.Rows.Add(newRow);
GridView1.DataSource = dt;
GridView1.DataBind();
string[] myString1 = { "sum", "minus"};
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
foreach (string item in myString1)
{
System.Data.DataRow row = dt.NewRow();
row["Name"] = item; // Assign the string to the column
dt.Rows.Add(row); // Add the row to the DataTable
}
GridView1.DataSource = dt;
GridView1.DataBind();
>To use this, you have to first connect these devices by bluetooth
> Second you have to install GlideX, Phone mirror , Remote mouse, PC remote to your both devices
>Right click on desktop
>Go to display settings
> and there is option of "Duplicate these videos", "Extend these videos" and click on Extend these videos , it will work for both monitors.
and use "microsoft without borders" for two different computers and having same mouse.
byte[] bytes = file.FileData;
Response.Clear();
Response.ContentType = file.ContentType;
Response.BinaryWrite(bytes);
<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>
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
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;
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;
}
}
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
> Go to developer option
> Click on memory and you will see the total memory usage.
> 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
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();
}
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.
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}");
}
}
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
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);
}
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();
//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.
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);
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>
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);
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/
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.
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
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);
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
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)
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);
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);
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABkAAAAOECAYAAAD5Tf2iAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAP+lSURBVHhe7N0LYFTVuTb+B1AkeIGEm0CABBAiglyD3CINoqJoKRSRNqWtSEUK51NrgVKPHD48LYLHqt8fSvEgtlJaRAqlFouKIAUBCYIXREAggVwAA0lQgQgK//2uvfbMnvueaybx+dld9m1m1r5OZr17rbdOt249LoGIiIiIiIiIiIiIiKgWqav/JSIiIiIiIiIiIiIiqjUYACEiIiIiIiIiIiIiolqHARAiIiIiIiIiIiIiIqp1GAAhIiIiIiIiIiIiIqJahwEQIiIiIiIiIiIiIiKqdep069bjkh4nIiIiIiIiIiKq1erXv0KPEVFtdf78V3qMvu3YAoSIiIiIiIiIiIiIiGodBkCIiIiIiIiIiIiIiKjWqdeixbWz9Hi1qFevHn7zmydwyy1DUFVVhaKiIr2EiIiIiIiIiIgoturVu0yP
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)
{
}
>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.
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);