Friday, December 30, 2011

Refreshing FRAME

FRAMEs are tricky in nature; it is advisable to avoid them. But in many scenarios you have no other choices but to deal with it. Here are some useful tips while handling a FRAME.

Creating a frameset

<html>
<head>
<title>Simple frames</title>
</head>
<frameset cols="250,*">
  <frame name="frmLeft" src="LeftPage.htm" />
  <frame name="frmRight" src="RightPage.htm" />
</frameset>
</html>

 

Refreshing one frame using JavaScript

parent.frames['frameName'].location.reload();

Replacing a specific frame using JavaScript

document.forms[0].target='_top';

Here index 0 indicates the first frame.

Tuesday, December 20, 2011

Multi Header Footer Gridview

You may come across a situation, where you may have to display multiple headers rather just single one, and also some of these header or footer values has to be updated dynamically.  Here is a simple example on how to do it using a simple ASPX page.

WebForm1.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Multi Header Gridview</title>
</head>
<body>
    <form id="form1" runat="server">
 
    <div id="searchArea" align=center>
        <asp:Button ID="btnGetData" runat="server" Text="Get Data" />
        <br />
 
    </div>
 
    <div align="center">
 
      <asp:GridView ID="gvwRecord" runat="server"  AutoGenerateColumns="false" FooterStyle-Wrap="false" 
                            EmptyDataText="No data is available for this search criteria." DataKeyNames="ID" AllowPaging="false"   > 
             <Columns>                                                                                                   
                <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-HorizontalAlign="left"/> 
                <asp:BoundField DataField="Name" HeaderText="Name"  ItemStyle-HorizontalAlign="left" ItemStyle-Wrap="false" /> 
                <asp:BoundField DataField="Age" HeaderText="Age"  ItemStyle-HorizontalAlign="Right"  ItemStyle-Wrap="false" /> 
                <asp:BoundField DataField="Sex" HeaderText="Sex" ItemStyle-HorizontalAlign="Right" />  
                <asp:BoundField DataField="Title" HeaderText="Title" ItemStyle-Wrap="false"/>                
            </Columns>
 
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 

WebForm1.aspx.vb

The sample is generated for the test purpose

Public Class WebForm1
    Inherits System.Web.UI.Page
 
 
    Protected Sub btnGetData_Click(sender As Object, e As EventArgs) Handles btnGetData.Click
        Dim tst As New TestRecord
        Dim recs As List(Of TestRecord) = tst.LoadData
        Session("Data") = recs
        gvwRecord.DataSource = recs
        gvwRecord.DataBind()
    End Sub
 
    Private Sub gvwRecord_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvwRecord.RowCreated
        If e.Row.RowType = DataControlRowType.Header Then
            Dim headerCell1 As TableCell = New TableCell()
            Dim headerCell2 As TableCell = New TableCell()
 
            headerCell1.ColumnSpan = 3
            headerCell1.Text = "Main Header 1"
            headerCell1.BackColor = Drawing.Color.LightGray
            headerCell1.HorizontalAlign = HorizontalAlign.Center
 
            headerCell2.ColumnSpan = 2
            headerCell2.Text = "Main Header 2"
            headerCell2.BackColor = Drawing.Color.LightGray
            headerCell2.HorizontalAlign = HorizontalAlign.Center
 
            Dim rowHeader1 As GridViewRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal)
            rowHeader1.Cells.Add(headerCell1)
            rowHeader1.Cells.Add(headerCell2)
            rowHeader1.ForeColor = Drawing.Color.Black
            rowHeader1.Font.Bold = True
            rowHeader1.Visible = True
            gvwRecord.Controls(0).Controls.AddAt(0, rowHeader1)
 
            Dim fields2 As TableCellCollection = e.Row.Cells
            Dim headerCell11 As TableCell = New TableCell()
            Dim headerCell12 As TableCell = New TableCell()
 
            headerCell11.ColumnSpan = 2
            headerCell11.Text = "ID and Name"
            headerCell11.BackColor = Drawing.Color.Maroon
 
            headerCell12.ColumnSpan = 3
            headerCell12.Text = "Age and Sex"
            headerCell12.BackColor = Drawing.Color.Maroon
 
            Dim rowHeader2 As GridViewRow = New GridViewRow(1, 1, DataControlRowType.Header, DataControlRowState.Normal)
            rowHeader2.Cells.Add(headerCell11)
            rowHeader2.Cells.Add(headerCell12)
 
            rowHeader2.Font.Size = 12
            rowHeader2.ForeColor = Drawing.Color.White
            rowHeader2.HorizontalAlign = HorizontalAlign.Center
            rowHeader2.Visible = True
            rowHeader2.Font.Bold = True
            gvwRecord.Controls(0).Controls.AddAt(1, rowHeader2)
 
        ElseIf e.Row.RowType = DataControlRowType.Footer Then
            Dim footerCell1 As TableCell = New TableCell()
            Dim footerCell2 As TableCell = New TableCell()
            Dim footerCell3 As TableCell = New TableCell()
            Dim footerCell4 As TableCell = New TableCell()
 
            Dim dataRecs As List(Of TestRecord) = Nothing
            Dim totalRec As Integer = 0
            Dim totalMale As Integer = 0
            Dim totalFemale As Integer = 0
            Dim totalAgeBelow30 As Integer = 0
            Dim totalAgeAbove30 As Integer = 0
 
 
            If Session("Data") IsNot Nothing Then
                dataRecs = DirectCast(Session("Data"), List(Of TestRecord))
                If Not dataRecs Is Nothing AndAlso dataRecs.Count > 0 Then
                    totalRec = dataRecs.Count
                    Dim list1 = From r As TestRecord In dataRecs Where r.Sex = "Male"
                    totalMale = list1.Count
 
                    Dim list2 = From r As TestRecord In dataRecs Where r.Sex = "Female"
                    totalFemale = list2.Count
 
                    Dim list3 = From r As TestRecord In dataRecs Where r.Age < 30
                    totalAgeBelow30 = list3.Count
 
                    Dim list4 = From r As TestRecord In dataRecs Where r.Age >= 30
                    totalAgeAbove30 = list4.Count
 
                End If
            End If
 
            footerCell1.Text = "Summary"
            footerCell2.Text = "Age [< 30yrs: " & totalAgeBelow30.ToString() & "] [>=30yrs:" & totalAgeAbove30.ToString() & "]"
            footerCell3.ColumnSpan = 2
            footerCell3.Text = "Male: " & totalMale.ToString() & " Female:" & totalFemale.ToString()
            footerCell4.Text = "Total Count:" & totalRec.ToString()
 
            Dim rowFooter1 As GridViewRow = New GridViewRow(gvwRecord.Rows.Count + 3, 0, DataControlRowType.Footer, DataControlRowState.Normal)
            rowFooter1.Cells.Add(footerCell1)
            rowFooter1.Cells.Add(footerCell2)
            rowFooter1.Cells.Add(footerCell3)
            rowFooter1.Cells.Add(footerCell4)
            rowFooter1.ForeColor = Drawing.Color.Black
            rowFooter1.BackColor = Drawing.Color.LightGray
            rowFooter1.HorizontalAlign = HorizontalAlign.Left
            rowFooter1.Font.Bold = True
            rowFooter1.Visible = True
 
            For cellCount As Integer = 0 To rowFooter1.Cells.Count - 1
                rowFooter1.Cells(cellCount).Wrap = False
            Next
            gvwRecord.Controls(0).Controls.AddAt(gvwRecord.Rows.Count + 3, rowFooter1)
 
        End If
    End Sub
