Friday, 11 January 2013

Creating Asynchrous File Uploader in MVC3 with Kendo UI



Asynchronous Upload
View: UploadFile.cshtml
@using Kendo.Mvc.UI
@{
    ViewBag.Title = "UploadFile";
    //Layout = "~/Views/Shared/_PlainLayout.cshtml";
}

<h2>Upload File</h2>

<div style="width:45%">
    @(Html.Kendo().Upload()
          .Name("files")
          .Async(a => a
                          .Save("SaveFiles", "Upload")
                          .Remove("RemoveFiles", "Upload")
                          .AutoUpload(true)
          )
          )
</div>

<script type="text/javascript">
    $(document).ready(function () {
       
        $(".k-dropzone").css("height","100px");

    });
</script>
<script src="~/Scripts/kendo.all.min.js"></script>
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />

Controller:
  public class UploadController : Controller
    {
        public ActionResult UploadFile()
        {
            return View();
        }

        public ActionResult SaveFiles(IEnumerable<HttpPostedFileBase> files)
        {
            if (files != null)
            {
                foreach (var file in files)
                {
                   
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/UploadFile"), fileName);

                    // Saving the File
                    file.SaveAs(physicalPath);
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

        public ActionResult RemoveFiles(string[] fileNames)
        {
           if (fileNames != null)
            {
                foreach (var fullName in fileNames)
                {
                    var fileName = Path.GetFileName(fullName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Content/UploadFile"), fileName);

                   

                    if (System.IO.File.Exists(physicalPath))
                    {
                        // Deleting the File from the Location
                         System.IO.File.Delete(physicalPath);
                    }
                }
            }
            return Content("");
        }
    }

Calling to the File Upload Control
$('#Searchwindow').kendoWindow({
        title: "Upload File",
        content: "/Upload/UploadFile",
        height: "400px",
        width: "600px",
        iframe: true,
        visible: false
    }).data('kendoWindow').center();
<div id="grid">
            <div id="Searchwindow"></div>
</div>

Error n(e.g. 8 or 12)Files has invalid value "<<<<<<< .mine". Illegal characters in path.

I got some peculiar error after taking the update of the solution  from SVN.
So in order to fix it i tried a lot of way but unable to find out the issue as it doesn't show the file where  .>>>>>>>>>>>>>>>>> mine or .<<<<<<<<<<<< mine exists. After a through review i find out that it is due to the different version of the files in the respective folder where .obj folder is there.


So, in order to fix this issue, just go to the respective folder and delete the version-ed file names or delete the old ones and rename the latest file to the original one.

The other approach is simply delete the /obj folder in each project that is complaining and re-compile.

This error is caused by the Subversion "Resolved..." function.

Enjoy !

Monday, 12 November 2012

Preventing the backbutton not to go to the previous URL when the control is in focus inside a textbox, textarea or radio button in any browser


While developing a website in Asp.net MVC4, I noticed that when my control is in focus inside a text-box or text-area, which are read only, it is moving to the parent of the current URL. In order to solve it i had written a JQuery below which will prevent the back to the parent URL in any browser and in any web developing programming languages.


    $(document).keydown(function(e) {
        var doPrevent;
        if (e.keyCode == 8) {
            var d = e.srcElement || e.target;
            if (d.tagName.toUpperCase() == 'INPUT' || d.tagName.toUpperCase() == 'TEXTAREA') {
                doPrevent = d.readOnly || d.disabled;
            }
            else
                doPrevent = true;
        }
        else
            doPrevent = false;

        if (doPrevent)
            e.preventDefault();
    });



Enjoy!..........

Monday, 5 November 2012

Issue with the sorting the telerik grid for Asp.net MVC

While working on telerik grid , I found a peculiar issue in Internet Explorer(IE) browsers. The issue is that on the column bound HeaderTemplate if you are providing a link for sorting purpose and if you used a label inside the link then the link will not work in IE but will work for all other browsers.


Solution: So, while providing the link text for sorting the grid on that column, just be care full that u must not used any label for that link. See below:

The code below will  not work:
column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> <label>Name<label> </a>  ---> This will not work
    </text>);



The code below will work:
 column.Bound(m => m.Name).Template(
        @<text>
    <a target="_blank" href="@item.Url">@item.Name</a>
    </text>) .HeaderTemplate(
        @<text><a href="javascript:void(0)" class="t-link"> Name </a>  ---> This will work.
    </text>);



Enjoy!.......

Friday, 2 November 2012

In MVC4 Telerik grid I got an error that telerik.textbox.js not found in the 'Script\telerik.textbox.js'

This is the tricky one, there is no problem in any where but it is throwing the problem because you might have passed some integer value to the column bound in the telerik grid in mvc3/mvc4.

There are two ways to fix it:

Method 1:

  Download the telerik.textbox.js and put in the specified location and it will work fine.

Note: Don't go for this method, since you are adding some more bytes to the  size of the Cod.

 Method 2:

 Just while binding the int value to the grid just convert it into a string. That's all, now your code will work fine



Enjoy!...

Friday, 26 October 2012

After getting the Ajax result from the Action Method the the view is not updating in mvc3/mvc4

One of my friend while doing a task of a project , he implemented the Ajax call to send request to the  action method. he had done it and resend the model to the client side, but the data is not updating in the view.

So, I thought of a while and scrutinized it and found that the model is updated when the data comes from the action method but it is not updating the view. so, here is the trick how to do it.

$.ajax({
                data: { retailLocation: $("#ddlLanguages").val().split('-')[1] + "-" + this.value },
                url: '/App/index',
                success: function (result) {
                    $("#container").empty().html(result);
                    $('#container').fadeIn('fast');


                },
                complete: function (result) {
                    $("#RetailPartnerLocation option:contains(" + currentselection + ")").attr('selected', 'selected');
                },
                Error: function (result) { alter("Error occured while processing"); }
            });


Here you need to empty the container where the previous data exist and bind the new data to it.

How to Show the date like facebooks shows when you provide comments such as 1 min ago, 2 days ago, 1 Month Ago in Asp.Net/ Asp.Net MVC 2/MVC 3/ MVC 4

While working on a project , I need to show the comments published or updated as 1 min ago, 1 Hours ago, so on. So in order to do it I had written a helper class to do it for me.

Here is the code below:
 public static string GetFormattedDate(string date)
        {
            string formattedDate = string.Empty;
            TimeSpan ts = System.DateTime.Now - DateTime.Parse(date);
            int weeks = (int)(DateTime.Now - DateTime.Parse(date)).TotalDays / 7;

            if (ts.Minutes == 0)
                formattedDate = "Few Seconds Ago";
            if (ts.Minutes > 0 && ts.Minutes < 59)
                formattedDate = ts.Minutes + (ts.Minutes == 1 ? " Minute Ago" : " Minutes Ago");
            if (ts.Hours > 0 && ts.Hours < 24)
                formattedDate = ts.Hours + (ts.Hours == 1 ? " Hour ago" : " Hours ago");
            if (ts.Days >= 1 && ts.Days<30)
            {
                if (ts.Days == 1)
                {
                    formattedDate = "Today";
                }
                else if (ts.Days>1 && ts.Days < 7)
                {
                    formattedDate = ts.Days + (ts.Days == 1 ? " Day ago" : " Days ago");
                }
                else
                {
                    formattedDate = (ts.Days / 7).ToString() + ((ts.Days / 7).ToString() == "1" ? " Week Ago" : " Weeks Ago");
                }
            }
            else if (ts.Days >= 30 && ts.Days<365)
            {
                formattedDate = ts.Days/30 + ( ts.Days<60 ? " Month ago" : " Months ago");
            }
            else if(ts.Days>=365)
            {
                formattedDate = ts.Days / 365 + ( ts.Days < 730 ? " Year ago" : " Years ago");
            }
          
            return formattedDate;
        }

How to Write a Extension method to strip html-tags from a rich text Editor in ASP.Net/ MVC

Today while working with CKEditor , I find out that what ever I provide in the Editor body and saved, it is not properly translating the html tags such as paragraph in the Editor body.

So to fix it I had written an extension method to strip the HTML tags as :


        public static string StripHtml(string inputString)
        {
            if (!string.IsNullOrEmpty(inputString))
                return Regex.Replace(inputString, "<.*?>", string.Empty);

            return string.Empty;

        }


How to call: Classname.StripHtml("some string");

How to Minimize Long Title or Overflowed text with less text followed with ellipsis using Jquery or CSS


While working on a project I got a requirement  of showing a limited amount of text followed with ellipsis(...)  in  a telerik grid, to do it I thought I will use the CSS property  text-overflow: ellipsis; but unable to succeed. I thought a lot and at last done it with CSS.

What I had done with CSS:
So in order to get the text as "Hello Hai how Are..." I used the following CSS

#divContainer td:first-child + td {height: 45px;width:280px;max-width: 280px;overflow: hidden;
text-overflow: ellipsis; display:block;white-space: nowrap;}

Here divContainer is the Container and td:first-child + td  : refers to the second column of a table. InOrder to make it work you need to specify the width,max-width(for IE), white-space and Overflow:hidden and text-overflow: ellipsis;

The output is:
 


 *Note: Here We get the desired result with single line only but I need multiple line with  ellipsis, so to do it I followed JQuery.


What I had done with JQuery:

In order to fix this issue I just write below the two line to get multiple lines followed with ellipsis(...)

$("#divContainer td:first-child + td").each(function() {
            $(this).text($(this).text().substr(0,75)+"...");
        });


The Output is: