Wednesday, January 21, 2015

Autocomplete Location Search using Google API in .Net Jquery

The following code is implemented in Razor MVC:

1. _TestView.cshtml
<script src="https://maps.google.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>
/*
Your JQuery Files
*/
<div>
/* Your View Code */
.
.
.
.
<input id="txtLocation" type="text" />
</div>



2. Jquery Code:
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
    var input = document.getElementById('textbox_Location');
    var autocomplete = new google.maps.places.Autocomplete(input);


    google.maps.event.addListener(autocomplete, 'place_changed', function () {

        var place = autocomplete.getPlace();
        if (typeof (place.address_components) !== 'undefined') {
            //Saved location
            var placeName = place.name;
            var completeAddress = place.formatted_address;
            var latValue = place.geometry.location.lat();
            var lonValue = place.geometry.location.lng();
        }      
        return false;
    });
}
 




Monday, December 15, 2014

C#: Update specific column(s) of the generic list with one value in different ways (Without iteration)

C#: Update one value to specific column(s) of the generic list in many ways:

1. Update column of each item of the list using Select() Clause: 

collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();

Here, The ToList() is needed in order to evaluate the select immediately 
due to lazy evaluation. 
 

2.Update list using ForEach(): 

collection.Where(c => IdsList.Contains(c.PkId).ToList().ForEach(cc => cc.PropertyToSet = "Updated Value");

 

Sunday, November 9, 2014

Create Entity Class based on Database Schema Structure

Create Entity Class based on Database Schema Structure

declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'char'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
            then '?'
            else ''
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Monday, August 18, 2014

Simple Task Scheduling in asp.net website in Global.asax file

Global.asax.cs

private static DateTime taskLastRun;

void Application_Start(object sender, EventArgs e)
{
    taskLastRun= DateTime.Now;
}
 
void Session_Start(object sender, EventArgs e)
{
  DoTask();
}

/*Private method implemented in Global.asax file.
* Example Task to run every time application runs
* In this, it will delete the one day old files stored in uploads directory. 
*/

static void DoTask()
{
  var aDayAgo = DateTime.Now.AddDays(-1);
  if (taskLastRun.IsGreaterThan(aDayAgo))
  {
    var path = HttpContext.Current.Server.MapPath("Uploads");
    var folder = new DirectoryInfo(path);
    FileInfo[] files = folder.GetFiles();
    foreach (var file in files)
    {
      if(file.CreationTime.IsOlderThan(aDayAgo))
      {
        File.Delete(path + file.Name);
      }
    }
    taskLastRun= DateTime.Now;
  }
}
 
//Extension method to compare two dates 
public static bool IsGreaterThan(this DateTime dt1, DateTime dt2)
{
  return dt1 < dt2;
} 

Thursday, August 14, 2014

Check if page is PostBack in asp.net at the client side using Jquery

 

Design:

 
<script type="text/javascript">
    $(document).ready(function () { 
    //Check here if Page is postback and fire events accordingly.
    if (isPostBack){ 
 
     }
});  
</script>
 

Code Behind:


    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack",
                                                   IsPostBack ? "var isPostBack = true;" : "var isPostBack = false;",
                                                   true);
    }

Wednesday, July 9, 2014

Allow entering only numeric values using jquery in asp.net

Jquery


<script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8);                       //Backspace

        jQuery(document).ready(function () {
            $(".numeric").bind("keypress", function (e) {
                var keyCode = e.which ? e.which : e.keyCode
                var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
                $(".intervalError").css("display", ret ? "none" : "inline");
                return ret;
            });
            $(".numeric").bind("paste", function (e) {
                return false;
            });
            $(".numeric").bind("drop", function (e) {
                return false;
            });
        });
    </script>

 .Aspx Web Form

//Textbox for Entering Age (allowing only numeric values to enter here)
 <div>
<asp:TextBox CssClass="numeric" ID="txtAge" runat="server" />
</div>





Tuesday, July 1, 2014

Reference CSS / Js Files in asp.net using ResolveUrl()

If you need to reference jQuery and jQueryUI your MasterPage <head> should look similar as the following:



<link href="<%# ResolveUrl("~/") %>css/custom-theme/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />

 <script src="<%# ResolveUrl("~/") %>Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
 <script src="<%# ResolveUrl("~/") %>Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>