Friday, January 24, 2014

sql_variant check varchar and nvarchar for stored procedure

if you have sql_variant field type and you search for any value in column you will get nothing in your query so you should convert the column and the check value to varchar first or nvarchar to get your search

example

begin
declare @x varchar(10) = 10
SELECT ProfileID FROM Profile WHERE
CONVERT(nvarchar(100),  MR_PATIENT_IF, 126) LIKE @x + '%';
end

SQL SERVER STORED PROCEDURE if else and variable declaration

stored procedure sample for
-how to create if else statement
-how to declare vaiable and set field value for this variable and re-using in procedure


Create PROCEDURE [dbo].[xxx](@ProfileID int,@MR_TYPE INT ,@PATIENT_ID INT)
AS
DECLARE @XPROFILE varchar(200)

if(@MR_TYPE = 0)
BEGIN
SELECT @XPROFILE = ProfileID FROM Profile WHERE MR_PATIENT_IF=@PATIENT_ID
SELECT [Doc_ID],[ProfileID],[Doc_Title]
FROM [Profile_Docs]
 WHERE [ProfileID] = @XPROFILE
order by CreateDate desc;
END
else
BEGIN
SELECT [Doc_ID],[ProfileID],[Doc_Title],[ApplicationID],[Phisical_Name],[Locked],[DocServerID],[Author],[CreatedBy],[CreateDate],[LastupdatedBy],[LastUpdateDate],[Comment],[LastLockedBy],[LastLockedDate],[LastAccessedBy],[LastAccessDate],[published],[PublishDate],[PublishedBy],MR_TYPE
FROM [Profile_Docs]
 WHERE [ProfileID]=@ProfileID
 and (MR_TYPE =@MR_TYPE)
 order by CreateDate desc;
 END;

Thursday, January 23, 2014

web twain Scan Using TWAINX control , Javascript function ,

http://www.codeproject.com/Articles/1376/NET-TWAIN-image-scanner

-----------------------------------------------------------------------------
web application Sample to scan pages using twainX control with asp.net web page
you can download source from the following Link
https://drive.google.com/file/d/0B1U-9REzhHKENUF2SkVzR1k2MTg/view?usp=sharing


steps to run the Application
setup twainX from rar file exists on the referred link.
open the project as web site using vs2010 or vs2012
run the application you should got the folllowing Page

Press On the button and confirm that scanner power is ok

you should get saved image.tiff
and the message for archiving succeeded.
if any problem occur confirm two things
-- twainX Control setup succeeded (you can get it from the link above .rar file)
--confirm scanner setup and try to scan pages outside development using twain driver . 

after the file scanned you can publish it by code to any server do db info ............etc .

thanks


Wednesday, January 22, 2014

Sql Server Stored Procedures Templates For Select , insert , update , Search and how to generate all db Basic Procedures using CS2GEN Tool


if you need generation tools for sql server db you can use the following component CS2GEN

download the latest version  .exe file 
you can easily connect to your db and generate c# ORM and sql server script file for stored procedures
after finish installation you will get the following screen 
choose db from left menu open database 
enter you db connection information
enter you output directory to save your file

open the folder to get your files 
you will find ready ORM Desktop sample or Web Application in c# you can use it as database Layer 
and also you will find the .sql file related your database .

Open the script file .sql in management studio and choose stored Procedures you need to apply to your database to safe your time.
if you need to use c# ORM as db layer you should execute whole the file to keep stored procedures by name (don't change the name of stored procedures) if you will use the generated code .














