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>

Monday, June 23, 2014

Autoclose Message box in Window Forms C#


Helper Class:

public class AutoClosingMessageBox
    {
        System.Threading.Timer _timeoutTimer;
        string _caption;
        AutoClosingMessageBox(string text, string caption, int timeout)
        {
            _caption = caption;
            _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
                null, timeout, System.Threading.Timeout.Infinite);
            MessageBox.Show(text, caption);
        }
        public static void Show(string text, string caption, int timeout)
        {
            new AutoClosingMessageBox(text, caption, timeout);
        }
        void OnTimerElapsed(object state)
        {
            IntPtr mbWnd = FindWindow(null, _caption);
            if (mbWnd != IntPtr.Zero)
                SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            _timeoutTimer.Dispose();
        }
        const int WM_CLOSE = 0x0010;
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    }

Calling:

//Three parameters: Text to be shown, Caption and message timeout in milliseconds
AutoClosingMessageBox.Show("Message to be shown", "Caption", 5000);

Monday, June 2, 2014

Change Language in SQL

SQL Query


Set LANGUAGE Norwegian

Select Datename(month, getdate())


Output:


juni

Wednesday, May 21, 2014

Another way to remove the specific item From n-dimensional array using Jquery


//Array 
var elementsArray = [
        { name: 'First Element', id: 1},
        { name: 'Second Element', id: 2 },
        { name: 'Third Element', id: 3 },
       ];


//Jquery Function to remove the current object from the array
    function RemoveElementFromArray(array, id) {
        if (array != null && array.length > 0) {
            array = $.grep(array, function (value) {
                return value.id != id;
            });
            return array;
        }
        else {
            return null;
        }
    }


//Calling
function remove()
{
//For instance, we want to remove the 2nd element having ID 2

elementsArray  =  RemoveElementFromArray(elementsArray, 2);
for(int i=0; i<elementsArray.length; i++)
{
alert(elementsArray[i].name);
}
}

Tuesday, May 6, 2014

Pass DataTable to SQL Server Stored Procedure using C# ADO.Net

Database:

//Create new type (i.e. Table data type) as input parameter to be used in ADO.Net SQL Command

CREATE TYPE DtFile as Table
(
    Id int
)

//Create Procedure and use the above created type in it.

Create Proc dbo.UspInsertFileData
(
@FileId dbo.DtFile READONLY
)
AS
Begin
        INSERT INTO MainFileData (FileId, AddedOn)
        SELECT Id, GETDATE() From dbo.DtFile
End

C# Asp.Net:

Data Access Layer:


public static int InsertFileData(DataTable dtFileIds)
{
         var sqlConnectionString = ConfigurationManager.AppSettings["fileConnection"];
         var sqlParameters = new SqlParameter[1];
         sqlParameters[0] = new SqlParameter
                                   {
                                       ParameterName = @"FileId",
                                       SqlDbType = SqlDbType.Structured,
                                       Value = fileTreeIds,
                                       TypeName = @"DtFile"
                                   };
          var result = SqlHelper.ExecuteScalar(sqlConnectionString,  CommandType.StoredProcedure,  @"UspInsertFileData" , sqlParameters);          return Convert.ToInt32(result);
}

Presentation Layer:

protected void BtnClickAddFileData(object sender, EventArgs e)
{
      var fileIds = new[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
      var dtFileData = new DataTable();
      if (fileIds.Length > 0)
      {
                /* Make Sure to keep the name of the data column same as given in the SQL User-Defined  type */
                dtFileData.Columns.Add(new DataColumn(@"Id", typeof(int)));
                foreach (var id in fileIds)
                {
                           var dr = dtFileData.NewRow();
                          dr["FileTreeId"] = item;
                          dtFileData.Rows.Add(dr);
                          dtFileData.AcceptChanges();
                }
       }
       var result = Dal.InsertFileData(dtFileData);
}



Tuesday, April 29, 2014

Regular Expression for Password

var Password_REGEX = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[_*#&%@]).{8,}$/;

It meets the following criteria:
- Minimum 8 charaters
- At least one number, one alphabet and one special charater.

Thursday, April 17, 2014

Explicitly Set the MAX Size to SQLParameter Object C#

ByDefault, it will take max 400 characters. E.g.
sqlParameters[1] = new SqlParameter("@usernames", usernames);

We can explicitly Set the MAX Size to SQLParameter Object by the following way:
sqlParameters[1] = new SqlParameter("@usernames", SqlDbType.NVarChar, -1,
                                                usernames);


Wednesday, April 16, 2014

Use Multiple With Clause in one SQL Query

;With T (Name)
AS
(Select Top 1 Test1Name From Test), 
T2 (Name2) as
(
Select Top 1 Test2name From Test2
),
T3 (Name3) as
(
Select TOP 1 Test3Name From [Test3]
)
Select T.Name, T2.Name2, T3.Name3 From T, T2, T3

Thursday, April 10, 2014

Validate Emails Array using Jquery

var emailsString = "amit.jain@test.com, amit@test.com, aj@test.com";

var emailValidator = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var emails = emailsString.split(",");
var result = false;
var pattern = new RegExp(emailValidator);
        $.each(emails, function (i) {
            debugger;
            if (emails[i] != null && emails[i] != '') {
                var email = $.trim(emails[i]);
                result = pattern.test(email);
                if (!result) {
                    alert("Enter the valid email(s) and try again !");
                    return false;
                }
            }
        });

Wednesday, February 5, 2014

How to dynamically set the application start page on Windows Phone 8

Introduction

The default start page for an application is set in WMAppManifest.xml - in the DefaultTask node of theNavigationPage tag. While having a static start page is ideal for some apps, there are many cases where it is useful to be able to dynamically select the start page.
For example, it is often useful to have:
  • a different start page for when user login credentials are stored from when they are not stored
  • a "wizard" start sequence for the first time the user activates the app
The article shows how to change the remove the default page and dynamically set the new start page in C# code. It uses the context of an app which has different screens for logging in (Login.xaml) and for when they have already entered their details (HomeScreen.xaml).
Note: It is also possible to have a default page which dynamically configures itself. While this may be suitable in many cases, usually it is better for code maintenance to have separate pages.

Removing the default page

The first step is to remove the default page that us set by default in the manifest file (WMAppManifest.xml) in apps created from the standard templates.
Simply remove NavigationPage="MainPage.xaml" from the code below.
<Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
</Tasks>


For instance:
<Tasks>
      <DefaultTask Name="_default" />
</Tasks>

Set the Start Page / View after the App has initialised

The start page is specified in InitializePhoneApplication() by calling RootFrame.Navigate() (after other initialisation has completed).
RootFrame.Navigate(new Uri("/StartPage.xaml", UriKind.RelativeOrAbsolute));
The example below shows a different start page being selected based on a check of the application settings to determine if login information has already been stored (Login status is checked with IsolatedStorageSettings.ApplicationSettings.Contains("islogin").)
  private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;
 
            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;
 
            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;
 
            // Handle reset requests for clearing the backstack
            RootFrame.Navigated += CheckForResetNavigation;
 
            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
 

           // Set the Start Page according to the below code.
//Here, If IsolatedStorageSettings contains "isLogin" key, then it is redirected to HomeScreen that normally comes after login screen.            Uri uri;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("islogin"))
            {
                if (!(Convert.ToString(IsolatedStorageSettings.ApplicationSettings["islogin"]).ToLower() == "yes"))
                {
                    RootFrame.Navigate(new Uri("/LoginScreen.xaml", UriKind.RelativeOrAbsolute));
                }
                else
                {
                    RootFrame.Navigate(new Uri("/HomeScreen.xaml", UriKind.RelativeOrAbsolute));               
                }
            }
            else
            {
                RootFrame.Navigate(new Uri("/LoginScreen.xaml", UriKind.RelativeOrAbsolute));
            }          
        }


Tuesday, February 4, 2014

Consume data from REST service, Serialize / Deserialize the json string in Windows Phone 8 Apps


CommonClass:
Below are the Microsoft built-in Generic Methods to serialize / deserialize JSON data in Windows Phone 8:
        public static T DeserializeJSon<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(stream);
            return obj;
        }

        public static string SerializeToJson<T>(T obj)
        {
            MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer jsonSer =
            new DataContractJsonSerializer(typeof(T));
            jsonSer.WriteObject(stream, obj);
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            var json = sr.ReadToEnd();
            return json;
        }


