Friday 26 September 2014

Javascript function to select all checkboxes from gridview header checkbox

 function SelectheaderItemCheckbox(checkboxall) {
  
    if (checkboxall.checked) {
        var inputs = document.getElementById(dataGrid).getElementsByTagName('input');
     
        for (var i = 1; i < inputs.length; i++) {
            if (inputs[i].type == "checkbox") {
                inputs[i].checked = true;
            }
        }
    }
    else {
        var inputs = document.getElementById(dataGrid).getElementsByTagName('input');
        for (var i = 1; i < inputs.length; i++) {
            if (inputs[i].type == "checkbox") {
                inputs[i].checked = false;
            }
        }
    }

}

 function SelectchildCheckboxes(header) {

    var inputs = document.getElementById(dataGrid).getElementsByTagName('input');
    var countCheckboxItem = 0;
    var countCheckboxSelected = 0;
    for (var i = 1; i < inputs.length; i++) {
        if (inputs[i].type == "checkbox") {
            countCheckboxItem++;
            if (inputs[i].checked) {
                countCheckboxSelected++;
            }
        }
    }
    if (countCheckboxSelected == countCheckboxItem) {
        inputs[0].checked = true;
    }
    else {
        inputs[0].checked = false;
    }
}

<asp:GridView ID="GridViewItems" runat="server" AutoGenerateColumns="false" DataKeyNames="ItemId"
                    AllowPaging="true" PageSize="10" OnRowCommand="GridViewItems_RowCommand" OnPageIndexChanging="GridViewItems_PageIndexChanging">
                    <Columns>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                <div class="TblChk">
                                    <asp:CheckBox ID="CheckBoxSelectAll" onclick="javascript:SelectheaderItemCheckbox(this)"
                                        class="FloatLeft" runat="server" />
                                </div>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBoxItem" onclick="javascript:SelectchildCheckboxes(this)"
                                    runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                                           </Columns>
                    <EmptyDataTemplate>
                        No Records Found....
                    </EmptyDataTemplate>
                </asp:GridView>

Javascript to validate Textbox and Dropdownlist on submit in ASP .Net

<script type="text/javascript">
        var TextBoxItemName = '<%=TextBoxItemName.ClientID %>';
        var TextBoxPurchasePrice = '<%=TextBoxPurchasePrice.ClientID%>';
        var TextBoxSalePrice = '<%=TextBoxSalePrice.ClientID%>';
        var DropDownListUnit = '<%=DropDownListUnit.ClientID%>';
        var TextBoxDescription = '<%=TextBoxDescription.ClientID%>';   


        function Save() {
           
            if (document.getElementById(TextBoxItemName).value == "") {
                alert('Please enter item name.');
                document.getElementById(TextBoxItemName).focus();
                return false;
            }
            if (document.getElementById(DropDownListUnit).value == 0) {
                alert('Please select unit.');
                document.getElementById(DropDownListUnit).focus();
                return false;
            }           
            if (document.getElementById(TextBoxPurchasePrice).value == "") {
                alert('Please enter purchase price.');
                return false;
            }
            if (ex.test(document.getElementById(TextBoxPurchasePrice).value) == false) {
                alert('Incorrect purchase price');
                document.getElementById(TextBoxPurchasePrice).focus();
                return false;
            }
            if (document.getElementById(TextBoxSalePrice).value == "") {
                alert('Please enter sale price.');
                return false;
            }
            if (ex.test(document.getElementById(TextBoxSalePrice).value) == false) {
                alert('Incorrect sale price');
                document.getElementById(TextBoxSalePrice).focus();
                return false;
            }
        }     
      
    </script>

Monday 22 September 2014

Read Connection settings from XML file C# and VB.Net

Using C#