----------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
Manually Create Stored 
first we will create table called Users table  (run the following script to new database to create it )
USE [YourDBName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Users](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserFullName] [nvarchar](150) NOT NULL,
[LoginName] [varchar](50) NULL,
[LoginPassword] [varchar](50) NULL,
[Email] [varchar](100) NULL,
[Mobile] [varchar](15) NULL,
[Extension] [varchar](6) NULL,
[phone] [varchar](15) NULL,
[FaxNo] [varchar](15) NULL,
[Disabled] [bit] NULL,
[PrimaryGroup] [int] NULL,
[PrimaryProfile] [int] NULL,
[CreateDate] [datetime] NULL,
[CreatedBy] [int] NULL,
[LastLoginTime] [datetime] NULL,
[LastUpdateTime] [datetime] NULL,
[DegreeID] [int] NULL,
[themesColor] [nvarchar](50) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
[UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [FK_Users_Degrees] FOREIGN KEY([DegreeID])
REFERENCES [dbo].[Degrees] ([DegreeID])
GO

ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users_Degrees]
GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [FK_Users_Groups] FOREIGN KEY([PrimaryGroup])
REFERENCES [dbo].[Groups] ([GroupID])
GO

ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users_Groups]
GO

ALTER TABLE [dbo].[Users] ADD  CONSTRAINT [DF_Users_Disabled]  DEFAULT ((0)) FOR [Disabled]
GO
----------------------------------------------------------
 now we will create stored procedures for the table
1-insert Procedure
CREATEPROCEDURE [dbo].[InsertUser]
   @UserFullName nvarchar(150)
   ,@LoginName varchar(50)
   ,@LoginPassword varchar(50)
   ,@Email varchar(100)
   ,@Mobile varchar(15)
   ,@Extension varchar(6)
   ,@Phone varchar(15)
   ,@FaxNo varchar(15)
   ,@Disabled bit
   ,@PrimaryGroup int
   ,@PrimaryProfile int
   ,@CreatedBy int
   ,@DegreeID int
as
begin
declare @flag char(1)
set @flag= '0'
IF NOT EXISTS (select * from Users where  UserFullName = @UserFullName)
BEGIN
 
INSERT INTO [Users]
           ([UserFullName]
      ,[LoginName]
      ,[LoginPassword]
      ,[Email]
      ,[Mobile]
      ,[Extension]
      ,[phone]
      ,[FaxNo]
      ,[Disabled]
      ,[PrimaryGroup]
      ,[PrimaryProfile]
      ,[CreateDate]
      ,[CreatedBy]
      ,[DegreeID])
         
     VALUES
           (@UserFullName
           ,@LoginName
           ,@LoginPassword
           ,@Email
           ,@Mobile
           ,@Extension
           ,@phone
           ,@FaxNo
           ,@Disabled
           ,@PrimaryGroup
           ,@PrimaryProfile
           ,GETDATE()
           ,@CreatedBy
           ,@DegreeID)
set @flag = '1'
end
select @flag
end
------------------------------------------------------------------------------------
update stored procedure

CREATE  procedure [dbo].[UpdateUser]
@UserID int
   ,@UserFullName nvarchar(150)
   ,@LoginName varchar(50)
   ,@LoginPassword varchar(50)
   ,@Email varchar(100)
   ,@Mobile varchar(15)
   ,@Extension varchar(6)
   ,@Phone varchar(15)
   ,@FaxNo varchar(15)
   ,@Disabled bit
   ,@PrimaryGroup int
   ,@PrimaryProfile int
   ,@DegreeID int

as
begin

UPDATE [Users]

      set [UserFullName] = @UserFullName
      ,[LoginName] = @LoginName
      ,[LoginPassword] = @LoginPassword
      ,[Email] = @Email
      ,[Mobile] = @Mobile
      ,[Extension] = @Extension
      ,[phone] = @Phone
      ,[FaxNo] = @FaxNo
      ,[Disabled] = @Disabled
      ,[PrimaryGroup] = @PrimaryGroup
      ,[PrimaryProfile] = @PrimaryProfile
      ,[LastUpdateTime] = GETDATE()
      ,[DegreeID] = @DegreeID
 WHERE  UserID= @UserID

end

------------------------------------------------------------------------------------------------
delete Users
Create PROCEDURE [dbo].[DeleteUserInfo]
@ID int
as
begin





