Wednesday 16 March 2016

N-hibernate example for beginers using c# and MS sql

NHibernate:


NHibernate is an Object-Relational Mapping (ORM) solution for the .NET Platform. It provides a framework for mapping an object oriented domain model to a traditional relational database. It's primary feature is mapping from .NET classes to database tables and from CLR data types to SQL data types.

Why NHibernate?

In the past, we carefully hand-crafted our data access layers for the applications we wrote. We spent as much as 50% or more of our overall time to implement and maintain this data layer.It was not a very challenging task though, and a lot of repetitive coding was involved.
As we were not the only developers facing the problem of writing the data access code,some people started to write and publish a framework that would solve this problem. This was the birth of the ORM frameworks such as NHibernate. Nowadays, accessing relational data from an object-oriented application is a solved problem
Thus, writing your own data layer is a waste of time. Somebody even used a much more pronounced phrase to pinpoint this fact, "Writing your own data access layer is like stealing money from your client".

Example:

 In this example I am connecting test database with Emp table with primary key as ID and Name columns in "select * from Emp" query.

First Open-->new Project -->windows application(c#)-->named as(Nhibernatesample)

Step 1:Create class for table:(Emp.cs)

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace Nhibernatesample  
 {  
   public class Emp  
   {  
      public virtual int ID { get; set; }  
     public virtual string Name { get; set; }  
   }  
 }  

Here ID and Name are table Emp Columns.

Step 2:Create table Configuration(hbm.xml)

Add-->New Iem-->Data-->xml file-->named as Table name-->Emp.hbm.xml 

 <?xml version="1.0" encoding="utf-8" ?>  
 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"  
         assembly="Nhibernatesample"  
         namespace="Nhibernatesample">  
  <class name="Nhibernatesample.Emp" table="Emp">  
   <id name="ID" column="ID" type="Int32" unsaved-value="0">  
    <generator class="native">  
    </generator>  
   </id>  
   <property name="Name" />  
  </class>  
 </hibernate-mapping>  


Here  Project name as assembly="Nhibernatesample" namespace="Nhibernatesample" and class name "Nhibernatesample.Emp" and table name "Emp".Then Id is int32 and Name is name column.

Finally Emp.hbm.xml  --> Right-click-->properties-->Build Action-->(change)Embedded Resource

 Step 3: Write the Code in Sample Form1 in Button Click:

First add namesapce using addind two dll files in bin-->debug folder.Files are

i)Iesi.Collections.dll
ii)NHibernate.dll

Then Project-->add reference-->Browse-->bin-->debug add two dlls one by one.

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Linq;  
 using System.Text;  
 using System.Windows.Forms;  
 using System;  
 using NHibernate.Cfg;  
 using NHibernate.Dialect;  
 using NHibernate.Driver;  
 using System.Reflection;  
 namespace Nhibernatesample  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
     }  
     private void button1_Click(object sender, EventArgs e)  
     {  
       var cfg = new Configuration();  
       cfg.DataBaseIntegration(x =>  
       {  
         x.ConnectionString = @"Server=245.245.245.245\sql2005;DataBase=test;UID=sa;Pwd=testpass";  
         x.Driver<SqlClientDriver>();  
         x.Dialect<MsSql2005Dialect>();  
       });  
       cfg.AddAssembly(Assembly.GetExecutingAssembly());  
       var sessionFactory = cfg.BuildSessionFactory();  
       using (var session = sessionFactory.OpenSession())  
       {  
         using (var tx = session.BeginTransaction())  
         {  
           var datas = session.CreateCriteria<Emp>()  
             .List<Emp>();  
           if (datas.Count > 0)  
             {  
               dataGridView1.Visible = true;  
               dataGridView1.Refresh();  
               dataGridView1.DataSource = datas;  
             }  
           tx.Commit();  
         }  
       }  
     }  
   }  
 }  

In my Project I am using sql 2005. If you using Ms sql 2010 or 2012  use MsSql2010Dialect or MsSql2012Dialect in x.Dialect.

Finally We got the Result in Button1_click Event.

 


Friday 26 February 2016

Sub Total & Grand Total in Dataset(Datatables) using Group Names C#

