So Image gallery is an essential feature in mobile apps. So I created a video on how to create Image gallery in ionic using ion-gallery plugin
Month: August 2016
Remote modal validation attribute in ASP.NET MVC
We can use validation attribute to validate forms. Using Jquery validation plugin we can do client side validation with the help of modal validation attribute in mvc.
I have a post on client side validation.
Client Side Form validation in ASP.NET MVC
So some times we need to connect with server to validate properties. So now it is painless. We have Remote attribute to validate such properties behind the seen.
Let’s suppose we need to validate user name property. User name should be validated with server. It can not be duplicated. So we can Use Remote validation attribute.
To validate want to connect to the server. So we can provide controller action to Remote attribute to call action and validate property behind the seen.
We can decorate property as below
[Remote("CheckUserName","Home", ErrorMessage ="User name already exists" ) ]
public string UserName { get; set; }
Modal class

In action we should return true or false. if false returned from action error message will be shown.
Action
public JsonResult CheckUserName(string username)
{
//logic for check user name with database
return Json(false, JsonRequestBehavior.AllowGet);
}

My sample view contains form for enter user data
@model RemoteAttributeTestMVC.Models.User
@{
ViewBag.Title = "Home Page";
}
<div class="row" style="margin-top:10px;">
@using (Html.BeginForm("CreateUser", "Home"))
{
<div class="form-group order-form-group">
@Html.LabelFor(m => m.UserName)
@Html.EditorFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
}
</div>
This will render following form

To allow client side validation we have to add jquery validation plugin . I have added reference in _Layout.cshtml as below

Then run the project and when we enter values in user name text box and press tab it sends a request to CheckUserName action with parameter of user name behind the seen.
if action return false validation message will be shown in the form.

Custom session store in ASP.NET MVC with Dependency Injection
In this post I will explain creating custom session helper with Unity DI.
Step 1
Create empty MVC project
Step 2
Add new folder called Utility and Add a interface with name of ISession. In a real project we can separate this logic into another project.
ISession interface
T Get<T>(string key); void Set<T>(string key, T entry);
Step 3
Add a class called CustomSessionStore and implement ISession interface.
Add following logic to class.
public T Get<T>(string key)
{
HttpContext currentContext = GetSessionContext();
return (T)currentContext.Session[key];
}
public void Set<T>(string key, T entry)
{
HttpContext currentContext = GetSessionContext();
currentContext.Session[key] = entry;
}
private static HttpContext GetSessionContext()
{
HttpContext currentContext = HttpContext.Current;
if (currentContext == null)
{
throw new InvalidOperationException();
}
return currentContext;
}
we have to add System.Web reference in top of page
using System.Web;
Step 4
Add Unity.MVC to project via nuget package manager

Then we can see Two new classes inside App_Start folder

In UnityConfig.cs we can register dependecy as below.

Step 5
The add a controller called HomeController and implement as below

So as above we can easily set value to session using Set method. We can store any type of values since it is generic. Only thing we have to provide is type when saving and retrieving values as shown as above.
Prevents texts being selectable in Jquery
So in some situations it is needed to prevent user from selecting text in web page.
So it will play nice in some situations like drag and drop.
So it can be done using Jquery.
$('p').attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
Amazing File Upload with Jquery fileupload js in ASP.NET MVC

I just created a project for Uploading files in ASP.NET MVC with Jquery file upload pluging.
It has drap and drop feature also.
Could not load file or assembly ‘Newtonsoft.Json, Version=6.0.0.0, or one of its dependencies. The system cannot find the file specified.
Could not load file or assembly ‘Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’ or one of its dependencies. The system cannot find the file specified.
I got this error when I added to WEB API to ASP.NET MVC project.
So This is how I get it solved
Run this command in package manager console
Update-Package –reinstall Newtonsoft.Json
MERGE in Sql Server
From Sql server 2012 we can merge two tables. We can map data from one table to another table. If record exists can do a update and if not insert operation can be done.
Syntax
MERGE <target_table> USING <table_source> ON <Search> WHEN MATCHED THEN UPDATE SET <set_clause> WHEN NOT MATCHED THEN INSERT VALUES (<values_list>)
Create two tables and Insert some records
CREATE TABLE TargetTable([Id] INT, [Name] NVARCHAR(50)) CREATE TABLE SourceTable([Id] INT, [Name] NVARCHAR(50)) INSERT INTO TargetTable(Id,Name) VALUES(1, 'John'), (2, 'Mezi'), (3, 'Tom') INSERT INTO SourceTable(Id,Name) VALUES(1, 'JohnNew'), (4, 'Peter'), (3, 'Tom-new')
Then do Merge
MERGE TargetTable AS T USING SourceTable AS S ON T.Id = S.Id WHEN MATCHED THEN UPDATE SET T.Name = S.Name WHEN NOT MATCHED THEN INSERT VALUES (S.Id, S.Name);
Now view TargetTable Data

CHOOSE and IIF in Sql server
CHOOSE
- Returns a list item based on its location
- First parameter is index
- Next parameters are list
SELECT CHOOSE(2,'item1','item2' ) -- this will return item2 SELECT CHOOSE(1,'item1','item2' ) -- this will return item1 SELECT CHOOSE(1,[StandardCost],[ListPrice]) FROM [Production].[Product] p WHERE p.ProductID = 680 --this will return StandardCost
IIF
- Instant if
- Three parameters
- Boolean expression
- Return value if true
- Return value if false
SELECT IIF([ListPrice] > 0, [ListPrice], [StandardCost]) AS 'price' FROM [Production].[Product] p -- if ListPrice is greater than 0 it returns Listprice. Otherwise returns StandardCost
Sub Query in Sql
What is subquery?
Subquery is just a query inside of a query.
Why Subquery?
- Break down complex logic
- Simplify reading
Subqueries can be replaced by joins. But some times Joins can be complex. Other thing is we are not allowed to put aggregates in WHERE. But we can put it aggreagates inside subquery .
Where to Use?
We can put sub queries in three main places in query.
- SELECT
- FROM
- WHERE
Using in SELECT
- Access informations from tables withing select query
- Query must return a single(scalar) value
Creates a dynamic table. Useful for breaking down queries. Query must be aliased.
Note : I have used Adventureworks 2012 database for following queries
SELECT so.[SalesOrderID] ,so.OrderDate ,(SELECT COUNT([SalesOrderDetailID]) FROM [Sales].[SalesOrderDetail]sod WHERE sod.SalesOrderID = so.SalesOrderID ) AS 'OrderLineCount' FROM [Sales].[SalesOrderHeader] so

Using with FROM
SELECT so.[SalesOrderID] ,so.OrderDate ,X.OrderQty AS 'TotalItems' FROM [Sales].[SalesOrderHeader] so INNER JOIN (SELECT SUM([OrderQty]) AS 'OrderQty' , [SalesOrderID] FROM [Sales].[SalesOrderDetail] sod GROUP BY [SalesOrderID]) AS X ON so.[SalesOrderID] = X.[SalesOrderID]

With WHERE
Useful for comparing values from other tables
Predicates used with subqueries
IN
- Confirm column value exist in subquery
- Similar to inner join
SELECT [AccountNumber] FROM [Sales].[Customer] sc WHERE sc.CustomerID IN ( SELECT DISTINCT [CustomerID] FROM [Sales].[SalesOrderHeader] soh )
EXISTS
- Returns true if subquery returns value
- Used with correlated queries
Correlated subquery
Pass outer query column into subquery