Thursday, 18 December 2014

File upload using jquery Asp.Net MVC

 File Upload in ASP.NET MVC via ajax

Problem

While looking for fileupload options via ajax and without posting the whole form, we often come across code in the internet using FormData API, which works perfectly fine on chrome and mozilla but on on IE. so a code snippet using a FormData API would like this below
//View Code
<script type="text/javascript">
    function save() {
        $("#test").submit();
    }
    function submitForm() {
        var formData = new FormData($('#test')[0]);
            $.ajax({
                url: '@Url.Action("Upload","FileUpload")',
                type: 'POST',
                data: formData,
                async: false,
                success: function (data) {
                    alert('posted')
                },
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
    }
</script>
<h2>Index</h2>
<input type="button" value="Submit" onclick="save();" />
    
<form id="test" action="javascript:submitForm();" method="post" enctype = "multipart/form-data">
    <div>
        <label for="fileUpload">File upload</label>
        <input type="file" id="fileUpload" name="fileUpload" />
    </div>
</form>
//Controller Code
public ActionResult Upload()
        {
            HttpPostedFileBase postedFile = Request.Files[0];
            return View();
        }
The above snipped works fine on chrome and mozilla and you will be able to see the postedFile in the controller but it does not work on IE because most versions of IE does not support FormData.

Solution

So the solution I came up with after going some recommendations over internet about HTML controls on different browsers is that its better to use iframes. So Idea is to point the target of the form to an iframe and even bind a load event to the iframe so that you know when the upload is finished and write additional jquery functions. Also you can even hide the iframe and not show the user. But this solution works on IE as well. The code is as below
The code also shows how to post additional data along with the file post.
@{
    ViewBag.Title = "Index";
}
<script src="~/scripts/jquery-1.9.1.min_.js"></script>
<script type="text/javascript">
    function successFunction() {
        alert($('#my_iframe').contents().find('p').html());
    }
    function redirect() {
        //debugger;
        document.getElementById('my_form').target = 'my_iframe'; //'my_iframe' is the name of the iframe
        //document.getElementById('my_form').submit();
        var callback = function () {
            if (successFunction)
                successFunction();
            $('#frame').unbind('load', callback);
        };

        $('#my_iframe').bind('load', callback);
        $('#hfParam').val('id:1');

        $('#my_form').submit();
        //$("#my_form").trigger("submit");
     
    }
</script>
<h2>Index</h2>
<input type="button" name="action" value="Upload" onclick="redirect();"/>
<form id="my_form" name="my_form" action="/FileUpload/UploadFile" method="POST" enctype="multipart/form-data" >
    <div id="main">
        <input name="my_hidden" id="hfParam" type="hidden" />
        <input name="my_files" id="my_file" type="file" />
        <iframe id='my_iframe' name='my_iframe' src="">
        </iframe>
        <div id="someDiv"></div>
    </div>

</form>


[HttpPost]
        public ActionResult UploadFile()
        {
            ContentResult result = new ContentResult() { Content = "<p></p>", ContentType = "text/html"};
            HttpPostedFileBase postedFile = Request.Files[0];
            try
            {
                result.Content = "<p>" + postedFile.FileName + "</p>";
            }
            catch (System.Exception ex)
            {
                result.Content = ex.Message;
            }
            return result;
        }

Wednesday, 17 December 2014

Sql query to add new column in table

Syntax:

ALTER TABLE TableName
ADD ColumnName Datatype

Example:

ALTER TABLE AspNetUsers
ADD SubscripionDate datetime null

Tuesday, 28 October 2014

Format number or add comma separation using Jquery

<!-- Add below script CDN is to apply currency formmater using jquery -->

    <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>

Format

Numbers can be formatted to look like currency, percentages, times, or even plain old numbers with decimal places, thousands, and abbreviations.

var string = numeral(1000).format('0,0.00');
// '1,000.00'

Reference link: http://numeraljs.com/

Friday, 17 October 2014

How to apply Special character validation using Jquery

<input type="text" name="txtKeywords" id="txtKeywords" />
<input type="submit" value="Search" title="Search" id="btnSearch"  />

<script>
    $(document).ready(function () {
        $("#btnSearch").click(function () {

            var titleValue = $("#txtKeywords").val();

            // Apply check for special characters
            if ((/^[a-zA-Z0-9- ]*$/.test(titleValue) == false) ) {
                alert('Your String Contains illegal Characters.');
                return false;
            }
         
        });
    });
</script>

Thursday, 16 October 2014

Difference between loose coupling and tight coupling in object oriented paradigm

Tight coupling is when a group of classes are highly dependent on one another.

This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.
Interfaces are a powerful tool to use for decoupling.

Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface.

Example of tight coupling:

class CustomerRepository
{
    private readonly Database database;

    public CustomerRepository(Database database)
    {
        this.database = database;
    }

    public void Add(string CustomerName)
    {
        database.AddRow("Customer", CustomerName);
    }
}

class Database
{
    public void AddRow(string Table, string Value)
    {
    }
}

Example of loose coupling:


class CustomerRepository
{
    private readonly IDatabase database;

    public CustomerRepository(IDatabase database)
    {
        this.database = database;
    }

    public void Add(string CustomerName)
    {
        database.AddRow("Customer", CustomerName);
    }
}

interface IDatabase
{
    void AddRow(string Table, string Value);
}

class Database : IDatabase
{
    public void AddRow(string Table, string Value)
    {
    }
}

Enjoyyy.... !!!!

Wednesday, 15 October 2014

Example to create Facebook App to show list of friends using FQL(Facebook Query Language) and send Invite in C# (MVC)

To create such App firstly we need to create Facebook Developer account to get the Facebook Application Id.

Refer this link to create developer account and get FB App Id : 

Here we have used MVC  to develop this :

1. Create a controller of name PeopleController

2. Create an action

     public ActionResult InviteFBPeople()
        {
            return View();
        }

3. Create view for above action

@{
    ViewBag.Title = "Invite Facebook People";
}

<h2>Invite Facebook Friends</h2>

<div id="fb-root" style="display:inline; margin-left:20px;"></div>

<script language="javascript" type="text/javascript">
    //Facebook SDK initialize portion
    window.fbAsyncInit = function () {
        FB.init({
            appId: 'YourFBAppID',
            status: true, cookie: false, xfbml: true
        });
    };
    // All FB resources
    $(document).ready(function () {
        if (document.getElementById('fb-root') != undefined) {
            var e = document.createElement('script');
            e.type = 'text/javascript';
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }
    });

</script>

<script>
    // This is to get the Access Token of FB
    $(document).ready(function () {
        setTimeout(function () {
            //something you want delayed
            FB.getLoginStatus(function (response) {
                if (response.status === 'connected') {
                    var fbAccessToken = response.authResponse.accessToken;
                    window.location = '@Url.Action("ListFacebookFriends", "People")' + "?id=" + fbAccessToken;

                }
            });

        }, 2000);

    });
</script>

4. In above script we have made to fetch the access token of logged in FB user and passed it to an action of name "ListFacebookFriends" in same People Controller, 

 public ActionResult ListFacebookFriends(string id)
        {
            //get current access token
            var accessToken = id;

            List<FacebookFriends> Friends = new List<FacebookFriends>();

            if (accessToken != "")
            {

                Friends = GetFriends(accessToken, false,"").ToList();

            }

            ViewBag.FbFriends = Friends;


            return View();
        }

5. Create Function of name GetFriends 

public IEnumerable<FacebookFriends> GetFriends(string accessToken, bool isUsing)
            {
                string strQuery = string.Empty;
                if (isUsing)
                {
                    strQuery = "SELECT uid, name, pic_square, email FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND is_app_user";
                }
                else
                {
                    strQuery = "SELECT uid, name, pic_square, email FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND NOT is_app_user";
                }

                FacebookClient objFQL = new FacebookClient(accessToken);

                dynamic parameters = new ExpandoObject();
                parameters.q = strQuery;

                dynamic objFNU = objFQL.Get("fql", parameters);

                List<FacebookFriends> friendsToReturn = new List<FacebookFriends>();

                if (objFQL != null)
                {
                    foreach (dynamic row in objFNU.data)
                    {
                        friendsToReturn.Add(new FacebookFriends()
                        {
                            FriendID = Convert.ToString(row.uid),
                            FriendName = row.name,
                            PicURLSquare = row.pic_square,
                            Email = row.email
                        }
                    );
                    }
                }

                return friendsToReturn;
            } //Get FB Friends not already using this app

6. Create class of name FacebookFriends.

    public class FacebookFriends
        {
            public string FriendID { get; set; }
            public string FriendName { get; set; }
            public string PicURLSquare { get; set; }
            public string ProfileLink { get; set; }
            public bool Follower { get; set; }
            public string Email { get; set; }
            public string UserName { get; set; }
}

7. Create view for action "ListFacebookFriends".

@{
    ViewBag.Title = "ListFacebookFriends";
}

<div id="main">

    <div >
        
        <div >
            <h2>List of Facebook Friends</h2>
            <div ></div>
            <div id="fb-root" style="display:inline; margin-left:20px;"></div>

            <script type="text/javascript">
                //Initialize facebook SDK
                window.fbAsyncInit = function () {
                    FB.init({
                        appId: '470021713099348',
                        status: true, cookie: false, xfbml: true, frictionlessRequests: true
                    });
                };

                // All FB resources
                $(document).ready(function () {
                    if (document.getElementById('fb-root') != undefined) {
                        var e = document.createElement('script');
                        e.type = 'text/javascript';
                        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
                        e.async = true;
                        document.getElementById('fb-root').appendChild(e);
                    }
                });

                // Send Invite to friends
                function sendRequestToRecipients(targetid) {
                    FB.ui({
                        method: 'apprequests',
                        message: 'Try Talentcubed.com',
                        description: 'Play Games Get Hired',
                        to: targetid
                    }, requestCallback);

                    //    method: 'feed',

                }

                function requestCallback(response) {
                    // Handle callback here
                    var uid = response['to'];
                    var link = $('#inv_' + uid);
                    link.removeAttr('href');
                    $("#img_" + uid).fadeOut();
                }
                $(document).ready(function () {
                    $("#btnSearch").click(function () {
                        window.location = '@Url.Action("Search", "Wall")' + "?id=people";
                    });
                });
            </script>

            <div id="ListFbFriends">
                <div class="signupsearchTop" style="display:none;">
                    <input name="signupsearch" id="signupsearch" type="text" size="18" maxlength="150" placeholder="search for" class="signupfield" />
                    <input type="image" src="/images/btnsearch.jpg" name="image" class="signupsearchbtn" width="24" height="21">
                </div>

                <ul>
                    @foreach (var Friend in ViewBag.FbFriends)
                    {
                        <li>
                            <div ><img src='@Friend.PicURLSquare' alt='Friends' /></div>
                            <div ><p >@Friend.FriendName</p></div>
                            <div >
                                <a href="javascript:sendRequestToRecipients('@Friend.FriendID');" id="inv_@Friend.FriendID">Invite</a>
                            </div>
                        </li>
                    }
                </ul>
                
            </div>

        </div>

    </div>
    <!--row clearfix end -->
</div>

Enjoyyyyy...... !!!!!!




Monday, 25 August 2014

Convert HTML content values to Object in C# using Html Agility Pack (HAP)

In below code sample we are passing HTML in variable of name dataStream, In HTML we have a table of which we made to convert <th> and <td> in objects directly, using HAP(Html Agility Pack) need to be added using Nuget Package in our Native Application.
Sample Code:
using HtmlAgilityPack;
// Import Html table to datatable, Using “Html Agility Pack(Nuget)”
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(dataStream);
var headers = doc.DocumentNode.SelectNodes(“//tr/th”);
List<string> headingList = new List<string>();
List<string> valueList = new List<string>();
// Add th values in h
foreach (HtmlNode header in headers)
{
var headText = header.InnerText; //Get head columns from th
headText = headText.Replace(“:”, “”); // Remove colon(:) sign from head text
headingList.Add(headText);
}
// Select rows with td elements
foreach (var row in doc.DocumentNode.SelectNodes(“//tr[td]“))
{
var valueText = row.SelectNodes(“td”).Select(td => td.InnerText).ToArray();
var strValue = valueText[0].ToString();
valueList.Add(strValue);
}
Reference Link:

Error Logging using ELMAH in Asp.Net Web Application completely pluggable

Error Logging Modules And Handlers (ELMAH) offers another approach to logging runtime errors in a production environment.
It can be dynamically added to a running Asp.Net web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.
Reference Links:

Wednesday, 20 August 2014

The type 'System.Data.Entity.DbContext' is defined in an assembly that is not referenced.

I've got one solution - The one project is class library with .edmx data model The other is asp.net MVC Web API project.

when i start (Build) the solution I get the following exception:







Now, to resolve this issue :

I suggest you to check

Allow NuGet to download missing packages during build




In this way I got resolved the issue.

Thursday, 7 August 2014

Interface Example in C#

This article explains the following:
  • Why to use an interface in C#?
  • What is an interface?
  • What is the best example of an interface?
Why to use an interface

I hope everyone is quite familiar with OOP concepts in C++. (Class and Object, Inheritance and its type, so on).

Inheritance allows creating classes that are derived from other classes, so that they automatically include some of its "parent's" members, plus its own. The following are types of inheritances.

Multi-Level Inheritance
class Father{
    //Father Relations--Members}
class Mother: Father
{

    //Mother Relations--Members
}
class Child: Mother //Multi- Level Inheritance
{

    //Accessing both Relations class members.
}
Multiple Inheritance
class Father
{
    //Father Relations--Members
}

class Mother{
    //Mother Relations--Members
}

class
Child: Mother,Father //Multiple Inheritance

{
    //Accessing both Relations class members.}
This type of multiple inheritance is possible in C++ but it's not possible in C#.

SS.jpg

What is Interface?
An interface looks like a class, but has no implementation. The only thing it contains are declarations of events, indexers, methods and/or properties. The reason interfaces only provide declarations is because they are inherited by structs and classes, that must provide an implementation for each interface member declared.

So, what are interfaces good for if they don't implement functionality? They're great for putting together plug-n-play like architectures where components can be interchanged at will. Since all interchangeable components implement the same interface, they can be used without any extra programming. The interface forces each component to expose specific public members that will be used in a certain way.

Because interfaces must be implemented by derived structs and classes, they define a contract.
interface IMyInterface
{
            void MethodToImplement();//Abstract Method signature.
}
class InterfaceImplementer : IMyInterface
{
         static void Main()
         {
                     InterfaceImplementer  obj = new InterfaceImplementer();
                     obj.MethodToImplement();
         }

         public
void MethodToImplement()
         {
                //Abstract Method Implementation
         }
}
Here, we advised to use "I" as the prefix for the interface to understand that the interface is an interface.

Best example for Interface

Here I have the best example for understanding interfaces.

Not Possible:

InterF.jpg

1. Open a Console Application and give "InterFaceDemo" as the project name, then add a new class item and rename it "ODDEVEN.CS".

ODDEVEN.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterFaceDemo
{
    interface IOne
    {
        void ONE();//Pure Abstract Method Signature
    }
    interface ITwo
    {
        void TWO();
    }
    interface IThree:IOne
    {
        void THREE();
    }
    interface IFour
    {
        void FOUR();
    }
    interface IFive:IThree
    {
        void FIVE();
    }
    interface IEVEN:ITwo,IFour
    {

    }
    class ODDEVEN:IEVEN,IFive//Must Implement all the abstract method, in Derived class.
    {
        public void ONE()//Implementation of Abstract Method.
        {
            Console.WriteLine("This is ONE");
        }
        public void TWO()
        {
            Console.WriteLine("This is TWO");
        }
        public void THREE()
        {
            Console.WriteLine("This is THERE");
        }
        public void FOUR()
        {
            Console.WriteLine("This is FOUR");
        }
        public void FIVE()
        {
            Console.WriteLine("This is FIVE");
        }

    }
}

Program.cs
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterFaceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This is ODD");
            IFive obj1 = new ODDEVEN();
            obj1.ONE();
            obj1.THREE();
            obj1.FIVE();


            Console.WriteLine("\n\nThis is EVEN");
            IEVEN obj2 = new ODDEVEN();
            obj2.TWO();
            obj2.FOUR();


            Console.ReadLine();
        }
    }
}


The following is the output:

sss.jpg

Enjoy Coding.

Monday, 4 August 2014

How to Fix “Calling LoadLibraryEx on ISAPI filter c:\…isapi.dll failed” error

To fix this problem, all you have to do is open IIS7 and click on Application Pools.

application pool iis7

Then right-click on the application pool for your website or the default application pool and go to the Advanced Settings tab. Make sure that Enable 32-bit applications is set to True.

Calling LoadLibraryEx ISAPI filter failed


That’s it! Now restart IIS and load up Internet Explorer again and your website should load fine.

Wednesday, 30 July 2014

Return multiple values from a function in C# using Tuple

Using a Tuple


Base class library exposes two objects. It exposes the static class Tuple which allows you to get a number of Tuple instances based on the Static method Create, and a number of Tuple classes, each of which takes some specific number of Generic arguments.

  • Tuple.Create<t1>
  • Tuple.Create<t1,t2>
  • Tuple.Create<t1,t2,t3>
  • Tuple.Create<t1,t2,t3,t4>
  • Tuple.Create<t1,t2,t3,t4,t5>
  • Tuple.Create<t1,t2,t3,t4,t5,t6>
  • Tuple.Create<t1,t2,t3,t4,t5,t6,t7>
  • Tuple.Create<t1,t2,t3,t4,t5,t6,t7,t8>
Tuple.Create has 8 overloads and each of these overloads returns new object of Tuple<t1, t2...t8> class.  So .NET framework exposes 8 different classes each of them taking T1..... T8 number of arguments and each of them exposes Item1..... Item8 number of arguments.



The Tuple class can be instantiated directly as well without using static objects. Even If you see in Reflector, all the Create method actually returns its respective Tuple object. 

Hence, lets create object of Tuple.


Tuple<int, string> tuple = new Tuple<int, string>(20, "Abhishek");

Here the class with two Generic Type argument is created and hence it exposes the items as Item1 and Item2.



Similar to this, you can also create Tuple of 3, 4, 5 .....7 types 

How to generate N number of argument list?

Tuple actually supports more than 8 argument as it expects the 8th argument as another Tuple. Say for instance, if you write :


Tuple<int, string,int,int,int,int,int,int> tuple = new Tuple<int, string,int,int,int,int,int,int>(20, "Abhishek", 39, 39,59,49,30, 33);

You will eventually end up with an ArgumentException.





Hence the appropriate call to it must be :


Tuple<int, string,int,int,int,int,int,tuple<int>> tuple = new Tuple<int, string,int,int,int,int,int,tuple<int>>(20, "Abhishek", 39, 39,59,49,30, new Tuple<int>(33));

So you can see the last generic argument we pass as Tuple. Using this argument you can create as many arguments as you want.

Is Tuple a collection ?

Hmm, it must be an interesting question. But its not. Generally we call an object to be a collection only when all the elements inside the object are of same Type. In case of Tuple, each type might differ based on the Type argument, hence its not a collection.

Know a bit more .....

For enthusiastic, let me put this a bit further. After working for a while with Tuple, I was thinking why didnt microsoft expose an interface to define each of these Tuple classes (say ITuple) and Restrict the last argument TRest (8th argument)  using Generic constraint? To see what was the problem, I tried to dissemble it and seen few strange designs.


  1. Each Tuple is implemented from an Internal interface ITuple.
  2. ITuple cannot be accessed from outside and is kept hidden.
  3. Generic Constraint is not used for TRest while it throws ArgumentException intentionally from the constructor.


Interesting to Know

It should be noted, ToString is been implemented very well with Tuple objects. It puts the value as comma separated string with first braces around it.
So


Tuple<int, string,int,int,int,int,int,Tuple<int>> tuple = new Tuple<int, string,int,int,int,int,int,Tuple<int>>(20, "Abhishek", 39, 39,59,49,30, new Tuple<int>(33));

Console.WriteLine(tuple);

It will actually print :
(20, Abhinav, 39, 39, 59, 49, 30, 33)

Friday, 27 June 2014

The value '27/06/2014' is not valid for Date in MVC 4

Once I was getting this an model generated error message while choosing date in this format 27/06/2014 (any date more then 12/mm/yy).

Error Message is: The value '27/06/2014' is not valid for Date in MVC 4

Previously my Model and View was like this:

View Code Portion:

<div class="editor-field">
            @Html.TextBoxFor(model => model.DateOfBirth, new { style = "width:310px;height:25px" })
            @Html.ValidationMessageFor(model => model.DateOfBirth)
</div>

Model Code Portion:

[Required(ErrorMessage = "Date of birth field is required")]
        [DisplayName("Date of Birth:")]
        //[DataType(DataType.Date)]
 public System.DateTime? DateOfBirth { get; set; }

Note: Here even if I had DataType portion commented for DateOfBirth  model, I was getting error message. As it was not coming from model actually it was coming from controller end.

Solution For This:

In Web Config add this:

<system.web>
    <globalization culture="en-US" />
</system.web>

In Global.asax.cs add this:

 protected void Application_BeginRequest()
        {
            CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
            info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
            System.Threading.Thread.CurrentThread.CurrentCulture = info;
        }

Wednesday, 25 June 2014

How to Publish a Website from Visual Studio 2012 with IIS

Here is solution to Publish a Website from Visual Studio 2012 with IIS.



Monday, 9 June 2014

How to check version of MVC in which project is build.

There are two ways by which we can find the version of MVC in which project is build, they are as follows:

1. At design time: In the solution explorer, expand  "References" folder. Right click on System.Web.Mvc assembly and select "Properties" and you can find the version that's used as shown below.



2. At runtime using code: typeof(Controller).Assembly.GetName().Version.ToString();

Saturday, 15 February 2014

How to call Javascript function from Code Behind page in Asp.Net C#

This will work for you,

At .aspx Page :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call Jquery function from code behind</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <script type="text/javascript">
                function CallFunction() {
                    alert("Test");
                }
            </script>
        </div>
    </form>
</body>

</html>

At Code Behind (aspx.cs) Page:

protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "tmp", "<script type='text/javascript'> CallFunction();</script>", false);
    }

                                                            
 
Design by Abhinav Ranjan Sinha