This blog is useful to all my friends who are working on the .Net Technology and wants to enhance their skills as well their problem solving ability.

Monday, July 21, 2014

Jquery DataTable with Drill Down option

IN YOUR VIEW USE THE BELOW FUNCTION

Write below function in your document.ready event, this will bind "+" td.control img with function which will open drill down.

$("#myDataTable").on("click", "td.control img", function (event) {

                var nTr = this.parentNode.parentNode;
                var i = $.inArray(nTr, anOpen);

                if (i === -1) {

                    $('img', this.parentNode).attr('src', sImageUrl + "drildown_close.jpg");
                    oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), '');
                    anOpen.push(nTr);
                }
                else {
                    $('img', this.parentNode).attr('src', sImageUrl + "drildown_open.jpg");
                    oTable.fnClose(nTr);
                    anOpen.splice(i, 1);
                }
            });

  Below function used to open a div as drill down with passed parameter and data which return by method.

            function fnFormatDetails(oTable, nTr) {
                var sOut = '';
                $('#DivLoading').show();
                $.ajax({
                    "url": '@Url.Content("method name to fetch data")',
                    data: { para: paraID },
                    "async": false,
                    cache: false,
                    "dataType": "text",
                    "success": function (json) {
                        sOut = json;
                        $('#DivLoading').hide();
                    },
                    error: function (response) {
                        //// debugger;
                    }
                });

                return sOut;
            }

            /*Functions used for nasted data binding END*/

You can use this function in PHP or .NET code , as this is Jquery stuff so you don't need to worry about any platform.


Thursday, February 6, 2014

Update only Those records which are affected using Update Tirgger

COLUMNS_UPDATED

500 is a bit mask for checking number of columns affected or you want to check ...

IF (COLUMNS_UPDATED() & 500 > 0)
    BEGIN
            INSERT INTO TableName
            select  'update' as [Action], * from inserted 
    END

For more update or info use below link ...

http://technet.microsoft.com/en-us/library/ms186329.aspx

Wednesday, February 5, 2014

Paging same like EF take and skip in Sql 2012 ... awesome work :)

select * from TableName order by ID desc
offset 0 rows fetch next 20 rows only

Here 0 means starting from and 20 means how many records you want to fetch ....

Another great things in 2012 is ... you can use "Through" steatement direct inside the catch block ...

BEGIN TRY
DECLARE @VarToTest INT
SET @VarToTest = 'C'
END TRY
BEGIN CATCH
THROW
END CATCH


Quite superb ....

Tuesday, June 18, 2013

Alert for unsaved changes in form Using JQUERY

var unsaved = false;

$(":input").change(function(){ //trigers change in all input fields including text type
    unsaved = true;
});

function unloadPage(){ 
    if(unsaved){
        return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
    }
}

window.onbeforeunload = unloadPage;

Thursday, April 25, 2013

Adding your Custom validation in MVC 4 using Validation Attribute and unobtrusive Jquery library


1)  DEFINED YOUR PROPERTY IN MODEL CLASS ....

//DefaultReorderQuantity
        [Display(Name = "DefaultReorderQuantity", ResourceType = typeof(ResItemMaster))]
        [RegularExpression(@"^[0-9\.]*$", ErrorMessageResourceName = "InvalidValue", ErrorMessageResourceType = typeof(ResMessage))]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ResMessage))]
        [DefaultReorderQuantityCheck("MaximumQuantity", ErrorMessage = "Default Reorder quantity must be less then Maximum quantity")]
        public System.Double DefaultReorderQuantity { get; set; }

 2) IN MODEL CREATE NEW CLASS WITH SAME NAME OF PROPERTY

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class DefaultReorderQuantityCheckAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string _MaxQTYFieldName;
    public DefaultReorderQuantityCheckAttribute(string MaxQtyFieldName)
    {
        _MaxQTYFieldName = MaxQtyFieldName;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_MaxQTYFieldName);
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
        if (value != null)
        {
            double DefReQTY = (double)value;
            if (DefReQTY >= (double)otherPropertyValue)
            {
                ValidationResult Ok = new ValidationResult("Default Reorder quantity must be less then Maximum quantity");
                return Ok;
            }
        }
        return ValidationResult.Success;
    }
    public IEnumerable
           GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "defaultreorderquantity"
        };
    }
}



3)  IN YOUR VIEW ADD THIS LINES TO CHECK VALIDATION FROM CLIENT SIDE

$("form").submit(function (e) {
        $.validator.unobtrusive.parse("#frmItemMaster");
       
        if ($(this).valid()) {
                   }
        e.preventDefault();
    });   


4) ADD BELOW LINES TO ADD THE RULE OF VALIDATION IN unobtrusive  VALIDATION LIBRARY ....

jQuery.validator.addMethod('defaultreorderquantity', function (value, element, params) {
            if (parseInt(element.form.DefaultReorderQuantity.value == '' ? 0 : element.form.DefaultReorderQuantity.value, 10) >= parseInt(element.form.MaximumQuantity.value == '' ? 0 : element.form.MaximumQuantity.value, 10))
                return false;
            else
                return true;
        }, '');
        jQuery.validator.unobtrusive.adapters.add('defaultreorderquantity', {}, function (options) {
            options.rules['defaultreorderquantity'] = true;
            options.messages['defaultreorderquantity'] = options.message;
        });

