Showing posts with label ASP.net. Show all posts
Showing posts with label ASP.net. Show all posts

Thursday, 21 June 2012

ASP.net Partial Classes


In ASP.net whenever you right click and add file to the solution/project a new file will be created. In the newly created code behind file you can able to see the Partial keyword just before the class name of that file.

Do you know why the class is mentioned as Partial class in the code behind?  The main reason of having the class file as a Partial class because of the same class name can be used across different physical files this will help the developer to develop the own module without affecting the others code.

The complier will treat different physical files of the partial classes with the same class name as a single entity.

Below code is sample example of a partial class.

1 .file1.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

2 .file2.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

3 .file3.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

Wednesday, 23 May 2012

ASP.net Copy Files and Folder from source to destination with creating backup folder.


The manual deployment of files is applicable in most of the enhancement or maintenance project. This method is applicable only for certain applications that are developed before 2002 for classic asp and other programming languages with no class libraries. Still it is a part of activity performed by the deployment team to transfer the modified file from staging folder to the production folder. Normally the developers copy the files from the development environment or UAT environment and put it in a staging environment. And then after approval process the deployment team takes the code from staging and deployment in production.  The whole process is so cumbersome and difficult for the developer to copy the files from the development or UAT to staging. So the below code is so self explanatory for creating the files and folders in the staging environment with a deployment instruction in the staging location.

The Code accepts various parameters like source location, destination location, backup folder location, ticket name.
Create deployment instruction and rollback instruction along with the files and folders to be copied in the staging environment with the same structure.

This code can used as a part in a web application for creating deployment instruction.