public static string xxx = string.Empty;
    static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    public static string Connection()
    {
        DataSet _ds = new DataSet("MyDataSet");
        _ds.ReadXml(executableLocation + "\\ServerInfo.xml");
        if (_ds.Tables[0].Rows.Count > 0)
        {
            xxx = "Data Source=" + _ds.Tables[0].Rows[0]["DataSource"] + ";Database=" + _ds.Tables[0].Rows[0]["DatabaseName"] + ";uid=" + _ds.Tables[0].Rows[0]["UserName"] + ";pwd=" + _ds.Tables[0].Rows[0]["Password"];
            return xxx;
        }
        return xxx;
    }



Using VB.Net


Public Shared xxx As String = String.Empty
Shared executableLocation As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Public Shared Function Connection() As String
 Dim _ds As New DataSet("MyDataSet")
 _ds.ReadXml(executableLocation & "\ServerInfo.xml")
 If _ds.Tables(0).Rows.Count > 0 Then
  xxx = ((("Data Source=" + _ds.Tables(0).Rows(0)("DataSource") & ";Database=") + _ds.Tables(0).Rows(0)("DatabaseName") & ";uid=") + _ds.Tables(0).Rows(0)("UserName") & ";pwd=") + _ds.Tables(0).Rows(0)("Password")
  Return xxx
 End If
 Return xxx
End Function

Connection string in app.config file in c#

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="test" connectionString="Data Source=local;Initial Catalog=test;User ID=sa;Password=test;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="test" value="server=local;Initial Catalog=test;User ID=sa;Password=test"/>
  </appSettings>
  <system.net>
    <mailSettings>
      <smtp from="test@gmail.com">
        <network host="smtp.gmail.com" password="test" port="25" userName="test@gmail.com"/>
      </smtp>
    </mailSettings>
  </system.net>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

Read Pdf Files data Using coordinates with ITextSharp and C# and VB.Net

Using C#


public string[] ReadPdfFiles(string filepath, int pageno, int cordinate1, int coordinate2, int coordinate3, int coordinate4)
        {
            PdfReader reader = new PdfReader(filepath);
            string text = string.Empty;
            string[] words = null;
            try
            {

                iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(cordinate1, coordinate2, coordinate3, coordinate4);
                RenderFilter[] renderFilter = new RenderFilter[1];
                renderFilter[0] = new RegionTextRenderFilter(rect);
                ITextExtractionStrategy textExtractionStrategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
                text = PdfTextExtractor.GetTextFromPage(reader, pageno, textExtractionStrategy);
                words = text.Split('\n');
                return words;

            }
            catch (Exception Ex)
            {
                reader.Close();
                return words;
            }
            finally
            {
                reader.Close();
            }


        }


Using VB.Net


Public Function ReadPdfFiles(filepath As String, pageno As Integer, cordinate1 As Integer, coordinate2 As Integer, coordinate3 As Integer, coordinate4 As Integer) As String()


	Dim reader As New PdfReader(filepath)

	Dim text As String = String.Empty

	Dim words As String() = Nothing

	Try



		Dim rect As New iTextSharp.text.Rectangle(cordinate1, coordinate2, coordinate3, coordinate4)

		Dim renderFilter As RenderFilter() = New RenderFilter(0) {}

		renderFilter(0) = New RegionTextRenderFilter(rect)

		Dim textExtractionStrategy As ITextExtractionStrategy = New FilteredTextRenderListener(New LocationTextExtractionStrategy(), renderFilter)

		text = PdfTextExtractor.GetTextFromPage(reader, pageno, textExtractionStrategy)

		words = text.Split(ControlChars.Lf)



		Return words

	Catch Ex As Exception


		reader.Close()


		Return words
	Finally




		reader.Close()
	End Try



End Function

C# Console application to Exit from application

static void Main(string[] args)
        {
            Program prg = new Program();
            prg.ImportData();
            Environment.Exit(0);
        }

Extract zip files in C#

private void ExtractZipFile(string zipFileLocation, string destination)
        {
            try
            {
                System.IO.Compression.ZipFile.ExtractToDirectory(zipFileLocation, destination);
            }
            catch (Exception ex)
            {
            }
        }

