ASP.NET AJAX, mostly called AJAX, is
a set of extensions of ASP.NET. It is developed by Microsoft to implement AJAX
functionalities in Web applications. ASP.NET AJAX provides a set of components
that enable the developers to develop applications that can update only a
specified portion of data without refreshing the entire page.
Interview Funda
frequently asked interview questions for freshers and experienced
Monday, 12 November 2012
Friday, 17 August 2012
3 Tier Architecture using ASP.NET
3-Tier architecture is one of the most popular approaches in software development.
Tier Vs Layer
Tier indicates a physical separation of components.
Here separate assemblies/services are made to represent each component.
Layer indicates a logical separation of components with the help of namespaces and classes
Components of 3-Layer Architecture
Code Walkthrough
What we are developing.
We are developing a customer screen which supports 2 operations:
Gold, Silver or Normal which represents Id as 1, 2 and 3 respectively.
Note: In the database CustomerTypeId will be stored but in the grid the descriptive text will be shown.
Step 1: Create Business Objects required - we need 2 things,
one representing the customer type and anotehr representing the customer itself.
public class ClsCustomerType
{
public ClsCustomerType(int id)
{
this.Id = id;
switch(Id)
{
case 0:
this.Name = "--Select--";
break;
case 1:
this.Name = "Gold";
break;
case 2:
this.Name = "Silver";
break;
case 3:
this.Name = "Normal";
break;
}
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
public class ClsCustomer{
public string CustomerCode
{
get;
set;
}
public string CustomerName
{
get;
set;
}
public ClsCustomerType CustomerType
{
get;
set;
}
}
}
Step 2: Create Business Access Layer
public class ClsCustomerBAL{
public List<ClsCustomerType> LoadCustomerTypes()
{
return new List<ClsCustomerType>()
{
new ClsCustomerType(0),new ClsCustomerType(1),new ClsCustomerType(2),new ClsCustomerType(3)
};
}
public IEnumerable<ClsCustomer> LoadCustomers()
{
DataTable dtCustomer=new ClsCustomerDAL().LoadCustomers();
}
public void SaveRecord(ClsCustomer objCustomer)
{
new ClsCustomerDAL().SaveRecord(objCustomer);
}
public ValidationResult ValidateCustomerCode(string strPriCustomerCode)
{
if(strPriCustomerCode.Trim() == string.Empty)
{
return ValidationResult.Empty;
}
else if(strPriCustomerCode.Trim().Length < 5)
{
return ValidationResult.InValid;
}
return ValidationResult.Valid;
}
}
Step 3: Next we need a Data Access Layer:
using System.Data;
using System.Data.SqlClient;
using Entities;
namespace DAL
{
public class ClsCustomerDAL {
private const string ConnectionString = @"Data Source=ONENESS-PC\S2;Initial Catalog=3LayerApp;Persist
Security Info=True;User ID=sa;Password=aa";
public DataTable LoadCustomers()
{
//Load Data From Database
}
public void SaveRecord(ClsCustomer objCustomer)
{
//Save Data Into Database
}
}
}
Step 4: That's it; now the only thing remaining is creation of the UI:
In the UI the code behind we will just call the functions created on BAL, there will not be any database logic, and neither wll there be validation logic.
Hope this explanation was enough to understand, how to create a simple 3-Layer application using ASP.Net also I hope you enjoyed reading this article.
Tier Vs Layer
Tier indicates a physical separation of components.
Here separate assemblies/services are made to represent each component.
Layer indicates a logical separation of components with the help of namespaces and classes
Components of 3-Layer Architecture
- Presentation Tier: in simple terms, the UI with which the end user actually interacts.
- Data Tier: Where actual data is stored.
- Business Tier: It acts a bridge between Data Tier and the Presentation Tier. It collects raw data from the Presentation Tier, checks for validations, converts them to a standard format and finally sends them to the Data Tier. Similarly it collects data from the Data Tier, purifies it and sends it to the Presentation Tier for display.
- Business Objects: Its nothing but a class representation of actual data.
Code Walkthrough
What we are developing.
We are developing a customer screen which supports 2 operations:
- Add New Customer
- List All Customers.
Gold, Silver or Normal which represents Id as 1, 2 and 3 respectively.
Note: In the database CustomerTypeId will be stored but in the grid the descriptive text will be shown.
Step 1: Create Business Objects required - we need 2 things,
one representing the customer type and anotehr representing the customer itself.
public class ClsCustomerType
{
public ClsCustomerType(int id)
{
this.Id = id;
switch(Id)
{
case 0:
this.Name = "--Select--";
break;
case 1:
this.Name = "Gold";
break;
case 2:
this.Name = "Silver";
break;
case 3:
this.Name = "Normal";
break;
}
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
public class ClsCustomer{
public string CustomerCode
{
get;
set;
}
public string CustomerName
{
get;
set;
}
public ClsCustomerType CustomerType
{
get;
set;
}
}
}
Step 2: Create Business Access Layer
public class ClsCustomerBAL{
public List<ClsCustomerType> LoadCustomerTypes()
{
return new List<ClsCustomerType>()
{
new ClsCustomerType(0),new ClsCustomerType(1),new ClsCustomerType(2),new ClsCustomerType(3)
};
}
public IEnumerable<ClsCustomer> LoadCustomers()
{
DataTable dtCustomer=new ClsCustomerDAL().LoadCustomers();
}
public void SaveRecord(ClsCustomer objCustomer)
{
new ClsCustomerDAL().SaveRecord(objCustomer);
}
public ValidationResult ValidateCustomerCode(string strPriCustomerCode)
{
if(strPriCustomerCode.Trim() == string.Empty)
{
return ValidationResult.Empty;
}
else if(strPriCustomerCode.Trim().Length < 5)
{
return ValidationResult.InValid;
}
return ValidationResult.Valid;
}
}
Step 3: Next we need a Data Access Layer:
using System.Data;
using System.Data.SqlClient;
using Entities;
namespace DAL
{
public class ClsCustomerDAL {
private const string ConnectionString = @"Data Source=ONENESS-PC\S2;Initial Catalog=3LayerApp;Persist
Security Info=True;User ID=sa;Password=aa";
public DataTable LoadCustomers()
{
//Load Data From Database
}
public void SaveRecord(ClsCustomer objCustomer)
{
//Save Data Into Database
}
}
}
Step 4: That's it; now the only thing remaining is creation of the UI:
In the UI the code behind we will just call the functions created on BAL, there will not be any database logic, and neither wll there be validation logic.
Hope this explanation was enough to understand, how to create a simple 3-Layer application using ASP.Net also I hope you enjoyed reading this article.
Tuesday, 14 August 2012
Replace characters in javascript
Replace characters in javascript
Example :
var StringChar = "this is my 324o234u324t2342p234u234t"; //Your string to get replaced
In this case i need to remove the numbers and get the filtered output.
Replace Method in Javascript :
var ReplacedCharacters = String.replace("0123456789"," ");
Output : "this is my 324o234u324t2342p234u234t";
In this cases we can do like this :
var ReplacedChar = "";
var Characters = "";
var InValidChars = "0123456789";
for (d = 0; d < StringChar.length; d++) {
Characters = StringChar.charAt(d);
if (InValidChars.indexOf(Characters) == -1) {
ReplacedChar = ReplacedChar + Characters;
}
the resulting output is : ReplacedChar = this is my output
how to get sum of 2 or more text box values in javascript
Generally we will add text box values in java script as follows
Test out with the 2 Text boxes , to see what yours should do. Enter a 2 in the first box, and a 2 in the second box. Then third Text Box will get updated by sum value.
Here we are using key press event to validate and allow only numbers, Key Up event to sum of the values and update in third text box.
so to ADD two or More text box values in java script follow this code :-
JAVA SCRIPT
<script type="text/javascript" language="javascript">
function AllowOnlyNumbers(obj, e) {
var key = window.event ? e.keyCode : e.which;
if ((key > 45 && key < 58) || key == 8) {
if (key == 47) {
return false;
}
}
else {
return false;
}
if (obj.value == "") {
if (key == 46) {
return false;
}
}
var DecimalCount = 0;
for (d = 0; d < obj.value.length; d++) {
var Character = obj.value.charAt(d);
if (Character == ".") {
DecimalCount++;
}
}
if (key == 46) {
if (DecimalCount == 1) {
return false;
}
}
}
function SumValue() {
var txtbox1 = document.getElementById("TextBox1").value;
if (txtbox1 == "" || txtbox1 == ".") {
txtbox1 = 0;
}
var txtbox2 = document.getElementById("TextBox2").value;
if (txtbox2 == "" || txtbox2 == ".") {
txtbox2 = 0;
}
var txtbox3 = document.getElementById("TextBox3");
txtbox3.value = parseFloat(txtbox1) + parseFloat(txtbox2);
}
</script>
ASPX PAGE
<div>
<asp:TextBox ID="TextBox1" runat="server" onKeyUp="return SumValue();" onkeypress="return AllowOnlyNumbers(this,event);"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" onKeyUp="return SumValue();" onkeypress="return AllowOnlyNumbers(this,event);"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" onKeyUp="return SumValue();" onkeypress="return AllowOnlyNumbers(this,event);"></asp:TextBox>
</div>
OUTPUT
Word Documents and Excel Documents in IFRAME
In this case we are converting and giving converted HTML file as ""src"" to ""iframe"".
Step By Step Procedure :
1)First step is create one folder in your application which needs to maintain the documents in that because iframe will take src within the application itself,outside of the application it will not work.
2) The aspx page as follows :
3) Add Interop.Excel & Interop.Word dll references for the application :
4) The button click event will be like this :
First get the binary data of file and save that file to its original
format in documents folder.After saving the file according to the file
extension convert to Html format and give the Html file as src for
iframe.
private Word.ApplicationClass MSWord; // The Interop Object for Word
private Excel.ApplicationClass MSExcel; // The Interop Object for Excel
object Unknown = Type.Missing; // For passing Empty values
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnView_Click(object sender, EventArgs e)
{
byte[] BinaryFile = null;
if (FileUpload2.PostedFile != null)
{
int FileSize = FileUpload2.PostedFile.ContentLength;
BinaryFile = new byte[FileSize];
FileUpload2.PostedFile.InputStream.Read(BinaryFile, 0, (int)FileUpload2.PostedFile.ContentLength);
string FileName = FileUpload2.FileName;
lblFileName.Text = FileName;
string FileExtension = Path.GetExtension(FileName);
string FolderPath = Server.MapPath("~/Documents");
File.WriteAllBytes(FolderPath + "\\" + FileName, BinaryFile);
if (FileExtension == ".doc" || FileExtension == ".docx")
{
ConvertWordToHTML(FolderPath + "\\" + FileName, FolderPath + "\\" + FileName.Split('.')[0] + ".html");
}
else if (FileExtension == ".xls" || FileExtension == ".xlsx")
{
ConvertExcelToHTML(FolderPath + "\\" + FileName, FolderPath + "\\" + FileName.Split('.')[0] + ".html");
}
docPreview.Attributes["src"] = "../Documents/" + FileName.Split('.')[0] + ".html";
}
}
This method is used to convert WordDocument to HTML :
public void ConvertWordToHTML(object FilePath, object SaveTarget)
{
if (MSWord == null)
MSWord = new Word.ApplicationClass();
try
{
MSWord.Visible = false;
MSWord.Application.Visible = false;
MSWord.WindowState = Word.WdWindowState.wdWindowStateMinimize;
MSWord.Documents.Open(ref FilePath, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown, ref Unknown);
object format = Word.WdSaveFormat.wdFormatHTML;
MSWord.ActiveDocument.SaveAs(ref SaveTarget, ref format,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown);
}
catch (Exception e)
{
}
finally
{
if (MSWord != null)
{
MSWord.Documents.Close(ref Unknown, ref Unknown, ref Unknown);
MSWord.Quit(ref Unknown, ref Unknown, ref Unknown);
}
}
}
This method is used to convert ExcelDocument to HTML :
public void ConvertExcelToHTML(string Source, string Target)
{
if (MSExcel == null)
MSExcel = new Excel.ApplicationClass();
try
{
MSExcel.Visible = false;
MSExcel.Application.Visible = false;
MSExcel.WindowState = Excel.XlWindowState.xlMinimized;
MSExcel.Workbooks.Open(Source, Unknown,
Unknown, Unknown, Unknown,
Unknown, Unknown, Unknown,
Unknown, Unknown, Unknown,
Unknown, Unknown, Unknown, Unknown);
object format = Excel.XlFileFormat.xlHtml;
MSExcel.Workbooks[1].SaveAs(Target, format,
Unknown, Unknown, Unknown,
Unknown, Excel.XlSaveAsAccessMode.xlExclusive, Unknown,
Unknown, Unknown, Unknown,
Unknown);
}
catch (Exception e)
{
}
finally
{
if (MSExcel != null)
{
MSExcel.Workbooks.Close();
MSExcel.Quit();
}
}
}
5) Here in my example i have taken fileupload to upload word and excel documents, after selecting a file by clicking View button we can view the output just like this :
Output for WordDocument :
Output for ExcelDocument :
difference between Web site and Web application ?
Hi,
Scenarios In Web application projects :
0.we want to create webapplication the folder structure like One Project file and as well as Reference folder and along with One assembly file ie located in Bin folder.
1.We want to the compiler to create a single assembly for the entire site.
2.we want to be able to use the Edit and Continue feature of the Visual Studio debugger.
3. we want to run unit tests on code that is in the class files that are associated with ASP.NET pages.
4.we want to create project dependencies between multiple Web projects.
5.we want user MS-Build or Team Build for Compilation
6.we want avoid putting source code on a production server.
7.we want to use the automated deployment tools that are available in Visual Studio 2010.
Scenarios in which Web Sites :
0.we want to create website structure like folders and not having Reference folder
ask File Location
1.We want to include both C# and Visual Basic code in a single Web project
2.we want to open the production site in Visual Studio and update it in real time by using FTP.
3.If you pre compile the site, you want to be able to update individual ASP.NET Web pages (aspx files) without having to recompile the entire Web site.
4.if we want to create website ask File Location as FTP,HTTP etc
5.we want to be able to update individual files in production by just copying new versions to the production server, or by editing the files directly on the production server.
Scenarios In Web application projects :
0.we want to create webapplication the folder structure like One Project file and as well as Reference folder and along with One assembly file ie located in Bin folder.
1.We want to the compiler to create a single assembly for the entire site.
2.we want to be able to use the Edit and Continue feature of the Visual Studio debugger.
3. we want to run unit tests on code that is in the class files that are associated with ASP.NET pages.
4.we want to create project dependencies between multiple Web projects.
5.we want user MS-Build or Team Build for Compilation
6.we want avoid putting source code on a production server.
7.we want to use the automated deployment tools that are available in Visual Studio 2010.
Scenarios in which Web Sites :
0.we want to create website structure like folders and not having Reference folder
ask File Location
1.We want to include both C# and Visual Basic code in a single Web project
2.we want to open the production site in Visual Studio and update it in real time by using FTP.
3.If you pre compile the site, you want to be able to update individual ASP.NET Web pages (aspx files) without having to recompile the entire Web site.
4.if we want to create website ask File Location as FTP,HTTP etc
5.we want to be able to update individual files in production by just copying new versions to the production server, or by editing the files directly on the production server.
Sunday, 12 August 2012
Intelligence Bureau Online Registration 2012
Intelligence BureauMinistryHome Affirs
Government of India
Apply Online Registration For the recruitment of Assistant Central Intelligence Officer-Grade-II/Executive examination-2012
Government of India
Apply Online Registration For the recruitment of Assistant Central Intelligence Officer-Grade-II/Executive examination-2012
Monday, 6 August 2012
Extract Text from Word File with C#, VB.NET
In my last article, I introduce a pretty easy way to extract images from word file. Today,
I will share another method to extract text from word document with C#,
VB.NET. In our daily work, word document always plays an indispensable
role. It has powerful functions to edit the text with different formats,
such as font, header and footer, comments, hyperlink and so on. At the
same time, it is just because this reason, we need to extract only the
content without its format in a .txt file, while not using document.SaveToFile method to save Word as Text directly.
VB.NET Code:
Easy way to extract text from word document with C#, VB.NET
I am very happy that Spire.Doc, an MS Word component, can be my best hand to finish this task. Using Spire.Doc, I only need three simple steps to realize the text extraction function. If necessary,you can use the source code to freely download it.
I am very happy that Spire.Doc, an MS Word component, can be my best hand to finish this task. Using Spire.Doc, I only need three simple steps to realize the text extraction function. If necessary,you can use the source code to freely download it.
Procedure
Step1. Create a new project
1. Create a new project in Visual Studio and set its Target framework to be .NET Framework 4.
2. Add Spire.Doc DLL as reference.
3. Add below using at the top of the method.
Step1. Create a new project
1. Create a new project in Visual Studio and set its Target framework to be .NET Framework 4.
2. Add Spire.Doc DLL as reference.
3. Add below using at the top of the method.
C#
VB.NET
using System.IO; using Spire.Doc; using Spire.Doc.Documents;
VB.NET
Imports System.IO Imports Spire.Doc Imports Spire.Doc.Documents
Step2. Extract text from word document with C#, VB.NET
1. Load a Word document from system.
C# CODE:
Dim doc As New Document()
doc.LoadFromFile("D:\michelle\JaneEyre.doc", FileFormat.Doc)
1. Load a Word document from system.
C# CODE:
Document doc = new Document(); doc.LoadFromFile(@"D:\michelle\JaneEyre.doc", FileFormat.Doc);VB.NET CODE:
Dim doc As New Document()
doc.LoadFromFile("D:\michelle\JaneEyre.doc", FileFormat.Doc)
2. Extract text from word document.
C# Code:
//new a stringBuilder to extract text from word document StringBuilder sb = new StringBuilder(); //extract text from word document foreach (Section section in doc.Sections) { foreach (Paragraph paragraph in section.Paragraphs) { sb.AppendLine(paragraph.Text); } }
VB.NET Code:
'new a stringBuilder to extract text from word document Dim sb As New StringBuilder() 'extract text from word document For Each section As Section In doc.Sections For Each paragraph As Paragraph In section.Paragraphs sb.AppendLine(paragraph.Text) Next Next
Step3. Save the text to a .txt file and launch the .txt file.
C# Code:
Code Source:
C# Code:
//write the text of word document into a txt file File.WriteAllText(@"result.txt", sb.ToString()); //launch the text file System.Diagnostics.Process.Start(@"result.txt");VB.NET Code:
'write the text of word document into a txt file File.WriteAllText("result.txt", sb.ToString()) 'launch the text file System.Diagnostics.Process.Start("result.txt")
Code Source:
Sunday, 5 August 2012
Get Recent records from the table
Here is a small code snippet for getting the recent records from the table.
drop table VENKAT_TABLE
go
create table Venkat_Table(code varchar(100),rate decimal(10,8),date1 date)
go
insert into VENKAT_TABLE values ('sam', 1.240000, '01/08/2004')
insert into VENKAT_TABLE values ('sam', 1.840000, '02/08/2004')
insert into VENKAT_TABLE values ('pal', 1.240000, '01/08/2005')
insert into VENKAT_TABLE values ('pal', 0.840000, '10/08/2003')
select code,rate,date1 from
(
select ROW_NUMBER() over (partition by code order by date1) as rank1,*
from VENKAT_TABLE ) t
where rank1=1
drop table VENKAT_TABLE
go
create table Venkat_Table(code varchar(100),rate decimal(10,8),date1 date)
go
insert into VENKAT_TABLE values ('sam', 1.240000, '01/08/2004')
insert into VENKAT_TABLE values ('sam', 1.840000, '02/08/2004')
insert into VENKAT_TABLE values ('pal', 1.240000, '01/08/2005')
insert into VENKAT_TABLE values ('pal', 0.840000, '10/08/2003')
select code,rate,date1 from
(
select ROW_NUMBER() over (partition by code order by date1) as rank1,*
from VENKAT_TABLE ) t
where rank1=1
Session State Timeout in ASP.Net
Recently, I thought of including some job related information in my websiteWWW.KaaShivInfoTech.com
After deploying my code, I faced a typical issue of application pool fill for the objects.
After deploying my code, I faced a typical issue of application pool fill for the objects.
Due
to some poor coding, I allowed the user to logged in with a username
and password. Unfortunately, I didn't give proper access for signing
out.
Guessing,
the session of the user took 30 minutes expiration time (Standard
session expiration time). Since, most of the users are accessing this
site and closing it with proper signing out. The objects started
accumulating. At present, I dont have any idea to implement sign out
option.
So I thought putting some timeout options in the connection string and web.config file. Thought of sharing the same to you all.
In
the connection string, I've added timout option as 5 minutes. If the
database is accessed for more than 5 minutes, the connection should be
thrown out.
or else,
we can do some changes in web.config file under system.web section
cookieless="true"
regenerateExpiredSessionId="true"
Difference between Stored Procedure (SP) and User Defined Function
Ø
User Defined Function can be
executed using the "SELECT" clause whereas Stored Procedure cannot be Executed..
Ø
User Defined Function does not return any output
parameters while Stored Procedure will return output parameters.
Ø
User Defined Function cannot
make permanent changes to server environments while SP's can change some of the
server environment.
Ø
If there is an error in UDF its
stops executing. But in SP's it just ignores the error and moves to the next
statement.
Methods to Zoom PDF File by PDF Viewer with C#
Zoom
function in PDF file can help people change the text size of PDF
document page according to their view preference or need. When you want
to increase the percentage of the PDF file text, you can click the
button of zoom out or choose the percentage number directly as well as
scroll down your mouse. And if you want to zoom back to the original
text size, you can click the Actual Size button. Actually, you can
completely control the text percentage of the PDF document, which is
much more convenient than the zoom of Excel and Word files. Now it is
time to learn how to zoom PDF file by PDF Viewer with C#, VB.NET.
How to zoom PDF document by PDF Viewer with C#, VB.NET
In this article, I will introduce seven kinds of zoom functions to control PDF file text size by using a PDF Viewer component for .NET and WPF Spire.PDFViewer. It does NOT require Adobe Reader or any other 3rd party software/library installed on system. The whole procedure can be finished by below steps.
How to zoom PDF document by PDF Viewer with C#, VB.NET
In this article, I will introduce seven kinds of zoom functions to control PDF file text size by using a PDF Viewer component for .NET and WPF Spire.PDFViewer. It does NOT require Adobe Reader or any other 3rd party software/library installed on system. The whole procedure can be finished by below steps.
Step1. Create a new project.
1. Create a new project in Windows Forms Application.
2. Set the Target Framework to be .NET Framework 2 or above in Properties.
3. Add a toolScript and pdfDocumentViewer in Form1 from Toolbox. Then, add seven buttons, two ComboBoxes and a label from the toolScript dropdown list in Form1.
4. Set the Properties of the tools respectively. Such as the "Name", "Display Style", "Text" and " ToolTipText" of buttons, ComboBoxes and label. You can set the Dock property of pdfDocumentViewer in its Properties in order to view the PDF in enough space.
1. Create a new project in Windows Forms Application.
2. Set the Target Framework to be .NET Framework 2 or above in Properties.
3. Add a toolScript and pdfDocumentViewer in Form1 from Toolbox. Then, add seven buttons, two ComboBoxes and a label from the toolScript dropdown list in Form1.
4. Set the Properties of the tools respectively. Such as the "Name", "Display Style", "Text" and " ToolTipText" of buttons, ComboBoxes and label. You can set the Dock property of pdfDocumentViewer in its Properties in order to view the PDF in enough space.
Step2. Methods to zoom PDF file by Spire.PDFViewer
1. Add Spire. PDFViewer.Forms dll as reference.
2. Add below namespace at the top of the method.
C# Code:
3. Zoom PDF file. In this step, I have seven kinds of zoom fuctions to control the PDF text size. They are:
Zoom: Manually choose the percentage.
Zoom Out: Increase the PDF text size.
Zoom In: Decrease the PDF text size.
Zoom Dynamic: Scroll down/up the mouse directly to change the text size. A second click can cancel zoom dynamic.
Actual Size: When you click it, the document changes to the original size.
Fit Page: Fit page control the PDF page not going across the PDF page height and margin.
Fit Width: When you click the Fit Width button, you cannot see the margin of PDF document and only see the PDF text content.
Please look at the main code:
1. Add Spire. PDFViewer.Forms dll as reference.
2. Add below namespace at the top of the method.
C# Code:
using System.IO;using System.Windows.Forms;using Spire.PdfViewer.Forms;
3. Zoom PDF file. In this step, I have seven kinds of zoom fuctions to control the PDF text size. They are:
Zoom: Manually choose the percentage.
Zoom Out: Increase the PDF text size.
Zoom In: Decrease the PDF text size.
Zoom Dynamic: Scroll down/up the mouse directly to change the text size. A second click can cancel zoom dynamic.
Actual Size: When you click it, the document changes to the original size.
Fit Page: Fit page control the PDF page not going across the PDF page height and margin.
Fit Width: When you click the Fit Width button, you cannot see the margin of PDF document and only see the PDF text content.
Please look at the main code:
C# Code:
namespace pdfzoom{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } //private bool _isZoomout = true; private int _zoom = 100; private bool _isZoomDynamic = false; private void Form1_Load(object sender, EventArgs e) { string pdfDoc = @"D:\michelle\PDFViewer.pdf"; if (File.Exists(pdfDoc)) { this.pdfDocumentViewer1.LoadFromFile(pdfDoc); } //add zoom values to comboBox int[] intZooms = new Int32[] { 25, 50, 75, 100, 125, 150, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; foreach (int zoom in intZooms) { this.comBoxZoom.Items.Add(zoom.ToString()); } this.comBoxZoom.SelectedIndex = 3; //pdfDocumentViewer mouseWheel event this.pdfDocumentViewer1.MouseWheel += new MouseEventHandler(this.pdfDocumentViewer1_MouseWheel); this.pdfDocumentViewer1.LostFocus += new EventHandler(this.pdfDocumentViewer_LostFocus); } private void pdfDocumentViewer_LostFocus(Object sender, EventArgs args) { this._isZoomDynamic = false; this._zoom = 100; } private void pdfDocumentViewer1_MouseWheel(Object sender, MouseEventArgs args) { if (this._isZoomDynamic) { int wheelValue = (Int32)args.Delta / 24; this._zoom += wheelValue; if (this._zoom < 0) this._zoom = 0; this.pdfDocumentViewer1.ZoomTo(this._zoom); } } private void btnOPen_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "PDF document (*.pdf)|*.pdf"; DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { string pdfFile = dialog.FileName; this.pdfDocumentViewer1.LoadFromFile(pdfFile); } catch (Exception exe) { MessageBox.Show(exe.Message, "Spire.PdfViewer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void comBoxZoom_SelectedIndexChanged(object sender, EventArgs e) { if (this.pdfDocumentViewer1.PageCount > 0) { int zoomValue = Int32.Parse(this.comBoxZoom.SelectedItem.ToString()); this.pdfDocumentViewer1.ZoomTo(zoomValue); } } private void btnZoomOut_Click(object sender, EventArgs e) { if (this.pdfDocumentViewer1.PageCount > 0) { int delta = 10; this._zoom += delta; this.pdfDocumentViewer1.ZoomTo(this._zoom); } } private void btnZoonIn_Click(object sender, EventArgs e) { if (this.pdfDocumentViewer1.PageCount > 0) { int delta = 5; this._zoom -= delta; if (this._zoom < 0) this._zoom = 0; this.pdfDocumentViewer1.ZoomTo(this._zoom); } } private void btnActural_Click(object sender, EventArgs e) { this._zoom = 100; this._isZoomDynamic = false; this.btnDynamic.Text = "Zoom Dynamic"; if (this.pdfDocumentViewer1.PageCount > 0) { this.pdfDocumentViewer1.ZoomTo(100); this.comBoxZoom.SelectedIndex = 3; } } private void btnFitPage_Click(object sender, EventArgs e) { if (this.pdfDocumentViewer1.PageCount > 0) { this.pdfDocumentViewer1.ZoomTo(ZoomMode.FitPage); } } private void btnFitWidth_Click(object sender, EventArgs e) { if (this.pdfDocumentViewer1.PageCount > 0) { this.pdfDocumentViewer1.ZoomTo(ZoomMode.FitWidth); } } private void btnDynamic_Click(object sender, EventArgs e) { this._isZoomDynamic = !this._isZoomDynamic; if (this._isZoomDynamic) { this.btnDynamic.Text = "Cancel dynamic zoom"; this.btnDynamic.ToolTipText = "Cancel dynamic zoom"; } else { this.btnDynamic.Text = "Zoom dynamic"; this.btnDynamic.ToolTipText = "Zoom dynamic"; } } private void pdfDocumentViewer1_PdfLoaded(object sender, EventArgs args) { this.btnDynamic.Enabled = true; this.comBoxPages.Items.Clear(); int totalPage = this.pdfDocumentViewer1.PageCount; for (int i = 1; i <= totalPage; i++) { this.comBoxPages.Items.Add(i.ToString()); } this.comBoxPages.SelectedIndex = 0; } private void pdfDocumentViewer1_PageNumberChanged(object sender, EventArgs args) { if (this.comBoxPages.Items.Count <= 0) return; if (this.pdfDocumentViewer1.CurrentPageNumber != this.comBoxPages.SelectedIndex + 1) { this.comBoxPages.SelectedIndex = this.pdfDocumentViewer1.CurrentPageNumber - 1; } } private void comBoxPages_SelectedIndexChanged(object sender, EventArgs e) { int soucePage = this.pdfDocumentViewer1.CurrentPageNumber; int targetPage = this.comBoxPages.SelectedIndex + 1; if (soucePage != targetPage) { this.pdfDocumentViewer1.GoToPage(targetPage); } } private void comBoxPages_Click(object sender, EventArgs e) { } }}
Step3. Debug the project
Press F5 to launch the project
Note: 1. If you click the buttons and they cannot operate the zoom functions, please check the click event of each button.
2. When the ComboBox cannot show page number in the dropdown list, pleae check the SelectedIndexChanged event of it.
Preview
2. When the ComboBox cannot show page number in the dropdown list, pleae check the SelectedIndexChanged event of it.
Preview
Form1
Zoom Percentage
Zoom Dynamic
As
above picture, you can easily control the whole PDF document pages by
the methods that I introduced by using Spire.PDF Viewer. Spire.PDFViewer
not only enables you to open a PDF document that you load from system
in the code, but also allows you to open any other PDF file by clicking
the Open button in Form1, and then, choose it from a dialog box. You
also can choose which page you want to view or read in the dropdown
list. Why not give it a try?
Blog Source: htto://everlasting129.weebly.com
Code Source: http://www.e-iceblue.com
Subscribe to:
Posts (Atom)
Popular posts
-
In this below example we are converting word OR excel document to HTML. In this case we are converting and giving converted HTML f...
-
Replace characters in javascript In server side we have "Replace" method to replace the characters in a string but on javas...
-
Zoom function in PDF file can help people change the text size of PDF document page according to their view preference or need. When you ...
-
3-Tier architecture is one of the most popular approaches in software development. Tier Vs Layer Tier indicates a physical separatio...
-
Preference belongs to everyone, almost everybody has preferences . If you choose ten person and view the layout of their desktop, the...
-
Remoting What distributed process frameworks outside .NET do you know? Distributed Computing Environment/Remote Procedure Calls (DE...
-
Insert Images to SqlServer in ASP .NET Here I am explaining how insert images into database using asp.net. protected v...
-
Hi, Scenarios In Web application projects : 0.we want to create webapplication the folder structure like One Project file and as well as...
-
Things become difficult when a PDF document has tens or hundreds of pages. It wastes much time for people to reach the page that they wa...
-
SQL Server FAQ Transact-SQL Optimization Tips Use views and stored procedures instead of heavy-duty queries. This can ...