End Class
 
Public Class TestRecord
    Public Property ID As Integer = 0
    Public Property Name As String = String.Empty
    Public Property Age As Integer = 18
    Public Property Sex As String = "Male"
    Public Property Title As String = "CEO"
 
    Public Sub New()
 
    End Sub
 
    Public Sub New(ByVal ID As Integer, ByVal name As String, ByVal age As Integer, ByVal sex As String, ByVal title As String)
        Me.ID = ID
        Me.Name = name
        Me.Age = age
        Me.Sex = sex
        Me.Title = title
    End Sub
 
    Public Function LoadData() As List(Of TestRecord)
        Dim recs As New List(Of TestRecord)
        For i = 0 To 10
            Dim rec As New TestRecord(i, "LastName" & i.ToString & ", FirstName" & i.ToString(), 25 + i, IIf(i Mod 2 = 0, "Male", "Female").ToString, "Title #" & i.ToString)
            recs.Add(rec)
        Next
        Return recs
    End Function
End Class

Output at the runtime

Wednesday, November 30, 2011

Could not load file or assembly 'Microsoft.ReportViewer.Common

You may come across the above error while configuring and deploying SQL Server Reporting Services. Complete error will look like

Error: Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified

Problem: You are missing the installation and configuration info for ReportViewer

Solution: Check the following things

1. Have you installed the Report Viewer? If not you need to download and install it from Microsoft using this link
 
http://www.microsoft.com/downloads/details.aspx?FamilyID=a941c6b2-64dd-4d03-9ca7-4017a0d164fd&displaylang=en
 
2. Reboot the Machine on which you installed the Report Viewer

3. Make sure that following configuration is added in your web.config file

<system.web>
    <httpHandlers>
      <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false" />
    </httpHandlers>
</system.web>

Thursday, November 10, 2011

The Controls collection cannot be modified because the control

If you are using ASP.NET and JavaScript, also using some client side code to read Server side variables, you may get an error specially when you put that JavaScript Code inside Head section of the pager or if you are doing a dynamic operation such as exporting the Form’s data to Excel. Your error may look like following

Error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Problem: Page is unable to read the data at client side when server variables are not yet ready.

Solution: Put a Div around your script tag and add runat=”Server”, Example is given below

<div id="Div1" runat="server">
    <script language="javascript" type="text/javascript">
 
        function DoSomething(aValue, bValue) {
            document.getElementById("<%=txtAValue.ClientID%>").value = aValue;
            document.getElementById("<%=txtBValue.ClientID%>").value = bValue;
            document.getElementById("<%=btnShowData.ClientID%>").click();
        }
 
   </script>
</div>

Thursday, September 15, 2011

Error: The [Service_Name] service terminated unexpectedly

You may see the following error in your Event Log, specially when running a Windows Service.

The [Service_Name] service terminated unexpectedly.  It has done this 1 time(s).

Problem: There could be multiple reasons for the above. But if you find that your Service executable file (.exe) has been automatically deleted then guess no further, you must be running an AntiVirus Program, which may have recently updated its definition and finding your safe service program as a threat, so it is deleting when program is trying to run.

Solution: Go to AntiVirus console and find an option to exclude the program folder or path from being checked.

You may need an administrative privilege to  perform this operation.

Tuesday, August 23, 2011

WCF Service Schema are not being updated

You may face a situation, when you are updating schema of a WCF Service under another service or .NET project, but unfortunately, the project is not updating the schema.

Solution: Make sure that project’s build output path is pointing to bin\

Friday, July 15, 2011

Multi-threaded Parallel Processing

Many times you come across a situation when you have to execute the same logic across different clients or batch. While running them in simplest manner without multi-threading, your records will be sequentially processed means your process will take longer time to finish. 

You can speed up the above process by implementing multi-threaded parallel processing in few lines of code. To keep it simple in this example, you have to make sure that you have distinct batches or set of records which will not interfere or overlap during this processing. Here is how you can implement in quickest possible manner, make sure your machine has enough processing and threading capabilities.

Step 1

Create a property of method so that you can dynamically set the no of threads if needed

Private ReadOnly Property MaxAllowableThreadCount() As Integer
        Get
            'You can define this value in config file 
            Dim maxThreadCount As Integer = 15
            Return maxThreadCount
        End Get
    End Property

Step 2

Following is the example of multi threading or parallel processing code. Assuming each client will have unique set of records.

Private Function ProcessAllClients() As Integer
      Dim clientList As New List(Of String)
      Dim exceptionMessages As New List(Of String)
      Dim totalNoOfRecProcessed As Integer = 0
 
      'Add some Test Clients
      clientList.Add("A1")
      clientList.Add("A2")
      clientList.Add("A3")
 
 
      If clientList IsNot Nothing AndAlso clientList.Count > 0 Then
          'Customize No of Threads you may want to use as per need or you can simply use a value
          Dim noOfThreadCounts As Integer = MaxAllowableThreadCount
          Dim noOfClients As Integer = clientList.Count
          Dim noOfThreadsGroup As Integer = 0
 
          'Adjust No of Loops as per max allowable thread
          If (noOfClients Mod noOfThreadCounts = 0) Then
              noOfThreadsGroup = CInt(Math.Floor(noOfClients / noOfThreadCounts))
          Else
              noOfThreadsGroup = CInt(Math.Floor(noOfClients / noOfThreadCounts)) + 1
          End If
 
          'Set clients in each group/loop 
          For threadGroup As Integer = 0 To noOfThreadsGroup - 1
              Dim processingTaskCounter As Integer = noOfThreadCounts
 
              If threadGroup = (noOfThreadsGroup - 1) AndAlso (noOfClients Mod noOfThreadCounts > 0) Then
                  processingTaskCounter = noOfClients Mod noOfThreadCounts
              End If
 
              Dim allProcessingTasks(processingTaskCounter - 1) As Task(Of Integer)
              Dim clinetsToProcess As New List(Of String)
              Dim taskCounter As Integer = 0
 
              For i = 0 To processingTaskCounter - 1
                  clinetsToProcess.Add(clientList(CInt(threadGroup * noOfThreadCounts) + i))
              Next
 
              For Each clientCode As String In clinetsToProcess
                  Try
                      Dim currentClient As String = clientCode
                      allProcessingTasks(taskCounter) = New Task(Of Integer)(Function()
                                                                                 Dim pHelper As New ProcessHelper
                                                                                 Return pHelper.ClientProcessingLogic(currentClient)
                                                                             End Function)
                      taskCounter = taskCounter + 1
 
                  Catch ex As Exception
                      exceptionMessages.Add("Sorry! Error Occurred." & ex.Message)
                      totalNoOfRecProcessed = 0
                  End Try
              Next
 
              'Now Execute all client's tasks as once but in seperate thread
              Array.ForEach(allProcessingTasks, Sub(tx) tx.Start())
 
              'Wait till all finishes processing
              Task.WaitAll(allProcessingTasks)
 
              For Each tsk In allProcessingTasks
                  Select Case True
                      Case tsk.IsCanceled
                          exceptionMessages.Add("Task ID" & tsk.Id & " was canceled.")
                      Case tsk.IsFaulted
                          exceptionMessages.Add("Task ID" & tsk.Id & " was faulted.")
                      Case tsk.IsCompleted
                          totalNoOfRecProcessed += tsk.Result
                      Case Else
                          exceptionMessages.Add("Task ID" & tsk.Id & " was in unknown status.")
                  End Select
              Next
          Next
      End If
      Return totalNoOfRecProcessed
  End Function

Step 3

Call the Step 2 from wherever you want to call it

Dim allItemsProcessedCount As Integer = ProcessAllClients()

Now you can see the difference in processing time and no of records processed during one call.