Monday, 15 July 2013

The Use of ALL Operator in LINQ

Today, I came across the All operator in LINQ. This operator returns bool value rather than records after condition is satisfied. The operator will be highly helpful when you need some kind of validation to find unique data. for e.g. Checking the existing email  or UserID registered and so on.


Lets Go with a Example to do the Task:

int [] array = { 1,2,3,4,5 };

bool result = array.All(value => value > 2 );

Console.WriteLine(result);  // Here it will print False since it will check all the values and                                         // all the values must be grater than 2.


 result = array.All(value => value < 6 );
Console.WriteLine(result); // Here it will print True since it will check all the values and                                          // found all values are less than 6.


Hope it helps you!

Monday, 17 June 2013

Error 349: Duplicate headers received from server in Google Chrome while rendering PDF using ITextSharp in Asp.Net MVC



While working on generating  PDF in Asp.Net MVC3, I got a peculiar error while rendering the PDF in Chrome browsers, which is not being found in any other browsers like Internet Explorer or Fire Fox.
This error comes because chrome browsers doesn't ignore duplicate headers. This can be addressed easily the following ways, if you or your web app is sending out headers. Then check the following things:

 1. Enclose fileName using “”. i.e
Response.Addheader('Content-Disposition: attachment; filename="' + fileName '"');
instead of
Response.Addheader('Content-Disposition: attachment; filename='+ fileName);
2. If possible replace spaces and commas (,) with underscores (_)
 string regExp = @"[^\w\d]";
Response.AddHeader("content-disposition""attachment;filename=" + "Test_PDF_" + 
                           Regex.Replace(model.CompanyName, regExp, "_")+ "_" +
                              Regex.Replace(model.FullName, regExp, "_") + "_" +                                                         DateTime.Now.ToShortDateString());teString());

3. Explicitly tell Asp.Net MVC to override headers by setting optional replace parameter to true.
Response.AddHeader("Content-type: application/pdf",true);
Happy Coding!

Friday, 14 June 2013

How to prevent the multiple submit of record in ASP.Net MVC using JQuery

There are various methods are available to do that one, it can be done using JQuery, using sessions or Filters.


Method -1 ( Using JQuery Approach)
 $('form').submit(function () {
        if ($(this).find('.input-validation-error').length == 0) {
            $(this).find(':submit').attr('disabled''disabled');
        }
    });

This is the simplest method to prevent the multiple submission of the record in MVC and even it works on JQuery Unobstructive validations.

Happy Coding!

Wednesday, 5 June 2013

How to get a set of record from middle of the table, Say you need records from 5 to 15 from a table containing 100 records in SQL Server

Its a small query that will help you to find the records from from  n to m from a table having N records.

Where N :- total records in the table.
            n :- starting record number.
            m :- ending record number.

select top 20 * from School
except
select top (5) * from School

so, here it first select top 20 records and from it it discards the 1st top 5 records.

Enjoy!

Writing multiple condition for a Kendo Grid column Template to fetch the record.

Sometime you are required to write a template for Kendo Grid to fetch the data on a condition below is the column template to write multiple condition to do it. Its easy one, but to remember those small tricky things, I had posted this one.



Column[
{ field: "DateActivated", title: "Activated", width: 50, 
template: '#=(DateActivated==null)?"":(Status=="Requested")?"":
 kendo.toString(kendo.parseDate(DateActivated"),"MM/dd/yyyy")#',filterable: false }]



Happy Coding!

Tuesday, 4 June 2013

Getting the Error "The document has no pages" in PDF reporting Using ItextSharp in Asp.net MVC3/MVC4

Today while working with a project, I got a task to do i.e for creating dynamic PDFs of the View.
So I had started working on that and completed before time.

However , when I tried to put into the azure production environment, i got peculiar error which i had not observed in my dev Environment or in the stage.

The error I got is  "The document has no pages" . I started doing research into it but unable to find any solution. At last, I thought that it might be out of memory or buffering issue, no still that is not the case. the problem arises due to inability to find the relative source path that you had provided to the image source in the view while creating the PDF with the logo or images in it.

So, before deploying to the production server be sure the following things has been checked:

1) The Image file which u have used must be existing in the website inside some folder.
2) Be sure that PDF supports few file formats such as .jpg/.bmp, so use the image of that type.
3) Don't use the image source with relative URL, it will not be able to find the image. It will work in the local but throw an error in production or staging server. So better use the live site followed with the image source.


If you are still getting the same error then just try to render some text and check whether it is rendering or not. If it is rendering then there might be some image rendering issue. Is still getting the error then just recheck your code.


Happy coding!

Friday, 24 May 2013

Jquery Method to Check the File upload control Empty or not, File Size and File Type(e.g. JPG,BMP,PDF)


Html:
<input type="file" id="file" name="file" />
<span id="valFile" class=""></span> // span for showing error message.

CSS:


.field-validation-error {
    color: #f00;
}

.field-validation-valid {
    display: none;
}

.input-validation-error {
    border: 1px solid #f00;
    background-color: #fee;
}


JQuery Snippet:
$(document).ready(function( )
{

//Changing the Error message of the File Upload and checking the File size and File type.
        $("#file").change(function () {

            $("#valFile").html("Please select file."); // Default Error Message
         
            var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'doc', 'docx', 'pdf'];

            if ($(this).val() != "") { //checking wheather the file uploader is empty or not
             
                //Checking the File type
                if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                    $(this).addClass("input-validation-error").removeClass("valid");
                    $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                        .html("Invalid Filetype(only image files/doc/docx/pdf)");
                }
                else {
                    $(this).removeClass("input-validation-error").addClass("valid");
                    $("#valFile").removeClass("field-validation-error").addClass("field-validation-valid");

                    if ((this.files[0].size > 4194304) && ($(this).val() != '')) {
                        $(this).addClass("input-validation-error").removeClass("valid");
                        $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid")
                            .html("File size exceeded 4MB");
                    }
                }
            } else {
                $(this).addClass("input-validation-error").removeClass("valid");
                $("#valFile").addClass("field-validation-error").removeClass("field-validation-valid");
            }
        });

});

Happy Coding!

Wednesday, 22 May 2013

How to create a File Upload with File Validation in Asp.net MVC / How to Use the @Html.TextBoxFor() for File Upload ?

While Wonder how to validate the Upload control in a easy way, I find this solution as the best to do it, although lot of other ways are found.This is because you need not need to write much more code as a normal razor validation will solve the problem.


My View:


 <div id="dvUpload" class="hide fieldControlContainer">
                <div class="innerDivLeft">
                    <label class="blue">Upload Document:</label>
                </div>
                <div class="innerDivRight">
                      @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" })
                      @Html.ValidationMessageFor(model => model.File)
                </div>
 </div>

The magic lies with this line  @Html.TextBoxFor(model => model.File, new { @class = "inputTextBox", type="file" }), here it will be rendered as a file upload control rather than a text because we are over riding the default behavior of input tag rendering by specifying it as type="file".

My Controller:



 public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
                  //Codes written here.
        }


MyModel:

public class MyModel
{

       [Required(ErrorMessage = "Please select file")]     // this is for model validation
        public HttpPostedFileBase File { get; set; }

}

Now your file upload validation will be checked like any other normal control.

Friday, 17 May 2013

How to make a textbox to accept only integers as Input.

Html Page:
 <input type="text" name="age" id="txtAge" />&nbsp;<span id="errormsg"></span>

JQuery Snippet for the above TextBox:

Method-1:
$(document).ready(function () {
  //called when key is pressed in textbox
  $("#txtAge").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errormsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

Method-2:
$(document).ready(function () {
    $("#txtAge").keydown(function (e) {
        if (e.shiftKey) e.preventDefault();
        else {
            var nKeyCode = e.keyCode;
            //Ignore Backspace (Keycode=8), Tab keys(Keycode=9)  & Delete(Keycode=46)
         if (nKeyCode == 8 || nKeyCode == 9 || nKeyCode == 46) return;
            if (nKeyCode < 95) {
                if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
            } else {
                if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
            }
        }
    });
});

Enjoy!

Thursday, 16 May 2013

Uploading a file to Server in Asp.net MVC 3 /4.



View page:


@using (Html.BeginForm("Index", "MyController", FormMethod.Post , new { enctype = "multipart/form-data" }))
{
//  Controls for your Model........(see below)

 <div>
                <div class="innerLeftContainer">
                    <label >Full Name:</label>
                </div>
                <div class="innerRightContainer">
                    @Html.TextBoxFor(model => model.FullName, new {@class = "inputTextBox"})
                    @Html.ValidationMessageFor(model=>model.FullName)
                </div>
            </div>


<div id="dvUpload">
                <div class="innerLeftContainer">
                    <label>Upload Document:</label>
                </div>
                    <div class="innerRightContainer">
                        <input type="file" id="DocumentUpload" name="file" />
                    </div>
            </div>


}


Note: The Form Method and the enctype is highly required for uploading your file to the server orthrwise you will always get the HttpPostedFileBase as null.


Action Method: ( in the Controller)
 [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, MyModel model)
        {
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                if (fileName != null)
                {
                    // store the file inside ~/App_Data/uploads folder
                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                    file.SaveAs(path);
                }
            }
            // redirect back to the index action to show the form once again
            return RedirectToAction("Index");
        }