Monday, December 10, 2012

Operation is not valid due to the current state of the object Error

I got this error when I tried to save a Page with lots of form fields to SQL Server Database
The default max number of form fields that can be post is 1000.
Solution:
In order to solve this error add this Line to your Web.Config File:

   1:  <appSettings>
   2:  <add key="aspnet:MaxHttpCollectionKeys" value="10000" />
   3:  </appSettings>

Saturday, November 3, 2012

Programmatically Creating an ASP.NET GridView Control


The biggest project I’ve worked on in the past year involved building almost all of the ASP.NET controls for a page programmatically in the code-behind and putting them into a Placeholder, rather than declaring them in the markup file.
Many ASP.NET controls are relatively easy to build this way.  Buttons, TextBoxes, Labels, DropDownLists, even SqlDataSources can be created using a few simple lines of code.
Adding a print Button can be this simple:
Dim btnPrint As New Button
btnPrint.Attributes.Add("onclick", "javascript:window.print();")
btnPrint.Visible = False
Placeholder1.Controls.Add(btnPrint)



The instructions for adding simple controls such as these can be easily found on MSDN and many other sites.  Unfortunately,  instructions for building a complex GridView were nowhere to be found.  Take heart: It can be done!
Adding a GridView control is generally much more complicated than this, and also requires many more attributes.  Each column must be declared and added to the GridView prior to the GridView itself being added to the Form / Panel / Placeholder, etc.  Also, attributes like sorting, paging, Edit / Cancel Buttons must be taken into consideration.
Here is an example of the VB code for a full-featured GridView:
Dim gvExample As New GridView
With gvExample
.ID = "gvExample"
.CssClass = "gridview"
.DataSource = dvExample
.AutoGenerateColumns = False
.CellPadding = 4
.DataKeyNames = New String() {"ExampleID"}
.ForeColor = Drawing.ColorTranslator.FromHtml("#2a2723")
.GridLines = GridLines.None
.Width = Unit.Percentage(100)
.AllowSorting = True
.AllowPaging = False

Dim strHeadBack As String = "#ffcb00"
Dim strPagerBack As String = "#009ddb"
Dim strForeColor As String = "#000000"

.HeaderStyle.BackColor = Drawing.ColorTranslator.FromHtml(strHeadBack)
.HeaderStyle.Font.Bold = True
.HeaderStyle.ForeColor = Drawing.ColorTranslator.FromHtml(strForeColor)

.RowStyle.BackColor = Drawing.ColorTranslator.FromHtml("#FFFBD6")
.RowStyle.ForeColor = Drawing.ColorTranslator.FromHtml("#2a2723")
.RowStyle.HorizontalAlign = HorizontalAlign.Center

.AlternatingRowStyle.BackColor = Drawing.Color.White

.BorderColor = Drawing.ColorTranslator.FromHtml("#d80073")
.BorderStyle = BorderStyle.Groove

.Columns.Clear()

Dim ViewButton As New ButtonField
ViewButton.HeaderText = "View"
ViewButton.ButtonType = ButtonType.Button
ViewButton.Text = "View"
ViewButton.CommandName = "ViewExample"
.Columns.Add(ViewButton)

Dim EditButton As New TemplateField
EditButton.HeaderText = "Edit"
EditButton.ItemTemplate = New MyButtonTemplate ' This is a user-defined class that creates this Button
EditButton.Visible = bEditVisible
.Columns.Add(EditButton)

Dim Voided As New CheckBoxField
Voided.HeaderText = "Voided"
Voided.DataField = "Voided"
Voided.ReadOnly = True
Voided.Visible = bVoidVisible
.Columns.Add(Voided)

Dim ExampleDate As New TemplateField
ExampleDate.HeaderText = "Date/Time"
ExampleDate.SortExpression = "Date_and_Time"
ExampleDate.ItemTemplate = New MyLabelTemplate ' This is a user-defined class that creates this Label
ExampleDate.ItemStyle.Wrap = False
.Columns.Add(ExampleDate)

