Friday 12 October 2007

Build custon XML from database using XmlTextWriter

Simple way to out put as xml is using
dim ds as dataset
ds.WriteXml("C:\test\HCSReports\createdXML\employee.xml")

if you need custom xml output then use the below function



Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl

Public Function CreateCustomXML(ByVal objDataSet As DataSet) As String

Dim intI As Integer
Dim strPath As String

'create an instance of the XmlTextWriter object
Dim objWriter As XmlTextWriter = Nothing

Try

' location to the XML file to write
strPath = strFilepath & Now.Second & ".xml"

objWriter = New XmlTextWriter(strPath, System.Text.Encoding.Default)

' start writing the XML document
objWriter.WriteStartDocument()

' write a comment in our XML file
objWriter.WriteComment("PanelManagerMonthlyReport")

' starting with the root element i.e. "movies"
objWriter.WriteStartElement("PMMonthlyReport")

'Set data to XML tags
If objDataSet.Tables(0).Rows.Count > 0 Then
For intI = 0 To objDataSet.Tables(0).Rows.Count - 1
objWriter.WriteStartElement("Period") ' output the "Employee" element
objWriter.WriteElementString("Name", objDataSet.Tables(0).Rows(intI).Item("Name").ToString)
objWriter.WriteElementString("Prospects", objDataSet.Tables(0).Rows(intI).Item("Prospects").ToString)
objWriter.WriteElementString("Instructions", objDataSet.Tables(0).Rows(intI).Item("Instructions"))
objWriter.WriteElementString("Cancellations", objDataSet.Tables(0).Rows(intI).Item("Cancellations"))
objWriter.WriteElementString("Completions", objDataSet.Tables(0).Rows(intI).Item("Completions"))
objWriter.WriteElementString("Quotes", objDataSet.Tables(0).Rows(intI).Item("Quotes"))
objWriter.WriteElementString("IntroducerUserRegistrations", objDataSet.Tables(0).Rows(intI).Item("IntroducerUserRegistrations"))
objWriter.WriteElementString("IntroducerUserTrained", objDataSet.Tables(0).Rows(intI).Item("IntroducerUserTrained"))
objWriter.WriteElementString("SolicitorAppsIssued", objDataSet.Tables(0).Rows(intI).Item("SolicitorAppsIssued"))
objWriter.WriteElementString("SolicitorContractsReturned", objDataSet.Tables(0).Rows(intI).Item("SolicitorContractsReturned"))
objWriter.WriteElementString("Index", objDataSet.Tables(0).Rows(intI).Item("Index"))
objWriter.WriteEndElement() ' close "Employee" element
Next
End If

' end the "Menu" element
objWriter.WriteEndElement()

' flush and write XML data to the file
objWriter.Flush()

Return strPath
Catch ex As Exception
Return False
Finally
' clear up memory
objWriter.Close()
objWriter = Nothing
objDataSet = Nothing
End Try
End Function

Thursday 11 October 2007

Design Patterns

http://www.dofactory.com/Patterns/Patterns.aspx#list
scroll down...










































































































  Creational Patterns
  Abstract Factory   Creates an instance of several families of classes
  Builder   Separates object construction from its representation
  Factory Method   Creates an instance of several derived classes
  Prototype   A fully initialized instance to be copied or cloned
  Singleton   A class of which only a single instance can exist
  Structural Patterns
  Adapter   Match interfaces of different classes
  Bridge   Separates an object’s interface from its implementation
  Composite   A tree structure of simple and composite objects
  Decorator   Add responsibilities to objects dynamically
  Facade   A single class that represents an entire subsystem
  Flyweight   A fine-grained instance used for efficient sharing
  Proxy   An object representing another object
  Behavioral Patterns
  Chain of Resp.   A way of passing a request between a chain of objects
  Command   Encapsulate a command request as an object
  Interpreter   A way to include language elements in a program
  Iterator   Sequentially access the elements of a collection
  Mediator   Defines simplified communication between classes
  Memento   Capture and restore an object's internal state
  Observer   A way of notifying change to a number of classes
  State   Alter an object's behavior when its state changes
  Strategy   Encapsulates an algorithm inside a class
  Template Method   Defer the exact steps of an algorithm to a subclass
  Visitor   Defines a new operation to a class without change
'if the enum is :
Public Enum aslamEnum
Created = 0
AwaitingPayment
Active
InProduction
Complete
Cancelled
End Enum


'The function will return description if exist else the name:

