1
Ctrl + Shift + A
AllCaps
Makes the selection all capitals (toggle)
2
Alt + Ctrl + 1
ApplyHeading1
Applies Heading 1 style to the selected text
3
Alt + Ctrl + 2
ApplyHeading2
Applies Heading 2 style to the selected text
4
Alt + Ctrl + 3
ApplyHeading3
Applies Heading 3 style to the selected text
5
Ctrl + Shift + L
ApplyListBullet
Applies List Bullet style to the selected text
6
Alt + F10
AppMaximize
Enlarges the application window to full size
7
Alt + F5
AppRestore
Restores the application window to normal size
8
Ctrl+B
Bold
Makes the selection bold (toggle)
9
Ctrl + PgDn
BrowseNext
Jump to the next browse object
10
Ctrl + PgUp
BrowsePrev
Jump to the previous browse object
11
Alt + Ctrl + Home
BrowseSel
Select the next/prev browse object
12
Esc
Cancel
Terminates an action
13
Ctrl+E
CenterPara
Centers the paragraph between the indents
14
Shift+F3
ChangeCase
Changes the case of the letters in the selection
15
Left arrow
CharLeft
Moves the insertion point to the left one character
16
Shift + Left arrow
CharLeftExtend
Extends the selection to the left one character
17
Rt arrow
CharRight
Moves the insertion point to the right one character
18
Shift + Rt arrow
CharRightExtend
Extends the selection to the right one character
19
Alt + Shift + C
ClosePane
Closes the active window pane (if you are in Normal View and have,
for example, the Footnote pane open)
20
Alt+Drag (or press Ctrl + Shift + F8 and drag, but Alt + Drag is
far easier!)
ColumnSelect
Selects a columnar block of text
21
Ctrl +Shift+C
CopyFormat
Copies the formatting of the selection
22
Shift + F2
CopyText
Makes a copy of the selection without using the clipboard (press
Return to paste)
23
Alt + F3
CreateAutoText
Adds an AutoText entry to the active template
24
Ctrl+ Backspace
DeleteBackWord
Deletes the previous word without putting it on the Clipboard
25
Ctrl + Del
DeleteWord
Deletes the next word without putting it on the Clipboard
26
Ctrl+W, Ctrl+F4
DocClose
Prompts to save the document and then closes the active window.
(But doesn't intercept the menu command)
27
Ctrl + F10
DocMaximize
Enlarges the active window to full size
28
Ctrl + F7
DocMove
Changes the position of the active window
29
Ctrl + F5
DocRestore
Restores the window to normal size
30
Ctrl + F8
DocSize
Changes the size of the active window
31
Alt + Ctrl + S
DocSplit
Splits the active window horizontally and then adjusts the split
32
Alt + Shift + F9
DoFieldClick
Executes the action associated with macrobutton fields
33
Ctrl + Shift + D
DoubleUnderline
Double underlines the selection (toggle)
34
Alt R, G
DrawGroup
Groups the selected drawing objects
35
Alt R, I
DrawSnapToGrid
Sets up a grid for aligning drawing objects
36
Alt R, U
DrawUngroup
Ungroups the selected group of drawing objects
37
Ctrl+Shift+F5 (Or: Alt I, K)
EditBookmark
Brings up the bookmark dialog
38
Del
EditClear
Performs a forward delete or removes the selection without putting
it on the Clipboard
39
Ctrl+C
EditCopy
Copies the selection and puts it on the Clipboard
40
Ctrl+X
EditCut
Cuts the selection and puts it on the Clipboard
41
Ctrl+F
EditFind
Finds the specified text or the specified formatting
42
F5, Ctrl+G
EditGoTo
Jumps to a specified place in the active document
43
Alt E, K
EditLinks
Allows links to be viewed, updated, opened, or removed
44
Ctrl+V
EditPaste
Inserts the Clipboard contents at the insertion point
45
Alt E, S
EditPasteSpecial
Inserts the Clipboard contents as a linked object, embedded object,
or other format
46
Alt + Shift + Backspc
EditRedo
Redoes the last action that was undone
47
F4
EditRedoOrRepeat
Repeats the last command, or redoes the last action that was undone
(unfortunately, doesn't work for as many commands in Word 2000 as in Word 97 and
below, but this is still one of Word's most useful shortcuts, if not the most
useful)
48
Ctrl+H
EditReplace
Finds the specified text or the specified formatting and replaces
it
49
Ctrl+A
EditSelectAll
Selects the entire document
50
Ctrl+Z
EditUndo
Reverses the last action
51
Alt + PageDn (to select to end of column, use Alt + Shift + PgDn)
EndOfColumn
Moves to the last cell in the current table column
52
Ctrl+Shift+End
EndOfDocExtend
Extends the selection to the end of the last line of the document
53
Ctrl+End
EndOfDocument
Moves the insertion point to the end of the last line of the
document
54
End
EndOfLine
Moves the insertion point to the end of the current line
55
Shift+End
EndOfLineExtend
Extends the selection to the end of the current line
56
Alt+End
EndOfRow
Moves to the last cell in the current row
57
Alt + Ctrl + PgDn
EndOfWindow
Moves the insertion point to the end of the last visible line on
the screen
58
Shift + Alt + Ctrl + PgDn
EndOfWindowExtend
Extends the selection to the end of the last visible line on the
screen
59
F8 (press Esc to turn off)
ExtendSelection
Turns on extend selection mode and then expands the selection with
the direction keys
60
Alt + F4 (<9>)
FileCloseOrExit
Closes the current document, or if no documents are open, quits
Word. Horrible command, as it makes it a long winded business to quit Word. But
there's a simple solution - assign Alt+F4 to FileExit instead.
61
Alt + F4 (Word 97)
FileExit
Quits Microsoft Word and prompts to save the documents (does
intercept the menu item, but not the keyboard shortcut, or the x button. An
AutoExit macro is usually a better way of intercepting this).
62
NOT Ctrl+N!!
FileNew
Creates a new document or template (brings up the dialog). Note
that: Word pretends that Ctrl+N is assigned to FileNew but it isn't, it's
assigned to FileNewDefault You can fix this in Word 2000 by assigning Ctrl+N to
the FileNewDialog command. In Word 97 the only way to fix it is to create a
macro called FileNew (to do this, press Alt + F8, type "FileNew" without the
quotes and Click "Create". The macro will automatically contain the code needed
to make it work).
63
Ctrl+N
FileNewDefault
Creates a new document based on the Normal template.
64
Ctrl+O
FileOpen
Opens an existing document or template
65
Alt F, U
FilePageSetup
Changes the page setup of the selected sections
66
Ctrl + P
FilePrint
Prints the active document (brings up the dialog)
67
Ctrl+F2
FilePrintPreview
Displays full pages as they will be printed
68
Alt F, I
FileProperties
Shows the properties of the active document
69
Ctrl+S
FileSave
FileSave
70
Alt F, A (or F12)
FileSaveAs
Saves a copy of the document in a separate file (brings up the
dialog)
71
Ctrl+Shift+F
Font
Activates the Fonts listbox on the formatting toolbar
72
Ctrl+Shift+P
FontSizeSelect
Activates the Font Size drop-down on the formatting toolbar
73
Alt + Ctrl + K
FormatAutoFormat
Automatically formats a document (or sometimes, automatically
screws it up)
74
Alt O, B
FormatBordersAndShading
Changes the borders and shading of the selected paragraphs, table
cells, and pictures
75
Alt O, E
FormatChangeCase
Changes the case of the letters in the selection
76
Alt O, C
FormatColumns
Changes the column format of the selected sections (brings up the
dialog)
77
Alt O, D
FormatDropCap
Formats the first character of current paragraph as a dropped
capital (must select it first)
78
Ctrl+D
FormatFont
Brings up the Format + Font dialog
79
Alt + Shift + R
FormatHeaderFooterLink
Links the current header/footer to the previous section (but does
not intercept the button on the Header Footer toolbar)
80
Alt O, P
FormatParagraph
Brings up the Format Paragraph dialog
81
Alt O, S
FormatStyle
Applies, creates, or modifies styles
82
Alt O, T
FormatTabs
Brings up the Format Tabs dialog
83
Shift + F5
GoBack
Returns to the previous insertion point (goes back to up to 3
points, then returns to where you started; this is one of the most useful
shortcuts of them all. Also useful when opening a document, if you want to g
straight to where you were last editing it)
84
Ctrl + >
GrowFont
Increases the font size of the selection
85
Ctrl + ]
GrowFontOnePoint
Increases the font size of the selection by one point
86
Ctrl + T (or drag the ruler)
HangingIndent
Increases the hanging indent
87
F1
Help
Microsoft Word Help
88
Shift + F1
HelpTool
Lets you get help on a command or screen region or examine text
properties
89
Ctrl + Shift + H
Hidden
Makes the selection hidden text (toggle)
90
Click on it
HyperlinkOpen
Connect to a hyperlink's address
91
Ctrl + M (or drag the ruler)
Indent
Moves the left indent to the next tab stop
92
Alt + Ctrl + M (or Alt I, M)
InsertAnnotation
Inserts a comment
93
F3
InsertAutoText
Replaces the name of the AutoText entry with its contents
94
Alt I, B
InsertBreak
Ends a page, column, or section at the insertion point
95
Alt I, C
InsertCaption
Inserts a caption above or below a selected object
96
Ctrl + Shift + Return
InsertColumnBreak
Inserts a column break at the insertion point
97
Alt + Shift + D
InsertDateField
Inserts a date field
98
Alt + Ctrl + D
InsertEndnoteNow
Inserts an endnote reference at the insertion point without
displaying the dialog
99
Alt I, F
InsertField
Inserts a field in the active document
100
Ctrl+F9
InsertFieldChars
Inserts an empty field with the enclosing field characters
101
Alt I, L
InsertFile
Inserts the text of another file into the active document
102
Alt I, N
InsertFootnote
Inserts a footnote or endnote reference at the insertion point
103
Alt + Ctrl + F
InsertFootnoteNow
Inserts a footnote reference at the insertion point without
displaying the dialog
104
Ctrl + K
InsertHyperlink
Insert Hyperlink
105
Alt I, D
InsertIndexAndTables
Inserts an index or a table of contents, figures, or authorities
into the document
106
Alt + Ctrl + L
InsertListNumField
Inserts a ListNum Field
107
Alt + Shift + F
InsertMergeField
Brings up a dialog to insert a mail merge field at the insertion
point. (It does not intercept the button on the Mail merge. toolbar)
108
Ctrl + Return
InsertPageBreak
Inserts a page break at the insertion point
109
Alt + Shift + P
InsertPageField
Inserts a page number field
110
Ctrl + Shift + F3
InsertSpike
Empties the spike AutoText entry and inserts all of its contents
into the document
111
Alt + Shift + T
InsertTimeField
Inserts a time field
112
Ctrl + I
Italic
Makes the selection italic (toggle)
113
Ctrl + J
JustifyPara
Aligns the paragraph at both the left and the right indent
114
Ctrl + L
LeftPara
Aligns the paragraph at the left indent
115
Down arrow
LineDown
Moves the insertion point down one line
116
Shift + down arrow
LineDownExtend
Extends the selection down one line
117
Up arrow
LineUp
Moves the insertion point up one line
118
Shift + up arrow
LineUpExtend
Extends the selection up one line
119
Ctrl + F11
LockFields
Locks the selected fields to prevent updating
120
Alt + Shift + K
MailMergeCheck
Checks for errors in a mail merge
121
Alt+Shift+E
MailMergeEditDataSource
Lets you edit a mail merge data source
122
Alt + Shift + N
MailMergeToDoc
Collects the results of the mail merge in a document
123
Alt Shift + M
MailMergeToPrinter
Sends the results of the mail merge to the printer
124
Alt + Shift + I
MarkCitation
Marks the text you want to include in the table of authorities
125
Alt + Shift + X
MarkIndexEntry
Marks the text you want to include in the index
126
Alt + Shift + O
MarkTableOfContentsEntry
Inserts a TC field (but it is far better to use Heading Styles to
generate your Table of Contents instead)
127
Alt or F10
MenuMode
Makes the menu bar active
128
Alt + Shift + F11
MicrosoftScriptEditor
Starts or switches to Microsoft Development Environment
application, allowing you to view the HTML/XML source code that would be behind
the document if it were in .htm format (or that is behind it if it already is in
.htm format).
129
Alt + Ctrl + F1
MicrosoftSystemInfo
Execute the Microsoft System Info application
130
F2
MoveText
Moves the selection to a specified location without using the
clipboard (press Return to execute the more)
131
Tab
NextCell
Moves to the next table cell
132
F11
NextField
Moves to the next field
133
Alt + F7
NextMisspelling
Find next spelling error
134
Alt + down arrow
NextObject
Moves to the next object on the page
135
Ctrl + F6
NextWindow
Switches to the next document window, equivalent to selecting a
document from the Window menu.
136
Ctrl+Shift+N
NormalStyle
Applies the Normal style
137
Ctrl + 0
OpenOrCloseUpPara
Sets or removes extra spacing above the selected paragraph
138
F6
OtherPane
Switches to another window pane in Normal View (for instance, if
you have if you have a Footnotes pane open in Normal view and want to switch to
the main document and back without closing the pane).
139
Alt + _
OutlineCollapse
Collapses an Outline in Outline View by one level
140
Alt+Shift+rt arrow
OutlineDemote
Demotes the selected paragraphs one heading level
141
Alt + +
OutlineExpand
Expands an Outline in Outline View by one level
142
Alt+Shift+down arrow
OutlineMoveDown
Moves the selection below the next item in the outline
143
Alt+Shift+up arrow
OutlineMoveUp
Moves the selection above the previous item in the outline
144
Alt+Shift+left arrow
OutlinePromote
Promotes the selected paragraphs one heading level
145
Alt + Shift + L
OutlineShowFirstLine
Toggles between showing the first line of each paragraph only or
showing all of the body text in the outline
146
Ins
Overtype
Toggles the typing mode between replacing and inserting
147
PgDn
PageDown
Moves the insertion point and document display to the next screen
of text
148
Shift+ PgDn
PageDownExtend
Extends the selection and changes the document display to the next
screen of text
149
PgUp
PageUp
Moves the insertion point and document display to the previous
screen of text
150
Shift + PgUp
PageUpExtend
Extends the selection and changes the document display to the
previous screen of text
151
Ctrl + down arrow
ParaDown
Moves the insertion point to the beginning of the next paragraph
152
Shift + Ctrl + down arrow
ParaDownExtend
Extends the selection to the beginning of the next paragraph
153
Ctrl + up arrow
ParaUp
Moves the insertion point to the beginning of the previous
paragraph
154
Shift + Ctrl + up arrow
ParaUpExtend
Extends the selection to the beginning of the previous paragraph
155
Ctrl+Shift+V
PasteFormat
Applies the previously copied formatting to selection
156
Shift + Tab
PrevCell
Moves to the previous table cell
157
Shift + F11
PrevField
Moves to the previous field
158
Alt + up arrow
PrevObject
Moves to the previous object on the page
159
Ctrl + Shift + F6
PrevWindow
Switches back to the previous document window
160
Sfift+F4
RepeatFind
Repeats Go To or Find to find the next occurrence
161
Ctrl+Spacebar
ResetChar
Makes the selection the default character format of the applied
style
162
Ctrl+Q
ResetPara
Makes the selection the default paragraph format of the applied
style
163
Ctrl +R
RightPara
Aligns the paragraph at the right indent
164
Ctrl + *
ShowAll
Shows/hides all nonprinting characters
165
Alt + Shift + A
ShowAllHeadings
Displays all of the heading levels and the body text in Outline
View
166
Ctrl + <
ShrinkFont
Decreases the font size of the selection
167
Ctrl + [
ShrinkFontOnePoint
Decreases the font size of the selection by one point
168
Ctrl + Shift + K
SmallCaps
Makes the selection small capitals (toggle)
169
Ctrl + 1
SpacePara1
Sets the line spacing to single space
170
Ctrl + 5
SpacePara15
Sets the line spacing to one-and-one-half space
171
Ctrl + 2
SpacePara2
Sets the line spacing to double space
172
Ctrl + F3
Spike
Deletes the selection and adds it to the "Spike" AutoText entry
(which allows you to move text and graphics from nonadjacent locations)
173
Alt + PgUp
StartOfColumn
Moves to the first cell in the current column
174
Ctrl+Shift+Home
StartOfDocExtend
Extends the selection to the beginning of the first line of the
document
175
Ctrl +Home
StartOfDocument
Moves the insertion point to the beginning of the first line of the
document
176
Home
StartOfLine
Moves the insertion point to the beginning of the current line
177
Shift+Home
StartOfLineExtend
Extends the selection to the beginning of the current line
178
Alt+Home
StartOfRow
Moves to the first cell in the current row
179
Alt+Ctrl+PgUp
StartOfWindow
Moves the insertion point to the beginning of the first visible
line on the screen
180
Shift+ Alt+Ctrl+PgUp
StartOfWindowExtend
Extends the selection to the beginning of the first visible line on
the screen
181
Strl + Shift + S
Style
Activates the Style drop-down on the Formatting toolbar
182
Ctrl + =
Subscript
Makes the selection subscript (toggle)
183
Ctrl + +
Superscript
Makes the selection superscript (toggle)
184
Ctrl + Shift + Q
SymbolFont
Applies the Symbol font to the selection
185
Alt A, F
TableAutoFormat
Applies a set of formatting to a table
186
Alt A, H
TableHeadings
Toggles table headings attribute on and off
187
Alt + click
(Alt + drag to select several)
TableSelectColumn
Selects the current column in a table
188
Click in left margin
TableSelectRow
Selects the current row in a table
189
Alt + double-click
TableSelectTable
Selects an entire table
190
Alt + Ctrl + U
TableUpdateAutoFormat
Updates the table formatting to match the applied Table Autoformat
settings
191
Shift + F9 (Alt + F9 toggles all field codes on or off)
ToggleFieldDisplay
Shows the field codes or the results for the selection (toggle)
192
Alt T, C
ToolsCustomize
Allows you to customizes the Word user interface (menus, keyboard
and toolbars) and store the customizations in a template (defaults to
Normal.dot, so be careful!)
193
Alt + F8
ToolsMacro
Runs, creates, deletes, or revises a macro
194
F7
ToolsProofing
Checks the spelling and grammar in the active document
195
Ctr.l + Shift + E
ToolsRevisionMarksToggle
Toggles track changes for the active document
196
Shift + F7
ToolsThesaurus
Finds a synonym for the selected word
197
Ctrl+U
Underline
Formats the selection with a continuous underline (toggle)
198
Ctrl + Shift + T
(or drag the ruler)
UnHang
Decreases the hanging indent
199
Ctrl + Shift + M
(or drag the ruler)
UnIndent
Moves the left indent to the previous tab stop
200
Ctrl+Shift+F9
UnlinkFields
Permanently replaces the field codes with the results
201
Ctrl + Shift + F11
UnlockFields
Unlocks the selected fields for updating
202
F9
UpdateFields
Updates and displays the results of the selected fields
203
Ctrl + Shiift + F7
UpdateSource
Copies the modified text of a linked file back to its source file
204
Hover over comment
ViewAnnotations
Show or hide the comment pane
205
Dbl-click the endnote reference
ViewEndnoteArea
If in Normal View, opens a pane for viewing and editing the endnote
(toggle). If in Page/Print Layout View, switches from the body text to the
endnote or vice versa
206
At + F9
ViewFieldCodes
Shows the field codes or results for all fields (toggle)
207
Dbl-click the footnote reference
ViewFootnoteArea
If in Normal View, opens a pane for viewing and editing the
footnote (toggle). If in Page/Print Layout View, switches from the body text to
the footnote or vice versa.
208
Alt V, F
ViewFootnotes
If in Normal View, opens a pane for viewing and editing footnotes
and endnotes (toggle). If in Page/Print Layout View, switches from the body text
to the footnotes/endnotes or vice versa.
209
Alt V, H
ViewHeader
Displays header in page layout view
210
Alt V, N
(or Alt + Ctrl + N)
ViewNormal
Changes the editing view to normal view
211
Alt V, O
(or Alt + Ctrl + O)
ViewOutline
Displays a document's outline
212
Alt V, P
(or Alt + Ctrl + P)
ViewPage
Displays the page more-or-less as it will be printed, and allows
editing (In Word 2000 the menu item is called Print Layout, but fortunately the
command hasn't changed.
213
Alt + F11
ViewVBCode
Shows the VB editing environment (Tools + Macro + Visual Basic
Editor)
214
Alt + left arrow
WebGoBack
Backward hyperlink (useful if you clicked on a page number
hyperlink in the table of contents and then want to return to the TOC)
215
Alt + rt arrow
WebGoForward
Forward hyperlink
216
Alt W, A
WindowArrangeAll
Arranges windows as non-overlapping tiles
217
Ctrl + left arrow
WordLeft
Moves the insertion point to the left one word
218
Shift + Ctrl + left arrow
WordLeftExtend
Extends the selection to the left one word
219
Ctrl + rt arrow
WordRight
Moves the insertion point to the right one word
220
Shift + Ctrl + rt arrow
WordRightExtend
Extends the selection to the right one word
221
Ctrl + Shift + W
WordUnderline
Underlines the words but not the spaces in the selection (toggle)
Tuesday, June 21, 2011
Code for How to Highlight Row of Gridview on Mouse Over which doesn't use alternate row color in Asp.net
In .aspx File declare OnRowCreated eventas follow.
Following code will:
Highlight Gridview which is not using alternate row color.
protectedvoid OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//On Mouse Over Highlight Row
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ffff00'");
//On Mouse out restore default row color
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
}
}
Following code will:
Highlight Gridview which is not using alternate row color.
protectedvoid OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//On Mouse Over Highlight Row
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ffff00'");
//On Mouse out restore default row color
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
}
}
Code for How to Highlight Gridview Row on Mouse Over when gridview rows are using alternate row color in Asp.net
In .aspx File declare OnRowCreated eventas follow.
Following code will explain:
How to Highlight Gridview which uses alternate row color.
protectedvoid OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//On Mouse over highlight gridview
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ffff00'");
//On Mouse out restore girdview row color based on alternate row color//Please change this color with your gridview alternate color.
if (e.Row.RowIndex % 2 == 0)
{
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#F7F7DE'");
}
else
{
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
}
}
}
Following code will explain:
How to Highlight Gridview which uses alternate row color.
protectedvoid OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//On Mouse over highlight gridview
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ffff00'");
//On Mouse out restore girdview row color based on alternate row color//Please change this color with your gridview alternate color.
if (e.Row.RowIndex % 2 == 0)
{
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#F7F7DE'");
}
else
{
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#FFFFFF'");
}
}
}
Add Google Maps to your .Net site
Ever wanted to add a Google Map to your site but only had 15 minutes to spare? Now you can add a map and still have time to brag to your mates and bask in the worship that (inevitably) comes afterward.
Basically, the guys over at subgurim.net have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working.
But all this is cutting into your bragging time - so lets get started!
1. Get a Google Maps API key from here:
http://www.google.com/apis/maps/
2. Download the SubGurim wrapper dll from here:
http://en.googlemaps.subgurim.net/descargar.aspx
3. Unzip it, and put it in your \bin directory
4. Add it to your toolbox by
Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.
5. Add a new webpage.
6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′
7. Add the following lines to your web.config file:
appsettings>
add key="googlemaps.subgurim.net" value="YourGoogleMapsAPIKeyHere" />
/appSettings>
8. Add the following code to your Page.Load sub
Dim sStreetAddress As String
Dim sMapKey As String = ConfigurationManager.AppSettings("googlemaps.subgurim.net")
Dim GeoCode As Subgurim.Controles.GeoCode
sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia"
GeoCode = GMap1.geoCodeRequest(sStreetAddress, sMapKey)
Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng)
GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)
GMap1.addGMarker(oMarker)
Source:http://gathadams.com/
Basically, the guys over at subgurim.net have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working.
But all this is cutting into your bragging time - so lets get started!
1. Get a Google Maps API key from here:
http://www.google.com/apis/maps/
2. Download the SubGurim wrapper dll from here:
http://en.googlemaps.subgurim.net/descargar.aspx
3. Unzip it, and put it in your \bin directory
4. Add it to your toolbox by
Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.
5. Add a new webpage.
6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′
7. Add the following lines to your web.config file:
appsettings>
add key="googlemaps.subgurim.net" value="YourGoogleMapsAPIKeyHere" />
/appSettings>
8. Add the following code to your Page.Load sub
Dim sStreetAddress As String
Dim sMapKey As String = ConfigurationManager.AppSettings("googlemaps.subgurim.net")
Dim GeoCode As Subgurim.Controles.GeoCode
sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia"
GeoCode = GMap1.geoCodeRequest(sStreetAddress, sMapKey)
Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng)
GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)
GMap1.addGMarker(oMarker)
Source:http://gathadams.com/
Improving Performance with Connection Pooling
Opening a connection is a database-intensive task. It can be one of the slowest operations that you perform in an ASP.NET page. Furthermore, a database has a limited supply of connections, and each connection requires a certain amount of memory overhead (approximately 40 kilobytes per connection).
If you plan to have hundreds of users hitting your Web site simultaneously, the process of opening a database connection for each user can have a severe impact on the performance of your Web site.
Fortunately, you can safely ignore these bad warnings if you take advantage of connection pooling. When database connections are pooled, a set of connections is kept open so that they can be shared among multiple users. When you request a new connection, an active connection is removed from the pool. When you close the connection, the connection is placed back in the pool.
Connection pooling is enabled for both OleDb and SqlClient connections by default.
To take advantage of connection pooling, you must be careful to do two things in your ASP.NET pages.
First, you must be careful to use the same exact connection string whenever you open a database connection. Only those connections opened with the same connection string can be placed in the same connection pool. For this reason you should place your connection string in the web.config file and retrieve it from this file whenever you need to open a connection
Second, you must also be careful to explicitly close whatever connection you open as quickly as possible. If you do not explicitly close a connection with the Close() method, the connection is never added back to the connection pool.
Source: www.dotnetguts.blogspot.com
If you plan to have hundreds of users hitting your Web site simultaneously, the process of opening a database connection for each user can have a severe impact on the performance of your Web site.
Fortunately, you can safely ignore these bad warnings if you take advantage of connection pooling. When database connections are pooled, a set of connections is kept open so that they can be shared among multiple users. When you request a new connection, an active connection is removed from the pool. When you close the connection, the connection is placed back in the pool.
Connection pooling is enabled for both OleDb and SqlClient connections by default.
To take advantage of connection pooling, you must be careful to do two things in your ASP.NET pages.
First, you must be careful to use the same exact connection string whenever you open a database connection. Only those connections opened with the same connection string can be placed in the same connection pool. For this reason you should place your connection string in the web.config file and retrieve it from this file whenever you need to open a connection
Second, you must also be careful to explicitly close whatever connection you open as quickly as possible. If you do not explicitly close a connection with the Close() method, the connection is never added back to the connection pool.
Source: www.dotnetguts.blogspot.com
Difference between ASP & ASP.NET
ASP stands for Active Server Pages. ASP.NET is the next generation of ASP. After the introduction of ASP.NET, old ASP is called 'Classic ASP'.
Classic ASP uses vb script for server side coding. Vb Script is not supported any more in ASP.NET. Instead, ASP.NET supports more languages including C#, VB.NET, J# etc. VB.NET is very similar to vb script, so it should be easy for old Visual Basic or ASP programmers to switch to VB.NET and ASP.NET
VB Script is a simple scripting language, where as VB.NET or C# are modern, very powerfull, object oriented programming languages. Just for that reason, you will be able to write much more robust and reliable programs in ASP.NET compared to ASP.
In classic ASP, there was no server controls. You have to write all html tags manually. ASP.NET offers a very rich set of controls called Server Controls and Html Controls. It is very easy to drag and drop any controls to a web form. The VS.NET will automatically write the required HTML tags automatically for you.
ASP is interpreted, ASP.NET is compiled
Since ASP uses vb script, there is no compilation. All ASP pages are interpreted when th page is executed.
ASP.NET uses modern .NET languages like C#, VB.NET etc. They can be compiled to efficient Microsoft Intermediate Language (MSIL). When you compile an ASP.NET application, the server side code is compiled to assemblies. These assemblies are loaded at run time which makes the ASP.NET pages perform better than classic ASP.
ADO and ADO.NET
Classic ASP uses a technology called ADO to connect and work with databases. ASP.NET uses the ADO.NET technology (which is the next generation of ADO).
Event driven programming
If you have written Visual Basic programs before, you would love the event driven programming approach. It is so easy to drag and drop a button control and double click on the button to write the event handler for the button click event. When you click on the button at turn time, it will execute whatever code you have written in the event handler.
This type of event driven programming was not available with classic ASP. You cannot drag and drop a button and write a 'on click' event handler with ASP.
With ASP.NET, this is changed. It works pretty much like your Visual Basic program. You can write event handlers for several events like button click event, text changed event etc.
However, there is big difference between the way event handling works in regular Visual basic and ASP.NET. In ASP.NET, a page is loaded in the client browser. And the server may be in another location (may be in another country). When you click on the button in an ASP.NET page, the 'click event' handler has to be executed on the server, not on the client.
How does the server know when you click on a button your browser? This is a tricky thing in ASP.NET. When you write an event handler for a button lick or something like that in ASP.NET, lot of things happens behind the screens. ASP.NET will produce lot of client side javascript code to handle this and embed this javascript in the html page it sends to the browser. When you click on the button in the browser, the client side javascript will get executed. This javascript will generate some information required for the server and and submit the page request to the server. There is enough information embedded in this request so that the server will understand that user has clicked a specific button in the browser and it has to execute some 'specific event handler' code in the server side. So, when the user clicks on a button, the page is submitted automatically to the server with some special information. In the server side, it will process the event handler for the button click event and send back the output page to the browser again. Similary, you can write other event handlers like text changed event for Textboxes etc.
As a user of the web page, you will not even know what happened in the background. All you can see is, when you clicked the button, it executed the button click event handler in the server side and you got the result. However, you may notice a delay because the page has to be submitted to the server to execute the event handler.
NOTE: The event handling we just discussed is server side event handling. In addition to that, you can handle any events in the client side using Javascript. This is supported even in classic ASP. The client side event handling is used for simpel client side validation, displaying messages to the user etc. You cannot do any server side programming in client side java script (like accessing the database etc).
Source: www.dotnetspider.com
Classic ASP uses vb script for server side coding. Vb Script is not supported any more in ASP.NET. Instead, ASP.NET supports more languages including C#, VB.NET, J# etc. VB.NET is very similar to vb script, so it should be easy for old Visual Basic or ASP programmers to switch to VB.NET and ASP.NET
VB Script is a simple scripting language, where as VB.NET or C# are modern, very powerfull, object oriented programming languages. Just for that reason, you will be able to write much more robust and reliable programs in ASP.NET compared to ASP.
In classic ASP, there was no server controls. You have to write all html tags manually. ASP.NET offers a very rich set of controls called Server Controls and Html Controls. It is very easy to drag and drop any controls to a web form. The VS.NET will automatically write the required HTML tags automatically for you.
ASP is interpreted, ASP.NET is compiled
Since ASP uses vb script, there is no compilation. All ASP pages are interpreted when th page is executed.
ASP.NET uses modern .NET languages like C#, VB.NET etc. They can be compiled to efficient Microsoft Intermediate Language (MSIL). When you compile an ASP.NET application, the server side code is compiled to assemblies. These assemblies are loaded at run time which makes the ASP.NET pages perform better than classic ASP.
ADO and ADO.NET
Classic ASP uses a technology called ADO to connect and work with databases. ASP.NET uses the ADO.NET technology (which is the next generation of ADO).
Event driven programming
If you have written Visual Basic programs before, you would love the event driven programming approach. It is so easy to drag and drop a button control and double click on the button to write the event handler for the button click event. When you click on the button at turn time, it will execute whatever code you have written in the event handler.
This type of event driven programming was not available with classic ASP. You cannot drag and drop a button and write a 'on click' event handler with ASP.
With ASP.NET, this is changed. It works pretty much like your Visual Basic program. You can write event handlers for several events like button click event, text changed event etc.
However, there is big difference between the way event handling works in regular Visual basic and ASP.NET. In ASP.NET, a page is loaded in the client browser. And the server may be in another location (may be in another country). When you click on the button in an ASP.NET page, the 'click event' handler has to be executed on the server, not on the client.
How does the server know when you click on a button your browser? This is a tricky thing in ASP.NET. When you write an event handler for a button lick or something like that in ASP.NET, lot of things happens behind the screens. ASP.NET will produce lot of client side javascript code to handle this and embed this javascript in the html page it sends to the browser. When you click on the button in the browser, the client side javascript will get executed. This javascript will generate some information required for the server and and submit the page request to the server. There is enough information embedded in this request so that the server will understand that user has clicked a specific button in the browser and it has to execute some 'specific event handler' code in the server side. So, when the user clicks on a button, the page is submitted automatically to the server with some special information. In the server side, it will process the event handler for the button click event and send back the output page to the browser again. Similary, you can write other event handlers like text changed event for Textboxes etc.
As a user of the web page, you will not even know what happened in the background. All you can see is, when you clicked the button, it executed the button click event handler in the server side and you got the result. However, you may notice a delay because the page has to be submitted to the server to execute the event handler.
NOTE: The event handling we just discussed is server side event handling. In addition to that, you can handle any events in the client side using Javascript. This is supported even in classic ASP. The client side event handling is used for simpel client side validation, displaying messages to the user etc. You cannot do any server side programming in client side java script (like accessing the database etc).
Source: www.dotnetspider.com
Difference between Close() and Dispose() Method
The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.
Example showing difference between Close() and Dispose() Method:
using System;
using System.Data;
using System.Data.SqlClient;
public class Test
{
private string connString = "Data Source=COMP3;Initial Catalog=Northwind;User Id=sa;Password=pass";
private SqlConnection connection;
public Test()
{
connection = new SqlConnection(connString);
}
private static void Main()
{
Test t = new Test();
t.ConnectionStatus();
Console.ReadLine();
}
public void ConnectionStatus()
{
try
{
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection opened..");
}
if(connection.State == ConnectionState.Open)
{
connection.Close();
Console.WriteLine("Connection closed..");
}
// connection.Dispose();
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection again opened..");
}
}
catch(SqlException ex)
{
Console.WriteLine(ex.Message+"\n"+ex.StackTrace);
}
catch(Exception ey)
{
Console.WriteLine(ey.Message+"\n"+ey.StackTrace);
}
finally
{
Console.WriteLine("Connection closed and disposed..");
connection.Dispose();
}
}
}
In the above example if you uncomment the "connection.Dispose()" method and execute, you will get an exception as, "The ConnectionString property has not been initialized.".This is the difference between Close() and Dispose().
Example showing difference between Close() and Dispose() Method:
using System;
using System.Data;
using System.Data.SqlClient;
public class Test
{
private string connString = "Data Source=COMP3;Initial Catalog=Northwind;User Id=sa;Password=pass";
private SqlConnection connection;
public Test()
{
connection = new SqlConnection(connString);
}
private static void Main()
{
Test t = new Test();
t.ConnectionStatus();
Console.ReadLine();
}
public void ConnectionStatus()
{
try
{
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection opened..");
}
if(connection.State == ConnectionState.Open)
{
connection.Close();
Console.WriteLine("Connection closed..");
}
// connection.Dispose();
if(connection.State == ConnectionState.Closed)
{
connection.Open();
Console.WriteLine("Connection again opened..");
}
}
catch(SqlException ex)
{
Console.WriteLine(ex.Message+"\n"+ex.StackTrace);
}
catch(Exception ey)
{
Console.WriteLine(ey.Message+"\n"+ey.StackTrace);
}
finally
{
Console.WriteLine("Connection closed and disposed..");
connection.Dispose();
}
}
}
In the above example if you uncomment the "connection.Dispose()" method and execute, you will get an exception as, "The ConnectionString property has not been initialized.".This is the difference between Close() and Dispose().
Monday, June 20, 2011
Trick for disabling anyone to copy webpage content
Trick for
* disabling anyone to copy screen content
* disabling drag
* disabling select (selection of content)
body ondragstart='return false' onselectstart='return false'>
* disabling anyone to copy screen content
* disabling drag
* disabling select (selection of content)
body ondragstart='return false' onselectstart='return false'>
Export Datagrid Data To Excel ASP.net
private void btnExportToExcel_Click(object sender,
System.EventArgs e)
{
ExportToExcel("Report.xls",DataGrid1);
}
private void ExportToExcel(string strFileName,DataGrid dg)
{ Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Source: http://dotnetguts.blogspot.com
System.EventArgs e)
{
ExportToExcel("Report.xls",DataGrid1);
}
private void ExportToExcel(string strFileName,DataGrid dg)
{ Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Source: http://dotnetguts.blogspot.com
Import Excel To Datagrid ASP.net
Working Effectively with Legacy Code
Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...
private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);
//da.TableMappings.Add("Table", "ExcelTest");
da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}
Note: If you want to give client upload facility, than first upload the file to the server. Next call the excel file from the following server location.
Source: http://dotnetguts.blogspot.com
Learn how to find and create seams in your application, no matter "Legacy" it may be, and over time improve application's design. Read more...
private void btnImportExcelToGrid_Click(object sender,
System.EventArgs e)
{
String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\\Book2.xls;" +
"Extended Properties=Excel 8.0;";
DataSet ds = new DataSet();
//You must use the $ after the object
//you reference in the spreadsheet
OleDbDataAdapter da = new OleDbDataAdapter
("SELECT * FROM [Sheet1$]", strConn);
//da.TableMappings.Add("Table", "ExcelTest");
da.Fill(ds);
DataGrid2.DataSource = ds.Tables[0].DefaultView;
DataGrid2.DataBind();
}
Note: If you want to give client upload facility, than first upload the file to the server. Next call the excel file from the following server location.
Source: http://dotnetguts.blogspot.com
Basics of Web Services in .net
What is Web Service?
* Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
* Web Service is
o Language Independent
o Protocol Independent
o Platform Independent
o It assumes a stateless service architecture.
* We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.
History of Web Service or How Web Service comes into existence?
* As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
* 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
* 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
* 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
* 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
* Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
* Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
* News Headline: You can display latest news update by using News Headline Web Service in your website.
* In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.
Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
* HTTP
* XML
* SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Terms which are frequently used with web services
* What is SOAP?
o SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
* What is WSDL?
o WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
o WSDL contains every details regarding using web service
+ Method and Properties provided by web service
+ URLs from which those method can be accessed.
+ Data Types used.
+ Communication Protocol used.
* What is UDDI?
o UDDI allows you to find web services by connecting to a directory.
* What is Discovery or .Disco Files?
o Discovery files are used to group common services together on a web server.
o Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
o .Disco File (static)
+ .Disco File contains
# URL for the WSDL
# URL for the documentation
# URL to which SOAP messages should be sent.
+ A static discovery file is an XML document that contains links to other resources that describe web services.
o .VsDisco File (dynamic)
+ A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
* What is difference between Disco and UDDI?
o Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
* What is Web Service Discovery Tool (disco.exe) ?
o The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
* What is Proxy Class?
o A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
o A proxy class object allows a client to access a web service as if it were a local COM object.
o The Proxy must be on the computer that has the web application.
* What is Web Service Description Language Tool (wsdl.exe)?
o This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
o Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
o Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
* Testing a Web Service?
o You can test web service without building an entire client application.
+ With Asp.net you can simply run the application and test the method by entering valid input paramters.
+ You can also use .Net Web Service Studio Tool comes from Microsoft.
Example of Creating Web Service in .Net
This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.
Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"
Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"
Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"
Step4: Create a Logic for Web Service
* Create a Method "GetCustomerCountryWise"
* Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
* Specify proper argument and return type for method in web service.
* It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";
SqlConnection connCustomer = new SqlConnection(sConn);
DataSet dsCustomer = new DataSet();
SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);
daCustomer.Fill(dsCustomer,"Customers");
//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340
//So to access data we need to make use of XmlElement.
// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}
Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.
By pressing "Invoke" button will generate XML File.
So you are done creating web service application.
Example of Testing Web Service in .Net
This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".
Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"
Step2: Displaying data in gridview, so drag the gridview on to the form.
Step3: Right Click Solution Explorer and Choose "Add Web Reference"
Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.
Step5: Press "Add Reference button"
Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();
DataSet dsCustomer = new DataSet();
// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");
// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);
GridView1.DataSource = dsCustomer;
GridView1.DataBind();
}
}
Few Facts about Web Service in .Net
* Each Response from web service is a new object, with a new state.
* Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
* This allow client application and the web service to continue processing while the interaction is ongoing.
* Instead of a user interface, it provides a standard defined interface called a contract.
Source: http://dotnetguts.blogspot.com
* Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet.
* Web Service is
o Language Independent
o Protocol Independent
o Platform Independent
o It assumes a stateless service architecture.
* We will discuss more on web service as the article proceed. Before that lets understand bit on how web service comes into picture.
History of Web Service or How Web Service comes into existence?
* As i have mention before that Web Service is nothing but means for Interacting with objects over the Internet.
* 1. Initially Object - Oriented Language comes which allow us to interact with two object within same application.
* 2. Than comes Component Object Model (COM) which allows to interact two objects on the same computer, but in different applications.
* 3. Than comes Distributed Component Object Model (DCOM) which allows to interact two objects on different computers, but within same local network.
* 4. And finally the web services, which allows two object to interact internet. That is it allows to interact between two object on different computers and even not within same local network.
Example of Web Service
* Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.
* Stock Quote: You can display latest update of Share market with Stock Quote on your web site.
* News Headline: You can display latest news update by using News Headline Web Service in your website.
* In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your companies advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.
Web Service Communication
Web Services communicate by using standard web protocols and data formats, such as
* HTTP
* XML
* SOAP
Advantages of Web Service Communication
Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.
Terms which are frequently used with web services
* What is SOAP?
o SOAP are remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.
* What is WSDL?
o WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
o WSDL contains every details regarding using web service
+ Method and Properties provided by web service
+ URLs from which those method can be accessed.
+ Data Types used.
+ Communication Protocol used.
* What is UDDI?
o UDDI allows you to find web services by connecting to a directory.
* What is Discovery or .Disco Files?
o Discovery files are used to group common services together on a web server.
o Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service.
o .Disco File (static)
+ .Disco File contains
# URL for the WSDL
# URL for the documentation
# URL to which SOAP messages should be sent.
+ A static discovery file is an XML document that contains links to other resources that describe web services.
o .VsDisco File (dynamic)
+ A dynamic discovery files are dynamic discovery document that are automatically generated by VS.Net during the development phase of a web service.
* What is difference between Disco and UDDI?
o Disco is Microsoft's Standard format for discovery documents which contains information about Web Services, while UDDI is a multi-vendor standard for discovery documents which contains information about Web Services.
* What is Web Service Discovery Tool (disco.exe) ?
o The Web Services Discovery Tool (disco.exe) can retrieve discovery information from a server that exposes a web service.
* What is Proxy Class?
o A proxy class is code that looks exactly like the class it meant to represent; however the proxy class doesn't contain any of the application logic. Instead, the proxy class contains marshalling and transport logic.
o A proxy class object allows a client to access a web service as if it were a local COM object.
o The Proxy must be on the computer that has the web application.
* What is Web Service Description Language Tool (wsdl.exe)?
o This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service.
o Alternate of generating Proxy class through WSDL.exe is you can use web reference. Web Reference automatically generate a proxy classes for a web service by setting a web reference to point to the web service.
o Advantage of using Web Reference as compare to using WSDL.exe Tool is you can update changes done in web service class easily by updating web reference, which is more tedious task with WSDL.exe tool.
* Testing a Web Service?
o You can test web service without building an entire client application.
+ With Asp.net you can simply run the application and test the method by entering valid input paramters.
+ You can also use .Net Web Service Studio Tool comes from Microsoft.
Example of Creating Web Service in .Net
This Web Service will retrieve CustomerList Country Wise and return as dataset to client application for display.
Step1: Create a Web Service Application by File > New > Web Site > Asp.net Web Services
Named the web service, for example here i have choosen name "WSGetCustomerCountryWise"
Step2: Rename the default Service.asmx file to proper name, you also need to switch design view and change the class name with the same name you use to rename the service.asmx.
For example, "WSGetCustomerCountryWise.asmx" and switch to design view and change the class="Service" to class="WSGetCustomerCountryWise"
Step3: Rename the Service.CS File to proper name, you need to change the class name and constructor name too.
For example, "WSGetCustomerCountryWise.CS" and switch to code view and change the class and constructor name to "WSGetCustomerCountryWise"
Step4: Create a Logic for Web Service
* Create a Method "GetCustomerCountryWise"
* Note: You need to specify [WebMethod] before method definition, if you want it to be accessible public, otherwise the method would not be accessible remotely.
* Specify proper argument and return type for method in web service.
* It is also good practise to specify the use "Description" attribute to tell what method is meant for.
For example, here i need to access data of northwind customers and want to return customer list country wise, so add namespace for
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
[WebMethod(Description="It will generate Customer List, Country Wise")] public System.Xml.XmlElement GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
string sSQL = "select CustomerId, CompanyName, ContactTitle, City " +
" from Customers where country = '" + sCountry + "'";
SqlConnection connCustomer = new SqlConnection(sConn);
DataSet dsCustomer = new DataSet();
SqlDataAdapter daCustomer = new SqlDataAdapter(sSQL, sConn);
daCustomer.Fill(dsCustomer,"Customers");
//Known bug while return "DataSet" is "Data source is an invalid type.
It must be either an IListSource, IEnumerable, or IDataSource."
//For more details on Error: http://support.microsoft.com/kb/317340
//So to access data we need to make use of XmlElement.
// Return the DataSet as an XmlElement.
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}
Step5: Build Web Service and Run the Web Service for testing by pressing F5 function key.
By pressing "Invoke" button will generate XML File.
So you are done creating web service application.
Example of Testing Web Service in .Net
This Web Service will display the information which had been retrieved from Remote computer by accessing public method "GetCustomerCountryWise".
Step1: Create a Test Web Site by File > New > Web Site > Asp.net Web Site
Named the web site, for example here i have choosen name "TestGetCustomerCountryWise"
Step2: Displaying data in gridview, so drag the gridview on to the form.
Step3: Right Click Solution Explorer and Choose "Add Web Reference"
Step4: Choose the option Web Service on the local machine or you can enter the .WSDL File address directly in URL space and press Go button.
Step5: Press "Add Reference button"
Step6: Writing Code for Displaying data in GridView
Here note: I have Pass "USA" as parameter in Country Field.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create object of WSGetCustomerCountryWise Object
localhost.WSGetCustomerCountryWise objGetCustomerCountryWise
= new localhost.WSGetCustomerCountryWise();
DataSet dsCustomer = new DataSet();
// Get the data from Webservice.
XmlElement elem = objGetCustomerCountryWise.GetCustomerCountryWise("USA");
// Load the XML to the Typed DataSet that you want.
XmlNodeReader nodeReader = new XmlNodeReader(elem);
dsCustomer.ReadXml(nodeReader, XmlReadMode.Auto);
GridView1.DataSource = dsCustomer;
GridView1.DataBind();
}
}
Few Facts about Web Service in .Net
* Each Response from web service is a new object, with a new state.
* Web Service are asynchronous because the request object from the client application and the response object from the web service are unique SOAP envelopes that do not require shared connection.
* This allow client application and the web service to continue processing while the interaction is ongoing.
* Instead of a user interface, it provides a standard defined interface called a contract.
Source: http://dotnetguts.blogspot.com
Understanding DateTime and TimeSpan in .Net
//Creating Two Instance of DateTime
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
//Initializing DateTime Object
dt1 = DateTime.Now.Date; //Initializing with Current Date
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:00:00
//Examples for DateTime Manipulation in .Net
//Example 1 : Adding Minutes to Current Date.
dt1 = dt1.AddMinutes(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:00
//Example 2 : Adding Seconds to DateTime Object., similarly you can add milliseconds
dt1 = dt1.AddSeconds(30.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:30
//Example 3 : Adding Hours to DateTime Object in .Net.
dt1 = dt1.AddHours(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 05:05:30
//Example 4 : Adding Time to DateTime Object.
//You can replace Example 1,2 and 3 by simply adding TimeSpan with your desired
//TimeSpan value.
//Here we are adding 5 Hours, 5 Minutes and 30 Seconds.
dt1 = dt1.Add(new TimeSpan(5,5,30));
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 10:11:00
//Example 5 : Adding Days to DateTime Object in .Net
dt2 = dt1.AddDays(7.0); //Initializing dt2 object with 7 days ahead from
//dt1 DateTime value.
Response.Write(dt2.ToString() + "
");
//Output: 29-06-2007 10:11:00
//Example 6 : Adding Month to DateTime Object
dt2 = dt2.AddMonths(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2007 10:11:00
//Example 7 : Adding Year to DateTime Object
dt2 = dt2.AddYears(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2008 10:11:00
//Examples of Retrieving DateTime object value.
//Example 1 : Get Day value.
int intDay = dt1.Day;
Response.Write(intDay.ToString() + "
");
//Output: 22
//Example 2 : Get Day of Week.
DayOfWeek dow = dt1.DayOfWeek;
Response.Write(dow.ToString() + "
");
//Output: Friday
//How to find whether day of week is sunday or saturday?
if(dow == DayOfWeek.Sunday dow == DayOfWeek.Saturday)
{
//Hurray its weekend.
}
//Example 3 : Get the Day of Year
int intYear = dt1.DayOfYear; //Similarly you can get Year value.
Response.Write(intYear.ToString() + "
");
//Output: 173
//Similarly you can get Hours, Minutes, Seconds, Milliseconds value.
//Conversion of String to DateTime
//Make use of Parse Method of DateTime to "Convert String to DateTime in .Net"
DateTime dt4 = DateTime.Parse("08/06/2007");
DateTime dt5 = DateTime.Parse("10/06/2007");
//Comparing Date
//How to Find whether both dates are equal or Not?
//How to compare two dates in .Net?
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Dates are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToString() + " is Less than " + dt5.ToString() + "
");
}
else
{
Response.Write(dt4.ToString() + " is Greater than "
+ dt5.ToString() + "
");
}
//Output: 08-06-2007 00:00:00 is Less than 10-06-2007 00:00:00
/*Note: You may recieve error: "String was not recognized as a valid
DateTime." This may be occur as in India the DateTime format is followed
as "dd/mm/yyyy" But let say if you are in USA than it follow "mm/dd/yyyy" so here
there is crash situation and so you might recieve above error, so to avoid such
error make sure that user input valid date before you Parse date. */
//Difference between Date
//How to Find difference between two dates in .Net?
//How to Find days difference between two dates in .Net?
//How to subtract one date from another?
TimeSpan tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " +
dt5.ToString() + " is " + tsDiff.Days.ToString() + " days." + "
");
//Output: Difference between 08-06-2007 00:00:00 and 10-06-2007 00:00:00 is 2 days.
//Similarly you can also find:
//How many hour difference between two dates
//How many seconds difference between two dates
//And so on... by changing tsDiff property value to hours, seconds....
//instead of tsDiff.Days.
//Compare Time
//How to Find whether both Time are equal or Not?
//How to compare Time in .Net?
dt4 = DateTime.Parse("4:30 AM");
dt5 = DateTime.Parse("7:30 PM");
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Times are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToShortTimeString() + " is Less than " + dt5.ToShortTimeString() + "
");
}
else
{
Response.Write(dt4.ToShortTimeString() + " is Greater than "
+ dt5.ToShortTimeString() + "
");
}
//Output: 04:30:00 is Less than 19:30:00
//Difference between Time
//How to Find difference between two Time value in .Net?
//How to Find Hours difference between two Time in .Net?
//How to subtract one Time from another?
//How to find elapsed Time between Two Time value in .Net?
tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " + dt5.ToString() + " is " + tsDiff.Hours.ToString() + " Hours." + "
");
//Output: Difference between 22-06-2007 04:30:00 and 22-06-2007 19:30:00 is 15 Hours.
//More on DateTime
//How many days in a given month in .Net?
int intDaysInMonth = DateTime.DaysInMonth(2007, 6); //Pass valid year, and month
Response.Write(intDaysInMonth.ToString() + "
");
//Output: 30
//How to find whether given year is Leap year or not in .Net?
Response.Write( DateTime.IsLeapYear(2007)); //Pass valid year
//Output: False
//How to find current date and time?
Response.Write("Current Date and Time: " + DateTime.Now + "
");
//Output: Current Date and Time: 22-06-2007 11:31:04
//How to find current date?
Response.Write("Current Date: " + DateTime.Today + "
");
//Output: Current Date: 22-06-2007 00:00:00
Source: http://dotnetguts.blogspot.com
DateTime dt1 = new DateTime();
DateTime dt2 = new DateTime();
//Initializing DateTime Object
dt1 = DateTime.Now.Date; //Initializing with Current Date
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:00:00
//Examples for DateTime Manipulation in .Net
//Example 1 : Adding Minutes to Current Date.
dt1 = dt1.AddMinutes(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:00
//Example 2 : Adding Seconds to DateTime Object., similarly you can add milliseconds
dt1 = dt1.AddSeconds(30.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 00:05:30
//Example 3 : Adding Hours to DateTime Object in .Net.
dt1 = dt1.AddHours(5.0);
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 05:05:30
//Example 4 : Adding Time to DateTime Object.
//You can replace Example 1,2 and 3 by simply adding TimeSpan with your desired
//TimeSpan value.
//Here we are adding 5 Hours, 5 Minutes and 30 Seconds.
dt1 = dt1.Add(new TimeSpan(5,5,30));
Response.Write(dt1.ToString() + "
");
//Output: 22-06-2007 10:11:00
//Example 5 : Adding Days to DateTime Object in .Net
dt2 = dt1.AddDays(7.0); //Initializing dt2 object with 7 days ahead from
//dt1 DateTime value.
Response.Write(dt2.ToString() + "
");
//Output: 29-06-2007 10:11:00
//Example 6 : Adding Month to DateTime Object
dt2 = dt2.AddMonths(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2007 10:11:00
//Example 7 : Adding Year to DateTime Object
dt2 = dt2.AddYears(1);
Response.Write(dt2.ToString() + "
");
//Output: 29-07-2008 10:11:00
//Examples of Retrieving DateTime object value.
//Example 1 : Get Day value.
int intDay = dt1.Day;
Response.Write(intDay.ToString() + "
");
//Output: 22
//Example 2 : Get Day of Week.
DayOfWeek dow = dt1.DayOfWeek;
Response.Write(dow.ToString() + "
");
//Output: Friday
//How to find whether day of week is sunday or saturday?
if(dow == DayOfWeek.Sunday dow == DayOfWeek.Saturday)
{
//Hurray its weekend.
}
//Example 3 : Get the Day of Year
int intYear = dt1.DayOfYear; //Similarly you can get Year value.
Response.Write(intYear.ToString() + "
");
//Output: 173
//Similarly you can get Hours, Minutes, Seconds, Milliseconds value.
//Conversion of String to DateTime
//Make use of Parse Method of DateTime to "Convert String to DateTime in .Net"
DateTime dt4 = DateTime.Parse("08/06/2007");
DateTime dt5 = DateTime.Parse("10/06/2007");
//Comparing Date
//How to Find whether both dates are equal or Not?
//How to compare two dates in .Net?
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Dates are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToString() + " is Less than " + dt5.ToString() + "
");
}
else
{
Response.Write(dt4.ToString() + " is Greater than "
+ dt5.ToString() + "
");
}
//Output: 08-06-2007 00:00:00 is Less than 10-06-2007 00:00:00
/*Note: You may recieve error: "String was not recognized as a valid
DateTime." This may be occur as in India the DateTime format is followed
as "dd/mm/yyyy" But let say if you are in USA than it follow "mm/dd/yyyy" so here
there is crash situation and so you might recieve above error, so to avoid such
error make sure that user input valid date before you Parse date. */
//Difference between Date
//How to Find difference between two dates in .Net?
//How to Find days difference between two dates in .Net?
//How to subtract one date from another?
TimeSpan tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " +
dt5.ToString() + " is " + tsDiff.Days.ToString() + " days." + "
");
//Output: Difference between 08-06-2007 00:00:00 and 10-06-2007 00:00:00 is 2 days.
//Similarly you can also find:
//How many hour difference between two dates
//How many seconds difference between two dates
//And so on... by changing tsDiff property value to hours, seconds....
//instead of tsDiff.Days.
//Compare Time
//How to Find whether both Time are equal or Not?
//How to compare Time in .Net?
dt4 = DateTime.Parse("4:30 AM");
dt5 = DateTime.Parse("7:30 PM");
if (DateTime.Compare(dt4, dt5) == 0)
{
Response.Write("Both Times are Equal" + "
");
}
else if (DateTime.Compare(dt4, dt5) < 0) { Response.Write(dt4.ToShortTimeString() + " is Less than " + dt5.ToShortTimeString() + "
");
}
else
{
Response.Write(dt4.ToShortTimeString() + " is Greater than "
+ dt5.ToShortTimeString() + "
");
}
//Output: 04:30:00 is Less than 19:30:00
//Difference between Time
//How to Find difference between two Time value in .Net?
//How to Find Hours difference between two Time in .Net?
//How to subtract one Time from another?
//How to find elapsed Time between Two Time value in .Net?
tsDiff = dt5.Subtract(dt4); //Note: Always subtract smaller date
//value from greater date
Response.Write("Difference between " + dt4.ToString() + " and " + dt5.ToString() + " is " + tsDiff.Hours.ToString() + " Hours." + "
");
//Output: Difference between 22-06-2007 04:30:00 and 22-06-2007 19:30:00 is 15 Hours.
//More on DateTime
//How many days in a given month in .Net?
int intDaysInMonth = DateTime.DaysInMonth(2007, 6); //Pass valid year, and month
Response.Write(intDaysInMonth.ToString() + "
");
//Output: 30
//How to find whether given year is Leap year or not in .Net?
Response.Write( DateTime.IsLeapYear(2007)); //Pass valid year
//Output: False
//How to find current date and time?
Response.Write("Current Date and Time: " + DateTime.Now + "
");
//Output: Current Date and Time: 22-06-2007 11:31:04
//How to find current date?
Response.Write("Current Date: " + DateTime.Today + "
");
//Output: Current Date: 22-06-2007 00:00:00
Source: http://dotnetguts.blogspot.com
What is WPF
WPF is Windows Presentation Foundation Framework that shipped as part of the .NET Framework 3.0 . First it has shipped with Windows Vista OS in built, and is re-distributable for Windows XP or Windows Server 2008.
WPF is Object Oriented , XAML based.
* It Uses DirectX Engine for rendering GUI
* It do not use GDI 32 programming at all as opposed to Win32 applications
* It do not require more time or cost for graphics, drawing or animation programming
* It is Easy to change resolution unlike win32 application
* It is XAML Friendly.
* It has .NET API that has integrated to XAML (Xtensible Application Markup Language)
* Easily select the Controls unlike Win32 Controls.
* It has the ability to create 3D graphics in windows apps
* It contains Separate API for graphics and animation
* Most powerful Windows UI Framework
It is used for the
* For the better User Interface & the Design
* Customization of Controls
* Integrating Flash, Direct, Win32, Windows Forms
* For Generic consistency professional look (Using Styles like CSS in Web)
WPF Provides an unified Model for producing high end GUI easily using normal XML syntax to render output on graphics devices than using GDI components.
Source: http://beyondrelational.com
WPF is Object Oriented , XAML based.
* It Uses DirectX Engine for rendering GUI
* It do not use GDI 32 programming at all as opposed to Win32 applications
* It do not require more time or cost for graphics, drawing or animation programming
* It is Easy to change resolution unlike win32 application
* It is XAML Friendly.
* It has .NET API that has integrated to XAML (Xtensible Application Markup Language)
* Easily select the Controls unlike Win32 Controls.
* It has the ability to create 3D graphics in windows apps
* It contains Separate API for graphics and animation
* Most powerful Windows UI Framework
It is used for the
* For the better User Interface & the Design
* Customization of Controls
* Integrating Flash, Direct, Win32, Windows Forms
* For Generic consistency professional look (Using Styles like CSS in Web)
WPF Provides an unified Model for producing high end GUI easily using normal XML syntax to render output on graphics devices than using GDI components.
Source: http://beyondrelational.com
disable double Click on Web Page
Some time we face a problem like when we click on the server side button twice or more time ,it call a button event more then one time for single calling .some time it makes problem in our logic .so we need a solution code which hold the page till the server respond the single request .
Here i am placing a code which is useful in this case.
script type="text/javascript">
function pageLoad(sender, args) {
var rm = Sys.WebForms.PageRequestManager.getInstance();
rm.add_initializeRequest(initializeRequest);
rm.add_endRequest(endRequest);
}
function initializeRequest(sender, args) {
//Disable button to prevent double submit
var btn = $get(args._postBackElement.id);
if (btn) {
btn.disabled = true;
if (btn.className == 'button')
btn.className = 'buttonDisabled';
}
}
function endRequest(sender, args) {
//Re-enable button
var btn = $get(sender._postBackSettings.sourceElement.id);
if (btn) {
btn.disabled = false;
if (btn.className == 'buttonDisabled')
btn.className = 'button';
}
}
/script>
Source: http://itneeds4u.blogspot.com/
Here i am placing a code which is useful in this case.
script type="text/javascript">
function pageLoad(sender, args) {
var rm = Sys.WebForms.PageRequestManager.getInstance();
rm.add_initializeRequest(initializeRequest);
rm.add_endRequest(endRequest);
}
function initializeRequest(sender, args) {
//Disable button to prevent double submit
var btn = $get(args._postBackElement.id);
if (btn) {
btn.disabled = true;
if (btn.className == 'button')
btn.className = 'buttonDisabled';
}
}
function endRequest(sender, args) {
//Re-enable button
var btn = $get(sender._postBackSettings.sourceElement.id);
if (btn) {
btn.disabled = false;
if (btn.className == 'buttonDisabled')
btn.className = 'button';
}
}
/script>
Source: http://itneeds4u.blogspot.com/
Connection Pooling in ADO.NET
Why go for Connection Pooling?
Establishing connection to a database is cumbersome and resource burning, most important job in the applications, sometimes it might be slow. Most of the applications need to execute any query on the database server, a connection need to be established. Knowing about the Connection Pooling concepts and tips will definitely improves the performance while connecting to the database and the same time solves the requirement.
Connection Pooling at a glance?
Connection Pooling is the ability to reuse the database connection for more than one user. That connection might be SQL, OLEDB, ORACLE or whatever. This way of organizing connections in a smarter manner improves performance as the applications do not need to open and close the connection multiple times.
All of us know that we declare the connection string in web.config as follows in .NET Application and make use of this in code behind while connecting to databases.
view source
print?
1.
2.
5.
When the connection is closed or disposed in ADO.NET, it is returned to the connection pool and remains idle for until a request for a new connection comes in. If none comes in within this period, the connection to the backend is closed and the connection instance is removed from the Connection Pool. If all the connections are in the pool are busy then new connection waits in the queue for the existing connections to be released .We can set max connections, connection Pool size, Connection Time out etc settings in the web.config.
The following key value pairs explain the connection pooling settings.
* Connection Lifetime - The time of Connection Creation will be compared to the current time. If this period exceeds the Connection Lifetime value that is set, then object pooler destroys the connection. The default value is 0; this will give the maximum timeout for connection.
* Connection Reset - To reset the connection after it was take out from the Connection pool. The default value is true.
* Max pool size - Maximum number of connections allowed within the Connection pool. The value is 100 by default.
* Min pool size - Minimum number of connections allowed within the Connection pool. The value is 0 by default.
* Pooling - To set the connection Pooling if it is true, the connection is drawn from the pool or created if no connection available from the pool. The value is true by default.
* Connection Timeout - Maximum Time (in secs) to wait for a free connection from the pool. The value is 15 by default.
* Incr Pool Size - Controls the number of connections which are established, when all the connections are used. The value is 5 by default
* Decr Pool Size - Controls the number of connections which are closed when most of the established connections are unused. The value is 1 by default
Points to Ponder
* Disabling the connection pooling, infers that the connection object that is created by the user will not be re-used to any other user.
* A Connection pool will be created when Open() method of connection object is called. If the same application is using multiple Connection Strings (say more than one) then multiple connection pools will be created corresponding to each connection string.
* Connection Pooling is applied in ADO.Net by default.
* Connections that are not explicitly closed are not added or returned to the pool. Hence The Close() or Dispose() method of Connection need to be called to close the connection.
* A Connection Pool is freed from the memory when the last connection to the database is closed.
* Connection Pool’s life time is ended as soon as the application domain is unloaded. For example at any time when IISRESET runs the Connection Pool gets destroyed
* Connection Pools cannot be shared across application domains.
The best practice Code
The below code is the best practice that is recommended to use.
view source
print?
01.Try
02.{
03. SqlConnection _sqlConnection = new SqlConnection();
04. _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
05.
06. if (_sqlConnection.State = ConnectionState.Closed)
07. _sqlConnection.Open();
08.
09. /*Do some Operations … */
10.}
11.catch (Exception ex)
12.{
13. /*Do something */
14.}
15.finally
16.{
17. if (_sqlConnection.State != ConnectionState.Closed)
18. _sqlConnection.Close();
19.}
Connection Pooling improves the performance of the data driven B2B applications as we save some time in reusing the existing active database connections. I will be explaining it in more detail in my next article.
Source: http://beyondrelational.com
Establishing connection to a database is cumbersome and resource burning, most important job in the applications, sometimes it might be slow. Most of the applications need to execute any query on the database server, a connection need to be established. Knowing about the Connection Pooling concepts and tips will definitely improves the performance while connecting to the database and the same time solves the requirement.
Connection Pooling at a glance?
Connection Pooling is the ability to reuse the database connection for more than one user. That connection might be SQL, OLEDB, ORACLE or whatever. This way of organizing connections in a smarter manner improves performance as the applications do not need to open and close the connection multiple times.
All of us know that we declare the connection string in web.config as follows in .NET Application and make use of this in code behind while connecting to databases.
view source
print?
1.
2.
5.
When the connection is closed or disposed in ADO.NET, it is returned to the connection pool and remains idle for until a request for a new connection comes in. If none comes in within this period, the connection to the backend is closed and the connection instance is removed from the Connection Pool. If all the connections are in the pool are busy then new connection waits in the queue for the existing connections to be released .We can set max connections, connection Pool size, Connection Time out etc settings in the web.config.
The following key value pairs explain the connection pooling settings.
* Connection Lifetime - The time of Connection Creation will be compared to the current time. If this period exceeds the Connection Lifetime value that is set, then object pooler destroys the connection. The default value is 0; this will give the maximum timeout for connection.
* Connection Reset - To reset the connection after it was take out from the Connection pool. The default value is true.
* Max pool size - Maximum number of connections allowed within the Connection pool. The value is 100 by default.
* Min pool size - Minimum number of connections allowed within the Connection pool. The value is 0 by default.
* Pooling - To set the connection Pooling if it is true, the connection is drawn from the pool or created if no connection available from the pool. The value is true by default.
* Connection Timeout - Maximum Time (in secs) to wait for a free connection from the pool. The value is 15 by default.
* Incr Pool Size - Controls the number of connections which are established, when all the connections are used. The value is 5 by default
* Decr Pool Size - Controls the number of connections which are closed when most of the established connections are unused. The value is 1 by default
Points to Ponder
* Disabling the connection pooling, infers that the connection object that is created by the user will not be re-used to any other user.
* A Connection pool will be created when Open() method of connection object is called. If the same application is using multiple Connection Strings (say more than one) then multiple connection pools will be created corresponding to each connection string.
* Connection Pooling is applied in ADO.Net by default.
* Connections that are not explicitly closed are not added or returned to the pool. Hence The Close() or Dispose() method of Connection need to be called to close the connection.
* A Connection Pool is freed from the memory when the last connection to the database is closed.
* Connection Pool’s life time is ended as soon as the application domain is unloaded. For example at any time when IISRESET runs the Connection Pool gets destroyed
* Connection Pools cannot be shared across application domains.
The best practice Code
The below code is the best practice that is recommended to use.
view source
print?
01.Try
02.{
03. SqlConnection _sqlConnection = new SqlConnection();
04. _sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["sqlConnectionString"].ToString();
05.
06. if (_sqlConnection.State = ConnectionState.Closed)
07. _sqlConnection.Open();
08.
09. /*Do some Operations … */
10.}
11.catch (Exception ex)
12.{
13. /*Do something */
14.}
15.finally
16.{
17. if (_sqlConnection.State != ConnectionState.Closed)
18. _sqlConnection.Close();
19.}
Connection Pooling improves the performance of the data driven B2B applications as we save some time in reusing the existing active database connections. I will be explaining it in more detail in my next article.
Source: http://beyondrelational.com
All about Generics in C#
Introduction
Generics in C# are an extension to C# Programming using Generic Types and Methods. I see most of the developers still get confused about generics and do not know to use them in real time projects. That made me to write this article to help understand and refer how to use them?
Basic concept is similar to Templates in C++ with better extensibility and usability. The C++ Templates are compile time Feature whereas Generics is a feature of runtime.
These are a type of data structure that contains code, remains the same. The data type of the parameters will change for each use. We can also call them parameterized types or parametric polymorphism. Generics allow classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store.
The usage within the data structure adapts to the different data type of the passed variables. This Allows defining type-safe data structures need less committing to actual data types. We reuse data processing algorithms without duplicating type-specific code.
System.Collections.Generic
The System.Collections.Generic namespace contains several generic collection classes based on generics and it is recommended that we should use these collection classes in place of the earlier non-generic ones for better performance of our applications.
The namespace contains a lot of generic classes, structures, and interfaces like
* Dictionary
* List
* Queue
* SortedDictionary
* Stack
Examples
view source
print?
public class Gen
{
T t;
public T Val
{
get;
set;
}
}
The class name " Gencontaining the Type. This Type "T" is used to show that if we need to refer to the actual Type that is going to be used when we write this class".
T t; Creates member of the type T
The generic Type that we will specify during construction of the class will get inserted by the Common Language Runtime (CLR). The final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.
In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner as shown below.
view source
print?
static void Main(string[] args)
{
//create a string version of our generic class
Gen str = new Gen();
//set the value for the string type
str.Val = "Beyond Relational";
//output the type and value
System.Console.WriteLine(str.Val);
System.Console.WriteLine(str.Val.GetType());
//create another instance of our generic class, using a different type
Gen flt = new Gen();
flt.Val = 12.34;
System.Console.WriteLine(flt.Val);
//output
System.Console.WriteLine(flt.Val.GetType());
Console.ReadLine();
}
}
Generic Collections
view source
print?
public class MessageElement
{
//some functionality
}
public class MessageSearchCriteria
{
// some functioanlity
}
public List ListMessageElement
{
get
{
return lstMsgElemet;
}
set
{
lstMsgElemet = value;
}
}
MessageSearchCriteria objMsgSearch = new MessageSearchCriteria();
//usage of generics
objMsgSearch.ListMessageElement = new List();
Advantages
* Help to make the code in the software components much more reusable.
* High Quality Code and Code Maintainability
* No runtime Casting No Boxing hence Allows Performance Efficiency
* Creates Type safe at compile time as generics specify type at runtime
* Programmer has stronger and flexible control over the code
* The stronger type checking associated with generics helps in finding errors easily at compile time only.
* No code Duplication
Generics refer to classes and methods that work consistently on values of different types
Generics in C# are an extension to C# Programming using Generic Types and Methods. I see most of the developers still get confused about generics and do not know to use them in real time projects. That made me to write this article to help understand and refer how to use them?
Basic concept is similar to Templates in C++ with better extensibility and usability. The C++ Templates are compile time Feature whereas Generics is a feature of runtime.
These are a type of data structure that contains code, remains the same. The data type of the parameters will change for each use. We can also call them parameterized types or parametric polymorphism. Generics allow classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store.
The usage within the data structure adapts to the different data type of the passed variables. This Allows defining type-safe data structures need less committing to actual data types. We reuse data processing algorithms without duplicating type-specific code.
System.Collections.Generic
The System.Collections.Generic namespace contains several generic collection classes based on generics and it is recommended that we should use these collection classes in place of the earlier non-generic ones for better performance of our applications.
The namespace contains a lot of generic classes, structures, and interfaces like
* Dictionary
* List
* Queue
* SortedDictionary
* Stack
Examples
view source
print?
public class Gen
{
T t;
public T Val
{
get;
set;
}
}
The class name " Gen
T t; Creates member of the type T
The generic Type that we will specify during construction of the class will get inserted by the Common Language Runtime (CLR). The final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.
In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner as shown below.
view source
print?
static void Main(string[] args)
{
//create a string version of our generic class
Gen str = new Gen();
//set the value for the string type
str.Val = "Beyond Relational";
//output the type and value
System.Console.WriteLine(str.Val);
System.Console.WriteLine(str.Val.GetType());
//create another instance of our generic class, using a different type
Gen flt = new Gen();
flt.Val = 12.34;
System.Console.WriteLine(flt.Val);
//output
System.Console.WriteLine(flt.Val.GetType());
Console.ReadLine();
}
}
Generic Collections
view source
print?
public class MessageElement
{
//some functionality
}
public class MessageSearchCriteria
{
// some functioanlity
}
public List ListMessageElement
{
get
{
return lstMsgElemet;
}
set
{
lstMsgElemet = value;
}
}
MessageSearchCriteria objMsgSearch = new MessageSearchCriteria();
//usage of generics
objMsgSearch.ListMessageElement = new List();
Advantages
* Help to make the code in the software components much more reusable.
* High Quality Code and Code Maintainability
* No runtime Casting No Boxing hence Allows Performance Efficiency
* Creates Type safe at compile time as generics specify type at runtime
* Programmer has stronger and flexible control over the code
* The stronger type checking associated with generics helps in finding errors easily at compile time only.
* No code Duplication
Generics refer to classes and methods that work consistently on values of different types
Saturday, June 4, 2011
The Ultimate List of Freely Available .NET Libraries
Ajax
- Ajax Control Toolkit - Microsoft
- AJAXNet Pro
- ASP.NET MVC Project Awesome - a rich set of helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form and Pager. Thanks Omu (April 20, 2011)
Build Tools
- Prebuild - Generate project files for all VS version, including major IDE's and tools like SharpDevelop, MonoDevelop, NAnt and Autotools
- Genuilder - Precompiler which lets you transform your source code during the build. Thanks Harry McIntyre (April 13, 2011)
Charting/Graphics
- Microsoft Chart Controls for ASP.NET 3.5 SP1
- Microsoft Chart Controls for Winforms
- ZedGraph Charting
- NPlot - Charting for ASP.NET and WinForms
- Graph# - a graph layout framework contains some layout algorithms and a GraphLayout control for WPF applications. Thanks Florian Standhartinger (April 20, 2011)
Collections/Generics
- PowerCollections - is a library that provides generic collection classes that are not available in the .NET framework. Some of the collections included are the Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary, Set, OrderedSet, and OrderedMultiDictionary. Thanks Adam Ralph (April 20, 2011)
Compression
- SharpZipLib
- DotNetZip
- YUI Compressor (CSS and JS minification)
- AjaxMinifier (in other downloads) (CSS and JS minification. Also includes MSBuild task)
- SevenZipSharp to pack, unpack a lot of different packages (including RAR, 7ZIP, etc).
- ZipStorer A Pure C# Class to Store Files in Zip
Controls
- Krypton - Free winform controls. Link fixed (April 14, 2011)
- Source Grid - A Grid control
- DevExpress - Over 60 Free Controls from DevExpress. Thanks Florian Standhartinger (April 20, 2011)
- ObjectListView - is a C# wrapper around a .NET ListView. It makes the ListView much easier to use and provides some neat extra functionality. Thanks Florian Standhartinger (April 20, 2011)
Data Mapper
- XmlDataMapper
- AutoMapper
- Dapper
- Massive
- Mapper Extensions Thanks giometrix (April 14, 2011)
- Data accessors from the Data Access Application Block
- Value Injecter - ets you define your own convention-based matching algorithms (ValueInjections) in order to match up (inject) source values to destination values. Thanks Omu (April 20, 2011)
Dependency Injection/Inversion of Control
- Unity Framework - Microsoft
- StructureMap - Jeremy Miller
- Castle Windsor
- NInject
- Spring Framework
- Autofac
- Simple Service Locator
- Managed Extensibility Framework
- TinyIoC
- Funq - a high performance DI framework by eliminating all runtime reflection through the use of lambdas and generic functions as factories. Thanks Marcel Popescu (April 20, 2011).
- Munq - a very small, fast dependency injection container designed for ASP.NET applications, both Webforms and MVC. It has, by design, limited features. The main goal has been to minimize the CPU required for Resolving types from the container. Thanks Marcel Popescu (April 20, 2011).
Design by Contract
IDE
- SharpDevelop - is a free IDE for C#, VB.NET and Boo projects. Thanks Florian Standhartinger (April 20, 2011).
Logging
- Logging Application Block - Microsoft
- Log4Net - Apache
- Error Logging Modules and Handlers(ELMAH)
- NLog
- CuttingEdge.Logging
- Logging Abstraction Api "Common.Logging"
ORM
- NHibernate and FluentNHibernate
- Castle ActiveRecord
- Subsonic
- XmlDataMapper
- Truss Data binding and real time property sync library
PDF Creators/Generators
Automated Web Testing
Misc Testing/Qualitysupport/Behavoir Driven Development (BDD)
URL Rewriting
- url rewriter
- UrlRewriting.Net
- Url Rewriter and Reverse Proxy - Managed Fusion/Nick Berardi
MS Word/Excel Documents Manipulation
- DocX to create, read, manipulate formatted word documents. Easy syntax, working nicely, actively developed. No Microsoft Office necessary.
- Excel XML Writer allows creation of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated. It also provides code generator to create code from already created XLS file (saved as xml). Haven't tested this but looks very promising. Too bad author is long time gone.
- Excel Reader allows creation/reading of .XLS (Excel) files. No Microsoft Office necessary. Been a while since it has been updated.
- Excel Package allows creation/reading of .XLSX (Excel 2007) files. No Microsoft Office necessary. Author is gone so it's out of date.
- EPPlus is based on Excel Package and allows creation/reading of .XLSX (Excel 2007). It is actually the most advanced even comparing to NPOI.
- NPOI is the .NET version of POI Java project at http://poi.apache.org/. POI is an open source project which can help you read/write xls, doc, ppt files.
- sharp2word - a Word 2003 XML Documents Generator from C# code without any components or libraries. Thanks dublicator (April 20, 2011)
- ClosedXML - an actively developed library for generating OpenXML Excel files. Thanks Joseph Robichaud (April 26, 2011)
Serialization
- sharpserializer - xml/binary serializer for wpf, asp.net and silverlight
- Protobuf.NET - fastest serialization port protobuf format into .NET platform. Thanks slava pocheptsov (April 26, 2011)
Silverlight
Social Media
- LinqToTwitter - Linq-based wrapper for all Twitter API functionality in C#
- Facebook C# SDK - A toolkit for creating facebook applications / integrating websites with Facebook using the new Graph API or the old rest API.
Package managers for external libraries
- NuGet (formerly known as NuPack) - Microsoft (developer-focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development)
- OpenWrap - Sebastien Lambla - Open Source Dependency Manager for .net applications
Unit Testing/Mocking
- NUnit
- Rhino Mocks
- Moq
- TypeMock.Net
- xUnit.net
- Gallio/MbUnit
- Machine.Specifications
- fakeiteasy - a .Net dynamic fake framework for creating all types of fake objects, mocks, stubs etc. Thanks Omu (April 20, 2011)
- NSubstitute - a A friendly substitute for .NET mocking frameworks. Thanks xerxesb (May 10, 2011)
- Shouldly - How asserting should be. Thanks xerxesb (May 10, 2011)
Validation
Threading
- Smart Thread Pool - Thread Pool management library
- Retlang - a high performance C# threading library. Thanks MarcBot (April 13, 2011)
- bbv.Common - an open source library of software components that makes building multi-threaded, event-based and loosely coupled systems easy. Thanks Urs Enzler (April 14, 2011)
- PowerThreading - a llibrary (DLL) containing many classes to help with threading and asynchronous programming. Thanks Adam Ralph (April 20, 2011)
Unclassified
- CSLA Framework - Business Objects Framework
- AForge.net - AI, computer vision, genetic algorithms, machine learning
- Prism - Composit UI application block for WPF, Silverlight and WP7 - Microsoft patterns & practices
- Enterprise Library 5.0 - Logging, Exception Management, Caching, Cryptography, Data Access, Validation, Security, Policy Injection - Microsoft patterns & practices
- File helpers library
- C5 Collections - Collections for .NET
- Quartz.NET - Enterprise Job Scheduler for .NET Platform
- MiscUtil - Utilities by Jon Skeet
- Noda Time - DateTime replacement (idomatic port of Joda Time from Java)
- Lucene.net - Text indexing and searching
- Json.NET - Linq over JSON
- Flee - expression evaluator
- PostSharp - AOP
- IKVM - brings the extensive world of Java libraries to .NET.
- C# Webserver - Embeddable webserver
- Long Path - Microsoft
- .NET Engines for the GOLD Parsing System
- NCQRS - library for event-driven architectures (CQRS).
- Reactive Extensions for .NET - a library for composing asynchronous and event-based programs using observable collections. Thanks steve (April 14, 2011)
- Mono.GameMath - a project to develop a highly-performant math library for games, based on XNA APIs. Thanks Alex Rønne Petersen (April 14, 2011)
- SLSharp - a runtime IL-to-GLSL translation engine, allowing people to write GLSL shaders as C# code. Thanks Alex Rønne Petersen (April 14, 2011)
- InfusionSoftDotNet - a dll to ease the pain for .Net developers to access the InfusionSoft API. Thanks Michael Gibbs (April 20, 2011)
- re-mix - provides mixins for C# and Visual Basic .NET. Thanks Stefan Papp (April 20, 2011)
- Mono.Cecil - a library written by Jb Evain to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format. Thanks Florian Standhartinger (April 20, 2011)
Hide Form from Alt+Tab
Hide Form from Start Bar
To prevent a form from appearing in the Windows Start bar, add this statement to the form’s constructor:
this.ShowInTaskbar = false;Hide Tool Window from Alt+Tab
To prevent a form from appearing in the list of windows shown when the user presses Alt+Tab, you can designate the form to be a tool window. Note that you can use SizableToolWindow or FixedToolWindow, and ShowInTaskbar must be set to false:
this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
this.ShowInTaskbar = false;
Hide Borderless Form from Alt+Tab
However, if you want the form to be borderless, then you need to add the following statements to the form’s constructor:
this.FormBorderStyle = FormBorderStyle.None;
this.ShowInTaskbar = false;AND you must add the following method to your derived Form class:
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
// turn on WS_EX_TOOLWINDOW style bit
cp.ExStyle |= 0x80;
return cp;
}
}
To prevent a form from appearing in the Windows Start bar, add this statement to the form’s constructor:
this.ShowInTaskbar = false;Hide Tool Window from Alt+Tab
To prevent a form from appearing in the list of windows shown when the user presses Alt+Tab, you can designate the form to be a tool window. Note that you can use SizableToolWindow or FixedToolWindow, and ShowInTaskbar must be set to false:
this.FormBorderStyle = FormBorderStyle.SizableToolWindow;
this.ShowInTaskbar = false;
Hide Borderless Form from Alt+Tab
However, if you want the form to be borderless, then you need to add the following statements to the form’s constructor:
this.FormBorderStyle = FormBorderStyle.None;
this.ShowInTaskbar = false;AND you must add the following method to your derived Form class:
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
// turn on WS_EX_TOOLWINDOW style bit
cp.ExStyle |= 0x80;
return cp;
}
}
Reading the contents of a web page is easy in C#
Reading the contents of a web page is easy in C# with the System.Net.WebClient class:
using System.Net;
using System.Windows.Forms;
string url = "http://www.devtopics.com";
string result = null;
try
{
WebClient client = new WebClient();
result = client.DownloadString( url );
}
catch (Exception ex)
{
// handle error
MessageBox.Show( ex.Message );
}The web page is read into the ‘result’ string. Note the URL you pass to the DownloadString method must have the http:// prefix, otherwise it will throw a WebException.
A more complicated but also more flexible solution is to use the System.Net.HttpWebRequest class, which enables you to interact directly with servers using HTTP:
using System.Net;
using System.IO;
using System.Windows.Forms;
string result = null;
string url = "http://www.devtopics.com";
WebResponse response = null;
StreamReader reader = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( url );
request.Method = "GET";
response = request.GetResponse();
reader = new StreamReader( response.GetResponseStream(), Encoding.UTF8 );
result = reader.ReadToEnd();
}
catch (Exception ex)
{
// handle error
MessageBox.Show( ex.Message );
}
finally
{
if (reader != null)
reader.Close();
if (response != null)
response.Close();
}
using System.Net;
using System.Windows.Forms;
string url = "http://www.devtopics.com";
string result = null;
try
{
WebClient client = new WebClient();
result = client.DownloadString( url );
}
catch (Exception ex)
{
// handle error
MessageBox.Show( ex.Message );
}The web page is read into the ‘result’ string. Note the URL you pass to the DownloadString method must have the http:// prefix, otherwise it will throw a WebException.
A more complicated but also more flexible solution is to use the System.Net.HttpWebRequest class, which enables you to interact directly with servers using HTTP:
using System.Net;
using System.IO;
using System.Windows.Forms;
string result = null;
string url = "http://www.devtopics.com";
WebResponse response = null;
StreamReader reader = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( url );
request.Method = "GET";
response = request.GetResponse();
reader = new StreamReader( response.GetResponseStream(), Encoding.UTF8 );
result = reader.ReadToEnd();
}
catch (Exception ex)
{
// handle error
MessageBox.Show( ex.Message );
}
finally
{
if (reader != null)
reader.Close();
if (response != null)
response.Close();
}
Friday, June 3, 2011
Determine Windows Version and Edition with C#
This article explains how to use C# to determine the name, edition, service pack, version and bits of the host operating system.
For example, the results on my PC would be:
Operation System Information
—————————-
Name = Windows Vista
Edition = Home Premium
Service Pack = Service Pack 1
Version = 6.0.6001.65536
Bits = 64
Sample Program
Here is a simple console program that demonstrates this:
using System;
namespace CSharp411
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine( "Operation System Information" );
Console.WriteLine( "----------------------------" );
Console.WriteLine( "Name = {0}", OSInfo.Name );
Console.WriteLine( "Edition = {0}", OSInfo.Edition );
Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
Console.WriteLine( "Version = {0}", OSInfo.VersionString );
Console.WriteLine( "Bits = {0}", OSInfo.Bits );
Console.ReadLine();
}
}
}
For example, the results on my PC would be:
Operation System Information
—————————-
Name = Windows Vista
Edition = Home Premium
Service Pack = Service Pack 1
Version = 6.0.6001.65536
Bits = 64
Sample Program
Here is a simple console program that demonstrates this:
using System;
namespace CSharp411
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine( "Operation System Information" );
Console.WriteLine( "----------------------------" );
Console.WriteLine( "Name = {0}", OSInfo.Name );
Console.WriteLine( "Edition = {0}", OSInfo.Edition );
Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
Console.WriteLine( "Version = {0}", OSInfo.VersionString );
Console.WriteLine( "Bits = {0}", OSInfo.Bits );
Console.ReadLine();
}
}
}
Show ToolTip on TabPage in TabControl
So you’ve set the ToolTipText property of a TabPage in a TabControl. When the user moves the mouse pointer over the tab, the text you specified is supposed to show in a tooltip.
But what if the tooltip is not showing? Fortunately, this problem has an easy solution:
Set the ShowToolTips property in the TabControl to true.
But what if the tooltip is not showing? Fortunately, this problem has an easy solution:
Set the ShowToolTips property in the TabControl to true.
Cosing all forms in an application
Cosing all forms in an application seems like it would be a simple task of using a foreach loop in the Application.OpenForms collection, such as:
foreach (Form form in Application.OpenForms)
{
form.Close();
But there are two problems.
First, the code above will throw an exception because the OpenForms collection changes each time you close a form, and so the enumerator in your foreach loop becomes invalid when you close a form. Instead, you need to get an array of all open forms, then loop through the array:
static public void CloseAllForms()
{
// get array because collection changes as we close forms
Form[] forms = OpenForms;
// close every open form
foreach (Form form in forms)
{
CloseForm( form );
}
}
Second, it’s quite possible that your application opened one or more forms in a separate thread. If so, then trying to close a form from your main thread will throw an exception. So you need to close your forms in a thread-safe manner:
delegate void CloseMethod( Form form );
static private void CloseForm( Form form )
{
if (!form.IsDisposed)
{
if (form.InvokeRequired)
{
CloseMethod method = new CloseMethod( CloseForm );
form.Invoke( method, new object[] { form } );
}
else
{
form.Close();
}
}
}
foreach (Form form in Application.OpenForms)
{
form.Close();
But there are two problems.
First, the code above will throw an exception because the OpenForms collection changes each time you close a form, and so the enumerator in your foreach loop becomes invalid when you close a form. Instead, you need to get an array of all open forms, then loop through the array:
static public void CloseAllForms()
{
// get array because collection changes as we close forms
Form[] forms = OpenForms;
// close every open form
foreach (Form form in forms)
{
CloseForm( form );
}
}
Second, it’s quite possible that your application opened one or more forms in a separate thread. If so, then trying to close a form from your main thread will throw an exception. So you need to close your forms in a thread-safe manner:
delegate void CloseMethod( Form form );
static private void CloseForm( Form form )
{
if (!form.IsDisposed)
{
if (form.InvokeRequired)
{
CloseMethod method = new CloseMethod( CloseForm );
form.Invoke( method, new object[] { form } );
}
else
{
form.Close();
}
}
}
Rename a File in C#
If you want to rename a file in C#, you’d expect there to be a File.Rename method, but instead you must use the System.IO.File.Move method.
You must also handle a special case when the new file name has the same letters but with difference case. For example, if you want to rename “test.doc” to “Test.doc”, the File.Move method will throw an exception. So you must rename it to a temp file, then rename it again with the desired case.
///
/// Renames the specified file.
///
/// Full path of file to rename.
/// New file name.
static public void RenameFile( string oldPath, string newName )
{
if (String.IsNullOrEmpty( oldPath ))
throw new ArgumentNullException( "oldPath" );
if (String.IsNullOrEmpty( newName ))
throw new ArgumentNullException( "newName" );
string oldName = Path.GetFileName( oldPath );
// if the file name is changed
if (!String.Equals( oldName, newName, StringComparison.CurrentCulture ))
{
string folder = Path.GetDirectoryName( oldPath );
string newPath = Path.Combine( folder, newName );
bool changeCase = String.Equals( oldName, newName, StringComparison.CurrentCultureIgnoreCase );
// if renamed file already exists and not just changing case
if (File.Exists( newPath ) && !changeCase)
{
throw new IOException( String.Format( "File already exists:\n{0}", newPath ) );
}
else if (changeCase)
{
// Move fails when changing case, so need to perform two moves
string tempPath = Path.Combine( folder, Guid.NewGuid().ToString() );
Directory.Move( oldPath, tempPath );
Directory.Move( tempPath, newPath );
}
else
{
Directory.Move( oldPath, newPath );
}
}
}
You must also handle a special case when the new file name has the same letters but with difference case. For example, if you want to rename “test.doc” to “Test.doc”, the File.Move method will throw an exception. So you must rename it to a temp file, then rename it again with the desired case.
///
/// Renames the specified file.
///
/// Full path of file to rename.
/// New file name.
static public void RenameFile( string oldPath, string newName )
{
if (String.IsNullOrEmpty( oldPath ))
throw new ArgumentNullException( "oldPath" );
if (String.IsNullOrEmpty( newName ))
throw new ArgumentNullException( "newName" );
string oldName = Path.GetFileName( oldPath );
// if the file name is changed
if (!String.Equals( oldName, newName, StringComparison.CurrentCulture ))
{
string folder = Path.GetDirectoryName( oldPath );
string newPath = Path.Combine( folder, newName );
bool changeCase = String.Equals( oldName, newName, StringComparison.CurrentCultureIgnoreCase );
// if renamed file already exists and not just changing case
if (File.Exists( newPath ) && !changeCase)
{
throw new IOException( String.Format( "File already exists:\n{0}", newPath ) );
}
else if (changeCase)
{
// Move fails when changing case, so need to perform two moves
string tempPath = Path.Combine( folder, Guid.NewGuid().ToString() );
Directory.Move( oldPath, tempPath );
Directory.Move( tempPath, newPath );
}
else
{
Directory.Move( oldPath, newPath );
}
}
}
Subscribe to:
Posts (Atom)