Kuzhikkattil

Just another WordPress.com weblog

Mail ,GetBodyAsHtml,GetToList from Db

Private Function GetBodyAsHtml(ByVal Bodytext As String, ByVal HeaderText As String, ByVal FooterText As String) As String
Dim sb = New System.Text.StringBuilder

sb.Append(“Tasks”)
sb.Append(“

“)
sb.Append(“
“)
sb.Append(“
“)
sb.Append(“

“)
sb.Append(“

“)
sb.Append(“

“)
sb.Append(“

” & HeaderText & “

“)
sb.Append(Bodytext)
sb.Append(“

“)
sb.Append(FooterText)
sb.Append(“

“)
sb.Append(“”)

Return sb.ToString
End Function
======================================================================
Private Function GetToList(ByVal Strid As String) As String
Dim _sqlConnection As New SqlConnection()
Dim cmdSelect As New SqlCommand()
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim strTo As String = “”
Dim strConn As String = ConfigurationManager.ConnectionStrings(“sqlConnectionString”).ToString()

Try
_sqlConnection.ConnectionString = strConn
_sqlConnection.Open()

cmdSelect.Connection = _sqlConnection
cmdSelect.CommandType = CommandType.Text

cmdSelect.CommandText = “Select Name=MemEmail from Member1 where id= ‘” & Strid & “‘”

da = New SqlDataAdapter(cmdSelect)
da.Fill(ds, “Tasks”)

For Each row As DataRow In ds.Tables(“Tasks”).Rows
strTo = strTo & row(“Name”).ToString
strTo = strTo & “,”
Next
Return strTo
Catch ex As Exception
Return strTo
Finally
strConn = Nothing
da = Nothing
ds = Nothing
cmdSelect = Nothing
End Try
End Function
==========================================================================
Imports Microsoft.VisualBasic
Imports System.Configuration
Imports System.Net.Mail
Imports System
Public Function SendMail() As Boolean

’sends Mail

Dim strPath As String = “”
Dim NewMessage As MailMessage = New MailMessage()
Dim Client As SmtpClient = New SmtpClient()

Try

‘getting body for mail
Dim strbody As String = Body

Arrtoid = Split(ToId, “,”)
Arrccid = Split(CCId, “,”)

If Trim(FromId) “” Then NewMessage.From = New MailAddress(FromId)

For Each strT In Arrtoid
If Trim(strT) “” Then NewMessage.To.Add(New MailAddress(strT))
Next
For Each strC In Arrccid
If Trim(strC) “” Then NewMessage.CC.Add(New MailAddress(strC))
Next

NewMessage.Subject = Subject
NewMessage.Body = strbody

If Trim(AttachmentPath) “” Then
Dim attachFile As Attachment = New Attachment(AttachmentPath)
NewMessage.Attachments.Add(attachFile)
End If

NewMessage.IsBodyHtml = True
Client.Send(NewMessage)
Return True

Catch ex As Exception
Throw ex
Finally
NewMessage = Nothing
Client = Nothing
End Try

End Function

=========================================================================

July 18, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Convert Datatable To Html File,SaveAsHtmlFile (ByVal renderedOutput As StringBuilder

Private Function ConvertToHtmlFile(ByVal sentDataTable As DataTable) As String

‘ Check if the Sent DataTable is not empty or a Null
If sentDataTable Is Nothing Then
Throw New System.ArgumentNullException(“sentDataTable”)
End If

‘Get a worker object.
Dim HtmlStringBuilder As New StringBuilder()

‘Open tags and write the top portion.
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“Page-”)
HtmlStringBuilder.Append(Guid.NewGuid().ToString())
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“

“)

‘Add the headings row.

HtmlStringBuilder.Append(“

“)

For Each myColumn As DataColumn In sentDataTable.Columns
HtmlStringBuilder.Append(”

“)
Next

HtmlStringBuilder.Append(“

“)

‘Add the data rows.
For Each myRow As DataRow In sentDataTable.Rows
HtmlStringBuilder.Append(“

“)

For Each myColumn As DataColumn In sentDataTable.Columns
HtmlStringBuilder.Append(”

“)
Next

HtmlStringBuilder.Append(“

“)
Next

‘Close tags.
HtmlStringBuilder.Append(“

“)
HtmlStringBuilder.Append(myColumn.ColumnName)
HtmlStringBuilder.Append(“
“)
HtmlStringBuilder.Append(myRow(myColumn.ColumnName).ToString())
HtmlStringBuilder.Append(“

“)
HtmlStringBuilder.Append(“”)
HtmlStringBuilder.Append(“”)

Return SaveAsHtmlFile(HtmlStringBuilder)

HtmlStringBuilder = Nothing

End Function

Private Function SaveAsHtmlFile(ByVal renderedOutput As StringBuilder) As String
Dim outputStream As FileStream
Dim sWriter As StreamWriter
outputStream = New FileStream(Filename, FileMode.Create)
sWriter = New StreamWriter(outputStream)
sWriter.Write(renderedOutput.ToString())
sWriter.Flush()
sWriter.Close()
outputStream.Close()
sWriter = Nothing
outputStream = Nothing
Return Filename
End Function

July 18, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

desktop application Application.StartupPath & “..\..\..\Images”

Dim path As String = Application.StartupPath & “..\..\..\Images”
        Dim oFile As System.IO.File
        Dim oWrite As System.IO.StreamWriter
        oWrite = IO.File.CreateText(path & “\sample1.txt”)

July 18, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Date validations in a text box…javascript

<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
    <title>Untitled Page</title>
    <script type=”text/javascript” language=”javascript”>
  // Declaring valid date character, minimum year and maximum year
var dtCh= “/”;
var minYear=1900;
var maxYear=2100;

function isInteger(s){
 var i;
    for (i = 0; i < s.length; i++){  
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < “0″) || (c > “9″))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
 var i;
    var returnString = “”;
    // Search through string’s characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){  
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
 // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
 for (var i = 1; i <= n; i++) {
  this[i] = 31
  if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
  if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
 var daysInMonth = DaysArray(12)
 var pos1=dtStr.indexOf(dtCh)
 var pos2=dtStr.indexOf(dtCh,pos1+1)
 var strMonth=dtStr.substring(0,pos1)
 var strDay=dtStr.substring(pos1+1,pos2)
 var strYear=dtStr.substring(pos2+1)
 strYr=strYear
 if (strDay.charAt(0)==”0″ && strDay.length>1) strDay=strDay.substring(1)
 if (strMonth.charAt(0)==”0″ && strMonth.length>1) strMonth=strMonth.substring(1)
 for (var i = 1; i <= 3; i++) {
  if (strYr.charAt(0)==”0″ && strYr.length>1) strYr=strYr.substring(1)
 }
 month=parseInt(strMonth)
 day=parseInt(strDay)
 year=parseInt(strYr)
 if (pos1==-1 || pos2==-1){
  alert(“The date format should be : mm/dd/yyyy”)
  return false
 }
 if (strMonth.length<1 || month<1 || month>12){
  alert(“Please enter a valid month”)
  return false
 }
 if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
  alert(“Please enter a valid day”)
  return false
 }
 if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
  alert(“Please enter a valid 4 digit year between “+minYear+” and “+maxYear)
  return false
 }
 if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
  alert(“Please enter a valid date”)
  return false
 }
return true
}

function ValidateForm(){
      
 var dt=document.getElementById(‘<%=txtDate.ClientID %>’)
 if (isDate(dt.value)==false){
  dt.focus()
  return false
 }
    return true
 }
    </script>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
    <asp:TextBox ID=”txtDate” runat=”server”></asp:TextBox>
    <asp:Button ID=”btnSubmit” Text=”Validate Date” runat=”server” OnClientClick=”return ValidateForm();” />
    </div>
    </form>
</body>
</html>

July 18, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Service-Oriented Architecture

 

Realizing a Service-Oriented Architecture with .NET

 

 

Introduction

Web Services have emerged as a key strategic capability for integrating business processes, data, and organizational knowledge.

This article is meant to be a practical discussion guide to building a .NET application in a service-oriented architecture. We will consider real-world goals, real-world obstacles, and experience-based solutions. I quickly concede the approaches discussed here are not exhaustive or infallible. This paper is focused on application development, not application integration. We will specifically consider architectural issues and component design issues.

The Potential of Web Services

So why all the hype? Web Services obviously have great potential. It’s a way to integrate at many different levels. Consider this example. A single consumer application (perhaps interacting with your company over the Internet) wants to engage the company in some business process. To facilitate that business process, the company internally invokes processing that spans two discreet systems (A and B). However, through a service-oriented architecture, the entire end-to-end business process is exposed to the consumer application as a single service.

Figure 1. Exposing separate LOB applications as a single service.

Architectural Considerations

A good architecture emphasizes a separation of responsibilities. For example, the presentation tier manages presentation components; the business logic tier manages business logic components; and the data access tier manages data access components.

This separation provides for fault tolerance, easier maintenance, and future-proofing. A good service-oriented architecture is nothing new, just a smart way of separating (and exposing) a component’s responsibilities. It builds on classic object-oriented (OO) ideas.