If you have Linkbutton in asp.net ,you did't get Total ,sub Total in Row Data Bound if you using Model Popup.So you need to get  subtotal,grand total in Datatable itself.The given below example give you the Group Names{ProjectName} based total,subtotal using Linq.

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Text;  
 using System.Windows.Forms;  
 //added namespace  
 using System.Linq;  
 namespace testDatatablesum  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
     }  
     private DataTable getdata()  
     {  
       DataTable dt = new DataTable();  
       dt.Columns.Add("ProjectName");  
       dt.Columns.Add("Source");  
       dt.Columns.Add("SourceAmount");  
       // Add Rows  
       DataRow rowA1 = dt.NewRow();  
       rowA1["ProjectName"] = "A";  
       rowA1["Source"] = "ABC";  
       rowA1["SourceAmount"] = "10000";  
       dt.Rows.Add(rowA1);  
       DataRow rowA2 = dt.NewRow();  
       rowA2["ProjectName"] = "A";  
       rowA2["Source"] = "XYZ";  
       rowA2["SourceAmount"] = "50200";  
       dt.Rows.Add(rowA2);  
       DataRow rowA3 = dt.NewRow();  
       rowA3["ProjectName"] = "A";  
       rowA3["Source"] = "DFG";  
       rowA3["SourceAmount"] = "27000";  
       dt.Rows.Add(rowA3);  
       DataRow rowB1 = dt.NewRow();  
       rowB1["ProjectName"] = "B";  
       rowB1["Source"] = "LMN";  
       rowB1["SourceAmount"] = "12990";  
       dt.Rows.Add(rowB1);  
       DataRow rowB2 = dt.NewRow();  
       rowB2["ProjectName"] = "B";  
       rowB2["Source"] = "PQR";  
       rowB2["SourceAmount"] = "14000";  
       dt.Rows.Add(rowB2);  
       DataRow rowC1 = dt.NewRow();  
       rowC1["ProjectName"] = "C";  
       rowC1["Source"] = "KLM";  
       rowC1["SourceAmount"] = "10000";  
       dt.Rows.Add(rowC1);  
       return dt;  
     }  
     private void button1_Click(object sender, EventArgs e)  
     {  
       DataTable dt = new DataTable();  
       dt= getdata();  
       // Find distinct projects  
       var distinctProjects = (from r in dt.AsEnumerable()  
                   select r["ProjectName"]).Distinct().OrderBy(project => project);  
       // Get all amounts to tally later for the All Total entry  
       var allEntries = from r in dt.AsEnumerable()  
               select r["SourceAmount"];  
       // Loop through distinct project list and add project subtotal row to table  
       foreach (var p in distinctProjects)  
       {  
         var amt = from r in dt.AsEnumerable()  
              where r["ProjectName"] == p  
              select r["SourceAmount"];  
         DataRow dr = dt.NewRow();  
         dr["ProjectName"] = p + " Sub Total:";  
         dr["SourceAmount"] = amt.Sum(x => Convert.ToDecimal(x));  
         dt.Rows.Add(dr);  
       }  
       // Sort table so the sub totals fall under the project it belongs to  
       DataView dv = dt.DefaultView;  
       dv.Sort = "ProjectName ASC, Source ASC";  
       dt = dv.ToTable();  
       // Create and add the final total row  
       DataRow finalTotal = dt.NewRow();  
       finalTotal["ProjectName"] = "All Total:";  
       finalTotal["SourceAmount"] = allEntries.Sum(x => Convert.ToDecimal(x));  
       dt.Rows.Add(finalTotal);  
       // Display correct results with message box  
       foreach (DataRow r in dt.Rows)  
       {  
         MessageBox.Show(  
           r["ProjectName"].ToString() + "  " +  
           r["Source"].ToString() + "  " +  
           r["SourceAmount"].ToString()  
         );  
       }  
     }  
   }  
 }  



Output:
Dataset Input:
Dataset OUTPUT:


Thursday 18 February 2016

Multiple File Upload in FileUpload Control in asp.net in Visual Studio 2010 using jquery

Set the property "AllowMultiple = true" This property is available only for 4.5 framework.If you using  4.0.