Dim ShortColumn As New BoundField
ShortColumn.ItemStyle.CssClass = "left"
ShortColumn.HeaderText = "Short Column"
ShortColumn.SortExpression = "Short_Column"
ShortColumn.DataField = "Short_Column"
ShortColumn.ItemStyle.Wrap = True
ShortColumn.ItemStyle.Width = 150
.Columns.Add(ShortColumn)

Dim LongColumn As New BoundField
LongColumn.ItemStyle.CssClass = "left"
LongColumn.HeaderText = "Long Column"
LongColumn.SortExpression = "Long_Column"
LongColumn.DataField = "Long_Column"
LongColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Left
LongColumn.ItemStyle.Wrap = True
LongColumn.ItemStyle.Width = 200
.Columns.Add(LongColumn)

Dim CreatedBy As New BoundField
CreatedBy.HeaderText = "Created By"
CreatedBy.SortExpression = "CreatedBy"
CreatedBy.DataField = "CreatedBy"
.Columns.Add(CreatedBy)

.Visible = True
.PageIndex = GridViewPageIndex ' I used a Session variable to store the page number
Placeholder1.Controls.Add(gvExample)
.DataBind()
End With



Separate routines that handle the Sorting and PageIndexChanging events must be manually created if you want these functions to be included with your GridView.  In these modules, you can use Session variables to store the page numbers and sort direction.  It might be possible to use ViewState variables instead, though I did not try that here.  Also, a module that handles RowCommand events must be created if any buttons that are added to the GridView do something that is row-specific.
It is certain that creating a GridView programmatically is much more difficult than dragging and dropping from the Toolbar onto the Design page.  However, that may not always be the best way if you are creating a highly dynamic application, such as one where even the fundamental design of a page is database-driven.

Add Normal Column and Template Column Dynamically in Asp.net GridView

in most of case we build GridView statically or let asp.net do it it self but what if we want to add Columns to GridView Dynamically.like you may want to add TemplateField  with Several controls within it with code too.

Fist we will see how to add Normal column to GridView at runtime.
BoundField FirstName = new BoundField();
FirstName.DataField = "Some Database Field";
FirstName.HeaderText = "First Name";

GridView1.Columns.Add(FirstName);
Next , How to add Field With Custom template.to add Column with custom template you need to First Define Template using code for that you need to implement ITemplate interface. here is sample code about doing it .
/* Create Template Field by Implementing ITemplate */
public class MyCustomTemplate:ITemplate
{
    public void InstantiateIn(System.Web.UI.Control container)
    {
        CheckBox cb = new CheckBox();
        cb.ID = "testCheckBox";
        cb.Text = "Test";
        container.Controls.Add(cb);
    }
}
/* Adding Field With Template */
TemplateField tf = new TemplateField();
tf.HeaderText = "Custom Template Field Column";
tf.ItemTemplate = new MyCustomTemplate();

GridView1.Columns.Add(tf);
above example We Created Template of Item within the column with one check box by Implementing ITemplate Interface which we can set as Item Template while we Add TemplateField in GridView.

How to create template columns dynamically in a grid view


Sample Program:

Imports System.Data
Imports System.Web.UI.WebControls
Public Class MyCustomTemplate
    Implements ITemplate
    Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
        Dim cb As New CheckBox()
        cb.ID = "PageID"
        AddHandler cb.DataBinding, AddressOf CheckBox_DataBining
        container.Controls.Add(cb)
    End Sub
    Public Sub CheckBox_DataBining(ByVal sender As Object, ByVal e As EventArgs)
        Dim button As CheckBox = TryCast(sender, CheckBox)
        Dim container As GridViewRow = CType(button.NamingContainer, GridViewRow)
        Dim dataValue As Object = DataBinder.Eval(container.DataItem, "id")
        If Not IsDBNull(dataValue) Then
            button.Text = dataValue.ToString()
        End If
    End Sub