In a service-oriented architecture, clients consume services, rather than invoking discreet method calls directly. In a 3-tier model (Figure 2), objects are marshaled across process boundaries through the proxy/stub techniques we know from COM. This provides benefits such as location transparency. The same techniques are used in .NET Remoting via channels and sinks. The basic philosophy is that one tier should only communicate with the tier contiguous to it.

One disadvantage to object-orientation at an architectural level is the number of communication links. Client code is responsible for traversing complex object models and understanding details about domain-specific logic. In a service-oriented model, we introduce a further “layer of indirection”. This alleviates some of the pain associated with traversing complex object models. The services layer, denoted below in Figure 3 by the cloud, provides black-box functionality.

Figure 2. A typical 3-tier application architecture

Figure 3. A service-oriented application architecture

Designing Services and Objects

In a service-oriented design, services should be course-grained. Course-grained services are modeled after and align to business processes.

Objects should be fine-grained and align to real business entities. These discreet objects provide the detailed business logic. Specificity is good when building discreet business objects. This is also a very successful way to codify organizational knowledge. Each business object is responsible for its own behavior and business rule implementation, such as updating a database table, sending an email, or placing a message on a queue.

Services provide the orchestration of the detailed business objects to expose a full service to the consumer. Services are responsible for orchestrating calls to discreet business objects, managing the responses, and acting accordingly. Service methods may invoke and manage several business objects.

Service methods align to business processes by design. Class methods align to detailed object-level operations by design.

Consider the following example in Figure 4. Notice we have a Web service called BookStoreService and a Web method called orderBook(). This single Web method instantiates and manages 3 separate objects, Book, Order, and OrderDetail.

Figure 4. Designing services and objects.

Design Considerations

Minimize Roundtrips

A design goal should be to design services to minimize round-trips. This was true with COM and it continues to be true with .NET and Web Services.

Recall in classic n-tiered distributed architectures that conventional wisdom said it was better to move 1000 bytes across process boundaries 1 time, rather than moving 1 byte across 1000 times. We would optimize method signatures and design stateless components, and we would use database helper routines to convert ADO recordsets to XML to provide a lightweight payload for distributed applications.

With SOAP and Web Services, we generally see the same approach. However, we need to take it one step further. We should now consider using the Web Service as a service, not just a data pump, and XML as a self-describing package, not just a payload.

Align Web Methods to Forms

Web methods should be designed to perform an entire service for an entire form. In short, our design goals are:

  • Provide a course-grained Web method at the form level
  • Have the Web method invoke whatever business objects it needs
  • Return to the consumer the whole service result, like a DataSet with numerous tables within it

Consider the following example. We may be designing a search form to search a bookstore for certain titles. To support this search screen in this figure, we would design a Web method called GetSearchScreenInfo which returns a DataSet that has a number of tables within it. This Web Method is designed to provide all the information the form needs to draw itself on the load event.

Figure 5. Align service methods to forms

On this particular form, we need two lists just to populate the screen: a list of valid publishers, and a list of valid categories. Rather than making two calls to the Web Service (one for each dropdown), we design our Web method to provide everything we need in a single call. We service the loading of the search form in a single interaction. Later work, such as performing the search or drilling into details, is handled by separate Web methods.

Behind the scenes, our web method is invoking and managing all the business objects it needs to satisfy the request.

Moving Data Between Tiers

Data can be moved between architectural tiers as DataSets, serialized objects, raw XML, etc. — but design your solution to be consumed. DataSets are .NET specific objects that serialize nicely but are intended for other .NET applications. If your application needs to interoperate with, for example, a J2EE solution, DataSets may be too troublesome to employ because the J2EE side would not readily understand a DataSet.

Serializing business objects is also an option. But remember that the full object is not marshaled. The object’s public properties and data members are serialized and shipped, but the calling client cannot re-inflate the object and access its private data members or methods.

XML is, of course, an obvious choice also. XML formatted exchanges are a solid and proven technique for moving data around any distributed architecture.

Distributed Transactions

Web methods can act as the root of a distributed transaction. These transactions are managed by the Distributed Transaction Coordinator (DTC). Our Web Service classes must reference the System.EnterpriseServices namespace, and can then use the ContextUtil class to use the SetAbort() and SetComplete() methods. This provides for declarative transaction control.

Each object enlisted by the Web method is a child object and will participate in the transaction and “vote” on the outcome. This provides the best fit for keeping objects granular enough to manage their own data from a persistent store, while still allowing them to be orchestrated by a transaction-root controller.

Transactional context is managed by the root. Web Methods must be adorned with the TransactionOption attribute, something like this:

 
[WebMethod(TransactionOption=TransactionOption.RequiresNew)] 
 

Child objects need nothing special. They do NOT need to derive from the ServicedComponent base class. The same child object can be enlisted in a transaction for one Web method, but not enlisted in a transaction for another Web method.