Simply add js file (http://code.jquery.com/jquery-1.8.2.js) and inline script js( http://code.google.com/p/jquery-multifile-plugin/) file in your control form.And to anything with your .cs file.

the aspx file is, Like below,you can download sample at multifileupload.html


 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title></title>  
   <link href="file-upload.css" rel="stylesheet" type="text/css" />  
     <style type="text/css">  
 /****************** Start page styles ********************************************/  
 body {  
      background: #DFA01B;  
      font-family: arial, sans-serif;  
      font-size: 11px;  
      }  
 #wrap {  
      max-width: 600px;  
      margin: 30px auto;  
      background: #fff;  
      border: 4px solid #FFD16F;  
      -moz-border-radius: 15px;  
      -webkit-border-radius: 15px;  
      border-radius: 15px;  
      padding: 20px;  
   }  
 .field {   
      padding: 0 0 1em;   
      }  
 </style>  
   <script src="http://code.jquery.com/jquery-1.8.2.js"></script>  
   <script language="javascript" type="text/javascript">  
     /*  
     ### jQuery Multiple File Upload Plugin v1.48 - 2012-07-19 ###  
     * Home: http://www.fyneworks.com/jquery/multiple-file-upload/  
     * Code: http://code.google.com/p/jquery-multifile-plugin/  
     *  
     * Dual licensed under the MIT and GPL licenses:  
     *  http://www.opensource.org/licenses/mit-license.php  
     *  http://www.gnu.org/licenses/gpl.html  
     ###  
     */  
     /*# AVOID COLLISIONS #*/  
     ; if (window.jQuery) (function ($) {  
       /*# AVOID COLLISIONS #*/  
       // plugin initialization  
       $.fn.MultiFile = function (options) {  
         if (this.length == 0) return this; // quick fail  
         // Handle API methods  
         if (typeof arguments[0] == 'string') {  
           // Perform API methods on individual elements  
           if (this.length > 1) {  
             var args = arguments;  
             return this.each(function () {  
               $.fn.MultiFile.apply($(this), args);  
             });  
           };  
           // Invoke API method handler  
           $.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);  
           // Quick exit...  
           return this;  
         };  
         // Initialize options for this call  
         var options = $.extend(  
                {}/* new object */,  
                $.fn.MultiFile.options/* default options */,  
                options || {} /* just-in-time options */  
           );  
         // Empty Element Fix!!!  
         // this code will automatically intercept native form submissions  
         // and disable empty file elements  
         $('form')  
           .not('MultiFile-intercepted')  
           .addClass('MultiFile-intercepted')  
           .submit($.fn.MultiFile.disableEmpty);  
         //### http://plugins.jquery.com/node/1363  
         // utility method to integrate this plugin with others...  
         if ($.fn.MultiFile.options.autoIntercept) {  
           $.fn.MultiFile.intercept($.fn.MultiFile.options.autoIntercept /* array of methods to intercept */);  
           $.fn.MultiFile.options.autoIntercept = null; /* only run this once */  
         };  
         // loop through each matched element  
         this  
            .not('.MultiFile-applied')  
                .addClass('MultiFile-applied')  
           .each(function () {  
             //#####################################################################  
             // MAIN PLUGIN FUNCTIONALITY - START  
             //#####################################################################  
             // BUG 1251 FIX: http://plugins.jquery.com/project/comments/add/1251  
             // variable group_count would repeat itself on multiple calls to the plugin.  
             // this would cause a conflict with multiple elements  
             // changes scope of variable to global so id will be unique over n calls  
             window.MultiFile = (window.MultiFile || 0) + 1;  
             var group_count = window.MultiFile;  
             // Copy parent attributes - Thanks to Jonas Wagner  
             // we will use this one to create new input elements  
             var MultiFile = { e: this, E: $(this), clone: $(this).clone() };  
             //===  
             //# USE CONFIGURATION  
             if (typeof options == 'number') options = { max: options };  
             var o = $.extend({},  
     $.fn.MultiFile.options,  
     options || {},  
                            ($.metadata ? MultiFile.E.metadata() : ($.meta ? MultiFile.E.data() : null)) || {}, /* metadata options */  
                                         {} /* internals */  
     );  
             // limit number of files that can be selected?  
             if (!(o.max > 0) /*IsNull(MultiFile.max)*/) {  
               o.max = MultiFile.E.attr('maxlength');  
             };  
             if (!(o.max > 0) /*IsNull(MultiFile.max)*/) {  
               o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];  
               if (!(o.max > 0)) o.max = -1;  
               else o.max = String(o.max).match(/[0-9]+/gi)[0];  
             }  
             o.max = new Number(o.max);  
             // limit extensions?  
             o.accept = o.accept || MultiFile.E.attr('accept') || '';  
             if (!o.accept) {  
               o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';  
               o.accept = new String(o.accept).replace(/^(accept|ext)\-/i, '');  
             };  
             //===  
             // APPLY CONFIGURATION  
             $.extend(MultiFile, o || {});  
             MultiFile.STRING = $.extend({}, $.fn.MultiFile.options.STRING, MultiFile.STRING);  
             //===  
             //#########################################  
             // PRIVATE PROPERTIES/METHODS  
             $.extend(MultiFile, {  
               n: 0, // How many elements are currently selected?  
               slaves: [], files: [],  
               instanceKey: MultiFile.e.id || 'MultiFile' + String(group_count), // Instance Key?  
               generateID: function (z) { return MultiFile.instanceKey + (z > 0 ? '_F' + String(z) : ''); },  
               trigger: function (event, element) {  
                 var handler = MultiFile[event], value = $(element).attr('value');  
                 if (handler) {  
                   var returnValue = handler(element, value, MultiFile);  
                   if (returnValue != null) return returnValue;  
                 }  
                 return true;  
               }  
             });  
             //===  
             // Setup dynamic regular expression for extension validation  
             // - thanks to John-Paul Bader: http://smyck.de/2006/08/11/javascript-dynamic-regular-expresions/  
             if (String(MultiFile.accept).length > 1) {  
               MultiFile.accept = MultiFile.accept.replace(/\W+/g, '|').replace(/^\W|\W$/g, '');  
               MultiFile.rxAccept = new RegExp('\\.(' + (MultiFile.accept ? MultiFile.accept : '') + ')$', 'gi');  
             };  
             //===  
             // Create wrapper to hold our file list  
             MultiFile.wrapID = MultiFile.instanceKey + '_wrap'; // Wrapper ID?  
             MultiFile.E.wrap('<div class="MultiFile-wrap" id="' + MultiFile.wrapID + '"></div>');  
             MultiFile.wrapper = $('#' + MultiFile.wrapID + '');  
             //===  
             // MultiFile MUST have a name - default: file1[], file2[], file3[]  
             MultiFile.e.name = MultiFile.e.name || 'file' + group_count + '[]';  
             //===  
             if (!MultiFile.list) {  
               // Create a wrapper for the list  
               // * OPERA BUG: NO_MODIFICATION_ALLOWED_ERR ('list' is a read-only property)  
               // this change allows us to keep the files in the order they were selected  
               MultiFile.wrapper.append('<div class="MultiFile-list" id="' + MultiFile.wrapID + '_list"></div>');  
               MultiFile.list = $('#' + MultiFile.wrapID + '_list');  
             };  
             MultiFile.list = $(MultiFile.list);  
             //===  
             // Bind a new element  
             MultiFile.addSlave = function (slave, slave_count) {  
               //if(window.console) console.log('MultiFile.addSlave',slave_count);  
               // Keep track of how many elements have been displayed  
               MultiFile.n++;  
               // Add reference to master element  
               slave.MultiFile = MultiFile;  
               // BUG FIX: http://plugins.jquery.com/node/1495  
               // Clear identifying properties from clones  
               if (slave_count > 0) slave.id = slave.name = '';  
               // Define element's ID and name (upload components need this!)  
               //slave.id = slave.id || MultiFile.generateID(slave_count);  
               if (slave_count > 0) slave.id = MultiFile.generateID(slave_count);  
               //FIX for: http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=23  
               // 2008-Apr-29: New customizable naming convention (see url below)  
               // http://groups.google.com/group/jquery-dev/browse_frm/thread/765c73e41b34f924#  
               slave.name = String(MultiFile.namePattern  
               /*master name*/.replace(/\$name/gi, $(MultiFile.clone).attr('name'))  
               /*master id */.replace(/\$id/gi, $(MultiFile.clone).attr('id'))  
               /*group count*/.replace(/\$g/gi, group_count)//(group_count>0?group_count:''))  
               /*slave count*/.replace(/\$i/gi, slave_count)//(slave_count>0?slave_count:''))  
     );  
               // If we've reached maximum number, disable input slave  
               if ((MultiFile.max > 0) && ((MultiFile.n - 1) > (MultiFile.max)))//{ // MultiFile.n Starts at 1, so subtract 1 to find true count  
                 slave.disabled = true;  
               //};  
               // Remember most recent slave  
               MultiFile.current = MultiFile.slaves[slave_count] = slave;  
               // We'll use jQuery from now on  
               slave = $(slave);  
               // Clear value  
               slave.val('').attr('value', '')[0].value = '';  
               // Stop plugin initializing on slaves  
               slave.addClass('MultiFile-applied');  
               // Triggered when a file is selected  
               slave.change(function () {  
                 //if(window.console) console.log('MultiFile.slave.change',slave_count);  
                 // Lose focus to stop IE7 firing onchange again  
                 $(this).blur();  
                 //# Trigger Event! onFileSelect  
                 if (!MultiFile.trigger('onFileSelect', this, MultiFile)) return false;  
                 //# End Event!  
                 //# Retrive value of selected file from element  
                 var ERROR = '', v = String(this.value || ''/*.attr('value)*/);  
                 // check extension  
                 if (MultiFile.accept && v && !v.match(MultiFile.rxAccept))//{  
                   ERROR = MultiFile.STRING.denied.replace('$ext', String(v.match(/\.\w{1,4}$/gi)));  
                 //}  
                 //};  
                 // Disallow duplicates  
                 for (var f in MultiFile.slaves)//{  
                   if (MultiFile.slaves[f] && MultiFile.slaves[f] != this)//{  
                   //console.log(MultiFile.slaves[f],MultiFile.slaves[f].value);  
                     if (MultiFile.slaves[f].value == v)//{  
                       ERROR = MultiFile.STRING.duplicate.replace('$file', v.match(/[^\/\\]+$/gi));  
                 //};  
                 //};  
                 //};  
                 // Create a new file input element  
                 var newEle = $(MultiFile.clone).clone(); // Copy parent attributes - Thanks to Jonas Wagner  
                 //# Let's remember which input we've generated so  
                 // we can disable the empty ones before submission  
                 // See: http://plugins.jquery.com/node/1495  
                 newEle.addClass('MultiFile');  
                 // Handle error  
                 if (ERROR != '') {  
                   // Handle error  
                   MultiFile.error(ERROR);  
                   // 2007-06-24: BUG FIX - Thanks to Adrian Wróbel <adrian [dot] wrobel [at] gmail.com>  
                   // Ditch the trouble maker and add a fresh new element  
                   MultiFile.n--;  
                   MultiFile.addSlave(newEle[0], slave_count);  
                   slave.parent().prepend(newEle);  
                   slave.remove();  
                   return false;  
                 };  
                 // Hide this element (NB: display:none is evil!)  
                 $(this).css({ position: 'absolute', top: '-3000px' });  
                 // Add new element to the form  
                 slave.after(newEle);  
                 // Update list  
                 MultiFile.addToList(this, slave_count);  
                 // Bind functionality  
                 MultiFile.addSlave(newEle[0], slave_count + 1);  
                 //# Trigger Event! afterFileSelect  
                 if (!MultiFile.trigger('afterFileSelect', this, MultiFile)) return false;  
                 //# End Event!  
               }); // slave.change()  
               // Save control to element  
               $(slave).data('MultiFile', MultiFile);  
             }; // MultiFile.addSlave  
             // Bind a new element  
             // Add a new file to the list  
             MultiFile.addToList = function (slave, slave_count) {  
               //if(window.console) console.log('MultiFile.addToList',slave_count);  
               //# Trigger Event! onFileAppend  
               if (!MultiFile.trigger('onFileAppend', slave, MultiFile)) return false;  
               //# End Event!  
               // Create label elements  
               var   
      r = $('<div class="MultiFile-label"></div>'),  
      v = String(slave.value || ''/*.attr('value)*/),  
      a = $('<span class="MultiFile-title" title="' + MultiFile.STRING.selected.replace('$file', v) + '">' + MultiFile.STRING.file.replace('$file', v.match(/[^\/\\]+$/gi)[0]) + '</span>'),  
      b = $('<a class="MultiFile-remove" href="#' + MultiFile.wrapID + '">' + MultiFile.STRING.remove + '</a>');  
               // Insert label  
               MultiFile.list.append(  
      r.append(b, ' ', a)  
     );  
               b  
                                         .click(function () {  
                                           //# Trigger Event! onFileRemove  
                                           if (!MultiFile.trigger('onFileRemove', slave, MultiFile)) return false;  
                                           //# End Event!  
                                           MultiFile.n--;  
                                           MultiFile.current.disabled = false;  
                                           // Remove element, remove label, point to current  
                                           MultiFile.slaves[slave_count] = null;  
                                           $(slave).remove();  
                                           $(this).parent().remove();  
                                           // Show most current element again (move into view) and clear selection  
                                           $(MultiFile.current).css({ position: '', top: '' });  
                                           $(MultiFile.current).reset().val('').attr('value', '')[0].value = '';  
                                           //# Trigger Event! afterFileRemove  
                                           if (!MultiFile.trigger('afterFileRemove', slave, MultiFile)) return false;  
                                           //# End Event!  
                                           return false;  
                                         });  
               //# Trigger Event! afterFileAppend  
               if (!MultiFile.trigger('afterFileAppend', slave, MultiFile)) return false;  
               //# End Event!  
             }; // MultiFile.addToList  
             // Add element to selected files list  
             // Bind functionality to the first element  
             if (!MultiFile.MultiFile) MultiFile.addSlave(MultiFile.e, 0);  
             // Increment control count  
             //MultiFile.I++; // using window.MultiFile  
             MultiFile.n++;  
             // Save control to element  
             MultiFile.E.data('MultiFile', MultiFile);  
             //#####################################################################  
             // MAIN PLUGIN FUNCTIONALITY - END  
             //#####################################################################  
           }); // each element  
       };  
       /*--------------------------------------------------------*/  
       /*  
       ### Core functionality and API ###  
       */  
       $.extend($.fn.MultiFile, {  
         /**  
         * This method removes all selected files  
         *  
         * Returns a jQuery collection of all affected elements.  
         *  
         * @name reset  
         * @type jQuery  
         * @cat Plugins/MultiFile  
         * @author Diego A. (http://www.fyneworks.com/)  
         *  
         * @example $.fn.MultiFile.reset();  
         */  
         reset: function () {  
           var settings = $(this).data('MultiFile');  
           //if(settings) settings.wrapper.find('a.MultiFile-remove').click();  
           if (settings) settings.list.find('a.MultiFile-remove').click();  
           return $(this);  
         },  
         /**  
         * This utility makes it easy to disable all 'empty' file elements in the document before submitting a form.  
         * It marks the affected elements so they can be easily re-enabled after the form submission or validation.  
         *  
         * Returns a jQuery collection of all affected elements.  
         *  
         * @name disableEmpty  
         * @type jQuery  
         * @cat Plugins/MultiFile  
         * @author Diego A. (http://www.fyneworks.com/)  
         *  
         * @example $.fn.MultiFile.disableEmpty();  
         * @param String class (optional) A string specifying a class to be applied to all affected elements - Default: 'mfD'.  
         */  
         disableEmpty: function (klass) {  
           klass = (typeof (klass) == 'string' ? klass : '') || 'mfD';  
           var o = [];  
           $('input:file.MultiFile').each(function () { if ($(this).val() == '') o[o.length] = this; });  
           return $(o).each(function () { this.disabled = true }).addClass(klass);  
         },  
         /**  
         * This method re-enables 'empty' file elements that were disabled (and marked) with the $.fn.MultiFile.disableEmpty method.  
         *  
         * Returns a jQuery collection of all affected elements.  
         *  
         * @name reEnableEmpty  
         * @type jQuery  
         * @cat Plugins/MultiFile  
         * @author Diego A. (http://www.fyneworks.com/)  
         *  
         * @example $.fn.MultiFile.reEnableEmpty();  
         * @param String klass (optional) A string specifying the class that was used to mark affected elements - Default: 'mfD'.  
         */  
         reEnableEmpty: function (klass) {  
           klass = (typeof (klass) == 'string' ? klass : '') || 'mfD';  
           return $('input:file.' + klass).removeClass(klass).each(function () { this.disabled = false });  
         },  
         /**  
         * This method will intercept other jQuery plugins and disable empty file input elements prior to form submission  
         *  
         * @name intercept  
         * @cat Plugins/MultiFile  
         * @author Diego A. (http://www.fyneworks.com/)  
         *  
         * @example $.fn.MultiFile.intercept();  
         * @param Array methods (optional) Array of method names to be intercepted  
         */  
         intercepted: {},  
         intercept: function (methods, context, args) {  
           var method, value; args = args || [];  
           if (args.constructor.toString().indexOf("Array") < 0) args = [args];  
           if (typeof (methods) == 'function') {  
             $.fn.MultiFile.disableEmpty();  
             value = methods.apply(context || window, args);  
             //SEE-http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27  
             setTimeout(function () { $.fn.MultiFile.reEnableEmpty() }, 1000);  
             return value;  
           };  
           if (methods.constructor.toString().indexOf("Array") < 0) methods = [methods];  
           for (var i = 0; i < methods.length; i++) {  
             method = methods[i] + ''; // make sure that we have a STRING  
             if (method) (function (method) { // make sure that method is ISOLATED for the interception  
               $.fn.MultiFile.intercepted[method] = $.fn[method] || function () { };  
               $.fn[method] = function () {  
                 $.fn.MultiFile.disableEmpty();  
                 value = $.fn.MultiFile.intercepted[method].apply(this, arguments);  
                 //SEE http://code.google.com/p/jquery-multifile-plugin/issues/detail?id=27  
                 setTimeout(function () { $.fn.MultiFile.reEnableEmpty() }, 1000);  
                 return value;  
               }; // interception  
             })(method); // MAKE SURE THAT method IS ISOLATED for the interception  
           }; // for each method  
         } // $.fn.MultiFile.intercept  
       });  
       /*--------------------------------------------------------*/  
       /*  
       ### Default Settings ###  
       eg.: You can override default control like this:  
       $.fn.MultiFile.options.accept = 'gif|jpg';  
       */  
       $.fn.MultiFile.options = { //$.extend($.fn.MultiFile, { options: {  
         accept: '', // accepted file extensions  
         max: -1,  // maximum number of selectable files  
         // name to use for newly created elements  
         namePattern: '$name', // same name by default (which creates an array)  
         /*master name*/ // use $name  
         /*master id */ // use $id  
         /*group count*/ // use $g  
         /*slave count*/ // use $i  
         /*other   */ // use any combination of he above, eg.: $name_file$i  
         // STRING: collection lets you show messages in different languages  
         STRING: {  
           remove: 'X',  
           denied: 'You cannot select a $ext file.\nTry again...',  
           file: '$file',  
           selected: 'File selected: $file',  
           duplicate: 'This file has already been selected:\n$file'  
         },  
         // name of methods that should be automcatically intercepted so the plugin can disable  
         // extra file elements that are empty before execution and automatically re-enable them afterwards  
         autoIntercept: ['submit', 'ajaxSubmit', 'ajaxForm', 'validate', 'valid' /* array of methods to intercept */],  
         // error handling function  
         error: function (s) {  
           /*  
           ERROR! blockUI is not currently working in IE  
           if($.blockUI){  
           $.blockUI({  
           message: s.replace(/\n/gi,'<br/>'),  
           css: {   
           border:'none', padding:'15px', size:'12.0pt',  
           backgroundColor:'#900', color:'#fff',  
           opacity:'.8','-webkit-border-radius': '10px','-moz-border-radius': '10px'  
           }  
           });  
           window.setTimeout($.unblockUI, 2000);  
           }  
           else//{// save a byte!  
           */  
           alert(s);  
           //}// save a byte!  
         }  
       }; //} });  
       /*--------------------------------------------------------*/  
       /*  
       ### Additional Methods ###  
       Required functionality outside the plugin's scope  
       */  
       // Native input reset method - because this alone doesn't always work: $(element).val('').attr('value', '')[0].value = '';  
       $.fn.reset = function () { return this.each(function () { try { this.reset(); } catch (e) { } }); };  
       /*--------------------------------------------------------*/  
       /*  
       ### Default implementation ###  
       The plugin will attach itself to file inputs  
       with the class 'multi' when the page loads  
       */  
       $(function () {  
         //$("input:file.multi").MultiFile();  
         $("input[type=file].multi").MultiFile();  
       });  
       /*# AVOID COLLISIONS #*/  
     })(jQuery);  
     /*# AVOID COLLISIONS #*/  
     </script>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div>  
     <table style="width:100%;">  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           <asp:FileUpload ID="FileUpload1" class="multi" runat="server" />  
         </td>  
         <td>  
            </td>  
       </tr>  
       <tr>  
         <td>  
           </td>  
         <td>  
          <asp:Button ID="btnSubmit" Text="Submit" runat="server" />  
   <asp:Label ID="lblErrInfo" runat="server"></asp:Label></td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
       <tr>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
         <td>  
           &nbsp;</td>  
       </tr>  
     </table>  
   </div>  
   </form>  
 </body>  
 </html>  


Finally execute and enjoy, sample Output:

Changing FileUpload control text in asp.net

Add the Default.aspx file like below

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <script src="script/jelly.js" type="text/javascript"></script>  
   <style type="text/css">  
 /****************** Start page styles ********************************************/  
 body {  
      background: #DFA01B;  
      font-family: arial, sans-serif;  
      font-size: 11px;  
      }  
 #wrap {  
      max-width: 600px;  
      margin: 30px auto;  
      background: #fff;  
      border: 4px solid #FFD16F;  
      -moz-border-radius: 15px;  
      -webkit-border-radius: 15px;  
      border-radius: 15px;  
      padding: 20px;  
   }  
 .field {   
      padding: 0 0 1em;   
      }  
 </style>  
 <head runat="server">  
   <title></title>  
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <div id="wrap">  
 <form enctype="multipart/form-data" action="#" method="post">  
      <div class="field">  
           <label class="file-upload">  
                <span><strong>Put YOUR TEXT</strong></span>  
                <%--<input type="file" name="uploadfile" onclintclick="test_load()" />--%>  
       <asp:FileUpload  
         ID="FileUpload1" name="uploadfile" runat="server"   
       ondatabinding="FileUpload1_DataBinding" />  
           </label>  
      </div>  
 </form>  
 </div><!--/ wrap -->  
   <script src="script/file-upload.js" type="text/javascript"></script>  
   </form>  
 </body>  
 </html>  

Then add js files http://the-echoplex.net/demos/upload-file/file-upload.js and http://the-echoplex.net/demos/upload-file/jelly/min.js .finally code in .cs file what you need.And add the file-upload.css file.Excecute and enjoy...

Sample application Download ASP.net code link

OUTPUT:

Thursday 28 January 2016

printing all pages with paging in gridview in asp.net using c#

In Print button Click,

Add the following Code ,Here I want to Print GridView1 Data without Paging but  visually Paged Grid.
So Here First Remove Paging and Bind Grid then apply Javascript  for Print Preview PopUp then again Apply Paging in Gridview.


 PrintAllPages(object sender, EventArgs e)  
  {  
   GridView1.AllowPaging = false;  
   GridView1.DataBind();  
   StringWriter sw = new StringWriter();  
   HtmlTextWriter hw = new HtmlTextWriter(sw);  
   GridView1.RenderControl(hw);  
   string gridHTML = sw.ToString().Replace("\"", "'")  
    .Replace(System.Environment.NewLine, "");  
   StringBuilder sb = new StringBuilder();  
   sb.Append("&lt;script type = 'text/javascript'&gt;");  
   sb.Append("window.onload = new function(){");  
   sb.Append("var printWin = window.open('', '', 'left=0");  
   sb.Append(",top=0,width=1000,height=600,status=0');");  
   sb.Append("printWin.document.write(\"");  
   sb.Append(gridHTML);  
   sb.Append("\");");  
   sb.Append("printWin.document.close();");  
   sb.Append("printWin.focus();");  
   sb.Append("printWin.print();");  
   sb.Append("printWin.close();};");  
   sb.Append("&lt;/script&gt;");  
   ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());  
   GridView1.AllowPaging = true;  
   GridView1.DataBind();  
  }   

Thursday 26 November 2015

Adding Two Data Table using Uniqe Ids Join

  DataTable dt1 = new DataTable("Table1");  
     DataTable dt2 = new DataTable("Table2");  
     DataSet ds = new DataSet("DataSet");  
     dt1.Columns.Add("Eno", typeof(Int32));  
     dt1.Columns.Add("Ename", typeof(String));  
     dt1.Columns.Add("Salary", typeof(Double));  
     dt1.Columns.Add("Deptno", typeof(Int32));  
     dt1.PrimaryKey = new DataColumn[] { dt1.Columns["Eno"] };  
     dt2.Columns.Add("Deptno", typeof(Int32));  
     dt2.Columns.Add("Dname", typeof(String));  
     dt2.PrimaryKey = new DataColumn[] { dt2.Columns["Deptno"] };  
     ds.Tables.Add(dt1);  
     ds.Tables.Add(dt2);  
     // Loading data into dt1, dt2:  
     object[] o1 = { 1, "Ravi", 50000.50, 10 };  
     object[] o2 = { 2, "Raj", 4000.50, 20 };  
     object[] o3 = { 3, "Joni", 10000.50, 10 };  
     object[] c1 = { 10, "MFG" };  
     object[] c2 = { 20, "EAS" };  
     object[] c3 = { 30, "E&amp;U" };  
     object[] c4 = { 40, "PES" };  
     dt2.Rows.Add(c1);  
     dt2.Rows.Add(c2);  
     dt2.Rows.Add(c3);  
     dt2.Rows.Add(c4);  
     dt1.Rows.Add(o1);  
     dt1.Rows.Add(o2);  
     dt1.Rows.Add(o3);  
     DataRelation drel = new DataRelation("EquiJoin", dt2.Columns["Deptno"], dt1.Columns["Deptno"]);  
     ds.Relations.Add(drel);  
     DataTable jt = new DataTable("Joinedtable");  
     jt.Columns.Add("Eno", typeof(Int32));  
     jt.Columns.Add("Ename", typeof(String));  
     jt.Columns.Add("Salary", typeof(Double));  
     jt.Columns.Add("Deptno", typeof(Int32));  
     jt.Columns.Add("Dname", typeof(String));  
     ds.Tables.Add(jt);  
     foreach (DataRow dr in ds.Tables["Table1"].Rows)  
     {  
       DataRow parent = dr.GetParentRow("EquiJoin");  
       DataRow current = jt.NewRow();  
       // Just add all the columns' data in "dr" to the New table.  
       for (int i = 0; i &lt; ds.Tables["Table1"].Columns.Count; i++)  
       {  
         current[i] = dr[i];  
       }  
       // Add the column that is not present in the child, which is present in the parent.  
       current["Dname"] = parent["Dname"];  
       jt.Rows.Add(current);  
     }  
     GridView1.Visible = true;  

finally bind gridiew
      
  GridView1.DataSource = ds.Tables["Joinedtable"];  
  GridView1.DataBind();