Upload multiple files ASP.NET MVC without AJAX

<form enctype="multipart/form-data" action="/SubmitImage"
         method="post" >
    <input type="file" name="photos" multiple />
    <input type="text" name="caption"/>
    <textarea name="description"></textarea>
    <input type="submit" value="Submit" />
</form>
[ValidateInput(false)]
[HttpPost]
public ActionResult SubmitImage(IEnumerable<HttpPostedFileBase> photos,
                                   FormCollection data)
{
    String authString = Request.QueryString["auth"].ToString();
 
    String caption = data["caption"].ToString();
    string description = data["description"].ToString();
 
    if (Request.Files["photos"] != null)
    {
        //The directory where photo will be saved.
        var directory = HttpContext.Server.MapPath("~/Photos");
        foreach (var photo in photos)
        {
            //Get the file name of photo as it being sent.
            //It's required to get the original file extension.
            var photoName = photo.FileName.ToString();
            var extension = Path.GetExtension(photoName).ToLower();
            //Give photo a new name so that it can avoid duplicate name.
            var newName = Guid.NewGuid() + extension;
            string filePath = Path.Combine(directory, newName);
 
            //Check file existence. If exist, try another name.
            if (System.IO.File.Exists(filePath))
            {
               newName = Guid.NewGuid() + extension;
            }
             
            string filePath = Path.Combine(directory, newName);
            photo.SaveAs(filePath); //saving the photo to directory.                    
        }
    }
 
    return RedirectToAction("Index", "UploadImage", new { auth = authString, issubmitted = true });
}
Advertisements

Upload multiple files using AJAX- ASP.NET MVC

This technique is used to upload multiple files/photos by using single file input control, AJAX and ASP.NET-

1. Single file input control
2. JQuery AJAX
3. Form collection for additional data
4. ASP.NET MVC

<input type="file" id="Photos" multiple />
<!--Save button is disabled to prevent empty file submission-->
<button id="SavePhotos" disabled>Save</button>
<script>
$(function () {
    var fd, saveButton = $("#SavePhotos");
    $("#Photos").change(function (e) {
        fd = new FormData();
        fd.append("id", 1);    
        $.each(e.target.files, function (index, file) {
            fd.append("photos", file);
        });
        saveButton.prop("disabled", false)
    });

    saveButton.click(function () {
        $.ajax({
            url: URL-To-Submit,
            type: 'POST',
            data: fd,
            processData: false,
            contentType: false,
            beforeSend: function () {
            },
            success: function (response) {
                console.log(response);
            },
            error: function (request, status, error) {
            },
            complete: function () {
            }
        });
    });
});
[HttpPost]
public JsonResult SavePhotos(IEnumerable<HttpPostedFileBase> photos, FormCollection data)
{
    try
    {
        var directory = HttpContext.Server.MapPath("~/Photos");

        foreach (var file in photos)
        {
            String fileName = file.FileName;
            String fileExtension = Path.GetExtension(fileName);

            string imagePath = Path.Combine(directory, "HubPhotos", fileName);
            file.SaveAs(imagePath);
        }
    }
    catch (Exception Ex)
    {
        LogException(Ex);
    }

    return Json("success");
}

Auto complete search textbox like google (multiple input & extra data)

I have posted another article like this. https://programmershandbook.wordpress.com/2015/11/16/auto-complete-search-textbox-like-google-in-a-simple-easy-way/.

But a different approach is used here. Previous article has single textbox with id selector and only the textbox text. But this time, we have multiple textboxes with class selectors and few extra data in the ajax request.

<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AutoComplete Box with jQuery</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
     
</head>
<body>
   <table data-employeeid="5">
     <tbody>
       <tr data-id="546">
         <td>
           <input type="text" class="suggestexam" />
          </td>
        </tr>
        <tr data-educationid="103">
         <td>
           <input type="text" class="suggestexam" />
          </td>
        </tr>
      </tbody>
    </table>
</body>
</html>


//Put this code in head tag (placing this at the bottom of body tag may not work). 
    $(function () {
        $('body').on('focus', ".suggestexam", function () {
            var extra = $(this).closest('tr').attr("data-id");
            $(this).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "/Employee/GetExamNameSuggestion",
                        data: JSON.stringify({ prefix: request.term, extradata: extra }),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        //dataFilter: function (data) { return data; },
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
            });
        });
    });

Create GUID / UUID in JavaScript

    function generateUUID() {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now();; //use high-precision timer if available
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    };

 var guid = generateUUID();

Taken from a question from stackoverflow.com-
http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript

Auto complete search textbox like google in a simple & easy way.

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AutoComplete Box with jQuery</title>
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
    
</head>
<body>
    <div class="demo">
        <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
            <input type="text" id="txtSearch" class="autosuggest" style="width:300px;" />
        </div>
        </div>
</body>
</html>

Place the script in head tag

<script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $(".autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/Home/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }
    </script>
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAutoCompleteData(string username)
        {

            List<string> result = new List<string>();

            result.Add("Hello");
            result.Add("World");
            return Json(new { d = result }, JsonRequestBehavior.AllowGet);
        }
    }

SQL – Select Parent and Count Child from same table


//Let's say, you have a table as follows-
--------------------------------------------
 DesignationId | DesignationName| ParentId |
 -------------------------------------------
    1          |     A          |    0     |
 -------------------------------------------
    2          |     B          |    1     |
 -------------------------------------------
    3          |     C          |    1     |
 -------------------------------------------


// You would like to select records as follows
--------------------------------------------
 DesignationId | DesignationName| Childs   |
 -------------------------------------------
    1          |     A          |    2     |
 -------------------------------------------
    2          |     B          |    0     |
 -------------------------------------------
    3          |     C          |    0     |
 -------------------------------------------

Here is the SQL Statement-

SELECT DesignationId AS Id, DesignationName as Name, 
(SELECT COUNT(*)  FROM Designations AS T WHERE T.ParentID = O.DesignationId) 
FROM Designations AS O Where O.DesignationId>0

Configuring Classic ADO.NET in ASP.NET5 MVC6


{
  "webroot": "wwwroot",
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
    //The following line is important for MVC6
    "Microsoft.AspNet.Mvc": "6.0.0-beta8",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel"
  },

  "frameworks": {
        "dnx451": {
            "frameworkAssemblies": {
                //The following line is important for ADO.Net
                "System.Data": "4.0.0.0"
            }
        },
        "dnxcore50": {
            "dependencies": {
                //The following line is important for ADO.Net
                "System.Data.SqlClient": "4.0.0-beta-23409"
            }
        }
    },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ]
}


Using classic ADO.NET in ASP.NET 5

For some projects where performance makes a difference we usually use classic ADO.NET approach instead of EntityFramework or some other modern way to communicate with the database.

In this post I will try to explain how to fix some common issues with using ADO.NET in ASP.NET vNext.

If you have created ASP.NET 5 or ASP.NET vNext Class Library project (.NET Core Class Library project) and want to use ADO.NET you can have small issues.

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.


"aspnetcore50": {
           "dependencies": {
               "System.Runtime": "4.0.20-beta-22523",
               "System.Data.Common": "4.0.0.0-beta-22605",
               "System.Data.SqlClient": "4.0.0.0-beta-22605"
           }
       }

In the current Visual Studio CTP6 after this your ADO.NET still will not compile.

You will need to add a reference to System.Data.Common 1.0.0-beta1 and System.Data.SqlClient into aspnet50 section of project.json like this:

"aspnet50": {
           "dependencies": {
               "System.Data.Common": "1.0.0-beta1",
               "System.Data.SqlClient": "1.0.0-beta1"
           }
       }

I have also created little SqlHelper that works with ASP.NET 5 :

public sealed class SqlHelper
  {
      //Since this class provides only static methods, make the default constructor private to prevent 
      //instances from being created with "new SqlHelper()".
      private SqlHelper()
      {
 
      }
 
      private static string connectionString;
      public static string GetConnectionString()
      {
          if (string.IsNullOrEmpty(connectionString))
          {
              var config = new Configuration()
                    .AddJsonFile("config.json")
                    .AddEnvironmentVariables();
              connectionString = config.Get("Data:DefaultConnection:ConnectionString");
          }
 
          return connectionString;
      }
 
      public static int ExecuteNonQuery(SqlConnection conn, string cmdText, SqlParameter[] cmdParms)
      {
          SqlCommand cmd = conn.CreateCommand();
          using (conn)
          {
              PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, cmdParms);
              int val = cmd.ExecuteNonQuery();
              cmd.Parameters.Clear();
              return val;
          }
      }
 
      public static int ExecuteNonQuery(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
      {
          SqlCommand cmd = conn.CreateCommand();
          using (conn)
          {
              PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
              int val = cmd.ExecuteNonQuery();
              cmd.Parameters.Clear();
              return val;
          }
      }
 
 
      public static SqlDataReader ExecuteReader(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
      {
          SqlCommand cmd = conn.CreateCommand();
          PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
          var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
          return rdr;
      }
 
 
      public static object ExecuteScalar(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
      {
          SqlCommand cmd = conn.CreateCommand();
          PrepareCommand(cmd, conn, null, cmdType, cmdText, cmdParms);
          object val = cmd.ExecuteScalar();
          cmd.Parameters.Clear();
          return val;
      }
 
      private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] commandParameters)
      {
          if (conn.State != ConnectionState.Open)
          {
              conn.Open();
          }
          cmd.Connection = conn;
          cmd.CommandText = cmdText;
          if (trans != null)
          {
              cmd.Transaction = trans;
          }
          cmd.CommandType = cmdType;
          //attach the command parameters if they are provided
          if (commandParameters != null)
          {
              AttachParameters(cmd, commandParameters);
          }
      }
      private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters)
      {
          foreach (SqlParameter p in commandParameters)
          {
              //check for derived output value with no value assigned
              if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
              {
                  p.Value = DBNull.Value;
              }
 
              command.Parameters.Add(p);
          }
      }
  }

After this working with ADO.NET inside ASP.NET vNext is pretty straightforward:

public class LogRepository
    {
        public void Add(Log log)
        {
 
            var parameters = new[]
                    {
                        new SqlParameter("@JobId", log.JobId),
                        new SqlParameter("@ErrorInfo", log.ErrorInfo),
                        new SqlParameter("@DateTimeProcessedUTC", log.DateTimeProcessedUTC)
                    };
 
            using (var conn = new SqlConnection(SqlHelper.GetConnectionString()))
            {
                     SqlHelper.ExecuteNonQuery(
                        conn,
                        CommandType.Text,
                        @" INSERT dbo.Log ([JobId],[ErrorInfo],[DateTimeProcessedUTC])
                            SELECT @JobId, @ErrorInfo, @DateTimeProcessedUTC"
                          ,
                        parameters);
 
            }
 
        }
    }
}

Taken from http://blog.developers.ba/using-classic-ado-net-in-asp-net-vnext/

Installing Node.js (and npm) on Windows 10

Follow these steps, closely:

  • http://nodejs.org/download/ download the 64 bits version, 32 is for hipsters
  • Install it anywhere you want, by default: C:\Program Files\nodejs
  • Control Panel -> System -> Advanced system settings -> Environment Variables
  • Select PATH and choose to edit it.

If the PATH variable is empty, change it to this: C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

If the PATH variable already contains C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm, append the following right after: ;C:\Program Files\nodejs

If the PATH variable contains information, but nothing regarding npm, append this to the end of the PATH: ;C:\Users\{YOUR USERNAME HERE}\AppData\Roaming\npm;C:\Program Files\nodejs

Now that the PATH variable is set correctly, you will still encounter errors. Manually go into the AppData directory and you will find that there is no npm directory inside Roaming. Manually create this directory.

Re-start the command prompt and npm will now work.

Taken from this StackOverflow question.