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();

Tuesday, March 18, 2014

Combine Summary & Details Sales Table

USE [WomensWorld]
GO
/****** Object:  StoredProcedure [dbo].[GetDailySalesStatementNew]    Script Date: 03/18/2014 18:07:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- GetDailySalesStatementNew  'F001','05/16/2013','05/16/2013'
-- GetDailySalesStatementNew  'All','05/16/2012','05/16/2015'
-- =============================================
ALTER PROCEDURE [dbo].[GetDailySalesStatementNew]
(
    @ShopID nvarchar(4),
@startDT nvarchar(15),
@endDT nvarchar(15)
)
AS
BEGIN
SET NOCOUNT ON;
                                       
SELECT
      ROW_NUMBER() OVER (ORDER BY t.[barcode]) as SL
      ,s.[ShopID]
      ,s.[Invno]
      ,s.[invsl]
      ,s.[TotalAmt]
      ,s.[DiscPrcnt]
      ,s.[DiscAmt]
      ,s.[VatAmt]
      ,s.[counterid]
      ,CAST(Convert(nvarchar,s.[saledt],101) as DATE) as saledt
      ,s.[Disc_Ref]
      ,s.[Disc_Reasons]
      ,s.[PayType]
      ,s.[MAX_DISC]
      ,s.[CardName]
      ,s.[advamt]
      ,s.[cshamt]
      ,s.[crdamt]
      ,s.[netamt]
      ,s.[customer_id]
      ,s.[Customername]
      ,t.[userid] as userid
      ,s.[tsec]
      ,s.[PaidAmt]
      ,s.[ChangeAmt]
      ,s.[CorpID]
      ,s.[CorpName]
      ,s.[AptDt]
      ,s.[AptTime]
      ,s.[InvType]
      ,s.[AdvSlip]
      ,s.[Point]
      ,s.[PointRedeem]
      ,s.[RU]
      ,t.[barcode]
      ,t.[Prdname]
      ,t.[sqty]
      ,t.[Employee_ID]
      ,t.[Employee_Name]
  INTO #Temp_Sale_Summary
  FROM [Sale_SSummary] s
  RIGHT JOIN [Sale_TokenPrint] t ON s.[invsl] = t.[invsl]
  WHERE ((s.[ShopID] = @ShopID AND @ShopID<>'All') OR (@ShopID='All'))
        AND CAST(Convert(nvarchar,s.[saledt],101) as DATE) BETWEEN @startDT AND @endDT
  ORDER BY s.Invno

 
  DECLARE @invList TABLE
  (
    SL bigint
  )
 
  INSERT INTO @invList (SL)
  SELECT MAX(SL) FROM #Temp_Sale_Summary GROUP BY invsl
   
  UPDATE #Temp_Sale_Summary
  SET    TotalAmt=0,
       DiscPrcnt=0,
       DiscAmt=0,
       VatAmt=0,
       advamt=0,
cshamt=0,
crdamt=0,
netamt=0,
PaidAmt=0,
ChangeAmt=0,
Point=0
 FROM #Temp_Sale_Summary t LEFT JOIN @invList p ON t.SL = p.SL  WHERE p.SL IS NULL    

   
 
  SELECT
       s.SL
      ,s.[ShopID]
      ,s.[Invno]
      ,s.[invsl]
      ,s.[TotalAmt]
      ,s.[DiscPrcnt]
      ,s.[DiscAmt]
      ,s.[VatAmt]
      ,s.[counterid]
      ,s.saledt
      ,s.[Disc_Ref]
      ,s.[Disc_Reasons]
      ,s.[PayType]
      ,s.[MAX_DISC]
      ,s.[CardName]
      ,s.[advamt]
      ,s.[cshamt]
      ,s.[crdamt]
      ,s.[netamt]
      ,s.[customer_id]
      ,s.[Customername]
      ,s.userid
      ,s.[tsec]
      ,s.[PaidAmt]
      ,s.[ChangeAmt]
      ,(s.[PaidAmt] - s.[ChangeAmt]) as RecvAmt
      ,s.[CorpID]
      ,s.[CorpName]
      ,s.[AptDt]
      ,s.[AptTime]
      ,s.[InvType]
      ,s.[AdvSlip]
      ,s.[Point]
      ,s.[PointRedeem]
      ,s.[RU]
      ,s.[barcode]
      ,s.[Prdname]
      ,s.[sqty]
      ,s.[Employee_ID]
      ,s.[Employee_Name]
    FROM #Temp_Sale_Summary s
 
DROP TABLE #Temp_Sale_Summary
END

Saturday, February 22, 2014

Combine column from multiple rows into single row

he data looks like this:
id  row_num  customer_code comments
-----------------------------------
1   1        Dilbert        Hard
1   2        Dilbert        Worker
2   1        Wally          Lazy
My results need to look like this:
id  customer_code comments
------------------------------
1   Dilbert        Hard Worker
2   Wally          Lazy
DECLARE @x TABLE 
(
  id INT, 
  row_num INT, 
  customer_code VARCHAR(32), 
  comments VARCHAR(32)
);

INSERT @x SELECT 1,1,'Dilbert','Hard'
UNION ALL SELECT 1,2,'Dilbert','Worker'
UNION ALL SELECT 2,1,'Wally','Lazy';

SELECT id, customer_code, comments = STUFF((SELECT ' ' + comments 
    FROM @x AS x2 WHERE id = x.id
     ORDER BY row_num
     FOR XML PATH('')), 1, 1, '')
FROM @x AS x
GROUP BY id, customer_code
ORDER BY id;
Reference: http://dba.stackexchange.com/questions/17921/combine-column-from-multiple-rows-into-single-row