Public Shared Sub CreateFileFolder(ByVal srcFullPath As String, ByVal srcPath As String, ByVal dstPath AsString, ByVal fileName As String, ByVal ticketNo As String, ByVal lastFldr As Boolean, ByVal bkpFolder AsString)
        Dim dstDir, backupDir As DirectoryInfo
        Dim tmpPath As String
        ‘Create instr if it is the last folder 
        If lastFldr = True Then
            If File.Exists(DeployInstrPath & "Instr.txt") Then File.Delete(DeployInstrPath & "Instr.txt")
            WriteFile(DeployInstr, DeployInstrPath & "Instr.txt")
            If File.Exists(DeployInstrPath & "RollbackInstr.txt") Then File.Delete(DeployInstrPath &"RollbackInstr.txt")
            WriteFile(RollbackInstr, DeployInstrPath & "RollbackInstr.txt")
            Exit Sub
        End If

        Try
            If (srcPath.Contains("\")) Then
                tmpPath = srcPath.Substring(0, srcPath.IndexOf("\"))
                srcPath = srcPath.Substring(srcPath.IndexOf("\") + 1)
                lastFldr = False
            Else
                tmpPath = srcPath
                lastFldr = True
            End If
            If ticketNo.Length <> 0 Then
                dstPath += "\" + tmpPath + "\" + ticketNo
                backupDir = New DirectoryInfo(dstPath + "\Backup")
              ‘Create backupFolder 
                backupDir.Create()
                bkpFolder = dstPath + "\Backup"
            Else
                dstPath += "\" + tmpPath
                bkpFolder += "\" + tmpPath
              ‘Create folder inside the structure
                backupDir = New DirectoryInfo(bkpFolder)
                If (Not backupDir.Exists) Then backupDir.Create()
            End If
             ‘Create Main Folder
            dstDir = New DirectoryInfo(dstPath)
            If (Not dstDir.Exists) Then dstDir.Create()
            If lastFldr = True Then
                CopyFiles(srcFullPath, dstPath + "\" + fileName)
                WriteDeployInstruction(fileName, srcPath, bkpFolder & "\", dstPath & "\")
                WriteRollbackInstruction(fileName, srcPath, bkpFolder & "\")
            End If
            CreateFileFolder(srcFullPath, srcPath, dstPath, fileName, String.Empty, lastFldr, bkpFolder)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

Tuesday, 22 May 2012

ASP.net to write simple log file in VB.net language

In many applications we may came across lot logging techniques. Like writing log files in text file, some custom log file, log in event viewer, logging information in Databases etc.,

Here we are going to see a simple code in VB.net programming language that will help in logging information for any applications.

1. Use a system.IO namespace for any file handling operations.
2. When a variable is considered as a shared object, it means there is no need for object creation in the instantiation class.
3. The  System.Windows.Forms.Application.StartupPath is a application running folder path
4. Check to see the log folder and log file already exists. If not exist then create one or else concatenate with the existing content in the log file.
5. Create a filestream object and using streamwriter write the content to the log file.



Imports System
Imports System.IO
Public Class Log
    Private Shared LogPath As String = System.Windows.Forms.Application.StartupPath + "\Log\"
    Private Shared fs As FileStream
    Private Shared sw As StreamWriter
    ''' <summary>
    ''' Log result in the log file
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub Log(ByVal logStr As String)
        Dim logDir As DirectoryInfo
        Dim logFileName As String = LogPath + "Log.txt"
        logDir = New DirectoryInfo(LogPath)
        If (Not logDir.Exists) Then logDir.Create()
        If (Not File.Exists(logFileName)) Then File.Create(logFileName)
        If File.Exists(logFileName) Then
            sw = File.AppendText(logFileName)
            sw.WriteLine(logStr.ToString())
            sw.Close()
        Else
            fs = New FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
            sw = New StreamWriter(fs)
            sw.WriteLine()
            sw.WriteLine(logStr.ToString())
            sw.Close()
        End If
    End Sub
End Class

Monday, 30 April 2012

ASP.net Maintain scrollbar position after asynchronous post back


In order to maintain scrollbar position after asynchronous post back it is not at all enough to include the MaintainScrollPositionOnPostBack in the page directive alone. We need to include the below JavaScript code just below ScriptManager tag. Because during asynchronous post back, only code within the ScriptManager tag will be executed within aspx page and after that the below JavaScript will be executed and it maintain the scrollbar position.


1. First include the maintain scroll bar position as in the below code.
<pages maintainScrollPositionOnPostBack="true" />

2. Second Include the JavaScript code below the ScriptManager tag

 <script type="text/javascript">
       window.scrollTo = function () { }
</script>

Friday, 27 April 2012

ASP.net Copy using File Stream

This below code snippet will be so useful for copying the file from one physical location to another physical location in a server.  ASP.net has inbuilt classes IO.Filestream that is so useful for various file manipulation function.
Code
Public Shared Sub CopyFiles(ByVal srcPath_File As String,ByVal dstPath_File As String)

        Dim oFile As System.IO.FileInfo

        Dim oFileStream As System.IO.FileStream = Nothing
        Dim oFileStreamR As System.IO.FileStream = Nothing
        Try
            oFile = New System.IO.FileInfo(srcPath_File)
            oFileStream = oFile.OpenRead()

            Dim lBytes As Long = oFileStream.Length
            Dim fileData(lBytes) As Byte
            oFileStream.Read(fileData, 0, lBytes)

            If File.Exists(dstPath_File) ThenFile.Delete(dstPath_File)
            oFileStreamR = New System.IO.FileStream(dstPath_File, System.IO.FileMode.OpenOrCreate)
            oFileStreamR.Write(fileData, 0, fileData.Length)
            oFileStreamR.Flush()
            oFileStreamR.Close()
            oFileStreamR.Dispose()
        Catch ex As Exception
            Throw ex
        Finally
            oFileStream.Close()
            oFile = Nothing
            If oFileStreamR IsNot Nothing Then
                oFileStreamR = Nothing
            End If
        End Try
End Sub
Explanation of the code as below,
  1. Use System.IO namespace
  2. Create an instance for the fileinfo class to get the file information of the source file.
  3. Create two instances of filestream one for reading and other for writing the file.
  4. Find the length of the filestream object and store in a byte variable.
  5. Check to see the file already exist in the destination location. If file already exist in the location then delete the file.
  6. Using the filestream read instance read the content of the file and write the content in the target location using the filestream write instance.
  7. Flush and close the filestream write instance.
  8. Finally close the filestream instances.

ASP.net Dynamic MS Word Document creation from Word Template

1.  Create a Word document as per the need and place the bookmark for the text that need to be changed dynamically and save it in a location
2.  Add the Microsoft Object Library to the code
3. Imports Word = Microsoft.Office.Interop.word
4. Use the below code snippet in your asp.net application to create word document on a fly

Dim oWord As Word.Application
Dim oDoc As Word.Document
oWord = CreateObject("Word.Application")
oDoc = oWord.Documents.Open("<FILE LOCATION>")
With oDoc.Bookmarks
  .Item("<BOOKMARK NAME IN WORD DOC>")Range.Text = "<Either value from front end or value form database")
End With
oDoc.Save()
oDoc = Nothing
oWord = Nothing


Please post your queries incase of any doubts.