Friday 21 December 2012

Set Maximum file upload size and get the value in C#


Add these function in Web Config file
--------------------------------------
Normal file upload size is 4MB. Here Under system.web maxRequestLength mentioned in KB and in system.webServer maxAllowedContentLength as in Bytes.

<system.web>
  .
  .
  .
  <httpRuntime executionTimeout="3600" maxRequestLength="102400" useFullyQualifiedRedirectUrl="false" delayNotificationTimeout="60"/>
</system.web>


<system.webServer>
  .
  .
  .
  <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1024000000" />
        <fileExtensions allowUnlisted="true"></fileExtensions>
      </requestFiltering>
    </security>
</system.webServer>


and if we want to know the maxFile upload size use the given line in .cs page

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
HttpRuntimeSection section = config.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
               
double maxFileSize = Math.Round(section.MaxRequestLength / 1024.0, 1);

Generate CSV file using C#


public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        #region Export Grid to CSV
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        // First we will write the headers.
        //DataTable dt = m_dsProducts.Tables[0];
        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
        // Now write all the rows.
        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
        #endregion
    }

Thursday 20 December 2012

Shrink database using sql server


USE [master]
GO
ALTER DATABASE [TestDb] SET RECOVERY SIMPLE WITH NO_WAIT
DBCC SHRINKFILE(TestDbLog, 1)
ALTER DATABASE [TestDb] SET RECOVERY FULL WITH NO_WAIT
GO

SQL server Time formats


{0:dd-MMM-yyyy hh:mm tt}


SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)
                                        – Oct  2 2008 11:01AM        
SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008                
SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02          
SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) – dd mon yyyy
SELECT convert(varchar, getdate(), 107) – mon dd, yyyy
SELECT convert(varchar, getdate(), 108) – hh:mm:ss
SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)
                                        – Oct  2 2008 11:02:44:013AM  
SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) – yyyymmdd
SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm
                                        – 02 Oct 2008 11:02:07:577    
SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm

Convert Row to column using sqlserver


declare @col as nvarchar(max),
@query as nvarchar(max);

set @col=Stuff((select distinct ','+ wl.WI_Projname from WorklogTable as wl for xml path(''),type).value('.','nvarchar(max)'),1,1,'')
set @query ='select WL_Staffcode,name,' + @col + ' from(
select WL_Staffcode,
staff.Staff_Name as name,
Wl_Hours ,WI_Projname from WorklogTable as wl inner join
StaffMaster as staff on staff.Staff_Code=wl.WL_Staffcode
) x
pivot(sum(Wl_Hours)for WI_Projname in ('+@col+'))p'

print @query

Grant Permission for table using sql server


use DBName
grant exec on tbl_Name to public

Procedure to get datas by page index and size using sql server



create proc GridSample_Test --3,1,'Name','desc'  
(  
 @PageSize int=10,  
 @PageIndex int=1,
 @SortBy nvarchar(30)='AutoID',
 @SortOrd varchar(10)='ASC'
)  
as  
begin  

SET NOCOUNT ON

declare @orderby nvarchar(100)
declare @sqlStatement varchar(max)

set @orderby=(select case when @sortby='Name' then ' case when LastName is null then FirstName else FirstName'+'+'+'LastName end ' else @sortby end as orderby)
 
set @sqlStatement='select * from ( select Row_number() over  
  (  
  order by '+@orderby+' '+@SortOrd+'    
  ) as RowNumber,  
 AutoID  
 ,case when LastName is Null then    
  FirstName  
  else  
  FirstName+'+''' '''+'+LastName end as Name  
 ,Address1  
 ,Address2  
 ,City  
 ,State  
 ,Country  
 ,ZipCode  
 from tbl_GridSample ) as tbl where tbl.RowNumber BETWEEN (convert(int,'+convert(varchar,@PageIndex-1)+')) * convert(int,'+convert(varchar,@PageSize)+') + 1  
 AND ( ((convert(int,'+convert(varchar,@PageIndex -1)+') * convert(int,'+convert(varchar,@PageSize)+') + 1)) + convert(int,'+convert(varchar,@PageSize)+'))-1'

 --print @sqlStatement
 exec(@sqlStatement)  
end
 

Drop all procedure from particular database using cursor in sql server


//Here we can alter the code to get table name procedure name and so on in the exec command

declare @ProcName varchar(500)
declare cur cursor
for select [t.name ] from sys.objects as t where type='P'
open cur
fetch next from cur into @ProcName
while @@fetch_status = 0
begin
 exec ( 'drop procedure ' + @ProcName)
 fetch next from cur into @ProcName
end
close cur
deallocate cur

-------------------------------------------


declare @ProcName varchar(500)
declare cur cursor
for select t.name from sys.objects as t where type='P' and t.name like 'cpt%'
open cur
fetch next from cur into @ProcName
while @@fetch_status = 0
begin
 exec ( 'sp_helptext ' + @ProcName)
 fetch next from cur into @ProcName
end
close cur
deallocate cur

Separate with comma in SqlServer


For Join Two tables
---------------------

select a.CDM_PO_HeadId,
SUBSTRING(
(
select (', '+b.CDM_Circor_PartNo) from CDM_PO_LineItem as b
where a.CDM_PO_HeadId=b.CDM_PO_HeadId
order by b.CDM_PO_HeadId,b.CDM_Circor_PartNo for XML PATH('')),2,1000
) as PartNo
from CDM_PO_LineItem as a where (a.CDM_Circor_PartNo is not null or LEN(a.CDM_Circor_PartNo)>0) group by a.CDM_PO_HeadId


For Single Table
-------------------

declare @list varchar(max)
select @list=coalesce(@list+',','')+b.CDM_Circor_PartNo from CDM_PO_HeadItem as a
inner join CDM_PO_LineItem as b
on a.CDM_PO_HeadId=b.CDM_PO_HeadId
select @list as CirPartNo

Check case sesitive in sql server


check case sensitive words in sql server
----------------------------------------

select * from CPT_UserMgmt where CPT_Password collate latin1_general_cs_as='Baxter'

Bulk insert into table using csv file or excel file


bulk insert [ filename ] from '[ filepath ]'
with
(
fieldterminator=',',
rowterminator='\n'
)


Bulk insert from Excel file
-- Method#1
INSERT INTO dbo.ImportTest

SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',

'Data Source=C:\ImportData.xls;Extended Properties=Excel 8.0')...[Sheet1$]

--Method#2

INSERT INTO dbo.ImportTest

SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',

'Excel 8.0;Database=C:\ImportData.xls', 'SELECT * FROM [Sheet1$]')

Basic SQL Querys Like Get Max salary, triggers and etc.,


-- To fetch the alternate records from a table --Even row
select * from employee where empno%2=0

--To fetch the alternate records from a table -- Odd row
select * from employee where empno%2=1

-- find third max salary from the table
Select salary from employee order by salary desc
Select distinct  salary from employee order by salary desc
Select distinct top 3 salary from employee order by salary asc


Select top 1 salary from (Select distinct top 5 salary from employee order by salary desc) salarynew order by salary asc

-- find third min salary from the table
select top 1 salary from (Select distinct top 3 salary from employee order by salary asc) salarynew order by salary desc


-- find Select First n records from a table
Select top 5 * from employee order by empno asc
-- find select last n records from a table
select top 5 * from employee order by empno desc

--List dept no., Dept name for all the departments in which there are no employees in the department.

select * from employee where deptno in (select deptno from department)
Select * from department where deptno not in(Select deptno from employee)

--how to get 3 max salaries

select distinct top 3 salary from employee order by salary desc

--how to get 3 min salaries

Select distinct top 3 salary from employee order by salary asc

-- how to get n th max salaries
--here n is sample example 6
select distinct top 6 salary from employee order by salary  desc

--- select distinct records from emp table
select distinct * from employee

--how to delete duplicate rows in a table
Select  MAX(deptno) from employee group by empno,deptno

CREATE TABLE TestTable(COL1 INT, COL2 INT, COL3 VARCHAR(50))
INSERT INTO TestTable VALUES (1, 1, 'ONE')
INSERT INTO TestTable VALUES (1, 2, 'TWO')
INSERT INTO TestTable VALUES (1, 2, 'TWO')
INSERT INTO TestTable VALUES (1, 3, 'THREE')
INSERT INTO TestTable VALUES (1, 3, 'THREE')
INSERT INTO TestTable VALUES (1, 3, 'THREE')

--> to view removing depulicate records
Select Distinct *  from TestTable
Select * from TestTable
--step1:
Select *,ROW_NUMBER() over(partition by col1,col2,col3 order by col1) as rownumer from TestTable

--step2:
with deleteduplicaterows as
(
Select *,ROW_NUMBER() over(partition by col1,col2,col3 order by col1) as rownumer from TestTable
)

delete from deleteduplicaterows where rownumer >1

--Count of number of employees in department wise
Select * from employee
select * from department

select Count(*),dept.deptno,dept.deptname from employee emp inner join department dept on emp.deptno=dept.deptno group by dept.deptno,dept.deptname


--Suppose there is annual salary information provided by emp table. How to fetch monthly salary of each and every employee?

Select empname,salary/12 as monthlysalary from employee -- monthly salary

select empname,salary*12 from employee--annual salary

--Select all record from emp table where deptno =10 or 40.
Select * from employee
select * from employee where deptno=1 or deptno=4

--Select all record from emp table where deptno=30 and sal>1500.

Select * from employee where deptno=2 and salary>26000


--Select  all record  from emp where job not in SALESMAN  or CLERK.

Select * from employee
Select * from employee where job not in ('IT' , 'Ac')

--Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.

Select * from employee where empname in ('myil','Anu')

--Select all records where ename starts with ‘S’ and its lenth is 6 char.

Select * from employee where empname like 'R_____'

--Select all records where ename may be any no of  character but it should end with ‘R’.
Select * from employee where empname like '%R'

--Count  MGR and their salary in emp table.
Select distinct Count(Job),Count(salary) from employee
Select Count(salary) from employee where job='IT'
--emp table add comm+sal as total sal  .

Select empname,(salary +  bonus) from employee

--Select  any salary <3000 from emp table.

Select salary from employee where salary < 27000

Select * from employee
Select salary from employee where salary < 36000
Select * from employee where salary > any(Select salary from employee where salary < 36000)


--Select  All salary <3000 from emp table.


Select * from employee
Select salary from employee where salary < 30000
Select * from employee where salary > all(Select salary from employee where salary < 30000)

--Select all the employee  group by deptno and sal in descending order.

Select empname,deptno,salary from employee group by deptno,empno,empname,salary order by salary desc

--How can I create an empty table emp1 with same structure as emp?
create table employee1 as

select * into  employee1 from employee

select * from employee1

Select * into employee2 from employee where 1=2

Select * from employee2

--How to retrive record where sal between 1000 to 2000?
Select * from employee
select * from employee where salary<=40000 and salary>=25000
select * from employee where salary between 25000 and 40000
--Select all records where dept no of both emp and dept table matches.

Select * from employee emp join department dept on emp.deptno=dept.deptno

select * from employee emp where exists(select * from department dept where emp.deptno=dept.deptno)

--If there are two tables emp1 and emp2, and both have common record. How can I fetch all the recods but common records only once?
Select * from employee union select * from employee1
 Select * from employee intersect select * from employee1
--error coding
--Select * from employee Minus select * from employee1

--Count the totalsal  deptno wise where more than 2 employees exist.

Select count(empno) from employee group by deptno order by deptno
Select emp.deptno,SUM(emp.salary) as totalsalary from employee emp group by emp.deptno having Count(emp.empno)>2

 insert into employee1 ()
select * from department
Select * from employee order by deptno
Select emp.deptno,dept.deptname,SUM(salary) from employee emp join department dept on emp.deptno=dept.deptno group by emp.deptno,dept.deptname order by deptno
Select * from department



declare @name int
set @name =(Select MAX(salary) from employee)
Select @name

Select deptno,SUM(salary) as sal from employee group by  deptno having deptno >2

Select * from employee where deptno =(select deptno from department where deptno=2)
Select * from employee where deptno =2
Select salary from employee
Select MAX(salary) from employee
Select MAX(salary) from employee
Select salary from employee group by salary having MAX(salary) < (Select MAX(salary) from employee)

Select * from employee where deptno not in (select deptno from department)


Select deptno from department d where EXISTS(Select * from employee where d.deptno = employee.deptno )

Select * from employee1


CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)


alter trigger tr_persons on employee1
after insert,delete,update
as
PRINT 'TRIGGER OUTPUT' +  CONVERT(VARCHAR(5),@@ROWCOUNT)
+ 'ROW UPDATED'
Go
update employee1 set job='NonIT' where job='' or job=null

Select * from employee1
Select * from employee
insert into employee1(empname,empphone) values ('kamal','9638521254')

update employee1 set salary='20000' where empno=13


Create table TestEmp
(
empno int not null primary key,
empname varchar(50),
job varchar(20),
mgr numeric(4,0),
hiredate datetime,
sal numeric(10,2),
comm numeric(10,2),
deptno int foreign key references dept(depto)
)

Create table dept(
depto int not null primary key identity(1,1),
deptname varchar(20),
Location varchar(20)
)

Select * from dept
Create table Jobhist(
empno int not null,
startdate datetime not null,
enddate datetime,
job varchar(20),
comm numeric(10,2),
depto int,
chgdesc varchar(100),
constraint jobhisk_pk primary key (empno,startdate),
constraint jobhist_ref_emp_fk Foreign key (empno) references Testemp(empno),
constraint jobhist_ref_dept_fk Foreign key (depto) references dept(depto),
constraint jobhist_ref_date_ck Check (startdate <= enddate)
)


INSERT INTO dept VALUES ('ACCOUNTING','NEW YORK');
INSERT INTO dept VALUES ('RESEARCH','DALLAS');
INSERT INTO dept VALUES ('SALES','CHICAGO');
INSERT INTO dept VALUES ('OPERATIONS','BOSTON');


INSERT INTO TestEmp VALUES (7369,'SMITH','CLERK',7902,'17-DEC-80',800,NULL,2);
INSERT INTO TestEmp VALUES (7499,'ALLEN','SALESMAN',7698,'20-FEB-81',1600,300,3);
INSERT INTO TestEmp VALUES (7521,'WARD','SALESMAN',7698,'22-FEB-81',1250,500,3);
INSERT INTO TestEmp VALUES (7566,'JONES','MANAGER',7839,'02-APR-81',2975,NULL,2);
INSERT INTO TestEmp VALUES (7654,'MARTIN','SALESMAN',7698,'28-SEP-81',1250,1400,3);
INSERT INTO TestEmp VALUES (7698,'BLAKE','MANAGER',7839,'01-MAY-81',2850,NULL,3);
INSERT INTO TestEmp VALUES (7782,'CLARK','MANAGER',7839,'09-JUN-81',2450,NULL,1);
INSERT INTO TestEmp VALUES (7788,'SCOTT','ANALYST',7566,'19-APR-87',3000,NULL,2);
INSERT INTO TestEmp VALUES (7839,'KING','PRESIDENT',NULL,'17-NOV-81',5000,NULL,1);
INSERT INTO TestEmp VALUES (7844,'TURNER','SALESMAN',7698,'08-SEP-81',1500,0,3);
INSERT INTO TestEmp VALUES (7876,'ADAMS','CLERK',7788,'23-MAY-87',1100,NULL,2);
INSERT INTO TestEmp VALUES (7900,'JAMES','CLERK',7698,'03-DEC-81',950,NULL,3);
INSERT INTO TestEmp VALUES (7902,'FORD','ANALYST',7566,'03-DEC-81',3000,NULL,2);
INSERT INTO TestEmp VALUES (7934,'MILLER','CLERK',7782,'23-JAN-82',1300,NULL,1);

Select * from Jobhist
INSERT INTO jobhist VALUES (7369,'17-DEC-80',NULL,'CLERK',800,2,'New Hire');
INSERT INTO jobhist VALUES (7499,'20-FEB-81',NULL,'SALESMAN',1600,3,'New Hire');
INSERT INTO jobhist VALUES (7521,'22-FEB-81',NULL,'SALESMAN',1250,3,'New Hire');
INSERT INTO jobhist VALUES (7566,'02-APR-81',NULL,'MANAGER',2975,2,'New Hire');
INSERT INTO jobhist VALUES (7654,'28-SEP-81',NULL,'SALESMAN',1250,3,'New Hire');
INSERT INTO jobhist VALUES (7698,'01-MAY-81',NULL,'MANAGER',2850,3,'New Hire');
INSERT INTO jobhist VALUES (7782,'09-JUN-81',NULL,'MANAGER',2450,2,'New Hire');
INSERT INTO jobhist VALUES (7788,'19-APR-87','12-APR-88','CLERK',1000,2,'New Hire');
INSERT INTO jobhist VALUES (7788,'13-APR-88','04-MAY-89','CLERK',1040,2,'Raise');
INSERT INTO jobhist VALUES (7788,'05-MAY-90',NULL,'ANALYST',3000,2,'Promoted to Analyst');
INSERT INTO jobhist VALUES (7839,'17-NOV-81',NULL,'PRESIDENT',5000,1,'New Hire');
INSERT INTO jobhist VALUES (7844,'08-SEP-81',NULL,'SALESMAN',1500,3,'New Hire');
INSERT INTO jobhist VALUES (7876,'23-MAY-87',NULL,'CLERK',1100,2,'New Hire');
INSERT INTO jobhist VALUES (7900,'03-DEC-81','14-JAN-83','CLERK',950,1,'New Hire');
INSERT INTO jobhist VALUES (7900,'15-JAN-83',NULL,'CLERK',950,3,'Changed to Dept 30');
INSERT INTO jobhist VALUES (7902,'03-DEC-81',NULL,'ANALYST',3000,2,'New Hire');
INSERT INTO jobhist VALUES (7934,'23-JAN-82',NULL,'CLERK',1300,1,'New Hire');

Select * from dept
select * from TestEmp

How to Call Web Service ?


using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using AjaxControlToolkit;
using System.ServiceModel.Web;
using System.Xml;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService()]

public class CreatePOWS : System.Web.Services.WebService
{
   public CreatePOWS()
    {
        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

//If you want enable session and call this method in server side then uncomment the below line
//[System.Web.Services.WebMethod(EnableSession = true)]

//WebMethod used to call this method in client side
    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
}


//After that create object for call webservice in serverside

CreatePOWS  obj_CreatePOWS =new CreatePOWS ();

Response.Write(obj_CreatePOWS.HelloWorld());

//For ClientSide Call add the following lines inside the form

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
         <Services>
          <asp:ServiceReference Path="~/Service/CreatePOWS.asmx" />
         </Services>
    </asp:ScriptManager>


//then script call webservice methods through
alert(CreatePOWS.HelloWorld());