End Class
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub _Default_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Dim tf As New TemplateField()
        tf.HeaderText = "Custom Template Field Column"
        tf.ItemTemplate = New MyCustomTemplate()
        gvoutput.Columns.Add(tf)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim dt As New DataTable

            dt.Columns.Add("id", GetType(Long))
            dt.Rows.Add(1)
            dt.Rows.Add(2)
            dt.Rows.Add(3)
            dt.Rows.Add(4)

            gvoutput.DataSource = dt
            gvoutput.DataBind()

        End If
    End Sub
  
    Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
        Try
            Dim a As Long = 0

            For i As Integer = 0 To gvoutput.Rows.Count - 1
                Dim row As GridViewRow = gvoutput.Rows(i)
                Dim isChecked As Boolean = CType(row.FindControl("PageID"), CheckBox).Checked
                If isChecked Then
                    a = a + 1
                End If
            Next

            Response.Write(a)
        Catch ex As Exception

        End Try
        
    End Sub
End Class

Display a certain number of rows to columns on crystal report




For example


SQL Rows

Name
Fred
Jack
Dan
Bryan
Chris
Paul
William

This is what i need on the Crystal report

___Fred ___Jack ___Dan ___Bryan

___Chris ___Paul ___ William

Solution:


Here's what you need to do:

1) Place the fields on the details section
2) Go the Section Expert > select Details section > check "Format with multiple columns"
3) Then go to the Layout tab in the same window, set the width to 2.00 inches (you would need to play with this depending on the size of field)
4) Then check the option "Across then Down"
5) To draw the line, simply use the Line Object before the field





Thursday, October 25, 2012

SQL Server 2005 Expess – How to fix error 3417


Error:
The SQL Server service could not be started.
I have been getting the error 3417 (SQL Server service terminated with service-specific error 3417…).There was also a reference to the mastlog.ldf file, which is the Master’s database log file.
The database files usually reside on a folder like “C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data”. Therefore I checked that the master.mdf and mastlog.ldf were present.

Solution; 

All I had to do, was to add on the “Data” folder (mentioned above) security/permission settings, the “NETWORK SERVICE” account.

Cannot start SQL Server service + SQL Server 2005 Error 3417


When I try to start the Sql Server (MSSQLSERVER) or  Sql Server (SQLEXPRESS) services, get the following error :

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 3417.
After that, I looked at eventvwr. This is the error.
The file "C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\modellog.ldf" is compressed but does not reside in a read-only database or filegroup. The file must be decompressed.