5 ) CONTROLLER SIDE VALIDATION IF REQUIRED

if (!ModelState.IsValid)
            {
if (ModelState["DefaultReorderQuantity"].Errors.Count > 0)
                {
                    return Json(new { Message = ModelState["DefaultReorderQuantity"].Errors[0].ErrorMessage, Status = "Fa" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { Message = ResMessage.InvalidModel, Status = "Fa" }, JsonRequestBehavior.AllowGet);
                }
            }

AND YOU ARE DONE.... USE THIS AS PER YOUR REQUIREMENT ... HERE FIELD DEFAULT REORDER QUANTITY IS AN EXAMPLE ...

Monday, March 4, 2013

show hide div content using jquey

The HTML

Below is the sample text. Each text is wrapped in a DIV tag. Note that we have added a class “more” in each div. This class will decide if a text needs to be shortened and show more link showed or not.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis, quam ligula sodales orci, congue imperdiet eros tortor ac lectus. Duis eget nisl orci. Aliquam mattis purus non mauris blandit id luctus felis convallis. Integer varius egestas vestibulum. Nullam a dolor arcu, ac tempor elit. Donec.
Duis nisl nibh, egestas at fermentum at, viverra et purus. Maecenas lobortis odio id sapien facilisis elementum. Curabitur et magna justo, et gravida augue. Sed tristique pellentesque arcu quis tempor.
consectetur adipiscing elit. Proin blandit nunc sed sem dictum id feugiat quam blandit. Donec nec sem sed arcu interdum commodo ac ac diam. Donec consequat semper rutrum. Vestibulum et mauris elit. Vestibulum mauris lacus, ultricies.

The CSS

Below is the CSS code for our example. Note the class “.morecontent span” is hidden. The extra text from the content is wrapped in this span and is hidden at time of page loading.
a {
 color: #0254EB
}
a:visited {
 color: #0254EB
}
a.morelink {
 text-decoration:none;
 outline: none;
}
.morecontent span {
 display: none;
}
.comment {
 width: 400px;
 background-color: #f0f0f0;
 margin: 10px;
}

The Javascript

Below is the Javascript code which iterate through each DIV tags with class “more” and split the text in two. First half is showed to user and second is made hidden with a link “more..”.
You can change the behaviour by changing following js variables.
  • showChar: Total characters to show to user. If the content is more then showChar, it will be split into two halves and first one will be showed to user.
  • ellipsestext: The text displayed before “more” link. Default is “…”
  • moretext: The text shown in more link. Default is “more”. You can change to “>>”
  • lesstext: The text shown in less link. Default is “less”. You can change to “<<"
$(document).ready(function() {
 var showChar = 100;
 var ellipsestext = "...";
 var moretext = "more";
 var lesstext = "less";
 $('.more').each(function() {
  var content = $(this).html();

  if(content.length > showChar) {

   var c = content.substr(0, showChar);
   var h = content.substr(showChar-1, content.length - showChar);

   var html = c + '' + ellipsestext+ ' ' + h + '  ' + moretext + '';

   $(this).html(html);
  }

 });

 $(".morelink").click(function(){
  if($(this).hasClass("less")) {
   $(this).removeClass("less");
   $(this).html(moretext);
  } else {
   $(this).addClass("less");
   $(this).html(lesstext);
  }
  $(this).parent().prev().toggle();
  $(this).prev().toggle();
  return false;
 });
});



Tuesday, October 2, 2012

Convert Datatable or Export Datatable to Excel file


private void ExporttoExcel(DataTable table)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.ContentType = "application/ms-excel";
    HttpContext.Current.Response.Write(@""-//W3C//DTD HTML 4.0 Transitional//EN"">");
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");
   
    HttpContext.Current.Response.Charset = "utf-8";
    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
      //sets font
    HttpContext.Current.Response.Write("");
    HttpContext.Current.Response.Write("


");
    //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
    HttpContext.Current.Response.Write(" + 
      "borderColor='#000000' cellSpacing='0' cellPadding='0' " + 
      "style='font-size:10.0pt; font-family:Calibri; background:white;'>
");
    //am getting my grid's column headers
int columnscount = GridView_Result.Columns.Count;

    for (int j = 0; j < columnscount; j++)
    {      //write in new column
        HttpContext.Current.Response.Write(");
        //Get column headers  and make it as bold in excel columns
        HttpContext.Current.Response.Write("");
        HttpContext.Current.Response.Write(GridView_Result.Columns[j].HeaderText.ToString());
        HttpContext.Current.Response.Write("
"
"); HttpContext.Current.Response.Write(""); } HttpContext.Current.Response.Write(""); foreach (DataRow row in table.Rows) {//write in new row HttpContext.Current.Response.Write(" " ); for (int i = 0; i < table.Columns.Count; i++) { HttpContext.Current.Response.Write(""); HttpContext.Current.Response.Write(row[i].ToString()); HttpContext.Current.Response.Write(""); } HttpContext.Current.Response.Write(""); } HttpContext.Current.Response.Write(""); HttpContext.Current.Response.Write(""); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }