Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

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
    DBCC CHECKDB (AMMS, REPAIR_REBUILD)
    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.

Tuesday, January 22, 2013

How to filter special characters from user input?

Problem:
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.
Solution:
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>
        [DebuggerStepThrough()]
        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

Problem:
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.

Thursday, October 25, 2012

How can I reorder columns in a data table?

Problem: How can I reorder columns in a data table?

 Solution: Columns in datatable can be reordered using SetOrdinal method of datatable.
Here is an example code:


DataTable dt = new DataTable();
dt = lst.GetDataTable();
dt.Columns["bank"].SetOrdinal(6);
dt.Columns["remarks"].SetOrdinal(dt.Columns.Count - 1);

Here "bank" column will be set at position 6 and "remarks" column at last of all columns in the table.

Hope this small tips will be helpful.


How can I convert Datatable to Generic List and vice versa in C#?

Problem: I need to convert Generic list to Datatable and Data table to Generic list. How can I do this in C#?

 Solution: You may often require to convert your Datatable to Generic list of your Generic list to Datatable. Following code snippet use extension method for the conversion:




using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Text;

/// <summary>
/// Summary description for GenericListExtensionMethod
/// </summary>
public static class GenericListExtensionMethod
{
    public static DataTable GetDataTable<T>(this List<T> obj)
    {
        DataTable dt = new DataTable();
        //special handling for value types and string
        if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
        {
            DataColumn dc = new DataColumn("Value");
            dt.Columns.Add(dc);
            foreach (T item in obj)
            {
                DataRow dr = dt.NewRow();
                dr[0] = item;
                dt.Rows.Add(dr);
            }
        }

        else//for reference types other than  string
        {

            //find all the public properties of this Type using reflection
            PropertyInfo[] piT = typeof(T).GetProperties();
            foreach (PropertyInfo pi in piT)
            {
                //create a datacolumn for each property
                if (pi.PropertyType.Name.Contains("Nullable"))
                {
                    DataColumn dc = new DataColumn(pi.Name, typeof(string));
                    dt.Columns.Add(dc);
                }
                else
                {
                    DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
                    dt.Columns.Add(dc);
                }
            }

            //now we iterate through all the items in current instance, take the corresponding values and add a new row in dt
            for (int item = 0; item < obj.Count; item++)
            {
                DataRow dr = dt.NewRow();

                for (int property = 0; property < dt.Columns.Count; property++)
                {
                    dr[property] = piT[property].GetValue(obj[item], null);
                }

                dt.Rows.Add(dr);
            }
        }

        return dt;
    }

    public static List<T> ToCollection<T>(this DataTable dt)
    {
        List<T> lst = new List<T>();
        Type tClass = typeof(T);
        PropertyInfo[] pClass = tClass.GetProperties();
        List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList();
        T cn;
        foreach (DataRow item in dt.Rows)
        {
            cn = (T)Activator.CreateInstance(tClass);
            foreach (PropertyInfo pc in pClass)
            {
                string ptp = pc.PropertyType.Name;
               
                DataColumn d = dc.Find(c => c.ColumnName == pc.Name);
                if (d != null && item[pc.Name] != null && item[pc.Name] != DBNull.Value)
                {
                    string tt = d.DataType.Name;
                    switch (tt)
                    {
                        case "String":
                                pc.SetValue(cn, Convert.ToString(item[pc.Name]), null);
                            break;
                        case "Int16":
                            pc.SetValue(cn, Convert.ToInt16(item[pc.Name]), null);
                            break;
                        case "Int32":
                            pc.SetValue(cn, Convert.ToInt32(item[pc.Name]), null);
                            break;
                        case "Decimal":
                            pc.SetValue(cn, Convert.ToDecimal(item[pc.Name]), null);
                            break;
                        case "DateTime":
                            pc.SetValue(cn, Convert.ToDateTime(item[pc.Name]), null);
                            break;
                        default:
                            pc.SetValue(cn, Convert.ToString(item[pc.Name]), null);
                            break;
                    }
                   
                }
            }
            lst.Add(cn);
        }
        return lst;
    }

}