Exception Handling

Exceptions should be considered a rarity. They should be thrown only in exceptional situations, not in normal branching. Each caller should catch exceptions and deal with them appropriately. In its simplest form, an exception could be bubbled up the call stack from the backend to the UI and presented to the end-user. However, each step up the stack should have processing done at that layer. All exceptions thrown over SOAP get shipped as SOAP exceptions. For example, we might throw an exception if someone tried to log on inappropriately using this simplified code:

 
               Throw New BadPasswordException()
 

The caller would need to catch that exception, like this:

 
      Catch x1 As BadPasswordException 
               // do something
 

In this example, the caller catches the particular exception and reacts to it. However, if the Web Service threw an application exception to the end-user client, the exception is transformed into a SOAP exception. In fact, the client program must specifically catch that SOAP exception, as in Figure 6.

 
               catch e as System.Web.Services.Protocols.SoapException
 

Figure 6. Throwing exceptions over a SOAP connection.

The client program must catch at least 3 different types of exceptions. The first is SoapException.

On the client, SoapExceptions should be caught for any middle-tier exceptions. This is useful for throwing exceptions from the middle tier application logic. However, ANY middle tier exceptions will be thrown as a SoapException.

We can encode the inner exception to be business-problem specific information we need. As an example, we can pass a SoapException with a meaningful message, such as “Database access error”, so that the client can deal with it.

Next the client should catch WebExceptions. This is useful when the network goes down in the middle of an end-user’s session.

Finally, the client must catch client-side exceptions. These are thrown by client-side processing, and are something local to client, like FileNotFound.

Conculsion

The key messages to take away from this discussion about constructing .NET applications in a service-oriented architecture are as follows:

1.     Service-oriented architecture is rooted in object-orientation but adds a layer of abstraction. I like to think that service-orientation is not a departure from object-orientation, but rather an evolution. Services orchestrate calls to discreet business objects to satisfy requests. Objects are enlisted, behind the scenes, to formulate a response.

2.      The openness of the technologies is exciting and easy to use. The current industry work on standards around UDDI, WSDL, Web Services, etc. promises that more and more applications can be constructed from constituent services rather than re-invented domain-specific code.

3.      The statelessness of the technologies can be a challenge for performance heavy applications. Be aware of the non-functional requirements of the solution you want to build. Sometime line-of-business applications desire long-running transactions that are better suited to other distributed application technologies.

4.      Design your solution for Web Services – you will have different approaches than you would for Remoting or DCOM. Again, remember that service-orientation is appropriate for some business applications, but not all. A service-oriented architecture is one possible architecture pattern to consider when designing solutions.

July 18, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Viewstate Session Cache

Viewstate is used to store Value for the current page only.

 

Session saves Value till the Browser is not closed.

 

Cache  also stored the Value till the Browser exist but when the System resouce goes low then the items in the Cache are dropped directly.

SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user’s session variables.

 

VIEWSTATE   Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.

The viewstate data will be sent twice over the internet (from server to browser, and back), so you will want to keep that as small as possible. Plus, viewstate will only work in postback-scenarios, you will lose it if you redirect or you supply the user with a regular link to some page of yours (but this might be exactly what you want)

 

On the other hand, if you store lots of data for lots of sessions, you need a lot of memory on your server. Plus session-state management itself costs some time on the server.

 

I don’t think it is possible to give a hard formula whether to use viewstate or sessionstate, but if you really don’t need sessions, you might investigate a session-less site (<sessionState mode=”off”/>

in web.config) using viewstate to keep some state.

 

Session: Memory space used to persist user-specific data on the server side.One Session created per user per Session.

ViewState: Hidden form field in ASP.Net form, used to persist page-instance-specific data.

State: A generic term for persistence of data

 

Caching
=======

It’s performance-related. We can store data in local memory through caching for data serving from memory directly for incoming requests.
Benefits are – Fast page rendering, minimization of database hits and minimization of server resources consumption.
Types,
· Page Level Caching (called Output Caching)
· Page Fragment Caching (called Partial-Page Output Caching)
· Programmatic or Data Caching

Output Caching (Page Level Caching)
We can implement Page level, or output caching through Output Cache engine.
It’s a powerful technique, particularly useful for only static pages implementation.
Ex:
<%@OutputCache Duration=”60″ VaryByParam=”none” %>
Note: To solve the request of two pages caching problems follow below specifications,

To solve the problem, We can specify explicitly, like VaryByParam=”PartNo”, or by saying to vary on all GET/POST parameters, like: VaryByParam=”*”.
Partial-Page Output Caching (Page fragment caching)
It’s for specific regions of pages to be cached. We can cache a specific regions of a page like for user control or other listing of inventory list, stock in shopping cart.
<%@ OutputCache Duration=”15″
VaryByControl=”EmpID;DeptID” VaryByParam=”*”%>  
This directive is placed at the top of any User Control (.axcx file).
Data Caching
It’s take advantage of the .NET Runtime cache engine to store any data or objects between responses. So we can store object into a cache but notable point is we should ot store open database connections in the cache.

Cache["foo"] = bar;
To retrieve a value, simply reverse the syntax like this:
bar = Cache["foo"];

note, the cache value should not null prior to doing something with the data.
Ex:
The method GetUserInfo checks to see if the data exists in the cache. If it is present, it is returned from the cache, else, the GetUserInfoFromDatabase method fills the DataSet from the database and then populates the Cache.
public DataSet GetUserInfo()
{   
  string cacheKey = ”UserInfo”;   
  DataSet ds = Cache[cacheKey] as DataSet;   
  if (ds == null)   
 {     
   ds = GetUserInfoFromDatabase();     
   Cache.Insert(cacheKey, ds, null, NoAbsoluteExpiration,       
   TimeSpan.FromHours(15),CacheItemPriority.High, null);   
}      
return ds;
}  

DataSet GetUserInfoFromDatabase()
{
// Usual code to populate a data set from thedatabase. This data set
// object is then returned.
}

Session State Management
=====================

Session State Management

On behalf of clients it’s keep maintaining state for track of items. It’s very much useful in online shopping cart.

InProc:
State is maintained within the managed memory of the Asp.Net process. So runs in same process area. Speed is advantage but no stability.

OutProc :
State is maintained and managed by external resource like stateserver or SQL Server.
It works outside the clients memory. We have to compromise a bit on speed but stability is there.

Note :
The storage, fast and robustness is,
Inproc :
Kept as live object in web server(aspnet_wp.exe). ie. Stored in memory space of appdomain.
Fast, consume memory on webserver.
Session state will loss on recycle of worker process(aspnet_wp.exe) or restart of appdomain.
Because session state is stored in memory space of an appdomain.
Stateserver :
Session serialized and stored in memory(aspnet_state.exe). State server can run on another machine.
15% Slowerthan InProc while stroing basic data types like string,integer,etc. and serialization/deserialization too affect performance.
Session state won’t loss because webform store session on central server.

SQL Server :
Session serialized and stored in sql server
25% Slowerthan InProc while stroing basic data types like string,integer,etc. and serialization/deserialization too affect performance.
Similar to stateserver but Sqlserverprocess.

July 15, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Stored proc (xmldoc XML) calling methods

