Archive for the ‘Web Coding’ Category
Planning to Host WordPress Blog
Read this article..
http://www.gchandra.com/scripts/?p=172
Handling multiple configuration settings (Development, Staging, Production) gracefully.
In Asp.net 2.0 multiple connectionStrings & appSettings can be handled very easily using the attribute “configSource”
create a new xml file devAppSettings.config under a new folder myConfigsettings
How to Preserve Fileupload value in Asp.net ?
If you form has Fileupload control along with other controls like dropdownlist, calendar.. you will be facing standard problem of Fileupload control losing value when other controls are selected.
Click here to read the article in full…
AJAX – Export to Excel / Word
If you are using Update Panel and try to Export gridview contents to EXCEL or Word, your asp.net page will throw nasty error. “Sys.WebForms.PageRequestManagerParserErrorException”
Its because AJAX & Response.write don’t go together. By calling Response.Write() directly you are bypassing the normal rendering mechanism of ASP.NET controls. The bits you write are going straight out to the client without further processing (well, mostly…). This means that UpdatePanel can’t encode the data in its special format.
There are couple of ways to solve this problem.
1. Place the Export Button outside of Update Panel.
2. By Pass the Export Button using <Triggers>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID=”cmdExport” />
</Triggers>
</asp:UpdatePanel>
if your Export button is part of UserControl then specify usercontrolid:buttonid
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID=”uscSelCtl:cmdExport” />
</Triggers>
</asp:UpdatePanel>
Asp.Net Filter Datatable by Column
Filter Datatable by Rows
If you need to get subset of a big dataset into datatable Rowwise …
Dim dtEmp as DataTable Dim dsEmployee as New DataSet dsEmployee = someobject.getdata() 'dataset can be populated in many ways which is not explained here. Dim sExpr as String Dim drRows() as DataRow, drSingleRow as DataRow sExpr = "EmpID > 100" 'Condition drRows = dsEmployee.Tables(0).Select(sExpr) 'If you need to add Sort Order it can be added to sExpr Dim sSortOrder as String sSortOrder = "EmpName DESC" drRows = dsEmployee.Tables(0).Select(sExpr,sSortOrder) For Each drSingleRow in drRows dtEmp.ImportRow(drRows) Next ' Datatable dtEmp has filtered records
Filter Datatable by Column
If you need to get subset of big dataset into datatable columnwise…
Dim dtEmp as DataTable Dim dsEmployee as New DataSet dsEmployoee = someobject.getdata() 'dataset can be populated in many ways which is not explained here. 'This copies the structure and data dtEmp = dsEmployee.Tables(0).Copy dtEmp.Columns.Remove("Unwanted Column 1") dtEmp.Columns.Remove("Unwanted Column 2") dtEmp.Columns.Remove("Unwanted Column 3")
Prevent Session Timeout in Asp.net
Prevent Session Timeout in Asp.net [VB]
ASP.Net 2.0 [VB]
Inspired by this article from Code Project. [Thanks Ach1lles ]
I slightly modified few things to work for VB and VS2005 environment. The code works perfect and I’m very happy with it.First I created a Module file and created this function.
Public Function KeepAlive() As String Dim int_MilliSecondsTimeOut As Integer = (HttpContext.Current.Session.Timeout * 60000) - 30000 Dim sScript As New StringBuilder sScript.Append("<script type='text/javascript'>" & vbNewLine) 'Number Of Reconnects sScript.Append("var count=0;" & vbNewLine) 'Maximum reconnects Setting sScript.Append("var max = 6;" & vbNewLine) sScript.Append("function Reconnect(){" & vbNewLine) sScript.Append("count++;" & vbNewLine) sScript.Append("var d = new Date();" & vbNewLine) sScript.Append("var curr_hour = d.getHours();" & vbNewLine) sScript.Append("var curr_min = d.getMinutes();" & vbNewLine) sScript.Append("if (count < max){" & vbNewLine) sScript.Append("window.status = 'Refreshed ' + count.toString() + ' time(s) [' + curr_hour + ':' + curr_min + ']';" & vbNewLine) sScript.Append("var img = new Image(1,1);" & vbNewLine) sScript.Append("img.src = 'http://localhost/myapp/reconnect.aspx';" & vbNewLine) sScript.Append("}" & vbNewLine) sScript.Append("}" & vbNewLine) sScript.Append("window.setInterval('Reconnect()',") sScript.Append(int_MilliSecondsTimeOut.ToString() & "); //Set to length required" & vbNewLine) sScript.Append("</script>") KeepAlive = sScript.ToString End Function
All this code does is, build a simple javascript function and its called from server side.The works like this,- Gets the current session timeout duration.
– Subtract 30 seconds from it and assign it to MilliSecondsTimeOut variable
– Create a Reconnect() javascript function
– Create a global variable with max value 6
– Get current hour and Min [just for displaying the last refresh time]
– Verify whether count is less than max value (ie 6)
– If so, change the window status with Text
– Create a dummy image and set reconnect.aspx url as its source [this way a call is made to server and it wont session timeout]Create a timer using window.setInterval and assign the MilliSecondsTimeOut value.
[this way this function is called 30 seconds before session timeout]Tha max value (6) can be set to any number. If its 6 then this session timeout is avoided 5 times.
Default session timeout is 20min. 20 * 5 = 100 mins. Which is good for non-secure page.
Then
On the pages where I want to prevent Session Timeout I entered this line.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try 'dont forget to add this line Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "reconn key", KeepAlive()) If Not Page.IsPostBack Then --- --- --- End If Catch eX as Exception '---- End Try End Sub
Created reconnect.aspx in Visual Studio and deleted the .vb and .designer.vb files.This is the final version of reconnect.aspx
<%@ Page Language="vb" AutoEventWireup="false"%> <%@ OutputCache Location="None" VaryByParam="None" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" mce_href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>"> <html xmlns="<a href="http://www.w3.org/1999/xhtml" mce_href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" > </html>
Note : When you compile the project sometimes, VS2005 complains reconnect.aspx is not in right format.
So I EXCLUDED this file from my project. Now VS 2005 will compile without complaining and the logic will also work.- Happy Programming
Copy Datatable from one Dataset to another Dataset
Copying a datatable from one dataset to another was not that straightforward as I thought.
Dim dsSource As New DataSet Dim dsDestination As New DataSet 'Your way to get data from XML or DB. dsSource = object.getdata() dsDestination = object.getmoredata() 'This is important, without this it will result in error 'when you try to copy the datatable from one dataset to another dsSource.Tables(0).TableName = "NewTableName" dsDestination.Tables.Add(dsSource.Tables(0).Copy) dsDestination.Tables(0).Tablename = "SomeTable" dsDestination.Tables(1).Tablename = "NewTableName" 'The one we copied from other Dataset
Note 1 : When you are using more than one datatable in a dataset it is advisable you name the datatables.
Note 2 : These kinds of scenarios arise, when you are trying to establish Relation between datatables in a dataset.
(Cascading master – detail relation)
Creating dynamic, fancy EmptyDataText for GridView
Gridview has capability to display “default” messages when “No data” exists during binding.
Standard Way in .aspx
<asp:GridView ID=”gvControl” runat=”server” AutoGenerateColumns=”False” GridLines=”None” CellPadding=”0″ CellSpacing=”0″ OnRowDataBound=”gvCategories_RowDataBound” BackColor=”#dddddd” ShowHeader=”false” EmptyDataText=”<BR> No data exists <BR><BR>“>
….
…..
</asp:GridView>
Fancy Way (.vb or .cs)
You can make it fancy & dynamic by doing it in code behind.
Create fancy texts using WordArt (MS Word) and copy it to Image Editor (Paint.net, gimp, Paint) and save it as JPG.
gvControl.EmptyDataText = "<img src='~/images/NoData.jpg' border='0'>" gvControl.EmptyDataRowStyle.HorizontalAlign = HorizontalAlign.Center gvControl.databind
Note: When you use emptydatatext in codebehind donot forget to use databind.
‘The invoked member is not supported in a dynamic module.’
Error ‘The invoked member is not supported in a dynamic module.’ while generating exception string
While Using ASPUnhandledException.dll for exception handling, I received this error via email.
This error message was not at all helpful in production environment.
On careful debugging I found out that my Stored Proc failed.
Instead of giving the reason for Stored Proc failure it gave this obscure message. If someone knows why it gives this message it will be helpful.
(reason my sp failed was because I was calling a non-existing user defined function)
Locking Cell and Changing Cell Style UltraWebGrid
Refer this article for Column Locking / Freezing in Infragistics Ultra WebGrid
If you need to change background color for a frozen columns then ..
backcolor property must be changed first then cells have to be locked.
e.Layout.Bands(0).Columns(0).CellStyle.BackColor = Drawing.Color.Beige e.Layout.Bands(0).Columns(0).Header.Fixed = True
and in InitializeLayout of ultraWebgrid
Private Sub ultrawebgrid_InitializeLayout(ByVal sender As Object, ByVal e As Infragistics.WebUI.UltraWebGrid.LayoutEventArgs) Handles uwgCategory.InitializeLayout e.Layout.UseFixedHeaders = True End Sub
Call Javascript Function inside asp:Hyperlink Control
If you ever want to call a javascript function (with or without parameter) from a server side hyperlink control here it is..
Step 1 :
declare your javascript function between
Step 2:
<asp:HyperLink ID=”hypCate” runat=”server”
NavigateUrl='<%# “javascript:showPopUp(” & DataBinder.Eval(Container.DataItem, “ID”) & “);” %>’
Text='<%#DataBinder.Eval(Container.DataItem, “Name”)%>’ />
Carefully follow the single and double quotes for NavigateUrl attribute.
Needless to say showPopUp is the name of Javascript Function.
It displays the NAME as hyperlink. Clicking that calls javascript showPopUp.
Column Locking / Freezing in Infragistics Ultra WebGrid
(NetAdvantage for ASP.NET)
If you want to freeze first few columns like EXCEL and horizontally scroll rest of the columns in Ultra WebGrid here you go…
Event :
UltraWebGrid1_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e)
VB Code :
e.Layout.UseFixedHeaders = true e.Layout.Bands(0).Columns(1).Header.Fixed = true e.Layout.Bands(0).Columns(2).Header.Fixed = true
Above code freezes the two columns (second,third) in Grid.
C# Code
protected void UltraWebGrid1_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e) { e.Layout.UseFixedHeaders = true; e.Layout.Bands[0].Columns[1].Header.Fixed = true; e.Layout.Bands[0].Columns[2].Header.Fixed = true; }
GridView Sorting/Paging w/o a DataSourceControl DataSource (VB.NET)
This page is reproduced from this URL. Copied here for easy reference. All credits to the original author.
______________________
If you set AllowPaging=”true” or AllowSorting=”true” on a GridView control without using a DataSourceControl DataSource (i.e. SqlDataSource, ObjectDataSource), you will run into the following errors:
When changing the page on the GridView control:
The GridView ‘GridViewID’ fired event PageIndexChanging which wasn’t handled.
When clicking a column name to sort the column on the GridView control:
The GridView ‘GridViewID’ fired event Sorting which wasn’t handled.
As a result of not setting the DataSourceID property of the GridView to a DataSourceControl DataSource, you have to add event handlers for sorting and paging.
<%@ Page Language=”VB” %>
<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.OleDb” %>
<script runat=”server”>
Private Sub PopulatePublishersGridView()
Dim connectionString As String = AccessConnectionString()
Dim accessConnection As OleDbConnection = New OleDbConnection(connectionString)
Dim sqlQuery As String = “SELECT [PubID], [Name], [Company Name], [Address], [City], [State], [Zip], [Telephone], [Fax], [Comments] FROM Publishers ORDER BY [Name] ASC;”
Dim accessCommand As New OleDbCommand(sqlQuery, accessConnection)
Dim publishersDataAdapter As New OleDbDataAdapter(accessCommand)
Dim publishersDataTable As New DataTable(“Publishers”)
publishersDataAdapter.Fill(publishersDataTable)
Dim dataTableRowCount As Integer = publishersDataTable.Rows.Count
If dataTableRowCount > 0 Then
gridViewPublishers.DataSource = publishersDataTable
gridViewPublishers.DataBind()
End If
End Sub
Private Function AccessConnectionString() As String
Dim accessDatabasePath As String = Server.MapPath(“~/App_Data/biblio.mdb”)
Return String.Format(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};”, accessDatabasePath)
End Function
Private Property GridViewSortDirection() As String
Get
Return IIf(ViewState(“SortDirection”) = Nothing, “ASC”, ViewState(“SortDirection”))
End Get
Set(ByVal value As String)
ViewState(“SortDirection”) = value
End Set
End Property
Private Property GridViewSortExpression() As String
Get
Return IIf(ViewState(“SortExpression”) = Nothing, String.Empty, ViewState(“SortExpression”))
End Get
Set(ByVal value As String)
ViewState(“SortExpression”) = value
End Set
End Property
Private Function GetSortDirection() As String
Select Case GridViewSortDirection
Case “ASC”
GridViewSortDirection = “DESC”
Case “DESC”
GridViewSortDirection = “ASC”
End Select
Return GridViewSortDirection
End Function
Protected Sub gridViewPublishers_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gridViewPublishers.DataSource = SortDataTable(CType(gridViewPublishers.DataSource,DataTable), True) gridViewPublishers.PageIndex = e.NewPageIndex
gridViewPublishers.DataBind()
End Sub
Protected Function SortDataTable(ByVal pdataTable As DataTable, ByVal isPageIndexChanging As Boolean) As DataView
If Not pdataTable Is Nothing Then
Dim pdataView As New DataView(pdataTable)
If GridViewSortExpression <> String.Empty Then
If isPageIndexChanging Then
pdataView.Sort = String.Format(“{0} {1}”, GridViewSortExpression, GridViewSortDirection)
Else
pdataView.Sort = String.Format(“{0} {1}”, GridViewSortExpression, GetSortDirection())
End If
End If
Return pdataView
Else
Return New DataView()
End If
End Function
Protected Sub gridViewPublishers_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
GridViewSortExpression = e.SortExpression
Dim pageIndex As Integer = gridViewPublishers.PageIndex
gridViewPublishers.DataSource = SortDataTable(CType(gridViewPublishers.DataSource,DataTable), False)
gridViewPublishers.DataBind()
gridViewPublishers.PageIndex = pageIndex
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
PopulatePublishersGridView()
End Sub
</script>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1″ runat=”server”>
<title>GridView Sorting/Paging without a DataSourceControl DataSource</title>
</head>
<body>
<form id=”form” runat=”server”>
<div>
<asp:GridView ID=”gridViewPublishers” AllowPaging=”true” AllowSorting=”true” AutoGenerateColumns=”false”
EmptyDataText=”No records found” PagerSettings-Mode=”NumericFirstLast” PageSize=”25″
OnPageIndexChanging=”gridViewPublishers_PageIndexChanging” OnSorting=”gridViewPublishers_Sorting”
runat=”server”>
<AlternatingRowStyle BackColor=”LightGray” />
<HeaderStyle BackColor=”Gray” Font-Bold=”true” Font-Names=”Verdana” Font-Size=”Small” />
<PagerStyle BackColor=”DarkGray” Font-Names=”Verdana” Font-Size=”Small” />
<RowStyle Font-Names=”Verdana” Font-Size=”Small” />
<Columns>
<asp:BoundField DataField=”PubID” HeaderText=”Publisher ID” SortExpression=”PubID” />
<asp:BoundField DataField=”Name” HeaderText=”Name” SortExpression=”Name” />
<asp:BoundField DataField=”Company Name” HeaderText=”Company Name” SortExpression=”Company Name” />
<asp:BoundField DataField=”Address” HeaderText=”Address” SortExpression=”Address” />
<asp:BoundField DataField=”City” HeaderText=”City” SortExpression=”City” />
<asp:BoundField DataField=”State” HeaderText=”State” SortExpression=”State” />
<asp:BoundField DataField=”Zip” HeaderText=”Zip” SortExpression=”Zip” />
<asp:BoundField DataField=”Telephone” HeaderText=”Telephone” SortExpression=”Telephone” />
<asp:BoundField DataField=”Fax” HeaderText=”Fax” SortExpression=”Fax” />
<asp:BoundField DataField=”Comments” HeaderText=”Comments” SortExpression=”Comments” />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Must have tools for Web Developer – 2
Previous article : Must have tools for Web Developer – 1
IEDeveloper Toolbar
This is excellent application for web developers & designers. Not only on the pages you design, it can used on any website to learn about it or make fun of it in cafeteria.
You can see how your page looks on different resolution without changing your display setting.
Following lines are from Microsoft, which is what I also wanted to write.
– Explore and modify the document object model (DOM) of a Web page.
– Locate and select specific elements on a Web page through a variety of techniques.
– Selectively disable Internet Explorer settings.
– View HTML object class names, ID’s, and details such as link paths, tab index values, and access keys.
– Outline tables, table cells, images, or selected tags.
– Validate HTML, CSS, WAI, and RSS web feed links.
– Display image dimensions, file sizes, path information, and alternate (ALT) text.
– Immediately resize the browser window to a new resolution.
– Selectively clear the browser cache and saved cookies. Choose from all objects or those associated with a given domain.
– Display a fully featured design ruler to help accurately align and measure objects on your pages.
– Find the style rules used to set specific style values on an element.
– View the formatted and syntax colored source of HTML and CSS.
Click here to Download
Cost: Free
ooOoo
How can I upload larger files with ASP.NET?
By default, the file size limit on uploads in ASP.NET is 4mb. If you need to upload more than 4 MB .. here you go
To upload larger files through HTTP, you can use a configuration setting in your application Web.config file or your machine Web.config file:
Replace [ ] with angle brackets
[configuration]
[system.web]
[httpRuntime maxRequestLength=”10000″ /]
[/system.web]
[/configuration]
where “10000” is the file size in Kbytes that you want to allow. You can go upto 1GB.
If webservice is called for saving the files, then this configuration has to be made in both the applications.
WebService application and Web application.
Useful Undocumented SQL Server Extended Stored Procedures
– by Alexander Chigrik
An extended stored procedure (xp) is a dynamic link library that runs directly in the address space of SQL Server and is programmed using the SQL Server Open Data Services API. You can run extended stored procedures from the Query Analyzer, for example, just as you would normal stored procedures. Extended stored procedures are used to extend the capabilities of SQL Server.
sp_Msgetversion
This extended stored procedure can be used to get the current version of Microsoft SQL Server. To get the current SQL Server version, run:
EXEC master..sp_MSgetversion
Note. A more common way to retrieve the current SQL Server version (this way provides more information) is to use following SELECT statement:
SELECT @@version
xp_dirtree
This extended stored procedure can be used to get a list of all the folders for the folder named in the xp. To get a list of all the folders in the C:\MSSQL7 folder, run:
EXEC master..xp_dirtree ‘C:\MSSQL7’
xp_subdirs
This extended stored procedure is used to get the list of folders for the folder named in the xp. In comparison with xp_dirtree, xp_subdirs returns only those directories whose depth = 1.
This is the example:
EXEC master..xp_subdirs ‘C:\MSSQL7’
xp_enum_oledb_providers
This extended stored procedure is used to list of all the available OLE DB providers. It returns Provider Name, Parse Name and Provider Description. To get a list of all OLE DB providers for your SQL Server, run:
EXEC master..xp_enum_oledb_providers
xp_enumcodepages
This extended stored procedure can be used to list of all code pages, character sets and their description for your SQL Server. To see this, list, run:
EXEC master..xp_enumcodepages
xp_enumdsn
This extended stored procedure returns a list of all system DSNs and their descriptions. To get the list of system DSNs, run:
EXEC master..xp_enumdsn
xp_enumerrorlogs
This extended stored procedure returns the list of all error logs with their last change date. To get the list of error logs, run:
EXEC master..xp_enumerrorlogs
xp_enumgroups
This extended stored procedure returns the list of Windows NT groups and their description. To get the list of the Windows NT groups, run:
EXEC master..xp_enumgroups
xp_fileexist
You can use this extended stored procedure to determine whether a particular file exists on the disk or not. The syntax for this xp is:
EXECUTE xp_fileexist filename [, file_exists INT OUTPUT]
For example, to check whether the file boot.ini exists on disk c: or not, run:
EXEC master..xp_fileexist ‘c:\boot.ini’
xp_fixeddrives
This very useful extended stored procedure returns the list of all hard drives and the amount of free space in Mb for each hard drive. To see the list of drives, run:
EXEC master..xp_fixeddrives
xp_getnetname
This extended stored procedure returns the WINS name of the SQL Server that you’re connected to. To view the name, run:
EXEC master..xp_getnetname
xp_readerrorlog
This extended stored procedure returns the content of the errorlog file. You can find the errorlog file in the C:\MSSQL7\Log directory, by default. To see the text of the errorlog file, run:
EXEC master..xp_readerrorlog
xp_regdeletekey
This extended stored procedure will delete an entire key from the registry. You should use it very carefully. The syntax is:
EXECUTE xp_regdeletekey [@rootkey=]’rootkey’, [@key=]’key’
For example, to delete the key ‘SOFTWARE\Test’ from ‘HKEY_LOCAL_MACHINE’, run:
EXEC master..xp_regdeletekey @rootkey=’HKEY_LOCAL_MACHINE’, @key=’SOFTWARE\Test’
xp_regdeletevalue
This extended stored procedure will delete a particular value for a key in the registry. You should use it very carefully. The syntax is:
EXECUTE xp_regdeletevalue [@rootkey=]’rootkey’, [@key=]’key’, [@value_name=]’value_name’
For example, to delete the value ‘TestValue’ for the key ‘SOFTWARE\Test’ from ‘HKEY_LOCAL_MACHINE’, run:
EXEC master..xp_regdeletevalue @rootkey=’HKEY_LOCAL_MACHINE’, @key=’SOFTWARE\Test’, @value_name=’TestValue’
xp_regread
This extended stored procedure is used to read from the registry. The syntax is:
EXECUTE xp_regread [@rootkey=]’rootkey’, [@key=]’key’ [, [@value_name=]’value_name’] [, [@value=]@value OUTPUT]
For example, to read into the variable @test from the value ‘TestValue’ from the key ‘SOFTWARE\Test’ from the ‘HKEY_LOCAL_MACHINE’, run:
DECLARE @test varchar(20)EXEC master..xp_regread @rootkey=’HKEY_LOCAL_MACHINE’, @key=’SOFTWARE\Test’, @value_name=’TestValue’, @value=@test OUTPUTSELECT @test
xp_regwrite
This extended stored procedure is used to write to the registry. The syntax is:
EXECUTE xp_regwrite [@rootkey=]’rootkey’, [@key=]’key’, [@value_name=]’value_name’, [@type=]’type’, [@value=]’value’
For example, to write the variable ‘Test’ to the ‘TestValue’ value, key ‘SOFTWARE\Test’, ‘HKEY_LOCAL_MACHINE’, run:
EXEC master..xp_regwrite @rootkey=’HKEY_LOCAL_MACHINE’, @key=’SOFTWARE\Test’, @value_name=’TestValue’, @type=’REG_SZ’, @value=’Test’
Keep in mind that these undocumented extended stored procedures are not officially supported by Microsoft, and that they may not be found in the next version of SQL Server.
Atalasoft WebImageViewer (aka) AJAX Thin Client Viewer
When using Atalasoft Thin Client Viewer use the following basic settings.
‘PreCacheing to ALWAYS has some issues so its better not to use it.
Me.WebImageViewerMain.PreCacheTiles = PreCacheMode.Never‘ Opens the first page in Viewer
Me.WebImageViewerMain.OpenUrl(Server.Mappath(“.”) & “\Sample.tif”, 0)‘Setting the AntialiasDisplay
Me.WebImageViewerMain.AntialiasDisplay = AntialiasDisplayMode.ScaleToGray
If you have tiff images of size 8.5″ x 11.0″ or greater setting up the AntialiasDisplay to anything other than NONE chews memory but its worth it if used along with AutoZoom
‘Loading the page as FitToWidth
Me.WebImageViewerMain.AutoZoom = AutoZoomMode.FitToWidth
PS : If Autozoom is not used then AntialiasDisplay can be set to None.
Simple Annotation Using Atalasoft DotImage 4.0 (Asp.net)
DotNet framework 1.1 (not tested the same in 2.0)
Make sure you have the following references in BIN
Atalasoft.dotImage.dll
Atalasoft.dotImage.Lib.dll
Atalasoft.dotImage.Webcontrols.dll
Atalasoft.shared.dll
Use the following NameSpaces
Imports Atalasoft.Imaging
Imports Atalasoft.Imaging.WebControls
Imports Atalasoft.Imaging.ImageProcessing
Imports Atalasoft.Imaging.Codec
Imports Atalasoft.Imaging.Codec.Tiff
Avoid using Workspace object for simple tasks. As workspace occupies more memory (according to Atalasoft unofficial sources) and most of the operations can be done using AtalaImage object.
Annotate ONE PAGE TIFF Document
Dim tiffImage As AtalaImage
Dim watermarkimage As AtalaImage = New AtalaImage(Server.MapPath(“.”) & “watermark.jpg”)Dim overlay As OverlayCommand
Dim newAnnoatedFileName as String
tiffImage = New AtalaImage(Server.MapPath(“.”) & “Sample.tif”, 0, Nothing)
newAnnoatedFileName = Server.MapPath(“.”) & “\Sample-Annoated.tif”
‘Image Overlay
overlay = New OverlayCommand(watermarkimage, New Point(350, 550), 0)
overlay.Apply(tiffImage)
‘False in TiffEncoder means dont append (as the file is created for the first time there is nothing to append to.)
tiffImage.Save(newAnnoatedFileName, New TiffEncoder(TiffCompression.Default, False), Nothing)
————————————————————————————Annotate MULTIPAGE TIFF Document
Dim tiffImage As AtalaImage
Dim watermarkimage As AtalaImage = New AtalaImage(Server.MapPath(“.”) & “watermark.jpg”)Dim overlay As OverlayCommand
Dim newAnnoatedFileName as String
Dim numberofpages as integer,iCount as integernumberofpages = RegisteredDecoders.GetImageInfo(Server.MapPath(“.”) & “Sample.tif”).FrameCountnewAnnoatedFileName = Server.MapPath(“.”) & “\Sample-Annotated.tif”‘350,550 does the annotation from Bottom Left to Top Right.
‘0 is the set the transparency in the top Image. (Dot Image 4.0)
‘Use 1 if you are using Dot Image 3.0
overlay = New OverlayCommand(watermarkimage, New Point(350, 550), 0)
For iCount = 0 To numberOfPages – 1
‘Opens one frame (page) at a time as specified in iCount
tiffImage = New AtalaImage(Server.MapPath(“.”) & “Sample.tif”, iCount, Nothing)‘Image Overlay
overlay.Apply(tiffImage)‘Save the first page with FALSE param (as there is nothing to append to) for other pages set it to TRUE so that the same TIFF gets appended with multi frames (pages)If iCount = 0 Then
tiffImage.Save(newAnnoatedFileName, New TiffEncoder(TiffCompression.Default, False), Nothing)
ElsetiffImage.Save(newAnnoatedFileName, New TiffEncoder(TiffCompression.Default, True), Nothing)End IfNextIf Not watermarkimage Is Nothing Then
watermarkimage.Dispose()
End IfIf Not tiffImage Is Nothing Then
tiffImage.Dispose()
End If
If Not overlay Is Nothing Then
overlay = Nothing
End If