Monday, October 20, 2014

Cannot Add Reference To CrystalDecisions DLLS On VS 2010

Cannot add reference to CrystalDecisions.Shared, CrystalDecisions.ReportSource, CrystalDecisions.CrystalReports.Engine on VS 2010
I recently came across this situation where I had to print a report using crystal and VS2010
I had designed the report using Crystal Reports Designer. My task was to print the report on the click of the print button on my Win Form application.
First of all,Crystal doesn’t ship with VS 2010, you need to download and install this free exe from SAP Business Objects website
In the correct scenario , one can add the reference to to CrystalDecisions.Shared , CrystalDecisions.ReportSource, CrystalDecisions.CrystalReports.Engine using  Add Reference -> .NET tab .
However in my case I wasn’t seeing these dlls .
I tried adding them manually using browse and navigating to C:\Program Files\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjectsEnterpriseXI 4.0\win32_x86\dotnet
But I was tsill getting the reference error. After googling for some time I stumbled on the following page :
And following the discussion, I clicked on my Project Properties and Changed my target platform to .NET Framework 4 from .NET Framework 4 Client Profile.

Copied From: http://lazytechtips.wordpress.com/2011/07/15/cannot-add-reference-to-crystaldecisions-dlls-on-vs-2010/

Sunday, September 14, 2014

how to upload csv file to sqlserver in asp.net

            private void GetExcelSheets(string FilePath,string fileName, string Extension, string isHDR)
        {
            try
            {

       
            string conStr = "";
            switch (Extension)
            {
                case ".csv": //Excel 97-03
                    conStr = ConnectionStringXLS.CsvConString;
                    break;
                case ".xls" : //Excel 97-03
                    conStr = ConnectionStringXLS.Excel03ConString;
                    break;
                case ".xlsx": //Excel 07
                    conStr = ConnectionStringXLS.Excel07ConString;
                    break;
            }

            //Get the Sheets in Excel WorkBoo
            conStr = String.Format(conStr, FilePath, isHDR);

            OleDbConnection con = new OleDbConnection(conStr);
            if (con.State == System.Data.ConnectionState.Closed)
            {
                con.Open();
            }

            DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);


            string query = "";
             
            if(Extension.Substring(0,4) ==".xls")
                query = @"Select  TOP 5 * from [" + dt.Rows[0]["TABLE_NAME"] + "]";
            else
                query = @"Select  TOP 5 * from [" + fileName + "]";

         
            OleDbCommand cmd = new OleDbCommand(query, con);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);

            DataSet ds = new DataSet();
            da.Fill(ds);
            da.Dispose();
            con.Close();
            con.Dispose();

            DataTable dataDT = ds.Tables[0];

            List<MISLibrary.DAL.EmployeeTracking> emList = new List<MISLibrary.DAL.EmployeeTracking>();
            foreach (DataRow row in dataDT.Rows)
            {
             
                emList.Add(
                    new MISLibrary.DAL.EmployeeTracking
                    {
                        MSISDN = row[0].ToString(),
                        Name = row[1].ToString(),
                        PIN = row[2].ToString(),
                        Designation = row[3].ToString(),
                        Location = row[4].ToString(),
                        FirstTrackDate = Convert.ToDateTime(row[5].ToString()),
                        FirstTrackTime = row[6].ToString(),
                        LastTrackDate =  Convert.ToDateTime((row[7].ToString())),
                        LastTrackTime = row[8].ToString(),
                        Duration = row[9].ToString(),
                        Hit = Convert.ToInt32(row[10].ToString())
                    });
            }

            if (emList.Count > 0)
            {
                int numberOfAffectedRows = new MISLibrary.HRM.EmployeeManager().Save(emList);
                if (numberOfAffectedRows > 0)
                {
                    lblMsg.ForeColor = System.Drawing.Color.Green;
                    lblMsg.Text = "Uploaded Successfully.";
                }
                else
                {
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    lblMsg.Text = "Not Uploaded!";
                }
            }

          }
          catch(Exception ex)
            {
                lblMsg.Text = ex.Message;
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }


        }


    public static class ConnectionStringXLS
    {
     //   public const string CsvConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended          Properties='text;HDR={1}'";
 public const string CsvConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='text;HDR={1};IMEX=1'";
        public const string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
        public const string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
    }


         protected void btnUpload_Click(object sender, EventArgs e)
        {
            if(FileUpload1.HasFile)
            {
                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string folderPath = Path.GetFullPath(FileUpload1.PostedFile.FileName);

                if (extension.Substring(0, 4) != ".xls" && extension.Substring(0, 4) != ".csv")
                {
                    lblMsg.Text = "Only .xls and .xlsx or .csv Files are supported.";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    return;
                }


                string appFileName = Server.MapPath("~/AttendanceSheet/"+fileName) ;
                FileUpload1.SaveAs(appFileName);

                if (extension.Substring(0, 4) == ".csv")
                    GetExcelSheets(Server.MapPath("~/AttendanceSheet"), fileName ,extension, "Yes");
                else
                    GetExcelSheets(appFileName,fileName,extension,"Yes");
             

                       
            }
        }

Wednesday, July 2, 2014

XML PATH SQL PROBLEM

-- Create table
CREATE TABLE #Department (Department VARCHAR(100))

-- Populate table
INSERT INTO #Department (Department)
SELECT 'ICT'
UNION ALL
SELECT 'CSE'
UNION ALL
SELECT 'ESRM'
UNION ALL
SELECT 'CPS'
UNION ALL
SELECT 'TEX'
UNION ALL
SELECT 'BBA'

-- Create table
CREATE TABLE #Person (ID NVARCHAR(100),PersonName VARCHAR(100))

-- Populate table
INSERT INTO #Person (ID,PersonName)
SELECT '0','Zakir'
UNION ALL
SELECT '1','DILIP'
UNION ALL
SELECT '2','ARUN'
UNION ALL
SELECT '3','KARIM'
UNION ALL
SELECT '4','SUJAN'
UNION ALL
SELECT '5','RAHIM'


-- Create table
CREATE TABLE #Student (Department NVARCHAR(100),ID VARCHAR(100))

-- Populate table
INSERT INTO #Student (Department,ID)
SELECT 'ICT','0'
UNION ALL
SELECT 'ICT','1'
UNION ALL
SELECT 'ESRM','2'
UNION ALL
SELECT 'ESRM','3'
UNION ALL
SELECT 'TEX','4'
UNION ALL
SELECT 'BBA','5'


-- Check orginal data
SELECT *
FROM #Department

SELECT * FROM #Person

SELECT *
FROM #Student

--- the select query ---------
SET ARITHABORT ON; -- must write

 SELECT d.Department,STUFF(( SELECT '<br/>' + CAST((SELECT p.PersonName FROM #Person p WHERE p.ID = s.ID)  AS NVARCHAR(MAX))
                        -- Add a comma (,) before each value
                        FROM #Student s
                        WHERE
                        s.Department= d.Department
                      FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 5, '') AS [StudentName]
FROM #Department d
GROUP BY d.Department

------------------------------------------------------
-- Clean up
DROP TABLE #Person
DROP TABLE #Department
DROP TABLE #Student

Sunday, May 11, 2014

JQUERY CODE SNIPPETS MUST KNOW

1. Print Page Option

Providing option to print a page is a common task for web developers. Following is the available code:

<!-- jQuery: Print Page -->
$('a.printPage').click(function(){

           window.print();

           return false;
}); 

<!-- HTML: Print Page -->

<div>
<a  class="printPage" href="#">Print</a>
</div>



2. Helping Input Field/Swap Input Field

In order to make an Input Text field helpful, we normally display some default text inside it (For Example "Company Name") and when user click on it, text disappears and user can enter the value for it.
You can try it yourself by using the following code snippet.

<!-- jQuery: Helping Input Field -->

$('input[type=text]').focus(function(){    
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == title)
           {
               $this.val('');
           }
}).blur(function() {
           var $this = $(this);
           var title = $this.attr('title');
           if($this.val() == '')
           {
               $this.val(title);
           }
});

<!-- HTML: Swap Input Field -->

<div>
       <input type="text" 
name="searchCompanyName"
value="Company Name" 
title="Company Name" />
</div>



3. Select/Deselect All options

Selecting or Deselecting all available checkbox options using a link on HTML page is common task.

<!-- jQuery: Select/Deselect All -->

$('.SelectAll').live('click', function(){ $(this).closest('.divAll').find('input[type=checkbox]').attr('checked', true); return false; }); $('.DeselectAll').live('click', function(){ $(this).closest('.divAll').find('input[type=checkbox]').attr('checked', false); return false; });

<!-- HTML: Select/Deselect All -->



<div class="divAll"> <a href="#" class="SelectAll">Select All</a>&nbsp; <a href="#" class="DeselectAll">Deselect All</a> <br /> <input type="checkbox" id="Lahore" /><label for="Lahore">Lahore</label> <input type="checkbox" id="Karachi" /><label for="Karachi">Karachi</label> <input type="checkbox" id="Islamabad" /><label for="Islamabad">Islamabad</label> </div>


4. Disabling Right Click

For web developers, its common to disable right click on certain pages so following code will do the job.

<!-- jQuery: Disabling Right Click -->
$(document).bind("contextmenu",function(e){
       e.preventDefault();

   });



5. Identify which key is pressed.

Sometimes, we need to validate the input value on a textbox. For example, for "First Name" we might need to avoid numeric values. So, we need to identify which key is pressed and then perform the action accordingly.
<!-- jQuery: Which key is Pressed. -->
$('#txtFirstName').keypress(function(event){
     alert(event.keyCode);
  });

<!-- HTML: Which key is Pressed. -->
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>



6. Validating an email.

Validating an email address is very common task on HTML form.

<!-- jQuery: Validating an email. -->
$('#txtEmail').blur(function(e) {
            var sEmail = $('#txtEmail').val();
            if ($.trim(sEmail).length == 0) {
                alert('Please enter valid email address');
                e.preventDefault();
            }        
            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]
                             {2,4}|[0-9]{1,3})(\]?)$/;        
            if (filter.test(sEmail)) {
                alert('Valid Email');
            }
            else {
                alert('Invalid Email');
                e.preventDefault();
            }
        });

<!-- HTML: Validating an email-->
<asp:TextBox id="txtEmail" runat="server" />


7. Limiting MaxLength for TextArea

Lastly, it usual to put a textarea on a form and validate maximum number of characters on it.

<!-- jQuery: Limiting MaLength for TextArea -->
   var MaxLength = 500;
       $('#txtDescription').keypress(function(e)
       {
          if ($(this).val().length >= MaxLength) {
          e.preventDefault();}
       });

<!-- HTML: Limiting MaLength for TextArea-->
<asp:TextBox ID="txtDescription" runat="server" 
                         TextMode="MultiLine" Columns="50" Rows="5"></asp:TextBox>

Thursday, April 3, 2014

Increase Max Pool Sze

public static string srConnectionString = "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;Min Pool Size=10;Polling =True; ";
Currently the max pool size is 100;

Wednesday, April 2, 2014

Date Formatting in C#

Example Usage

<%= String.Format("{specifier}", DateTime.Now) %>
@DateTime.Now.ToString("F")
@DateTime.Now.ToString("hh:mm:ss.fff")
SpecifierDescriptionOutput
dShort Date08/04/2007
DLong Date08 April 2007
tShort Time21:08
TLong Time21:08:59
fFull date and time08 April 2007 21:08
FFull date and time (long)08 April 2007 21:08:59
gDefault date and time08/04/2007 21:08
GDefault date and time (long)08/04/2007 21:08:59
MDay / Month08 April
rRFC1123 dateSun, 08 Apr 2007 21:08:59 GMT
sSortable date/time2007-04-08T21:08:59
uUniversal time, local timezone2007-04-08 21:08:59Z
YMonth / YearApril 2007
ddDay08
dddShort Day NameSun
ddddFull Day NameSunday
hh2 digit hour09
HH2 digit hour (24 hour)21
mm2 digit minute08
MMMonth04
MMMShort Month nameApr
MMMMMonth nameApril
ssseconds59
fffmilliseconds120
FFFmilliseconds without trailing zero12
ttAM/PMPM
yy2 digit year07
yyyy4 digit year2007
:Hours, minutes, seconds separator, e.g. {0:hh:mm:ss}09:08:59
/Year, month , day separator, e.g. {0:dd/MM/yyyy}08/04/2007
.
Reference: http://www.mikesdotnetting.com/Article/23/Date-Formatting-in-CSharp
milliseconds separator

Enter Only Numbers in Textbox in c#

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
        && !char.IsDigit(e.KeyChar) 
        && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.' 
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
}

Monday, March 31, 2014

Binding Enum into DropDownList C#

public static class Enumeration
{
    public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct
    {
        var enumerationType = typeof (TEnum);

        if (!enumerationType.IsEnum)
            throw new ArgumentException("Enumeration type is expected.");

        var dictionary = new Dictionary<int, string>();

        foreach (int value in Enum.GetValues(enumerationType))
        {
            var name = Enum.GetName(enumerationType, value);
            dictionary.Add(value, name);
        }

        return dictionary;
    }
}
Bind To a DropDown:
ddlResponse.DataSource = Enumeration.GetAll<Response>();
ddlResponse.DataTextField = "Value";
ddlResponse.DataValueField = "Key";
ddlResponse.DataBind();