Declare @flag as int
set @flag=1
begin try
Delete FROM Group_Users where Group_Users.UserID = @ID
Delete FROM [Users] where UserID=@ID

end try
begin catch
set @flag = 0
end catch
select @flag


end
-------------------------------------------------------------------------------------------
search Users By Full Name
Create PROCEDURE [dbo].[UserSEARCH]
@name nvarchar(50)
as
begin
select  [UserID]
      ,[UserFullName]
      ,[LoginName]
      ,[LoginPassword]
      ,[Email]
      ,[Mobile]
      ,[Extension]
      ,[phone]
      ,[FaxNo]
      ,[Disabled]
      ,[PrimaryGroup]
      ,[PrimaryProfile]
      ,[CreateDate]
      ,[CreatedBy]
      ,[LastLoginTime]
      ,[LastUpdateTime]
      ,Degrees.[DegreeID]
       ,Degrees.DegreeName as DegreeName
  FROM [Users] inner join [Degrees]
on Degrees.DegreeID = Users.DegreeID

       where LoginName like '%'+@name+'%' or UserFullName like '%'+@name+'%'
end

if you need to search table all columns and need to depends on passed query regardless of if the parameter passed is null or not passed at all
here's example to handle good search form stored procedure .

create the following table
USE [HOSPITAL_DB]
GO