Private Function GetEnumDescription(ByVal Value As aslamEnum) As String
Dim objFieldInfo As FieldInfo
Dim sRetVal As String
Dim objDescriptionAttributes() As DescriptionAttribute
Dim tEnum As Type = GetType(aslamEnum)

objFieldInfo = tEnum.GetField([Enum].GetName(tEnum, Value))
objDescriptionAttributes = objFieldInfo.GetCustomAttributes(GetType(DescriptionAttribute), False)
With objDescriptionAttributes
If .Length > 0 Then
sRetVal = objDescriptionAttributes(0).Description
Else
sRetVal = [Enum].GetName(tEnum, Value)
End If
End With

Return Trim(sRetVal)
End Function


'To get the value back either in Name or Description use
value=GetEnumDescription(varmyEnum)

Wednesday 10 October 2007

Simple chat application for ASP.NET

http://www.codeproject.com/aspnet/SimpleChat.asp?df=100&forumid=53269&fr=26

Forum

http://www.codeproject.com/aspnet/JumpyForum.asp

asp.net vb.net shopping cart and c#

http://www.dotnetheaven.com/Uploadfile/munnamax/ShoppingCart02102006010016AM/ShoppingCart.aspx

c# http://www.codeproject.com/aspnet/ShoppingCartCSharp.asp

Payment Gateway:
http://www.vbdotnetheaven.com/UploadFile/munnamax/PaymentGateway02152006022631AM/PaymentGateway.aspx

Drag and Drop Products to the Shopping Basket Using JavaScript
http://www.codeproject.com/aspnet/DragAndDropShopping.asp

URL Rewriting with ASP.NET

http://www.codeproject.com/aspnet/URLRewriter.asp

Search Engine Optimization (SEO) ASP.NET

click on
1. http://www.codeproject.com/useritems/10_SEO_Tips.asp?msg=2263438

2. http://www.wwwcoder.com/main/parentid/457/site/6173/68/default.aspx

Build Google IG like Ajax Start Page

Nice article and code here

open pdf in webform

convert the file in byte array(i.e byte()) using function :

'get data from file and return as byte array
Public Function GetFileData(path as string) As Byte()
Try
Dim fsReader As New IO.FileStream(path , IO.FileMode.Open)
Dim data() As Byte = New Byte(fsReader.Length) {}
fsReader.Read(data, 0, fsReader.Length)
fsReader.Close()
Return data
Catch
Throw
End Try
End Function

dim buf() as byte
buf=GetFileData()

If buf.Length > 0 Then
'flush retrieved document
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.ContentType = "Application/pdf"
Response.AddHeader("content-disposition", "inline; filename=ehips_SW_" & sTaskRef & ".pdf")
Response.AddHeader("content-transfer-encoding", "binary")
Response.BinaryWrite(buf)
Response.End()
End If



should display PDF in browser

Thursday 4 October 2007

Stored procedure using Cursors

the below is a sample example for stored procedure and cursors
CREATE PROCEDURE prcCursorExample
AS

-- declare all variables!

DECLARE @iRowId int,
@vchCustomerName nvarchar(255),
@vchCustomerNmbr nvarchar(10)

-- declare the cursor
DECLARE Customer CURSOR FOR
SELECT iRowId,
vchCustomerNmbr,
vchCustomerName
FROM CustomerTable

OPEN Customer

FETCH Customer INTO @iRowId,
@vchCustomerNmbr,
@vchCustomerName


-- start the main processing loop.
WHILE @@Fetch_Status = 0

BEGIN

-- This is where you perform your detailed row-by-row processing. INSERT INTO ORDER(CUSTOMERNUMBER,CUSTOMERNAME) values(@vchCustomerNmbr,@vchCustomerName)

-- Get the next row.
FETCH Customer INTO @iRowId,
@vchCustomerNmbr,
@vchCustomerName
END

CLOSE Customer
DEALLOCATE Customer
RETURN

sql server tutorial

sql server tutorial

SQL Server views

click here

SQL Server : How to simulate the GROUP_CONCAT function

there is no groupconcat in sql server (only available in Mysql), but could be made using the example in the link below

Click the link

SQL Server : How to simulate the GROUP_CONCAT function

SQL Server How To

