Thursday, August 29, 2013

Extent (Error_ID) in database ID (DB_ID) is marked allocated in the GAM, but no SGAM or IAM has allocated it

Problem: I am getting a database error while checking database with DBCC CHECKDB command. The error message:
Extent (Error_ID) in database ID (DB_ID) is marked allocated in the GAM, but no SGAM or IAM has allocated it.

Solution: To resolve this error first try these sql commands:

    sp_dboption AMMS, single, true
    sp_dboption AMMS, single, false

This will  repair the error with no data loss.

In case of failure of above statements please try with following commands:

    exec sp_dboption AMMS, single, true
    begin try
    DBCC CHECKDB (AMMS, repair_allow_data_loss)
    end try
    begin catch
    DBCC CHECKDB (AMMS, repair_allow_data_loss)
    end catch
    exec sp_dboption AMMS, single, false

There may occur data loss with this statement.

This problem generally occurs when there is some hardware errors. Run hardware diagnostics and correct any problems. Fix any hardware related problems. It might find it beneficial to switch to a completely new hardware system.

How to find out database error?

Problem: How can I find out errors in SQL Server database?

Solution: While running database for a long time on live, it may occur some error in database. To find out database error DBCC CHECKDB command is commonly used. DBCC CHECKDB find out database memory allocation and structural integrity of all object in the specified database. DBCC CHECKDB performs a physical consistency check. DBCC CHECKDB is the safest repair statement because it identifies and repairs the most of the possible errors.