Now, to get the data from REST and deserialize the result json, back to object in Windows Phone 8:

        public static void GetDataAsync<T>(string restServiceMethodUrl)
        {
            var jsonResult = string.Empty;
            var webClient = new WebClient();

            webClient.DownloadStringAsync(new Uri(restServiceMethodUrl));
            webClient.DownloadStringCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    jsonResult = e.Result.ToString();
                    var objActualData = DeserializeJSon<TestViewModel>(jsonResult);
                }
            };
        }


To post / get data basis with input parameters, below is the method in Windows Phone 8:

        public static void PostDataAsync<T>(Uri uri, ObjectAsInput obj)
        {
            var jsonResult = string.Empty;
            var webClient = new WebClient();
            var jsonDataInput = SerializeToJson<ObjectAsInput >(obj);

            if (!string.IsNullOrEmpty(jsonDataInput))
            {
                webClient.Headers["Content-Type"] = "application/json; charset=utf-8";
                webClient.UploadStringAsync(uri, jsonDataInput);
                webClient.UploadStringCompleted += (s, e) =>
                {
                    if (e.Error != null)
                    {
                        jsonResult = e.Result.ToString();
                        var actualData = DeserializeJSon<TestViewModel>(jsonResult );
                    }

                };
            }
        }

        

Friday, January 31, 2014

Bind dataitem properties inside the method called in templatefield of DataGrid in asp.net

Bind dataitem properties inside the method called in templatefield of DataGrid in asp.net

<asp:DataGrid ID="overview_propertie" runat="server" AutoGenerateColumns="false"
                        CellPadding="0" CssClass="propertylist" GridLines="None" UseAccessibleHeader="true"
                        Width="100%" ShowHeader="False">
                        <AlternatingItemStyle CssClass="row1" />
                        <Columns>
                            <asp:BoundColumn DataField="Name" HeaderText="<%$ Resources:property%>" ItemStyle-CssClass="header">
                                <ItemStyle CssClass="header" />
                            </asp:BoundColumn>
                            <asp:BoundColumn DataField="Value" HeaderText="<%$ Resources:value%>" />
                            <asp:BoundColumn DataField="Description" HeaderText="Description" ReadOnly="true" />
                            <asp:TemplateColumn>
                                <ItemTemplate>
                                    <table>
                                        <tr>
                                            <td>
                                                <%# GetPropertyFiles(DataBinder.Eval(Container.DataItem, "ItemId"), DataBinder.Eval(Container.DataItem, "PropertyTypeId"))%>
                                                <a class="AttachButton" href="javascript://" onclick="return AddItemPropertyFiles('<%#Eval("ItemId") %>','<%#Eval("PropertyTypeId") %>');">
                                                    Attach File</a>

                                            </td>
                                        </tr>
                                    </table>
                                </ItemTemplate>
                            </asp:TemplateColumn>
                        </Columns>
                    </asp:DataGrid>

Wednesday, January 29, 2014

Issue "Unable to launch the IIS Express Web server"

Today I was figuring out the issue “Unable to launch the IIS Express Web server, Port is in use”
So, I was pushing hard to find the way how to manually assign the port to my VS Solution.
Here's the one:

Steps to manually assign the port to VS 2012 Solution:
1. Right Click on the Start-up executable Project that you are trying to run and select option properties. (See Screenshot 1 below)

 Screenshot 1


2. Now, You will the list of options in the left-panel menu. Select option 'Web'. (See Screenshot 2)




Screenshot 2

3. Here you will find the option 'Use Visual Studio Developement Server' under the Servers Section
4. Do Check it, select Specific Port and assign your own port number (say 8115 See Screenshot 2 above). Let the other options remain intact.
5. I hope you will able to run your project successfully.

Thanks
Amit Jain