following questions have been asnwered in the link
Add a column to a table unless it already exists
Count the total number of records in all user tables
Create a table unless it already exists
Create a temporary table
Create a view unless it already exists
Create an index unless it already exists
Determine the name of the database you are connected to
Determine the name of the user for the current session
Determine which service pack is installed
Export data to a comma separated file
Import data from a comma separated file
List all currently connected users
List all columns in a table
List all databases
List all indexes on a table
List all filegroups
List all tables
List all tables or indexes within a filegroup
List all tables that contain a given column name
List the size of each table in the database
List table information
Move a database file
Obtain record field size information
Restore an NT4 system and SQL Server 7 databases from a full backup
Restore a W2K system and SQL Server 2000 databases from a full backup
Run dbcc checkdb on each database (using cursors)
Script a full NT4 and SQL Server 7 backup
Script a full W2K and SQL Server 2000 backup
Set a single database into Single User Mode
SQL Server Replication
Start SQL Server 2000 in Single User Mode
Test if a trigger exists

Using the CASE in sql server

select title,
case
when price < 12.00 then 'Cheap'
when price < 3.00 then 'Really Cheap'
when price > 12.00 and price < 20.00 then 'Average'
else 'Expensive' end 'Price Category'
from pubs.dbo.titles

The output looks like this:

title Price Category
-------------------------------------------------------- ------------
The Busy Executive's Database Guide Average
Cooking with Computers: Surreptitious Balance Sheets Cheap
You Can Combat Computer Stress! Cheap
Straight Talk About Computers Average
Silicon Valley Gastronomic Treats Average


from http://www.databasejournal.com/features/mssql/article.php/3288921

Wednesday 3 October 2007

Most useful shortcuts in VS.NET

Switching between Windows:

Ctrl+F6 - navigate between various panes that appear in the base code editing window.
Shift+Alt+Enter - full-screen mode at any time. In full-screen mode, only the active window is visible in full screen.
Alt+F6/Alt +Shift+F6 - move cursor away from the main editing section into docked windows like Properties, Help, Dynamic help, Server Explorer (if these winows are open).
F7 - Jump to Code Behind/Base Code editing window

Editing:
Ctrl+Shift+V - cycle through the clipboard ring.
Ctrl+- (Ctrl + Hyphen) - similar with Internet Explorer, very easy to navigate from page to page.
Ctrl+Shift+- - cycles in the opposite direction.
Block Selection: - press Alt and then select the area you want with your mouse.
Line No in Code - Tools>Options>Text Editor>All Languages>General>Line numbers.
Ctrl+] :matching brace/comment/region/quote
F4: Property Window
Ctrl+Alt+L - Solution Explorer
Ctrl+Alt+O - Output Window
Ctrl+Alt+K - Task List
Ctrl+Shift+Space - intellisense window.
Ctrl+R - Word Wrap

BookMark:
Ctrl+K, Ctrl+K - Create/Remove Bookmark
Ctrl+K, Ctrl+N - Move to next bookmark
Ctrl+K, Ctrl+P - Move to previous bookmark
Ctrl+K, Ctrl+L - Clear all bookmarks

Code Format:
Ctrl+K, Ctrl+F - Auto-format selection
Ctrl+U - Convert to lower case
Ctrl+Shift+U - Convert to upper case
Ctrl+K, Ctrl+C - Comment selection
Ctrl+K, Ctrl+U - Uncomment selection

Code Outline:
Ctrl+M, Ctrl+M - Fold/Unfold the current code block
Ctrl+M, Ctrl+L - Unfold all
Ctrl+M, Ctrl+P - Stop outlining
Ctrl+M, Ctrl+O - Fold all

Running/Debugging:
F5 - Start Application in debug Mode
Ctrl+F5 - Start Without debugging
F11 - Step into
F10 – Step over.
Shift + F11 – Step Out.
Shift + F5 – Stop debugging.
Ctrl+Shift+F5 - Restart Debugging

from http://visualstudiotips.wordpress.com/

How to debug classic ASP pages in VS 2005

Here is how to make ASP debugging work:

1. Enable ASP debugging on the server. (IIS 5.1 right click on Virtual directory->properties->Configuration(in directory tab)->debugging tab->enable asp debugging)
2. Open classic ASP in VS 2005.
3. Set breakpoint.
4. View page in browser or run without debugging.
5. Debug | Attach to Process
6. Locate IIS ASP worker process (w3wp.exe on IIS6) which exposes x86 and Script and attach as Script.

When running on XP Pro/IIS 5, you need to attach to dllhost.exe instead of w3wp.exe. look for the one with Type "Script, x86" and the User Name column indicates your IIS process account (IWAM_machinename).
from http://blogs.msdn.com/mikhailarkhipov/archive/2005/06/24/432308.aspx

Tuesday 2 October 2007

Remove leading and trailing zeros from a numeric string

declare @str nvarchar(10)

set @str = '00101abc2300'

select replace(ltrim(rtrim(replace(@str, '0', ' '))), ' ', '0')