/****** Object:  Table [dbo].[Doc_Servers]    Script Date: 01/23/2014 09:25:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Doc_Servers](
[DocServerID] [int] IDENTITY(1,1) NOT NULL,
[Location] [varchar](250) NOT NULL,
[Disabled] [bit] NULL,
[LibraryName] [nvarchar](100) NOT NULL,
[LibraryDesc] [nvarchar](300) NULL,
[IsPrivateLibrary] [bit] NULL,
 CONSTRAINT [PK_Doc_Servers] PRIMARY KEY CLUSTERED
(
[DocServerID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Doc_Servers] ADD  CONSTRAINT [DF_Doc_Servers_Disabled]  DEFAULT ((1)) FOR [Disabled]
GO

ALTER TABLE [dbo].[Doc_Servers] ADD  CONSTRAINT [DF_Doc_Servers_IsPrivateLibrary]  DEFAULT ((0)) FOR [IsPrivateLibrary]
GO

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

search Procedure
ALTER PROCEDURE [dbo].[Doc_Servers_Search]
@DocServerID int = NULL,
    @LibraryName nvarchar(100) = NULL
 
 
   AS
BEGIN
   SELECT [DocServerID],[Location],[Disabled],[LibraryName],[LibraryDesc]
FROM [Doc_Servers] T
    WHERE (@DocServerID IS NULL     OR T.DocServerID = @DocServerID)
    and
          (@LibraryName IS NULL     OR T.LibraryName like '%'+@LibraryName+'%')
    and   (IsPrivateLibrary IS NULL OR IsPrivateLibrary <> 1)
                   
       
END

the previous syntax is very good for search if you have multiple columns and need to generate one procedure to search any of these columns so if the parameter passed to procedure it will check it's value condition else it will ignore filter condition and set default parameter value to null so this is good way to handle stored procedure for search structure for any table for you .

to execute and test procedure use the following script
exec Doc_Servers_Search  null, null
exec Doc_Servers_Search  null, ''
exec Doc_Servers_Search  null, 'Lib'

very important note if you need your varchar fields to be english Case sensitive or Insensitive
To create your search Case Sensetive use the following sample 
(@LibraryName IS NULL     OR T.LibraryName like '%'+@LibraryName+'%' Collate Latin1_General_CS_AI) 

to create your search Case insensitive 
(@LibraryName IS NULL     OR T.LibraryName like '%'+@LibraryName+'%' Collate Latin1_General_CI_AI) 


Example to test the two collation
begin 
if ('a'='A' Collate Latin1_General_CI_AI) 
    print'same 1'
else
    print 'different 1'

if ('a'='A' Collate Latin1_General_CS_AI) 
    print'same 2'
else
    print 'different 2'
end
-----------------------------------------------------------------------------------------------
i hope this post help you to create your own insert , update , delete , search Templates .

asp.net Hijri date validation expression using regular expression validator asp.net and some common validators

Number Validators
(^\d+$)
(\d+)

 <asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server" ControlToValidate="TXT_VACATION_NO_OF_DAYS"
                                                    ValidationExpression="\d+" ValidationGroup="a">
                                                    <img src="../images/Star.png" alt="" />رقم غير مقبول
                                                </asp:RegularExpressionValidator>

ANOTHER ONE
  <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TXT_REQUEST_REPORT_NO"
                                      ValidationExpression="^\d+$" ValidationGroup="a">
                                         <img src="../images/Star.png" alt="" />
                                        </asp:RegularExpressionValidator>
-----------------------------------------------------------------------------------------------------------------
Regular expression for integer number greater than zero
    ^[1-9][0-9]*$

regular expression for decimal numbers greater than zero


      0*[1-9][0-9]*(\.[0-9]+)?
------------------------------------------------------------------

Mobile Validator 

  <asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server"
                                                                ControlToValidate="txtMobile" ErrorMessage="رقم الجوال غير صحيح"
                                                                ValidationGroup="GR1" SetFocusOnError="True" ValidationExpression="(05)?\d{8}"></asp:RegularExpressionValidator>





Text Only Validators

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtFieldName_EN"
                                                    Display="Dynamic"  ValidationExpression="[\x00-\x80]+"
                                                    ValidationGroup="GR1">
                                                       <img  alt='' src="../Images/cancel.gif" />مسموح بالحروف الانجليزية فقط
                                                    </asp:RegularExpressionValidator>



 <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="txtFieldName_EN"
                                                    Display="Dynamic" ValidationExpression="^[A-Za-z_]*$"
                                                    ValidationGroup="GR1">
                                                       <img  alt='' src="../Images/cancel.gif" />الأرقام غير مسموح بها
                                                    </asp:RegularExpressionValidator>






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

الصيغه العامه لشرط التاريخ الهجري
RegularExpressionValidator  اداة
ValidationExpression  الشرط
---------------------------------------------------------------------
(0?[1-9]|[12][0-9]|3[00])[- /.](0?[1-9]|1[012])[- /.](14)?\d\d
--------------------------------------------------------------------
الشرح التفصيلي
----------------------------------
اليوم من 1 الي 30
(0?[1-9]|[12][0-9]|3[00])
----------------------------------
(0?[1-9]|[1][0-9]|[2][0-8])
----------------------------------
الشهر من  1 الي 12
(0?[1-9]|1[012])
----------------------------------
السنه من اول 1400 والي 1499
(14)?\d\d
----------------------------------
الفاواصل المسموح بها يسن اليوم والشهر والسنه- / .
[- /.]
----------------------------------

Tuesday, January 21, 2014

sql server error handling transaction

example for transaction and error handling using sql server stored procedure
-----------------------------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go



ALTER PROCEDURE [dbo].[usp_Example_ErrorHandler]

/* Example stored procedure to illustrate error handling
* Example:
DECLARE @RC int
EXEC @RC = usp_Example_ErrorHandler
PRINT 'Return value = ' + CONVERT(varchar(10), @RC)
****************************************************************/
AS

DECLARE @myERROR int -- Local @@ERROR
       , @myRowCount int -- Local @@ROWCOUNT

SET NOCOUNT ON

BEGIN TRAN
   INSERT INTO [MOWE_PORTAL].[dbo].[Cities]
           ([CityName]
           ,[CityDesc]
           ,[RegID])
     VALUES
           ('المدينة المنورة','وصف المدينة المنورة',1)

    SELECT @myERROR = @@ERROR, @myRowCount = @@ROWCOUNT
    IF @myERROR != 0 GOTO HANDLE_ERROR
    COMMIT TRAN -- No Errors, so go ahead
    RETURN 0