Public Function CreateXml() As String

        Dim xml As New StringBuilder()

        Try

            xml.Append(“<root><Tasks TasksId=”"”)

            xml.Append(TasksId)

 

            xml.Append(“”" Name=”"”)

            xml.Append(Name)

 

            xml.Append(“”" Priority=”"”)

            xml.Append(Priority)

 

            xml.Append(“”" IsNotificationOnly=”"”)

            xml.Append(IsNotificationOnly)

 

            xml.Append(“”" IsRetain=”"”)

            xml.Append(IsRetain)

 

            xml.Append(“”" EngagementID=”"”)

            xml.Append(EngagementID)

 

            xml.Append(“”" Assignor=”"”)

            xml.Append(Assignor)

 

            xml.Append(“”" AssignedDate=”"”)

            xml.Append(AssignedDate)

 

            xml.Append(“”" Desc=”"”)

            xml.Append(Desc)

 

            xml.Append(“”" DueDate=”"”)

            xml.Append(DueDate)

 

            xml.Append(“”" HasIssues=”"”)

            xml.Append(HasIssues)

 

            xml.Append(“”" HasAttachment=”"”)

            xml.Append(HasAttachment)

 

            xml.Append(“”" Requester=”"”)

            xml.Append(Requester)

 

            xml.Append(“”" HasServiceExtension=”"”)

            xml.Append(HasServiceExtension)

 

            xml.Append(“”" ReviewStatus=”"”)

            xml.Append(ReviewStatus)

 

            xml.Append(“”" ImportSrc=”"”)

            xml.Append(ImportSrc)

 

            xml.Append(“”" ImportSourceInfo=”"”)

            xml.Append(ImportSourceInfo)

 

            xml.Append(“”" ImportSourceItem=”"”)

            xml.Append(ImportSourceItem)

 

            xml.Append(“”" ImportSourceVersion=”"”)

            xml.Append(ImportSourceVersion)

 

            xml.Append(“”" ImportSourceType=”"”)

            xml.Append(ImportSourceType)

 

            xml.Append(“”" CreatedBy=”"”)

            xml.Append(CreatedBy)

 

            xml.Append(“”" CreatedOn=”"”)

            xml.Append(CreatedOn)

 

            xml.Append(“”" rowguid=”"”)

            xml.Append(rowguid)

 

 

 

            xml.Append(“”"/></root>”)

            Return (xml.ToString())

        Catch err As Exception

            Throw err

        End Try

    End Function

 

    Public Function saveTask(ByVal xmlTasks As String, ByVal StrTaskid As String) As Boolean

 

        Dim _sqlConnection As New SqlConnection()

        Dim cmdInsert As New SqlCommand()

        Dim retVal As Boolean

 

        Dim strConn As String = ConfigurationManager.ConnectionStrings(“sqlConnectionString”).ToString()

 

        Try

            _sqlConnection.ConnectionString = strConn

            _sqlConnection.Open()

 

            cmdInsert.Connection = _sqlConnection

            cmdInsert.CommandType = CommandType.StoredProcedure

 

            cmdInsert.CommandText = “Proc_SaveTask”

 

            cmdInsert.Parameters.Add(“@xmldoc”, SqlDbType.Xml)

            cmdInsert.Parameters(0).Value = xmlTasks

 

            cmdInsert.Parameters.Add(“@Id”, SqlDbType.VarChar)

            cmdInsert.Parameters(1).Value = StrTaskid

 

            cmdInsert.ExecuteNonQuery()

 

            retVal = True

 

        Catch ex As Exception

 

            retVal = False

 

        End Try

 

 

        Return retVal

 

 

    End Function

 

===============================================

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[Proc_SaveTask](@xmldoc XML,@Id varchar(50))

AS
DECLARE @idoc int

BEGIN TRAN
if isnull(@Id,”)<>”  delete from Task where TasksId=@Id
 

–Create an internal representation of the XML document.
EXEC sp_xml_preparedocument @idoc OUTPUT, @xmldoc

INSERT INTO Task (TasksId,[Name], Priority,IsNotificationOnly,IsRetain,
 EngagementID,Assignor, AssignedDate,[Desc],DueDate,
 HasIssues,HasAttachment,Requester,HasServiceExtension,
 ReviewStatus,ImportSrc,ImportSourceInfo,ImportSourceItem,
 ImportSourceVersion,ImportSourceType,CreatedBy,CreatedOn,rowguid)

SELECT   
 
 TasksId ,  
 CASE WHEN [Name] <>” THEN [Name] ELSE NULL END,
 CASE WHEN Priority <>” THEN Priority ELSE NULL END,
 CASE WHEN IsNotificationOnly <>” THEN IsNotificationOnly ELSE NULL END,
 CASE WHEN IsRetain <>” THEN IsRetain ELSE NULL END,
 CASE WHEN EngagementID <>” THEN EngagementID ELSE NULL END,
 CASE WHEN Assignor <>” THEN Assignor ELSE NULL END,
 CASE WHEN AssignedDate <>” THEN AssignedDate ELSE NULL END,  
 CASE WHEN [Desc] <>” THEN [Desc] ELSE NULL END,
 CASE WHEN DueDate <>” THEN DueDate ELSE NULL END,
 CASE WHEN HasIssues <>” THEN HasIssues ELSE NULL END,
 CASE WHEN HasAttachment <>” THEN HasAttachment ELSE NULL END,
 CASE WHEN Requester <>” THEN Requester ELSE NULL END,
 CASE WHEN HasServiceExtension <>” THEN HasServiceExtension ELSE NULL END,
 CASE WHEN ReviewStatus <>” THEN ReviewStatus ELSE NULL END,
 CASE WHEN ImportSrc <>” THEN ImportSrc ELSE NULL END,
 CASE WHEN ImportSourceInfo <>” THEN ImportSourceInfo ELSE NULL END,
 CASE WHEN ImportSourceItem <>” THEN ImportSourceItem ELSE NULL END,
 CASE WHEN ImportSourceVersion <>” THEN ImportSourceVersion ELSE NULL END,
 CASE WHEN ImportSourceType <>” THEN ImportSourceType ELSE NULL END,
 CASE WHEN CreatedBy <>” THEN CreatedBy ELSE NULL END,
 CASE WHEN CreatedOn <>” THEN CreatedOn ELSE NULL END,  
 rowguid
 
FROM       OPENXML (@idoc, ‘/root/Tasks’,1)
            WITH
    (TasksId varchar(50), [Name] varchar(200),Priority varchar(200),IsNotificationOnly varchar(200),
    IsRetain varchar(200),EngagementID varchar(50), Assignor varchar(200),  AssignedDate varchar(25),
    [Desc] varchar(200), DueDate varchar(25), HasIssues varchar(50), HasAttachment varchar(50),
    Requester varchar(50), HasServiceExtension varchar(200), ReviewStatus varchar(200),
    ImportSrc varchar(200), ImportSourceInfo varchar(200),  ImportSourceItem varchar(200),
    ImportSourceVersion varchar(200), ImportSourceType varchar(200),
    CreatedBy varchar(200), CreatedOn varchar(25), rowguid uniqueidentifier )
IF @@ERROR>0
BEGIN
ROLLBACK TRAN
END
ELSE
BEGIN
COMMIT TRAN
END
EXEC SP_XML_REMOVEDOCUMENT @xmldoc

——————————————————————————-
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create  PROCEDURE [dbo].[Proc_SelectTask](@TaskId varchar(50))

AS
select * from task Where TasksId=@TaskId For XML Auto  , ELEMENTS

——————————————————————————-

July 14, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

javascript validations radiobutton list etc…..(full page)

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head runat=”server”>

        <title>Untitled Page</title>

        <script type=”text/javascript”>

            function ValidateNumbers()

            {

                if(document.getElementById(‘txtNumber’).value!=)

                {

                     var input= document.getElementById(‘txtNumber’).value;

 

//                    var testName =/^([0-9])*$/;

//                    if(!testName.test(input))

//                    {

//                       alert(“Enter only numeric values”);

//                       return false;

//                    }

                    if (input == null || !input.toString().match(/^[-]?\d*\.?\d*$/))

                    {

                        alert(“Enter only numeric values”);

                        return false;

                    }

                    

                   

                }

                if(document.getElementById(‘ddlInput’).selectedIndex  == 0)

                {

                     alert(“Select Numbers”);

                       return false;

                }              

                 //validate radio list

                 var listItemArray = document.getElementsByName(‘ddlColors’);

                 var isItemChecked = false;

 

                 for (var i=0; i<listItemArray.length; i++)

                 {

                  var listItem = listItemArray[i];

 

                  if ( listItem.checked )

                  {

                   //alert(listItem.value);

                   isItemChecked = true;

                  }

                 }

 

                 if ( isItemChecked == false )

                 {

                  alert(‘Nothing is checked!’);

 

                  return false;

                 }

 

 

 

            }

        </script>

    </head>

<body>

    <form id=”form1″ runat=”server”>

    <div>

       

        <asp:TextBox ID=”txtNumber” runat=”server”></asp:TextBox>

        <asp:DropDownList ID=”ddlInput” runat=”server”>

             <asp:ListItem Text=”Select”></asp:ListItem>

            <asp:ListItem Text=”One”></asp:ListItem>

            <asp:ListItem Text=”Two”></asp:ListItem>

            <asp:ListItem Text=”Three”></asp:ListItem>

        </asp:DropDownList>

        <asp:RadioButtonList ID=”ddlColors” runat=”server”>

            <asp:ListItem Text=”Red”></asp:ListItem>

            <asp:ListItem Text=”Blue”></asp:ListItem>

            <asp:ListItem Text=”White”></asp:ListItem>

        </asp:RadioButtonList>

         <asp:Button ID=”btnSubmit” runat=”server” OnClientClick=”return ValidateNumbers()” Text=”Submit” />

    </div>

    </form>

</body>

</html>

 

July 14, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

javascripts -1

<script language=”javascript” type=”text/javascript”>

 

      

 

 

        //the following function is currently not used

    

        function reSize()

        {

            var winW = 630, winH = 460;

 

            if (parseInt(navigator.appVersion)>3)

            {

                if (navigator.appName==“Netscape”)

                {

                    winW = window.innerWidth;

                    winH = window.innerHeight;

                }

                if (navigator.appName.indexOf(“Microsoft”)!=-1)

                {

                    winW = document.body.offsetWidth;

                    winH = document.body.offsetHeight;

                }

            }

           

            alert(winH);

            winH = winH – 90;

            var windowheight = window.screen.height;

            var objMenu = document.getElementById(“CategoryMenu_tblMenuControl”);

            var objHeader = document.getElementById(“tbHeader”);

            //objMenu.height = winH + “px”

        }

       

        //The following ConfirmDialog function is used in MultiLocation grid events

        function ConfirmDialog()

        {          

            var obj = document.getElementById(“MultiLocation1_pnlMulti”); 

            if (obj.disabled == false)

            {          

                return confirm(‘Are you sure you want to delete this record’);

            }           

        }

       

       

       var dtpSdate;

      

        function GetDateName(strName)

       {

           var obj = document.getElementById(‘Engpanel1_Dtp’+ strName +‘_MyDtpText’);      

           dtpSdate=‘Engpanel1_Dtp’+ strName +‘_MyDtpText’;      

            if(obj == null)

           {

           obj = document.getElementById(‘Engpanel1_txt’+strName); 

            if(obj != null)

            {

             dtpSdate=‘Engpanel1_txt’+strName;            

            }

           }

           return dtpSdate;

       }

      

       function showAlert(msg)

       {

           alert(msg);     

           return false;

       }

   

        function Validate(ctrl,msg)

        {

            var obj = document.getElementById(ctrl); 

 

            if(obj != null)

            {

                if(obj.value == )

                {

                    showAlert(msg);                  

                    return false;

                }               

            }                   

        }

        function checkObjExsist(ctrl)

        {

            var obj = document.getElementById(ctrl);

            if(obj == null)

            {

                return false;

            }

        }

        function DateNullCheck()

        {

          

            if (Validate( GetDateName(‘Periodstartdate’) ,‘Period Start Date should not be empty’)== false  )

            {

                return false ;

            }

            if (Validate(GetDateName(‘Periodenddate’),‘Period End Date should not be empty’)== false  )

            {

                return false ;

            }

            if (Validate(GetDateName(‘Expectedreportingdate’),‘Reporting date should not be empty’)== false  )

            {

                return false ;

            }

            return true;

        }

       

        function ValidateDateControls()

        {  

             

          

            if (Validate(‘Engpanel1_txtClientname’,‘Client Name should not be empty’)== false && checkObjExsist(‘Engpanel1_txtClientname’)!=false)

            {             

                return false ;

            }

 

            if (Validate(‘Engpanel1_txtEngagementname’,‘Engagement Name should not be empty’)== false  )

            {

                return false ;

            }

                       

            if(checkObjExsist(‘Engpanel1_txtSentinelnumber’)!= false)

            {

                var input= document.getElementById(‘Engpanel1_txtSentinelnumber’).value;

              

                var testName =/^([0-9])*$/;

 

                if (Validate(‘Engpanel1_txtSentinelnumber’,‘Sentinel Number should not be empty’)== false  )

                {

                    return false ;

                }

 

                if(!testName.test(input))

                {

                   showAlert(“Digits Only Allowed in Sentinel number”);

                   return false;

                }

            }

               

            if(checkObjExsist(‘Engpanel1_txtEngagementnumber’)!= false)

            {

                var input= document.getElementById(‘Engpanel1_txtEngagementnumber’).value;

              

                var testName =/^([0-9])*$/;

 

                if (Validate(‘Engpanel1_txtEngagementnumber’,‘Engagement Number should not be empty’)== false  )

                {

                    return false ;

                }

 

                if(!testName.test(input))

                {

                   showAlert(“Digits Only Allowed in Engagement number”);

                   return false;

                }

            }                

         

 

            if ((checkObjExsist(GetDateName(‘Periodstartdate’))!= false && checkObjExsist(GetDateName(‘Periodenddate’))!= false && checkObjExsist(GetDateName(‘Expectedreportingdate’))!= false))

            {

                if (DateNullCheck()==false)

                {

                    return false;

                }

           

                if( document.getElementById(GetDateName(‘Periodstartdate’)).value != && document.getElementById(GetDateName(‘Periodenddate’)).value!= && document.getElementById(GetDateName(‘Expectedreportingdate’)).value!=)

                {

                    if( Date.parse(document.getElementById(GetDateName(‘Periodstartdate’)).value)> Date.parse(document.getElementById(GetDateName(‘Periodenddate’)).value))

                    {

                        showAlert(“End Date should not be less than Start Date”); 

                        return false;

                    }                       

                    if ( Date.parse(document.getElementById(GetDateName(‘Expectedreportingdate’)).value)>Date.parse(document.getElementById(GetDateName(‘Periodenddate’)).value))

                    {

                        showAlert(‘Expected Reporting Date should not be greater than Period End Date’);   

                        return false;

                    }                       

                    if (Date.parse(document.getElementById(GetDateName(‘Periodstartdate’)).value)> Date.parse(document.getElementById(GetDateName(‘Expectedreportingdate’)).value))

                    {

                        showAlert(‘Expected Reporting date should not be less than Period Start Date’);

                        return false;

                    }

                }

                else

                {

                    return false;

                }

            }//Datenullcheck

        

            if(checkObjExsist(‘Engpanel1_DrpInwhichcountryistheengagementbeingperformed?’)!= false && document.getElementById(‘Engpanel1_DrpInwhichcountryistheengagementbeingperformed?’).selectedIndex  == 0  )

            {                

               showAlert(“Select in Which Country is the engagement being performed”);

               return false;

            }

        }

    </script>

July 14, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet