Friday, December 27, 2013

Jquery Ajax Call in Asp.Net

 <div id="Result">Click here</div>
<script type="text/javascript">
    $('#Result').click(function() {
      $.ajax({
        type: "POST",
        url: "Default.aspx/HelloWorld",
        data: "{}",
        contentType: "application/json",
        dataType: "json",
        success: function(msg) {
          // Replace the div's content with the page method's return.
          $("#Result").text(msg.d);
        }
      });
    });
  </script>

Phone Number Validation Class using IDictionary

Class:
public class PhoneValidator {
static IDictionary<string, Regex> countryRegex = new Dictionary<string, Regex>() {
{ "USA", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}$")},
{ "UK", new Regex("(^1300\\d{6}$)|(^1800|1900|1902\\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\\d{4}$)|(^04\\d{2,3}\\d{6}$)")},
{ "Netherlands", new Regex("(^\\+[0-9]{2}|^\\+[0-9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-\\s]{10}$)")},
};
public static bool IsValidNumber(string phoneNumber, string country) {
if (country != null && countryRegex.ContainsKey(country))
return countryRegex[country].IsMatch(phoneNumber);
else
return false;
}
public static IEnumerable<string> Countries {
get {
return countryRegex.Keys;
}
}
}
Calling:
if (!PhoneValidator.IsValidNumber("+1-1234-232-232", "USA"))
      Console.Writeline('Enter Valid Phone Number');

 

Tuesday, December 24, 2013

C#: Get Hours, Minutes, seconds from total Minutes using TimeSpan

var ts = TimeSpan.FromMinutes(intMinutes);
var message = string.Format("Hours: {0}, Minutes: {1}, Seconds: {2}", ts.Hours, ts.Minutes, ts.Seconds);

Console.WriteLine(message);

Copy a table into new table with/without data conditionally / unconditionally - SQL Server

1. Copy only the structure of an existing table into new table:

SELECT * INTO [DBName]. dbo.tblNonExistingTable FROM [DBName].dbo.tblExistingTable WHERE 1=2

The above query will copy the structure of  an existing table(tblExistingTable ) into the new table(tblNonExistingTable).


2. Copy the structure plus all the data of an existing table into new table:

SELECT * INTO [DBName]. dbo.tblNonExistingTable FROM [DBName].dbo.tblExistingTable

The above query will copy the structure of  an existing table(tblExistingTable ) into the new table(tblNonExistingTable) as well as data.


3.  Copy only the data of an existing table into an existing table in other DB:
INSERT INTO [DBName]. dbo.tblDestExistingTable
SELECT * FROM [DBName].dbo.tblSourceExistingTable

The above query will copy all the data of  an source table(tblSourceExistingTable) into the another DB table(tblDestExistingTable).

4.  Copy only the data of an existing table into an existing table in other DB on the basis of some condition:
 INSERT INTO [DBName]. dbo.tblDestExistingTable
SELECT * FROM [DBName].dbo.tblSourceExistingTable Where id > 50

The above query will copy the data of  an source table(tblSourceExistingTable) into the another DB table(tblDestExistingTable) having id of source table(tblSourceExistingTable) greater than 50. So, Lets say, there are 100 records in source table from id 1 to 100, then it will copy only 50 records to destination table.




Tuesday, December 3, 2013

Calculate the dates of previous, current and next month

--SQL Server 2005/2008/2012
DECLARE @DATE DATETIME
 
Select @DATE = GetDate()
 
--First date of the Previous Month
SELECT CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE)-1,0),120) AS [Previous Month]
 
--First date of the Current Month
SELECT CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE),0),120) AS [Current Month]
 
--First date of the Next Month
SELECT CONVERT(VARCHAR(10),DATEADD(MONTH, DATEDIFF(MONTH,0,@DATE)+1,0),120) AS [Next Month]
 
Previous Month
--------------
2013-11-01
 
(1 row(s) affected)
 
Current Month
-------------
2013-12-01
 
(1 row(s) affected)
 
Next Month
----------
2014-01-01
 
(1 row(s) affected)

Thursday, November 21, 2013

Get the records Count of RADGRID using Jquery


<script type="text/javascript">
function RowCount()
{
    var grid = $find("<%=RadGrid1.ClientID %>");
    var MasterTable = grid.get_masterTableView();
    var Rows = MasterTable.get_dataItems();
    alert(Rows.length);
}
</script>

Show selected div on radiobutton list selection using Jquery

<label><input id="rdb1" type="radio" name="toggler" value="1" />Money</label>
<label><input id="rdb2" type="radio" name="toggler" value="2" />Interest</label>

<div id="blk-1" class="toHide" style="display:none">
    First Div
</div>
<div id="blk-2" class="toHide" style="display:none">
    Second Div
</div>

$(function() {
    $("[name=toggler]").click(function(){
            $('.toHide').hide();
            $("#blk-"+$(this).val()).show('slow');
    });
 });

Friday, November 8, 2013

Default location for storing the .SqlLite DB file on MAC

Default Location:
~/Library/Application Support/iPhone Simulator/[SDK version]/Applications/[App GUID]/Documents

To find the path at Finder (Hint):
Right Click on Finder -> Select Go to Folder -> Enter the following 
~/Library/Application Support/iPhone Simulator/




Monday, October 21, 2013

Regular Expression for Email

var regEmail = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";

Wednesday, September 25, 2013

Execute Stored Procedure in Select Statement in SQL Server

How to execute SP in Select Query:

Declare @YourTable table (Column1 int, Column2 int, Column nvarchar(100))

INSERT @YourTable
EXECUTE YourStoredProcedure @InParameter = @InParameterValue

Select * From @YourTable


Note: Columns of temporary table vairables should be same as that of the return rows of the Stored Procedure.


Happy Coding :)

Thursday, August 29, 2013

Regular Expression to strip HTML tags from String in C#

Regex.Replace(htmlString, @"<[^>]*>", String.Empty)

Send Mail using Gmail Host in asp.net

/* Code to Send Mail using Gmail Host Server Settings in asp.net   */

                    var fromAddress = new MailAddress("FromAddress@abc.com", "Display Name");
                    var toAddress = new MailAddress("ToAddress@abc.com", "Display Name");

                    var smtp = new SmtpClient
                    {
                        Host = "smtp.gmail.com",
                        Port = 587,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(fromAddress.Address, "GmailPassword")
                    };

                    var message = new MailMessage(fromAddress, toAddress)
                    {
                        Subject = "MailSubject",
                        Body =  "Mail Body",
                        IsBodyHtml = true
                    };

                    smtp.Send(message);

Friday, June 7, 2013

Multiple Item Templates in Windows Phone

How to use a template selector to dynamically select which item template to use for each list item.


Earlier this year we took a look at working with ListBoxes in a Windows Phone application. That article demonstrated how to style items within a Listbox using a single item template, ensuring that all items in the list have the same layout.
But there are some cases where this isn't the desired behavior. In this article you'll see how to use a template selector to dynamically select which item template to use for each list item.
From the previous article, we'll reuse the design time data; this is a collection of contacts, each with a Name and an ImageUrl property. The corresponding item template for the Listbox was similar to the following XAML, which has an Image control on the left and a TextBlock on the right.

<DataTemplate x:Key="ImageOnLeftItemTemplate">
    <Grid Margin="12,0,0,12">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Image  Width="100"
                Height="100"
                Source="{Binding ImageUrl}" />
        <TextBlock Grid.Column="1"
                    Text="{Binding Name}"
                    Style="{StaticResource PhoneTextLargeStyle}" />
    </Grid>
</DataTemplate>


In this example, we want to change this so  that each alternate contact has the Image on the right side. There are a number  of different ways to do this, but for the purpose of this article we're going  to use a template selector to switch between two different item templates. The  first thing we're going to need is an alternative item template, as in the  following XAML:

<DataTemplate x:Key="ImageOnRightItemTemplate">
    <Grid Margin="12,0,0,12">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding Name}"
                    Style="{StaticResource PhoneTextLargeStyle}" />
        <Image Grid.Column="1"
                Width="100"
                Height="100"
                Source="{Binding ImageUrl}" />
    </Grid>
</DataTemplate>


You can see from this XAML that it's  virtually the same as the previous XAML, with the exception that the columns  have been exchanged, positioning the Image on the right of the TextBlock. You may  wonder how we're going to switch between these two templates, since the ListBox  control only has a single ItemTemplate property. 
The trick is that we need to add a template selector control, which is going to dynamically pick which item template to use. The template selector actually comes in two parts: The first is a reusable abstract class, which can simply be added to any of your Windows Phone projects:

public abstract class TemplateSelector : ContentControl
{
    public abstract DataTemplate SelectTemplate(object item, DependencyObject container);
        
    protected override void OnContentChanged(object oldContent, object newContent)
    {
        base.OnContentChanged(oldContent, newContent);

        ContentTemplate = SelectTemplate(newContent, this);
    }
}


Essentially, the TemplateSelector abstract  class exposes a SelectTemplate method, which needs to be implemented for the  specific scenario within your application. The ContactTemplateSelector, in the  following code block, implements the SelectTemplate method in order to return  an item template used to display the Listbox item.

public class ContactTemplateSelector : TemplateSelector
{
    public DataTemplate ImageLeft
    {
        get;
        set;
    }

    public DataTemplate ImageRight
    {
        get;
        set;
    }


    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
 // Determine which template to return;
    }
}


In this case, the ContactTemplateSelector  has two DataTemplate properties. By exposing these properties it means that the  item templates returned by the SelectTemplate method can be designed in  Expression Blend, rather than being hard-coded within the  ContactTemplateSelector. 
The logic within the SelectTemplate method will vary depending on your application scenario. For this example, we're going to add a bool IsLeft property to the design time data in Expression Blend. Thus the SelectTemplate method uses this property to determine which item template to return.

public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
    var contact = item as ContactsItem;
    if (contact != null)
    {
        return contact.IsLeft ? ImageLeft : ImageRight;
    }

    return null;
}


So far, our XAML has two item templates: ImageOnLeftItemTemplate  and ImageOnRightItemTemplate. We need to add a new template which includes the  ContactTemplateSelector:

<DataTemplate x:Key="SelectingTemplate">
    <local:ContactTemplateSelector Content="{Binding}"
                                    ImageLeft="{StaticResource ImageOnLeftItemTemplate}"
                                    ImageRight="{StaticResource ImageOnRightItemTemplate}"
                                    HorizontalContentAlignment="Stretch" />
</DataTemplate>




We then need to update the Listbox to use  this new item template:

<ListBox x:Name="ContactListBox"
            ItemTemplate="{StaticResource SelectingTemplate}"
            ItemsSource="{Binding Contacts}"
            ItemContainerStyle="{StaticResource FullWidthListBoxItemStyle}" />



When you run this, your application should  look similar to Figure 1.

[Click on image for larger view.]
Figure 1. Alternating item templates.

Monday, May 20, 2013

SQL Query to List All Columns alphabetically


select c.name from
    sys.columns c
    join sys.tables t on c.object_id = t.object_id
where t.name = 'Article'
Order by
    c.name

Tuesday, April 2, 2013

Create Database from the .dbml file in .Net

If you have .dbml file, you just have to write two lines which are as follows:

YourDBMLDataContext objContext = new YourDBMLDataContext();
objContext.CreateDatabase();

Note: Make sure, you have given the right ConnectionString to the .dbml file.

By running the above code, New database will be created in the database server.

Monday, March 25, 2013

Generic Error occured in GDI+ while saving bitmap image

Most of the time, when this kind of issue occurs, then it must be due to the directory you are trying to save to, doesn't have proper permissions. You need to grant write permissions to that directory. 

Thursday, February 21, 2013

How to validate the File Size using JQuery


As the IE is not supporting the HTML 5 File API then what is the solution to check the file size. Well, with IE you can use FileSystem ActiveX object to get the file size. But the problem with latest IE versions (7,8 and 9) is that by default they don't allow ActiveX objects from security reason perspective. If you want to run this, then you have to explicitly allow ActiveX object by changing the settings of IE.

To allow ActiveX -> Go to Tools->Internet Options-> Security->Custom Level->Choose Enable or Prompt ActiveX.

But this is not a perfect solution as you can't ask your end-users to do these kind of settings. Hope that IE 10 will support the HTML 5 API.

So the complete code looks like below code. It first checks if browser is IE or not. If it's IE then using ActiveX object gets the file size. If not then get the file size using HTML 5 API.
$(document).ready(function() {
   $("#flUpload").change(function () 
   { 
     var iSize = 0;
     if($.browser.msie)
     {
        var objFSO = new ActiveXObject("Scripting.FileSystemObject");
        var sPath = $("#flUpload")[0].value;
        var objFile = objFSO.getFile(sPath);
        var iSize = objFile.size;
        iSize = iSize/ 1024;
     }
     else
        iSize = ($("#flUpload")[0].files[0].size / 1024); 

     if (iSize / 1024 > 1) 
     { 
        if (((iSize / 1024) / 1024) > 1) 
        { 
            iSize = (Math.round(((iSize / 1024) / 1024) * 100) / 100);
            $("#lblSize").html( iSize + "Gb"); 
        }
        else
        { 
            iSize = (Math.round((iSize / 1024) * 100) / 100)
            $("#lblSize").html( iSize + "Mb"); 
        } 
     } 
     else 
     {
        iSize = (Math.round(iSize * 100) / 100)
        $("#lblSize").html( iSize  + "kb"); 
     }    
  }); 
});
//Code Ends