HANDLE_ERROR:
    ROLLBACK TRAN
    RETURN @myERROR



export windows form datagridview to excel file using c#

1- add reference to the library
Microsoft.Office.Interop.Excel
2- copy past the following funciton to export excel sheet (it saved in temp directory for current user )

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            // creating Excel Application
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();


            // creating new WorkBook within Excel application
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);


            // creating new Excelsheet in workbook
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

            // see the excel sheet behind the program
            app.Visible = true;

            // get the reference of first sheet. By default its name is Sheet1.
            // store its reference to worksheet
            worksheet =(Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"];
            worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;

            // changing the name of active sheet
            worksheet.Name = "Exported from gridview";


            // storing header part in Excel
            for (int i = 1; i < grdCity.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = grdCity.Columns[i - 1].HeaderText;
            }



            // storing Each row and column value to excel sheet
            for (int i = 0; i < grdCity.Rows.Count - 1; i++)
            {
                for (int j = 0; j < grdCity.Columns.Count-1; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = grdCity.Rows[i].Cells[j].Value.ToString();
                }
            }

            string myTempFile = Path.Combine(Path.GetTempPath(), "ratings.xlsx");
            // save the application
            workbook.SaveCopyAs(myTempFile);// (myTempFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            worksheet = null;
            workbook = null;
           // File.Open(myTempFile, FileMode.Open);
            // Exit from the application
            app.Quit();

----------------------------------------------------------------------------------
Export DataTable To Excel

 public static  void ExporttoExcel(DataTable table)
     {
         var sb = new StringBuilder();
         HttpContext.Current.Response.Clear();
         HttpContext.Current.Response.ClearContent();
         HttpContext.Current.Response.ClearHeaders();
         HttpContext.Current.Response.Buffer = true;
         HttpContext.Current.Response.ContentType = "application/ms-excel;charset=windows-1256";
         sb.Append(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
         HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");
         HttpContext.Current.Response.Charset = "UTF-8";
         HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
         sb.Append("<font style='font-size:10.0pt; font-family:Calibri;'>");
         sb.Append("<BR><BR><BR>");
         //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
         sb.Append("<Table border='1' bgColor='#ffffff' " +
           "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
           "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
         //am getting my grid's column headers
         int columnscount = table.Columns.Count;

         for (int j = 0; j < columnscount; j++)
         {      //write in new column
             sb.Append("<Td>");
             //Get column headers  and make it as bold in excel columns
             sb.Append("<B>");
             sb.Append(table.Columns[j].ColumnName.ToString());
             sb.Append("</B>");
             sb.Append("</Td>");
         }
         sb.Append("</TR>");
         foreach (DataRow row in table.Rows)
         {//write in new row
             sb.Append("<TR>");
             for (int i = 0; i < table.Columns.Count; i++)
             {
                 sb.Append("<Td>");
                 sb.Append(row[i].ToString());
                 sb.Append("</Td>");
             }

             sb.Append("</TR>");
         }
         sb.Append("</Table>");
         sb.Append("</font>");
         HttpContext.Current.Response.Write(sb);
         HttpContext.Current.Response.Flush();
         HttpContext.Current.Response.End();
     }



Thursday, January 9, 2014

backup folder mirror or network path to folder ( copy from network path to folder)

to create Mirror Folder to specific network folder path or local pc path you can easy handle it by the following steps
1 : create new file name it mirror.bat.
2- past the following line in the folder
robocopy /MIR \\your Network Path here  your Local Physical path here (c:/xxfolder)
3- you can easily create schedual task to run the batch file any time you want

exmaples .

robocopy /MIR D:\MWA_STORE\TENDERS_STORE M
break
--pause