And here is how you can use these methods (in Ext.Net):

protected void btnExport_Click(object sender, DirectEventArgs e)
    {
        string json = e.ExtraParams["AllValues"];
        if (string.IsNullOrEmpty(json))
        {
            return;
        }
        List<dividend> lst = JSON.Deserialize<List<dividend>>(json);
        if (lst == null)
        {
            return;
        }
        try
        {
            DataTable dt = new DataTable();
            dt = lst.GetDataTable();

            string exportAs = "BankReturn" + CurrentDateString() + ".xlsx";


            List<string> columnNames = new List<string>() { "dividendyear", "declareid", "wno", "boid", "name", "bankcorr", "branch", "accno", "StatusName", "LastAction", "remarks" };
            Export(dt, columnNames, exportAs);

                    }
        catch (Exception ex)
        {
            X.Msg.Alert("Message", string.Format("{0}", ex.ToString())).Show();
            return;
        }
    }


protected void fuImport_FileSelected(object sender, DirectEventArgs e)
    {
        string json = e.ExtraParams["AllValues"];
        if (string.IsNullOrEmpty(json))
        {
            X.Msg.Alert("Message", string.Format("{0}", "Please search some data first to update on import")).Show();
            return;
        }

        List<dividend> lst = JSON.Deserialize<List<dividend>>(json);

        DataSet ds = ImportExcelXLS(fuImport.PostedFile, true);

        List<dividend> impLst = ds.Tables[0].ToCollection<dividend>();

        gpBoInfoStore.DataSource = lst;
        gpBoInfoStore.DataBind();
    }











Tuesday, September 18, 2012

How to solve error: 404.2 The page you are requesting cannot be served

Problem: 
I get the error while trying to visit home page of a deployed asp.net 4 application in IIS7: 404.2 The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

How can I solve this issue?

 Solution:
This error occurs because the requested ISAP(Internet Server API) and/or CGI(Common Gateway Interface) resource is restricted on the computer that is running IIS 7. After installing .NET Framework 4.0 on a machine there is a few configuration changes you need to do to IIS in order to get a ASP.NET 4.0 page running.

To resolve this issue you have to follow steps mentioned below:

1. Open IIS and Click on the sever name.
2. In Feature View Double click "ISAPI and CGI Restrictions"

3. Select ASP.Net V4 and click Allow in action panel. It will be set to Allowed.

Now your application should run.


Sunday, August 5, 2012

How to convert a file to byte array and create file from byte array?

Problem:
How to convert a file to byte array? and how can I create the file from byte array?

Solution:

To convert a file to byte array you need to used FileStream class. You have to open instance of the class in read mode and class Read() method to read bytes in byte array.

To retrieve the file from byte array you have to open the instance of the class in create mode with write access and call Write() method to write bytes and create file.

Look at following code example:


string sessionId = Session.SessionID;
        imgDocImage.ImageUrl = string.Empty;
        string fileName = hdfImagePath.Value.ToString();
        string docDtlId = hfDoctDtlId.Value.ToString();
        string tempPath = Server.MapPath("~/Uploads");
        tempPath = tempPath + "\\" + sessionId + "\\" + fileName;
        string newPath = Server.MapPath("~/Uploads");
        newPath = newPath + "\\" + docDtlId;
        if (!System.IO.Directory.Exists(newPath))
        {
            System.IO.Directory.CreateDirectory(newPath);
        }
        newPath = newPath + "\\" + fileName;
        int id = 0;
        if (!System.IO.File.Exists(newPath))
        {
            FileStream fsr = new FileStream(tempPath, FileMode.Open, FileAccess.Read);
            int bytesInFile = (int)fsr.Length;
            byte[] fileContent = new byte[bytesInFile];
            long bytesRead = fsr.Read(fileContent, 0, bytesInFile);
            fsr.Close();

            FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);
            fs.Write(fileContent, 0, fileContent.Length);
            fs.Close();
        }

Monday, July 30, 2012

How can I save record using jQuery in ASP.Net?

Problem: How can I save record using jQuery in ASP.Net? Please provide me source code for save record using jquery in asp.net.

Solution:

You need to create a web service and add a web method for saving record and call the method from jquery.
Look at the following example:
You need to add a method in your web service which is marked with WebMethod attribute. Similar to following code snipppet:


[WebMethod]
        public bool MarkProjectComplete(long projectID)
        {
            bool result = false;
            EnumStatus status = ProjectFacade.MarkProjectComplete(projectID);
            if (status == EnumStatus.Successfull)
            {
                result = true;
                if (projectID > 0)
                {
                    Project project = null;
                    project = ProjectFacade.GetProjectByID(projectID);
                }
            }
            return result;
        }
 

Then call your method from your jquery function. Look at following code snippet:

function MarkProjectComplete(projectID) {
            if (confirm('Are you sure you would like to mark this project as ‘Mark Project Complete’?')) {
                $.ajax({
                    type: "POST",
                    url: "<%= ApplicationPath %>/WebServices/YourWebService.asmx/MarkProjectComplete",
                    data: "{'projectID' : '" + projectID + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        if (msg.d == true) {
                            alert("Mark Project Complete Successfully");
                            
                        }
                    },
                    error: function () {
                    }
                });
            }
        }

Hope it will be helpful. Thanks.


Sunday, July 29, 2012

How can I protect by asp.net button from click multiple time or double click at a time?

Problem:  How can I protect by asp.net button from click multiple time or double click at a time?

Solution:
When clicking in save or insert button a user can click multiple times very quickly that sometimes is similar to double click. If you do not protect users from double click while inserting data, it may insert multiple records at a time which is unexpected.  Asp.net developers frequently face the problem.

To protect from this problem you need to add small java script function.

If you are not using validation group in your page then the function will be:


        <script language="javascript" type="text/javascript">
        var crnt = 0;
        function PreventClicks() {

            if (typeof (Page_ClientValidate) == 'function') {
                Page_ClientValidate();
            }

            if (Page_IsValid) {
                if (++crnt > 1) {
                    alert(crnt);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    </script>



<asp:Button runat="server" CssClass="primaryAction" ID="btnInsertUser" OnClick="InsertNewUser" Text="Save" OnClientClick="return PreventClicks();" />


If you use validation group then the function will be:


    <script language="javascript" type="text/javascript">
        var crnt = 0;
        function  PreventClicks() {

            if (typeof (Page_ClientValidate('change-password')) == 'function') {
                Page_ClientValidate();
            }

            if (Page_IsValid) {
                if (++crnt > 1) {
                    alert(crnt);
                    return false;
                }
                return true;
            }
            else {
                return false;
            }
        }
    </script>


<asp:Button runat="server" CssClass="primaryAction" ID="btnInsertUser" 

ValidationGroup="change-password"

OnClick="InsertNewUser" Text="Save" dd OnClientClick="return PreventClicks();" />


Hope that it will be helpful for developers.

Monday, June 18, 2012

Barcode scanner USB pen reader application in asp.net application

Problem: I have a USB barcode scanner pen. Is there any tutorial or project that I can use to test the pen in asp.net application?

Solution:

In a windows application that is not difficult, it can be done by accessing the Windows.Devices.Input namespace, and then creating a global hook so when a specific input device other than the mouse and keyboard is in use, it will auto return focus to the windows application, and the proper text box.

You won't be able to do that in asp.net though.

Monday, February 20, 2012

How to solve this configuration error while deploying application?

Problem:
I am getting a server error while setting up BugTracker.Net in my local machine.


How can I solve this issue?

 Solution:
This error gives when required .net  framework is not installed on your machine.
To install .net framework go to visual studio 2010  command prompt and write the following command:

aspnet_regiis -i

This will install .net framwork 4 on your machine.