Saturday, February 16, 2013

Regular Expressions for Validations in Jquery


1. Allow alphabets only:
var regExpressions = "^([a-zA-Z]+(_[a-zA-Z]+)*)(\s([a-zA-Z]+(_[a-zA-Z]+)*))*$";

2. var validEmail = "^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$"

Wednesday, February 13, 2013

Large File Upload in asp.net


I was trying to upload a larger file to my website (which was recently shifted to IIS7 from IIS6) when I start getting weird error and most common was
"404 not found
The requested document was not found on this server."


with almost a blank white page. I checked my web.config for maxRequestLength attribute and which was properly set that is maxRequestLength = 10240 i.e. I was allowing 10 MB file to be uploaded whereas the file I was trying to upload was just 3 MB, and it was known that files under 10 MB were successfully uploaded in past.

I started googling for the error but unfortunately there wasn't much about this error over the internet.
Started thinking that what special was done with the website recently. There wasn't anything special but the shift from IIS6 to IIS7.

Now when I searched for setting file size in IIS7 I came to know that maxRequestLength is no more functional inIIS7. We have to set maxAllowedContentLength under . Made the required change and whoaaa it start working again.
A thing to remember is that maxAllowedContentLength takes value in Bytes whereas maxRequestLengthaccepts value in Kilo Bytes.
So to set maxAllowedContentLength for 10MB you have to set maxAllowedContentLength = 10485760.
Following is the web.config code which should be set for IIS7 to allow 10MB(say) files.

<­system­.­webServer­>
<­security­>
<­requestFiltering­>
<­requestLimits maxAllowedContentLength="10485760"­/­>
<­/­requestFiltering­>
<­/­security­>
<­/­system­.­webServer­>

Wednesday, January 30, 2013

Query for fetching the records in Parent-Child DB table in SQL Server

DECLARE @FileTreeId INT = 300 (For instance)

;WITH FileTreeHierarchy AS
(
    SELECT FileTreeID, Company, Parent, Name, 1 AS 'Level'
    FROM FileTree 
    WHERE FileTreeID = @FileTreeId

    UNION ALL

    SELECT F.FileTreeID, F.Company, F.Parent, F.Name, 
    FH.Level + 1 AS 'Level'
    FROM FileTree F
    INNER JOIN FileTreeHierarchy FH ON FH.Parent = F.FileTreeID
)
 
SELECT FileTreeId, Company CompanyId, Parent, Name, 
[Level] = CAST([Level] as int) 
FROM FileTreeHierarchy Order By [Level] Desc 

Tuesday, January 29, 2013

Add Dynamic textboxes using Jquery

<head>
<script type="text/javascript">
function AddMoreTextboxes() {
    var counter = 1;
    var firstTextboxValue = $("#txtselectedValue").val();
    if (firstTextboxValue == '') {
        alert('Enter the value in First Textbox !');
        return;
    }
    else {
        if (counter > 5) {
            alert("Only 5 textboxes allow");
            return false;
        }
        var newTextBoxDiv = $(document.createElement('div'))
             .attr("id", 'TextBoxDiv' + counter);

        newTextBoxDiv.attr("class", "newTextBoxDiv");

        newTextBoxDiv.after('<label></label>' + '<input type="text" name="textbox' + counter +
            '" id="textbox' + counter + '" />').html('<label></label>' +
            '<input type="text" style="width:200px;" class="newTextbox" name="textbox' + counter + '" id="textbox' + counter + '" value="" />');

        newTextBoxDiv.appendTo("#TextBoxesGroup");
        counter++;
    }
}
</script>
</head>
<body>
<div>
<img src="../../Images/plus.png" width="16" height="16" id="ImgAddMoreTextbox" onclick="AddMoreTextboxes();" />
</div>
</body>

Monday, January 21, 2013

Delete all User-Defined Stored Procedures in SQL Server


declare @procName varchar(500)
declare cur cursor

for select [name] from sys.objects 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