SOLUTION :
Go to the folder C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\ and select all the files
and right click advanced, uncheck, “Compress contents to save disk space”.
That`s it,piece of cake. Now you can start the services. Try it.

Monday, October 8, 2012

SQL SERVER bottom to top order records hierarchy like parent and childid in a recursive CTE


SQL QUERY FOR TREE HIREARCHY BOTTOM TO TOP
DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
        SELECT   a.ParentID, a.CustID
        FROM     tblCustomer AS a
        WHERE    a.CustID = @LookupID
    UNION ALL
        SELECT   a.ParentID, a.CustID
        FROM     tblCustomer AS a
        INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
        WHERE c.CustID <> a.CustomerID)
So if tblCustomer looks like this:
ParentID    CustID5            5
1            8
5            4
4            1

Tuesday, September 25, 2012

installtuil – System.Security.SecurityException: The source was not found, but some or all event logs could not be searched

The lesson for this one is when in doubt, explicitly run as administrator.  Even though my colleague is an administrator to his Windows 7 machine, when he dropped to DOS prompt to install a service using installutil, he got an error message:


"Removing EventLog source service.
An exception occurred during the uninstallation of the System.Diagnostics.EventLogInstaller installer.
System.Security.SecurityException: The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security.
An exception occurred while uninstalling. This exception will be ignored and the uninstall will continue. However, the application might not be fully uninstalled after the uninstall is complete."



To get around this, we simply right clicked on  Command Prompt icon and chose to “Run as administrator“.  Then the installutil call worked fine and dandy.

Tuesday, September 18, 2012

Auto Resizing Images for Mobile Screens


One thing that I found out very quickly when working with jQuery Mobile was that my images did not auto resize to the device. If I made an image that was fairly large and looked ready for an iPad screen, that same image would be off in some way when viewed from an iPhone.
REMOVE HEIGHT AND WIDTH FROM YOUR IMG TAGS
After doing some research I found a simple fix that I wanted to share. There are a couple of things you need to do but the first thing is to not assign width and height dimensions for your images. For example, when you are inserting an image inside your HTML, typically you assign a width and a height to the image you insert, but when you are working with multiple screen sizes you don’t want your images to always be that size. If you assign a width and height to the image then no matter what that image will be that width and height and will never resize to the size you need. So again, do not assign width and height attributes to any of the images you want to resize, and it should look something like this

ADDING THE CSS TO MAKE IT ALL WORK
Now comes the important part, After you have removed all the width and height attributes from your img tags add this section to your main css file.
img, object{ max-height:90%; max-width:90%; }
You can change the max-height and max-width to whatever you want but we are addressing the objects within the img tags which in this case is the actual images and saying you have a max height/width of 90% that means you cannot go beyond 90% of the screen real-estate so if your image is wider than 90% it will auto resize but it will keep your image proportional. So I can take an image that would look great on an iPad and use it for an iPhone and not worry about it going off the screen.
CENTERING THE IMAGE
One other thing I am asked a lot is how to center the image. If you are targeting mobile then most likely the browser will support HTML5 so you can use HTML5′s center tag to accomplish this like the following.
<center><br /></center>
By wrapping the image inside of the center tags, it will always center my image in the middle of the screen. You can do this with any HTML element so it does not have to be an image.

Sunday, September 2, 2012

Removing both table and span tags from asp:DataList


A DataListis rendered with <table> or <span> tags, which I don't want.
I've set RepeatLayout="Flow" but that still gives me spans. I've setRepeaterDirection="Horizontal" but that still give me the tables.
how can i get a simple datalist without all the spans \ tables?

Solution 1:

 you might find it easier to use a repeater which will allow you to set your own markup.
Bascially, create an asp repeater, bind your data to it in much the same way as the datalist, and build your markup in the "itemtemplate " tag. (warning this is from memory - I'm on my roving laptop, so don't have Visual Studio to check syntax.)
<asp:Repeater runat="server" id="MyRepeater">
    <HeaderTemplate><h1>My Data Title</h1></HeaderTemplate>
    <TtemTemplate>
        <p>Any Markup you want. This bit gets repeated</p>
        <%#Container.DataItem("DataKeyOrColumnName")%>
    </ItemTemplate>
    <FooterTemplate><p>The footter (and header) only appear once.</p><p>you could use them to start and end a list or table</p></FooterTemplate>
</asp:Repeater>
You will only get the markup you put in the templates, nothing else. You can skip the header and footer if you don't need them. And if you want no markup at all, just have no tags in your template, the data will come out as plain text.

Solution 2:

Sometimes you can't use Repeater, because DataList provides additional possibilities (like updating the database via UPDATE and DELETE commands, working directly with the asp:DataSource).
Therefore, if you still need to use DataList but want to avoid it's html, you can do a bit of jQuery on top of it as I did it.
aspx code:
<ul class="list">
    <asp:DataList ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" DataKeyField="photo_id" RepeatLayout="Flow" RepeatDirection="Horizontal">
        <ItemTemplate>
            <li class="item" id='<%# Eval("photo_id") %>'>
                Whatever else you need here.
            </li>
            </ItemTemplate>
        </asp:DataList>
    </ul>
This will produce HTML like this:
<span id="SomeId" style="">
   <span>
      <li class="item ui-droppable" id="31349">
        Whatever else you need here.
     </li>
   </span>
</span>
Obviously there are 2 span tags you don't need. To remove them, you can add jQuery script on the page.
<script type="text/javascript">
$(document).ready(function () {
    $('.item').unwrap(); $('.item').unwrap();
});
</script>
In my case, I wanted to produce unordered list that I control. But as obvius, you can do it any other way by changing the HTML in DataList and targeting the right item in jQuery (.item).
Hope this helps someone else that needs DataList functionality and can't do it with Repeater.