Saturday 20 September 2014

Stored Procedure to Get all table names from database


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE Procedure [dbo].[proc_GetAllTables]      
        
AS   
       
BEGIN   
   
 Begin Try   

  SELECT name FROM sys.Tables
       
 End Try   
   
 BEGIN CATCH   
   
     return  '0';   
   
 END CATCH   
   
END

Thursday 18 September 2014

Stored Procedure to activate or deactivate user


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[proc_ActivateDeactivateUser]      
 ( 
 @UserId varchar(50),
 @IsActive bit, 
 @LastModifiedBy int 
 ) 
AS   
       
BEGIN   
   
 Begin Try 

    IF(@IsActive = 1)
        BEGIN
            set @IsActive=0;
        END
    ELSE
        BEGIN
            set @IsActive=1;;
        END

   Update tbl_Users set IsActive=@IsActive,LastModifiedBy = @LastModifiedBy where UserId =@UserId  
 
 End Try   
   
 BEGIN CATCH   
   
     return  '0';   
   
 END CATCH   
   
END

Stored Procedure to delete user by userid with exception handling


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[proc_DeleteUser]      
 ( 
 @UserId varchar(50), 
 @LastModifiedBy int 
 ) 
AS   
       
BEGIN   
   
 Begin Try    


   Update tbl_Users set IsDeleted='true',LastModifiedBy = @LastModifiedBy where UserId =@UserId  
       
 End Try   
   
 BEGIN CATCH   
   
     return  '0';   
   
 END CATCH   
   
END 


GO

Stored Procedure to delete user by UserId with exception handling


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[proc_DeleteUser]      
 ( 
 @UserId varchar(50), 
 @LastModifiedBy int 
 ) 
AS   
       
BEGIN   
   
 Begin Try    


   Update tbl_Users set IsDeleted='true',LastModifiedBy = @LastModifiedBy where UserId =@UserId  
       
 End Try   
   
 BEGIN CATCH   
   
     return  '0';   
   
 END CATCH   
   
END 


GO

Wednesday 17 September 2014

Stored Procedure to Validate duplicate entry for same user at the time of insert and update


/****** Object:  StoredProcedure [dbo].[proc_IsExistUser]    Script Date: 09/18/2014 08:23:03 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--exec [proc_IsExistCategory] 'aa'   
CREATE Procedure [dbo].[proc_IsExistUser]          
 (     
  @UserId bigint, 
  @UserName varchar(50)     
 )     
AS       
           
BEGIN      
       
 Begin Try   
 if (@UserId = 0)     
   select * from View_Users where UserName =@UserName      
 else 
   select * from View_Users where UserName =@UserName and UserId <> @UserId     
  
           
 End Try       
       
 BEGIN CATCH       
       
     return  '0';       
       
 END CATCH       
       
END
GO

Stored procedure to Validate duplicate insert for same Username


/****** Object:  StoredProcedure [dbo].[proc_IsExistUser]    Script Date: 09/18/2014 08:23:03 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--exec [proc_IsExistUser] 'aa'   
CREATE Procedure [dbo].[proc_IsExistUser]          
 (       
  @UserName varchar(50)     
 )     
AS       
           
BEGIN      
       
 Begin Try     
  
   select * from View_Users where UserName =@UserName  
  
 End Try       
       
 BEGIN CATCH       
       
     return  '0';       
       
 END CATCH       
       
END
GO

Tuesday 16 September 2014

Stored Procedure to search user by Username or Userid

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE procedure [dbo].[SEARCH_USER]
(
    @USER_FIRST_NAME VARCHAR(100),
    @USER_ID_PK         BIGINT
)
AS
BEGIN
    IF LEN(@USER_ID_PK) > 0
    BEGIN
        SELECT * FROM USER_REGISTRATION WHERE USER_ID_PK = @USER_ID_PK AND IS_RECSTATUS = 1;
    END
    ELSE
    BEGIN
        SELECT * FROM USER_REGISTRATION WHERE USER_FIRST_NAME LIKE @USER_FIRST_NAME AND IS_RECSTATUS = 1 ORDER BY USER_FIRST_NAME;
    END

END

Stored Procedure to Insert User Information to Database

--AUTHOR:    MANOJ KUMAR
--PURPOSE:     AUTHONTICATE USER
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[INSERT_USER]
(
    @LOGIN_ID                VARCHAR(100),
    @PASSWORD                VARCHAR(20),
    @GENDER                    VARCHAR(10),
    @DOB                    datetime,
    @FIRST_NAME                VARCHAR(100),
    @LAST_NAME                VARCHAR(100),
    @ALTERNATE_EMAIL        VARCHAR(100),
    @COUNTRY                BIGINT,
    @STATE                    BIGINT,
    @CITY                    BIGINT,
    @PHONE_NO                VARCHAR(100),
    @MOBILE_NO                VARCHAR(100),
    @TOTAL_EXPERIENCE        VARCHAR(50),
    @CURRENT_EMPLOYER        VARCHAR(200),
    @ANNUAL_SALARY            VARCHAR(100),
    @FUNC_AREA                BIGINT,
    @INDUSTRY                BIGINT,
    @KEY_SKILLS                VARCHAR(500),
    @SKILL_EXPERIENCE        VARCHAR(50),
    @SKILL_LEVEL            BIGINT,
    @PREFERED_JOB_LOCATION    BIGINT,
    @EXPECTED_ROLE            VARCHAR(500),
    @EXPECTED_PACKAGE        VARCHAR(100),
    @RESUME_HEADLINE        VARCHAR(200),
    @RESUME                    VARCHAR(5000),
    @GRADUATION                BIGINT,
    @GRAD_SPECIFICATION        VARCHAR(300),
    @GRAD_INSTITUTE            VARCHAR(300),
    @POST_GRADUATION        BIGINT,
    @PGRAD_SPECIFICATION    VARCHAR(300),
    @PGRAD_INSTITUTE        VARCHAR(300),
    @DOCTRATE                BIGINT,
    @DOC_SPECIFICATION        VARCHAR(300),
    @DOC_INSTITUTE            VARCHAR(300),
    @COURSE_ONE                VARCHAR(300),
    @COURSE_TWO                VARCHAR(300),
    @COURSE_THREE            VARCHAR(300),
    @OUTPUT                 VARCHAR(200) OUTPUT
)
AS
BEGIN
        DECLARE        @TranName VARCHAR(10)
        SELECT      @TranName =  'MyTransaction';
        --BEGIN TRANSACTION  @TranName;
INSERT INTO USER_REGISTRATION
        (
            LOGIN_ID,PASSWORD,GENDER,DATE_OF_BIRTH,USER_FIRST_NAME,USER_LAST_NAME,
            ALTERNATE_EMAIL_ID,COUNTRY_ID_FK,STATE_ID_FK,CITY_ID_FK,PHONE_NO,MOBILE_NO,TOTAL_EXPERIENCE,
            CURRENT_EMPLOYER,ANNUAL_SALARY,FUNC_AREA_ID_FK,INDUSTRY_ID_FK,KEY_SKILLS,
            SKILL_EXPERIENCE,SKILL_LEVEL,PREFERED_JOB_LOCATION_ID_FK,
            EXPECTED_ROLE_ID_FK,EXPECTED_PACKAGE,RESUME_HEADLINE,RESUME,GRADUATION_ID_FK,
            GRAD_SPECIFICATION,GRAD_INSTITUTE,POST_GRADUATION_ID_FK,
            PGRAD_SPECIFICATION,PGRAD_INSTITUTE,DOCTRATE_ID_FK,DOC_SPECIFICATION,DOC_INSTITUTE,
            COURSE_ONE,COURSE_TWO,COURSE_THREE,IS_RECSTATUS,REC_DATE
        )

VALUES (
            @LOGIN_ID,@PASSWORD,@GENDER,@DOB,@FIRST_NAME,@LAST_NAME,
            @ALTERNATE_EMAIL,@COUNTRY,@STATE,@CITY,@PHONE_NO,@MOBILE_NO,@TOTAL_EXPERIENCE,
            @CURRENT_EMPLOYER,@ANNUAL_SALARY,@FUNC_AREA,@INDUSTRY,@KEY_SKILLS,
            @SKILL_EXPERIENCE,@SKILL_LEVEL,@PREFERED_JOB_LOCATION,
            @EXPECTED_ROLE,@EXPECTED_PACKAGE,@RESUME_HEADLINE,@RESUME,@GRADUATION,
            @GRAD_SPECIFICATION,@GRAD_INSTITUTE,@POST_GRADUATION,@PGRAD_SPECIFICATION,
            @PGRAD_INSTITUTE,@DOCTRATE,@DOC_SPECIFICATION,@DOC_INSTITUTE,
            @COURSE_ONE,@COURSE_TWO,@COURSE_THREE,1,GETDATE()
        );

        BEGIN
            SELECT @OUTPUT = (SELECT MAX(ISNULL(USER_ID_PK,1)) FROM USER_REGISTRATION WHERE IS_RECSTATUS = 1);
        END
        RETURN @OUTPUT;
IF @@ERROR = 0
    BEGIN       
        COMMIT TRANSACTION @TranName;
    END
ELSE
    BEGIN
        ROLLBACK  TRANSACTION @TranName;
    END
END

Sql Server Stored Procedure to Authenticate User with output paramater

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--AUTHOR:    MANOJ KUMAR
--PURPOSE:     AUTHONTICATE USER

CREATE PROCEDURE [dbo].[AUTHENTICATE_USER_LOGIN]
(
    @PASSWORD VARCHAR(50),
    @LOGIN_ID VARCHAR(200),
    @OUTPUT VARCHAR(200) OUTPUT

)
AS
    DECLARE @COUNT INT
    BEGIN
        /*SET @COUNT =  (SELECT COUNT(*) FROM USER_REGISTRATION WHERE CAST ([PASSWORD] AS BINARY)= CAST(@PASSWORD AS BINARY)
        AND CAST([LOGIN_ID] AS BINARY)=CAST(@LOGIN_ID  AS BINARY)  AND REC_STATUS =1)*/

        SET @COUNT =  (SELECT COUNT(0) FROM USER_REGISTRATION WHERE [PASSWORD] =  @PASSWORD
        AND CAST([LOGIN_ID] AS BINARY)=CAST(@LOGIN_ID  AS BINARY)  AND IS_RECSTATUS =1);

        IF (@COUNT > 0)
        BEGIN
            SET @OUTPUT ='YES'
        END
        ELSE
        BEGIN
            SET @OUTPUT ='NO'
        END
    END
--    RETURN @OUTPUT
GO

Download Files from web using web client Asp.net

Download File Synchronously



using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://webxperts.com/myfile.pdf", @"c:\myfile.pdf");
 
 
 

Download File Asynchronously

You can  download file without blocking the main thread use asynchronous method DownloadFileA­sync. You can also set event handlers to show progress and to detect that the file is downloaded.


 

private void btnDownloadFiles_Click(object sender, EventArgs e)
{
  WebClient webClient = new WebClient();
  webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
  webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
  webClient.DownloadFileAsync(new Uri("http://webxperts.com/myfile.pdf"), @"c:\myfile.pdf");
}

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
  progressBar.Value = e.ProgressPercentage;
}

private void Completed(object sender, AsyncCompletedEventArgs e)
{
  Response.Write("Download completed!");
}

 

 

Monday 15 September 2014

.Net Framework

.Net framework is a platform given by Microsoft where anyone can develop the softwares, Websites and Mobile apps.