Lets See the syntax of DBCC CHECKDB command:
    ( 'database_name'
    )    [ WITH { [ ALL_ERRORMSGS ]
                    [ , [ NO_INFOMSGS ] ]
                    [ , [ TABLOCK ] ]
                    [ , [ ESTIMATEONLY ] ]
                    [ , [ PHYSICAL_ONLY ] ]

Lets see some important arguments:

'database_name': Name of the database you want to check for memory allocation and structural integrity errors.
NOINDEX: Specifies that non-clustered indexes should not be checked.

REPAIR_FAST: Performs minor, quick repair actions. No risk of data loss.
REPAIR_REBUILD: Performs all repairs done by REPAIR_FAST and repair actions like rebuilding indexes. No risk of data loss.
REPAIR_ALLOW_DATA_LOSS: This performs all repair actions done by REPAIR_REBUILD and includes allocation and reallocation of rows and pages for correcting allocation errors, structural row or page errors, and deletion of corrupted text objects.

Note: Database requires to be in single user mode while specified these arguments.

Example of commands:
1. Check current database errors

2. Check specified database without non-clustered indexes:

3. Check database errors with REPAIR_REBUILD specified:
    sp_dboption AMMS, single, true
    sp_dboption AMMS, single, false

4. Check database errors with REPAIR_ALLOW_DATA_LOSS specified:
    exec sp_dboption AMMS, single, true
    begin try
    DBCC CHECKDB (AMMS, repair_allow_data_loss)
    end try
    begin catch
    DBCC CHECKDB (AMMS, repair_allow_data_loss)
    end catch
    exec sp_dboption AMMS, single, false

Tuesday, January 22, 2013

How to filter special characters from user input?

I am using a textbox to capture user entry to create a custom SQL select statement. I have everything working fine but I get an exception thrown when I wanted to search by city name and I entered, "Cox's Bazar" in the textbox.
In this case you need to filter special characters from user input values that produce this error. You can filter user inputs using following method in your string helper class:

        /// <summary>
        /// Replace UnWanted Character from string
        /// </summary>
        /// <param name="input">Input string</param>
        /// <returns></returns>
        public static string ReplaceUnWantedCharacter(string input)
            input = input.Replace('+', ',');
            input = input.Replace("--", "++");
            input = input.Replace('&', ',');
            input = input.Replace("%", "[%]");
            input = input.Replace("_", "[_]");
            input = input.Replace("[", "[[]");
            input = input.Replace("]", "[]]");
            input = input.Replace("'", "''");
                        return input;

the use of this method may be like:
string cityName = StringHelper.ReplaceUnWantedCharacter(txtCityName.Text.Trim());

Sunday, January 20, 2013

Crystal Report Performance Improvement Tips

How can I improve performance of crystal report in my web application?

Solution: Here is some important tips for improvement of crystal report performance in a web application:
1. Avoid using Linked OLE object if not extremely necessary. Locating OLE object is potentially time consuming.
2. Avoid using Sub-report if you can do same without sub-report. Incorrect use of sub report may have huge impact on performance.
3. Avoid special functions: Page N of M, Total Page Count. This cause the report more time to display first page.
4. Avoid unnecessary use of graphics. This may cause disk I/O which will impact on performance.
5. Remove un-used objects from report.
6. Remove or suppress unnecessary report section.
7. If summaries are used in the report, use conditional formulas instead of running totals when ever possible.
8. Whenever possible, limit records through Record selection Formula, not suppression. Return only necessary data from your data source.
9.  Perform grouping on database server.
10.Disable report option Verify of First Refresh and Verify Stored Procedure on First Refresh.

Hope this will help.

Please feel free to add your valuable comments.

Wednesday, January 16, 2013

Important points that programmers should remember while developing web application software

I have tried to find out some points that every programmer should remember while coding in web application:
1. Do R&D about business logic and make a plan how you will implement it before you start writing code.
2. Should write code easy, understandable and maintainable way.
3. Make sure you are developing application wide consistent look and feel.
4. Should think in OOP way. 
5. Try best practices that are established in the industry.
6. Maintain Naming convention
7. Transaction should be used properly and where necessary.
8. Remember concurrency issue while coding. 
9. Validation should be checked properly. Validation should be done at client side so far possible.
10. User or role based permission should be implemented properly so that user can’t do anything if not permitted.
11. Should do comments where necessary.
12. Should be aware about security of application and database.
13. Write less code to do more jobs. Do re-factor where possible.
14.  Think about performance of your code.
15. Make use of client side Ajax.
16. Be aware of hacking options like Sql Injection, Cross Site Scripting etc.
17. Should do paging on database end where data is more than 20 in grid.
18. Do less use of Session and ViewState.
19. Do caching where possible.
20. Always check existence of an object before accessing it.
21. Be careful about exception handling.
22. Write error log to identify errors.
23. Make sure you dispose large objects.
24. Grid should have a SL column.
25. Dropdown or combo values should be in a specific order.
26. Remove unnecessary code and comments from your page.
27. Set a title in each page. Don’t keep it like Untitled Page.
28. Include search option when data is more than 100 records in a page.
29. Use Namespace properly for pages and code files.
30. Show short and friendly error message to user but log error details.
31. Do not have more than one class in a single class.
32. Please write copy right and author information at the top of each file.
33. Avoid unnecessary round trip to database server. Use batch SQL statement to reduce round trip.
34. Use light weight controls. Choose controls carefully for your page.
35. Make your database normalized.
36. Make sure optimization of your queries.
37. Always deploy release build of your application.
38. Use release build and minimized version of any third party controls used.
39. Deploy your application on staging first and do all testing in staging.
40. Before deployment in production make sure necessary configuration and changes are done properly if needed. For example setting up new encryption key, encrypting sensitive information and setup application settings information etc. 
41. Develop a way to notify users with friendly message while doing some changes or maintenance task after deployment.
42. Make sure to check all major functionality is working properly after deployment.

Monday, December 17, 2012

How to get list of sql server database objects?

Problem: How to get list of database objects?

 Solution: You can get list of objects in two ways.

1. Getting the list from sys.objects table. Ex:
List of tables:

FROM sys.objects where type='U'

List of stored procedures:

FROM sys.objects where type='P'

List of views:

FROM sys.objects where type='V'

2. Getting the list query from object related tables. Ex:

List of tables:

FROM sys.Tables

List of stored procedures:

FROM sys.procedures

List of views:

FROM sys.views

How to remove all data from table and reseed identity column to initial value?

Problem: How to remove all data from table and reseed identity column to initial value?

 Solution: For this purpose best solution is to use truncate sql command when you want to delete all data and reset identity column value to initial value.

Somebody uses the following command which results same output:


Tuesday, November 6, 2012

New blog on Ext.Net

I have started writing on Ext.Net in a new blog( that will be dedicated to Ext.Net technologies. Now a day I am working on Ext.Net and developing all my web application with highly used Ext.Net. I have faced many problems while started working. So I would like to share my knowledge and finding with developers on the community so that they get help in their work. Hope this will be helpful.


Saturday, November 3, 2012

Display Gridpanel cell tooltip in Ext.Net

You often want to display tooltip using cell data when data length overflows column width in your gridpanel. You will get an example to show tooltip with gridpanel cell data here:
But this is not working properly when it is included in some project especially if you have master page based design. I have tried this in my project and it worked properly with little bit changes. Here I want to share the codes with you guys:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <link href="../Style/examples.css" rel="stylesheet" type="text/css" />
    <ext:XScript ID="XScript1" runat="server">
        <script type="text/javascript">
            var showTip = function () {
                var rowIndex = #{gpList}.view.findRowIndex(this.triggerElement),
                cellIndex = #{gpList}.view.findCellIndex(this.triggerElement),
                record = #{gpListStore}.getAt(rowIndex),
                fieldName = #{gpList}.getColumnModel().getDataIndex(cellIndex),
                data = record.get(fieldName);
                if (data ==null){
                this.body.dom.innerHTML = "";
                this.body.dom.innerHTML = data;

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <ext:ResourceManager ID="rcm" runat="server">
    <ext:Hidden ID="hfPK" runat="server">
    <ext:TabPanel ID="tPnlMain" runat="server" ActiveTabIndex="0" AnchorHorizontal="100%"
        Height="500" Plain="true" Visible="true" Width="1024">
<ext:Panel ID="Tab2" runat="server" Title="Employee Search" Padding="1" AutoScroll="true">
                    <ext:RowLayout runat="server">
                            <ext:LayoutRow RowHeight=".25">
                                <ext:Panel ID="Panel1" runat="server" Header="false" Padding="1" AutoScroll="true">
                            <ext:LayoutRow RowHeight=".75">
                                <ext:Panel ID="Panel3" runat="server" Title="Employee List" Padding="1" AutoScroll="true">
                                        <ext:GridPanel ID="gpList" runat="server" StripeRows="true" AutoExpandColumn="EmployeeName"
                                            Collapsible="true" AnchorHorizontal="100%" Height="322" TrackMouseOver="true">
                                                <ext:Store ID="gpListStore" runat="server">
                                                        <ext:JsonReader IDProperty="EmployeeId">
                                                                <ext:RecordField Name="EmployeeId" />
                                                                <ext:RecordField Name="EmployeeName" />
                                                                <ext:RecordField Name="EnrollId" />
                                                                <ext:RecordField Name="FirstName" />
                                                                <ext:RecordField Name="MiddleName" />
                                                                <ext:RecordField Name="LastName" />
                                                                <ext:RecordField Name="AddressLine1" />
                                                                <ext:RecordField Name="DepartmentId" />
                                                                <ext:RecordField Name="DesignationId" />
                                                                <ext:RecordField Name="PolicyId" />
                                                                <ext:RecordField Name="CardNumber" />
                                                                <ext:RecordField Name="DesignationName" />
                                                                <ext:RecordField Name="DeptName" />
                                                                <ext:RecordField Name="SbuName" />
                                            <ColumnModel ID="ColumnModel1" runat="server">
                                                    <ext:RowNumbererColumn />
                                                    <ext:CommandColumn Header="Action" Width="65">
                                                            <ext:GridCommand Icon="ApplicationEdit" CommandName="Edit">
                                                                <ToolTip Text="Edit" />
                                                    <ext:Column ColumnID="cEnrollId" Header="Enroll Id" DataIndex="EnrollId" Width="50" />
                                                    <ext:Column ColumnID="cStaffCode" Header="Employee Code" DataIndex="StaffCode" Width="70" />
                                                    <ext:Column ColumnID="cEmployeeName" Header="EmployeeName" DataIndex="EmployeeName"
                                                        Width="130" />
                                                    <ext:Column ColumnID="cDesignationName" Header="Designation" DataIndex="DesignationName"
                                                        Width="150" />
                                                    <ext:Column ColumnID="cDepartmentName" Header="Department" DataIndex="DeptName" Width="100" />
                                                    <ext:Column ColumnID="cSbuId" Header="Branch" DataIndex="SbuName" />
                                                    <ext:Column ColumnID="cAddressLine1" Header="Address" DataIndex="AddressLine1" Width="180" />
                                                <ext:RowSelectionModel ID="RowSelectionModel1" runat="server" SingleSelect="true" />
                                                <ext:PagingToolbar ID="gpListPager" runat="server" PageSize="20" />
                                                <Command Handler=",,;" />
                                                <ext:ToolTip ID="RowTip" runat="server" Target="#{gpList}.getView().mainBody" Delegate=".x-grid3-cell" ShowDelay="0"
                                                        <Show Fn="showTip" />

Hope this will help my friends.

Friday, November 2, 2012

How to export data to excel?

Recently, I have worked on export data to excel and import data from excel. I have face many problems while working on this. So I have searched for different ways for doing export and import from excel. I would like to share with you guys different export methods so that you can easily try it.

Way 1: using Open XML when working with Office 2007 or later version

protected void ExportToExcel(DataTable dt, List<string> columnNames, string fileName)
        MemoryStream stream = DocumentFormat.OpenXml.Extensions.SpreadsheetReader.Create();
        DocumentFormat.OpenXml.Packaging.SpreadsheetDocument doc = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(stream, true);
        DocumentFormat.OpenXml.Packaging.WorksheetPart worksheetPart = DocumentFormat.OpenXml.Extensions.SpreadsheetReader.GetWorksheetPartByName(doc, "Sheet1");
        DocumentFormat.OpenXml.Extensions.WorksheetWriter writer = new DocumentFormat.OpenXml.Extensions.WorksheetWriter(doc, worksheetPart);

        //writer.PasteText("B2", "Hello World");
        DataTable dtc = new DataTable();
        for (int i = 0; i < columnNames.Count; i++)
            dtc.Columns.Add(new DataColumn(columnNames[i]));
        DataRow dr = dt.NewRow();
        for (int i = 0; i < columnNames.Count; i++)
            dr[i] = columnNames[i];
        dt.Rows.InsertAt(dr, 0);
        writer.InsertDataTable(dt, "A1", columnNames);
        //writer.PasteDataTable(dtc, "A1");
        //Save to the memory stream

        //Write to response stream
        this.Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", fileName));
        this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";


Way 2: working with office automation

protected void Exporttoexcel2(DataTable dt, string fileName)
        off.Application excel = new off.Application();
        off.Workbook workbook = excel.Application.Workbooks.Add(true);
        int iCol = 0;
        foreach (DataColumn c in dt.Columns)
            excel.Cells[1, iCol] = c.ColumnName;

        int iRow = 0;
        foreach (DataRow r in dt.Rows)
            iCol = 0;
            foreach (DataColumn c in dt.Columns)
                excel.Cells[iRow + 1, iCol] = r[c.ColumnName];

        string path = string.Empty;
        path = Server.MapPath("~/TempFiles/");
        path = path + fileName;

        object missing = System.Reflection.Missing.Value;
        workbook.SaveAs(path, off.XlFileFormat.xlXMLSpreadsheet, missing, missing, false, false, off.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
        excel.Visible = true;
        off.Worksheet worksheet = (off.Worksheet)excel.ActiveSheet;

        this.Response.ContentType = "application/";
        this.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + "");

Way 3: working with ExcelPackage library

protected void Exporttoexcel3(DataTable dt, string fileName)
        FileInfo newFile = new FileInfo(fileName);
        using (ExcelPackage xlPackage = new ExcelPackage(newFile))
            xlPackage.DebugMode = true;
            ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add(fileName);
            for (int i = 0; i < dt.Columns.Count; i++)
                worksheet.Cell(1, i + 1).Value = dt.Columns[i].ColumnName;

            for (int r = 0; r < dt.Rows.Count; r++)
                for (int i = 0; i < dt.Columns.Count; i++)

                    worksheet.Cell(r + 2, i + 1).Value = Convert.ToString(dt.Rows[r][i]);