Thursday, March 13, 2014

Get page name from URL, using Javascript

You can use following function to retrieve the current page name from the URL.

 function getCurentFileName() {
             var pagePathName = window.location.pathname;
             return pagePathName.substring(pagePathName.lastIndexOf("/") + 1);
         }

Thursday, January 30, 2014

Redirect to .aspx webform within ASP.NET MVC application

//Controller
public class PivotalController : Controller
    {
     
        //Action
        public RedirectResult Index()
        {
            return Redirect("/pages/PivotalWebForm.aspx");
        }

}

Tuesday, January 28, 2014

How to solve XMLHttpRequest cannot load. Origin is not allowed by Access-Control-Allow-Origin error in ASP.NET MVC 4

This error may occur when you try to communicate between different domain using AJAX calls. To solve the issue we need set up the WEB API to return correct headers.

Create a class called CrossDomainActionFilter inherited by ActionFilterAttribute.

public class CrossDomainActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            bool needCrossDomain = true;

            if (needCrossDomain)
            {
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            }

            base.OnActionExecuted(actionExecutedContext);
        }
    }


[AcceptVerbs("GET", "POST")]
[CrossDomainActionFilter]
    public object GetTest()
    {
         rep = new ChatRepository();
        chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null);

        System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult
        {
            Data = box,
            JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
        };


        return jsonResult.Data;
    }

Tuesday, January 21, 2014

How to validate dd/MM/yyyy date format in ASP.NET MVC client validations.

The problem is JQUERY validation does not consider the culture when performing the validation. So that, it will show you "Invalid date format" error message whenever you try to submit a form with a date field, which has the format of dd/MM/yyyy.

To fix the issue we can override the default validation behavior by including JQUERY Globalization plugin.

Right click on the application on in Visual Studio and select Manage NuGet Packages.


Then type globalize on search text box and install the package, which appears on the search results.



Finally, add the below script before the body closing tag on your page.

    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
   
    <script src="~/Scripts/globalize/globalize.js"></script>
    <script src="~/Scripts/globalize/cultures/globalize.culture.en-GB.js"></script>

    <script>
        $(document).ready(function () {
            $.culture = Globalize.culture("en-GB");
            $.validator.methods.date = function (value, element) {
                //This is not ideal but Chrome passes dates through in ISO1901 format regardless of locale
                //and despite displaying in the specified format.

                return this.optional(element)
                    || Globalize.parseDate(value, "dd/MM/yyyy", "en-GB")
                    || Globalize.parseDate(value, "yyyy-mm-dd");
            }
        });
    </script>

Sunday, January 19, 2014

Allow only decimal or integer numbers in a textbox using JQUERY

HTML:

<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed  (With Decimal Point) </div>  
    <br/>   <br/>   <br/>
   
 <span>Int</span>
<input type="text" name="numeric" class='allownumericwithoutdecimal'>
<div>Numeric values only allowed  (Without Decimal Point) </div>

Below code will allow user to enter only decimal numbers:

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
            //this.value = this.value.replace(/[^0-9\.]/g,'');
     $(this).val($(this).val().replace(/[^0-9\.]/g,''));
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        });


Below code will allow user to enter only integer numbers:

$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {  
           $(this).val($(this).val().replace(/[^\d].+/, ""));
            if ((event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        });

Tuesday, December 31, 2013

How to enable Client Side Validation for Kendo UI

Recently I was struggling with using Jquery validation in ASP.NET MVC 4 application which used Kendo UI. Except the kendo DropDownLists in a particular view, every other control fired client validations. So it had to be a problem with Kendo libraries. Finally, I added below code snippet and it started working.

Kendo DropDown:

@(Html.Kendo().DropDownListFor(m => m.SiteID)
                            .Name("SiteID")
                            .OptionLabel("Select Below...")
                            .DataTextField("Text")
                            .DataValueField("Value")
                            .Value(Model.SiteID.ToString())
                            .DataSource(ds =>
                            {
                                ds.Read("ToolbarTemplate_Categories", "EnterNewDocumentVendor");
                            })
                        )

Jquery Code:

<script>

    $(document).ready(function () {

        $.validator.setDefaults({
            ignore: ""
        });

        $("#SiteID").kendoValidator();
 
    });
</script>

Following link would be useful for newer versions of Jquery.

http://stackoverflow.com/questions/8466643/jquery-validate-enable-validation-for-hidden-fields

Tuesday, November 19, 2013

Telerik Reports for ASP.NET MVC 4 Caching issue.

I recently used Telerik reports, and i got into a problem where report viewer cached the previous versions other than refreshing the report.

I followed the sample in below link from telerik in order to generate my report.

http://www.telerik.com/help/reporting/mvc-report-viewer-extension-embedding.html

below is the code from my report viewer.

@(Html.TelerikReporting().ReportViewer()
        .Id("reportViewer1")
        .ServiceUrl("/api/reports/")
        .TemplateUrl("/Content/ReportViewer/templates/telerikReportViewerTemplate.html")
        .ReportSource(new TypeReportSource() { TypeName = "MvcReportApplication.MyReport.Report5, MvcReportApplication" })
        .ViewMode(ViewModes.INTERACTIVE)
        .ScaleMode(ScaleModes.SPECIFIC)
        .Scale(1.0)
        .PersistSession(true)
       
)

To disable the report viewer caching just change PersistSession(true) to PersistSession(false) and you are good to go.


Tuesday, October 1, 2013

Create/Read JavaScript Cookie

Following two methods can be used to create a cookie on the client browser and to read the value of the cookie.

Create Cookie:

name of the cookie, value need to be stored in the cookie and the number of days for cookie expiration are the parameters to be passed when calling the method.

function createCookie(name, value, days) {
                            if (days) {
                                var date = new Date();
                                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                                var expires = "; expires=" + date.toGMTString();
                            }
                            else var expires = "";
                            document.cookie = name + "=" + value + expires + "; path=/";
                        }


Read Cookie:

  function readCookie(name) {
                    var nameEQ = name + "=";
                    var ca = document.cookie.split(';');
                    for (var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                    }
                    return null;
                }

Thursday, September 26, 2013

How to Read MS Word Document Content using Office Interoperability Service Assemblies

Below code will read the content of a Microsoft Word document and return the text in a string variable.

public string GetText()
        {
     
                string Referees = string.Empty;
                string totaltext = "";
                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

                object miss = System.Reflection.Missing.Value;
                object path = Server.MapPath("~/Content/Documents/CV March 2013 Peter Corbitt.docx");
                object readOnly = true;
                Microsoft.Office.Interop.Word.Document docsw = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                try
                {
                 
                    for (int i = 0; i < docsw.Paragraphs.Count; i++)
                    {
                        totaltext += " \r\n " + docsw.Paragraphs[i + 1].Range.Text.ToString();
                    }

                    docsw.Close();
                    word.Quit();
                }
                catch (Exception ex)
                {
                    docsw.Close();
                    word.Quit();
                    throw ex;
                }

                return totaltext;
        }

Monday, September 2, 2013

How to use ajaxError

When ever an error occurs in an ajax call it fires ajaxError function. By examining the error details you'll be able to get an idea about the occurred error.

<script>
$( document ).ajaxError(function(event, xhr, options, exc) {
  alert('Couldn\'t load ' + options.url + ' because (' +
            xhr.status + ' - ' + xhr.statusText + ') ' + exc.message);
});
</script>