Drag n drop multiple file uploads with process bar using JavaScript. Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
namespace WebApplication4.Controllers
{
    public class DemoController : Controller
    {
        // GET: Demo
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult JqAJAX(List<string> list)
        {
            try
            {

                return Json(1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    public class Student
    {
        public string data { get; set; }
    }
}
--------------------

@{
    ViewBag.Title = "Index";
}

<!DOCTYPE html>
<html>
<head>
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <style>
        #dragandrophandler {
            border: 2px dotted #0B85A1;
            width: 400px;
            color: #92AAB0;
            text-align: left;
            vertical-align: middle;
            padding: 10px 10px 10 10px;
            margin-bottom: 10px;
            font-size: 200%;
        }
    </style>
    <style>
        #selectedFiles img {
            max-width: 200px;
            max-height: 200px;
            float: left;
            margin-bottom: 10px;
        }

        .thumbnail {
            width: 18px;
            height: 18px;
        }
    </style>
</head>
<body>
    <form id="myForm" method="post">
        <br />
        <br />
        <div id="dragandrophandler">Drag & Drop Files Here</div>
        Category : <input id="Text1" type="text" />
        Files: <input type="file" id="files" name="files" multiple><br />
        <div id="selectedFiles"></div>
        <input type="submit">
        <div class="row">
            <div class="col-sm-12">
                <div class="progress progress-striped active">
                    <div class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%;transition:none;">
                    </div>
                </div>
            </div>
        </div>
    </form>

    <script>
        var selDiv = "";
        var storedFiles = [];
        function handleFileSelect(e) {
            debugger
            var files = e.target.files;
            var filesArr = Array.prototype.slice.call(files);
            filesArr.forEach(function (f) {
                storedFiles.push(f.name);
                var reader = new FileReader();
                reader.onload = function (e) {
                    debugger
                    var html = "<div><img  src=\"" + '/Uploads/k.jpg' + "\" data-file='" + f.name + "' class='selFile thumbnail' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
                    selDiv.append(html);
                }
                reader.readAsDataURL(f);
            });

        }
        function handleFileSelect1(files) {
            debugger
            var filesArr = Array.prototype.slice.call(files);
            filesArr.forEach(function (f) {
                storedFiles.push(f.name);
                var reader = new FileReader();
                reader.onload = function (e) {
                    debugger
                    var html = "<div><img  src=\"" + '/Uploads/k.jpg' + "\" data-file='" + f.name + "' class='selFile thumbnail' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
                    selDiv.append(html);
                }
                reader.readAsDataURL(f);
            });

        }
        $(document).ready(function () {
            $("#files").on("change", handleFileSelect);
            selDiv = $("#selectedFiles");
            $("#myForm").on("submit", handleForm);
            $("body").on("click", ".selFile", removeFile);
            debugger
            var obj = $("#dragandrophandler");
            obj.on('dragenter', function (e) {
                e.stopPropagation();
                e.preventDefault();
                $(this).css('border', '2px solid #0B85A1');
            });
            obj.on('dragover', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });
            obj.on('drop', function (e) {
                debugger
                $(this).css('border', '2px dotted #0B85A1');
                e.preventDefault();
                var files = e.originalEvent.dataTransfer.files;
                handleFileSelect1(files);
            });
            $(document).on('dragenter', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });
            $(document).on('dragover', function (e) {
                e.stopPropagation();
                e.preventDefault();
                obj.css('border', '2px dotted #0B85A1');
            });
            $(document).on('drop', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });

        });

        function handleForm(e) {

            var items = new Array();
            e.preventDefault();
            debugger
            var data = new FormData();
            for (var i = 0, len = storedFiles.length; i < len; i++) {
                data.append('files', storedFiles[i]);
                items.push(storedFiles[i]);
            }
            var name = $("#Text1").val();
            debugger
            var Student = items;
            $.ajax({
                type: "POST",
                url: "/Demo/JqAJAX",
                data: JSON.stringify(Student),
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    debugger
                    var value = result;
                    debugger
                },
                error: function () {
                    alert("Error occured!!")
                }
            });
        }

        function removeFile(e) {
            var file = $(this).data("file");
            for (var i = 0; i < storedFiles.length; i++) {
                if (storedFiles[i].name === file) {
                    storedFiles.splice(i, 1);
                    break;
                }
            }
            $(this).parent().remove();
        }
    </script>

</body>
</html>
Share:

How to bind data table through html using jQuery?

@{
    Layout = null;
}
<H1>Employee Details</H1>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">

<div class="container">
    <table id="tblGrid" class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Salary</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            url: 'http://localhost:50148/api/EmpAPI/EmployeeDetails',
            type: "GET",
            dataType: "json",
            success: function (result) {
                debugger;
             
                var htmlContent = "";
                $.each(result, function (key, item) {
                    var itemDetails = [
                                 { "ItemName": item.ID }
                    ];
                    htmlContent = htmlContent + "<tr><td>" + item.ID + "</td>" + "<td>" + item.Name + "</td>" + "<td>" + item.Salary + "</td>" + "<td>" +
                    '<a href="http://localhost:50148/api/EmpAPI/EmployeeDetails?ID=' + item.ID + '">Edit</a>' + ' ' +
                    '<a href="http://localhost:50148/api/EmpAPI/DeleteEmployee?ID=' + item.ID + '">Delete</a>' + "</td></tr>";
                });
                $("#tblGrid").append(htmlContent);

                $('#tblGrid').DataTable({
                    "pagingType": "full_numbers",
                    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
                    //"paging": false,
                    //"ordering": false,
                    //"info": false,
                    //"searching": false
                });

            },
            error: function (err) {
                alert(err.statusText);
            }
        });
    });
</script>

Share:

What is the differences among ArrayList, HashTable, List and Dictionoiry in C#? Example.

class Program
    {
        static void Main(string[] args)
        {
            List<int> li = new List<int>();
            li.Add(1);
            li.Add(2);
            li.Add(3);
            foreach (int i in li)
            {
                Console.WriteLine(i);
            }
            Dictionary<int,string> di = new Dictionary<int,string>();
            di.Add(1,"kul");
            di.Add(2, "raj");
            di.Add(3, "neha");

            foreach(KeyValuePair<int,string> ob in di)
            {
                Console.WriteLine(ob.Key +" "+ob.Value);
            }
            HashSet<int> ht = new HashSet<int>();
            ht.Add(1);
            ht.Add(2);
            ht.Add(3);
            foreach (int i in ht)
            {
                Console.WriteLine(i);
            }

            ArrayList obj = new ArrayList();
            obj.Add(1);
            obj.Add("kul");
            obj.Add("noida");
            foreach (object i in obj)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
Share:

What is difference between List and Dictionory in C# with example?

class Program
    {
        static void Main(string[] args)
        {
            List<int> li = new List<int>();
            li.Add(1);
            li.Add(2);
            li.Add(3);
            foreach (int i in li)
            {
                Console.WriteLine(i);
            }
            Dictionary<int,string> di = new Dictionary<int,string>();
            di.Add(1,"kul");
            di.Add(2, "raj");
            di.Add(3, "neha");

            foreach(KeyValuePair<int,string> ob in di)
            {
                Console.WriteLine(ob.Key +" "+ob.Value);
            }
            Console.ReadLine();
        }
Share:

How to count character in your name using C#?

class Program
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string s = "kulshresth";
            var occurances = new Dictionary<char, int>();
            foreach (char c in s)
            {
                if (occurances.ContainsKey(c))
                    occurances[c] = occurances[c] + 1;
                else
                    occurances[c] = 1;
            }
            foreach (var entry in occurances)
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
            Console.ReadLine();
        }
    }
Share:

How to create Windows Services in C#? Example.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace ScheduledService
{
    public partial class ScheduledService : ServiceBase
    {
        Timer timer = new Timer();
        public ScheduledService()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            TraceService("start service");
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 1000;
            timer.Enabled = true;
        }
        protected override void OnStop()
        {
            timer.Enabled = false;
            TraceService("stopping service");
        }
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            TraceService("Another entry at " + DateTime.Now);
        }
        private void TraceService(string content)
        {
            FileStream fs = new FileStream(@"d:\ScheduledService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(content);
            sw.Flush();
            sw.Close();
        }
    }
}

Share:

How to check excel Date Format using C#? Example.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <style type="text/css">
        .auto-style1 {
            width: 50%;
        }
    </style>

</head>
<body>
    <form id="form1" runat="server">
 

    <table align="center" class="auto-style1">
        <tr>
            <td>
                <asp:FileUpload ID="FileUpload1" runat="server" Width="200px" />&nbsp;&nbsp;<asp:Button ID="Button1" runat="server" Style="margin-left: 0px" Text="Upload" OnClick="Button1_Click" /></td>
         
        </tr>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="ID" HeaderText="ID" HtmlEncode="False" ReadOnly="True" />
                        <asp:BoundField DataField="NAME" HeaderText="NAME" HtmlEncode="False" ReadOnly="True" />
                        <asp:BoundField DataField="JOINDATE" HeaderText="JOINDATE" HtmlEncode="False" DataFormatString="{0:d}" ReadOnly="True" />
                    </Columns>


                </asp:GridView>
            </td>

        </tr>
    </table>
      </form>
</body>
</html>
-----------------------------------------------
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel = Microsoft.Office.Interop.Excel.Application;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // processExcel("D:\\Book1.xlsx");
    }
    private void processExcel(string filename)
    {
        Application xlApp;
        Workbook xlWorkBook;
        Worksheet xlWorkSheet;

        var missing = System.Reflection.Missing.Value;

        xlApp = new ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open(filename);
        //xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        Range xlRange = xlWorkSheet.UsedRange;
        Array myValues = (Array)xlRange.Cells.Value2;



        int vertical = myValues.GetLength(0);
        int horizontal = myValues.GetLength(1);

        System.Data.DataTable dt = new System.Data.DataTable();
        DateTime tempD = new DateTime();
        //if (DateTime.TryParse(myValues.GetValue(3, 3).ToString(), out tempD))
        //{

        //}
        // must start with index = 1
        // get header information
        for (int i = 1; i <= horizontal; i++)
        {
            dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
        }

        // Get the row information
        for (int a = 2; a <= vertical; a++)
        {


            object[] poop = new object[horizontal];
            for (int b = 1; b <= horizontal; b++)
            {
                try
                {
                    poop[b - 1] = myValues.GetValue(a, b);
                    if (poop[2] != null)
                    {

                        double d = double.Parse(myValues.GetValue(a, b).ToString());
                        // DateTime conv = DateTime.FromOADate(d);
                        DateTime conv = DateTime.FromOADate(d);
                        //string date = conv.Date.ToString();
                        //string date = conv.ToShortDateString();
                        // poop[b - 1] = date;
                        poop[b - 1] = conv;
                    }
                    else
                    {
                        poop[b - 1] = myValues.GetValue(a, b);
                    }
                }
                catch (Exception ex)
                {
                    poop[b - 1] = "DateTime is not currect format !";
                }

            }
            DataRow row = dt.NewRow();
            row.ItemArray = poop;
            dt.Rows.Add(row);
        }
        //
        //foreach (DataRow dr in dt.Rows)
        //{
        //    double d = double.Parse(dr["JoinDate"].ToString());
        //    DateTime conv = DateTime.FromOADate(d);
        //    string date = conv.Date.ToString();


        //}

        // assign table to default data grid view

        GridView1.DataSource = dt;
        GridView1.DataBind();
        xlWorkBook.Close(true, missing, missing);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            Response.Write("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string FilePath = FileUpload1.PostedFile.FileName;
        //string path = @"D:\Book1.xlsx";
        // string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);

        processExcel(FilePath);
    }
}
Share:

How to read files data and save in directory using C#? Example.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    SqlConnection CN = new SqlConnection(@"SERVER=172.29.57.158\sql2012;Database=eMAAS;User ID=sa;Password=Mind1234");
    protected void Page_Load(object sender, EventArgs e)
    {
        Label2.Visible = false;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string ext;
        string[] allfiles = System.IO.Directory.GetFiles(TextBox1.Text, "*.*", System.IO.SearchOption.AllDirectories);
        foreach (var file in allfiles)
        {
            FileInfo info = new FileInfo(file);
           

            string name = info.Name.ToString();
            ext =info.Extension.ToString();
           
            if (ext == ".ldb" || ext == ".LDB")
            {
                ext = "Microsoft Access Record - Locking Information";
            }
            else if (ext == ".dbf" || ext == ".DBF")
            {
                ext = "DBF File";
            }
            else if (ext == ".xml" || ext == ".XML")
            {
                ext = "XML Document";
            }
            else if (ext == ".csv" || ext == ".CSV")
            {
                ext = "Microsoft Excel Comma Separated Values File";
            }
           
            else if (ext == ".CTL" || ext == ".ctl")
            {
                ext = "CTL File";
            }
            else if (ext == ".eds" || ext == ".EDS")
            {
                ext = "EDS File";
            }
            else if (ext == ".dts" || ext == ".DTS")
            {
                ext = "DTS File";
            }
            else if (ext == ".gfx" || ext == ".GFX")
            {
                ext = "GFX File";
            }
            else if (ext == ".pdf" || ext == ".PDF")
            {
                ext = "PDF File";
            }
            else if (ext == ".lnk" || ext == ".LNK")
            {
                ext = "LNK File";
            }
            else if (ext == ".txt" || ext == ".TXT")
            {
                ext = "TEXT File";
            }
            else if (ext == ".exe" || ext == ".EXE")
            {
                ext = "EXE File";
            }
            else if (ext == ".log" || ext == ".LOG")
            {
                ext = "LOG File";
            }
            else if (ext == ".dll" || ext == ".DLL")
            {
                ext = "DLL File";
            }
            else if (ext == ".gpd" || ext == ".GDP")
            {
                ext = "GPD File";
            }
            else if (ext == ".ppd" || ext == ".PPD")
            {
                ext = "PPD File";
            }
            else if (ext == ".prt" || ext == ".RPT")
            {
                ext = "PRT File";
            }
            else if (ext == ".dat" || ext == ".DAT")
            {
                ext = "DAT File";
            }
            else if (ext == ".ini" || ext == ".INI")
            {
                ext = "INI File";
            }

            else if (ext == ".tab" || ext == ".TAB")
            {
                ext = "TAB File";
            }

            else if (ext == ".rtp" || ext == ".RPT")
            {
                ext = "RPT File";
            }
            else if (ext == ".ZPP" || ext == ".zpp")
            {
                ext = "ZPP File";
            }
            else if (ext == ".BLD" || ext == ".sld")
            {
                ext = "BLD File";
            }
            else if (ext == ".zip" || ext == ".ZIP")
            {
                ext = "ZIP File";
            }
            else if (ext == ".cmp" || ext == ".CMP")
            {
                ext = "CMP File";
            }
         
            else if (ext == ".zrt" || ext == ".ZRT")
            {
                ext = "ZRT File";
            }

            else if (ext == ".rdl" || ext == ".RDL")
            {
                ext = "RDL File";
            }

            else if (ext == ".data")
            {
                ext = "DATA File";
            }

         
            else if (ext == ".DBI" || ext == ".dbi")
            {
                ext = "DBI File";
            }
            else if (ext == "")
            {
                ext = "File";
            }
            else if (ext == ".rpt" || ext == ".RPT")
            {
                ext = "RPT File";
            }
            else if (ext == ".rsv" || ext == ".RSV")
            {
                ext = "RSV File";
            }
            else if (ext == ".pfe" || ext == ".PFE")
            {
                ext = "PFE File";

            }
            else if (ext == ".sec" || ext == ".SEC")
            {
                ext = "SEC File";
            }
            else if (ext == ".als" || ext == ".ALS")
            {
                ext = "SEC File";
            }
            else if (ext == ".act" || ext == ".ACT")
            {
                ext = "ACT File";
            }
            else if (ext == ".mdb" || ext == ".MDB")
            {
                ext = "Microsoft Access Database";
            }
            else if (ext == ".csv" || ext == ".CSV")
            {
                ext = "Microsoft Excel";
            }
            else if (ext == ".vba" || ext == ".VBA")
            {
                ext = "VBA File";
            }
            else if (ext == ".ARS" || ext == ".ars")
            {
                ext = "ARS File";
            }
            else if (ext == ".AML" || ext == ".aml")
            {
                ext = "AML File";
            }
            else if (ext == ".rsv" || ext == ".RVS")
            {
                ext = "RVS File";
            }
            else if (ext == ".ARX" || ext == ".arx")
            {
                ext = "ARX File";
            }
            else if (ext == ".ARS" || ext == ".ars")
            {
                ext = "ARS File";
            }
            else if (ext == ".BIN" || ext == ".bin")
            {
                ext = "BIN File";
            }
            else if (ext == ".REE" || ext == ".ree")
            {
                ext = "REE File";
            }
            else if (ext == ".idx" || ext == ".IDX")
            {
                ext = "SQL Server Replication Snapshot Index Script";
            }
            else if (ext == ".CEL" || ext == ".CEL")
            {
                ext = "CEL File";
            }

            else if (ext == ".tmp" || ext == ".TMP")
            {
                ext = "TEP File";
            }
            else if (ext == ".ARI" || ext == ".ari")
            {
                ext = "ARI File";
            }
            else if (ext == ".ldf" || ext == ".LDF")
            {
                ext = "SQL Server Database Transaction Log File";
            }

            else if (ext == ".mdf" || ext == ".MDF")
            {
                ext = "SQL Server Database Primary Data File";
            }
            else if (ext == ".bak" || ext == ".BAK")
            {
                ext = "BAK File";
            }
            else if (ext == ".mdb" || ext == ".MDB")
            {
                ext = "Microsoft Access Database";
            }

            else if (ext == ".LDB")
            {

                ext = "Microsoft Access Record - Locking Information";
            }
            else if (ext == ".xlsx" || ext == ".xltx" || ext == ".xlt")
            {

                ext = "Microsoft Excel Worksheet";
            }

            string qry = "insert into eMAAS_Tbl_DirFileInfo (FileNames,Ext) values('" + name.Replace("'", "`").Trim() + "','" + ext.Trim() + "')";
            SqlCommand SqlCom = new SqlCommand(qry, CN);
            CN.Open();
            SqlCom.ExecuteNonQuery();
            CN.Close();
        }
        Label2.Text = "Successfully..";
        TextBox1.Text = "";
        Label2.Visible = true;
    }



    protected void Button3_Click(object sender, EventArgs e)
    {
        string qry = "truncate table eMAAS_Tbl_DirFileInfo";
        SqlCommand SqlCom = new SqlCommand(qry, CN);
        CN.Open();
        SqlCom.ExecuteNonQuery();
        CN.Close();
    }

}
Share:

Sunday, 16 December 2018

Drag n drop multiple file uploads with process bar using JavaScript. Example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
namespace WebApplication4.Controllers
{
    public class DemoController : Controller
    {
        // GET: Demo
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult JqAJAX(List<string> list)
        {
            try
            {

                return Json(1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    public class Student
    {
        public string data { get; set; }
    }
}
--------------------

@{
    ViewBag.Title = "Index";
}

<!DOCTYPE html>
<html>
<head>
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <style>
        #dragandrophandler {
            border: 2px dotted #0B85A1;
            width: 400px;
            color: #92AAB0;
            text-align: left;
            vertical-align: middle;
            padding: 10px 10px 10 10px;
            margin-bottom: 10px;
            font-size: 200%;
        }
    </style>
    <style>
        #selectedFiles img {
            max-width: 200px;
            max-height: 200px;
            float: left;
            margin-bottom: 10px;
        }

        .thumbnail {
            width: 18px;
            height: 18px;
        }
    </style>
</head>
<body>
    <form id="myForm" method="post">
        <br />
        <br />
        <div id="dragandrophandler">Drag & Drop Files Here</div>
        Category : <input id="Text1" type="text" />
        Files: <input type="file" id="files" name="files" multiple><br />
        <div id="selectedFiles"></div>
        <input type="submit">
        <div class="row">
            <div class="col-sm-12">
                <div class="progress progress-striped active">
                    <div class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%;transition:none;">
                    </div>
                </div>
            </div>
        </div>
    </form>

    <script>
        var selDiv = "";
        var storedFiles = [];
        function handleFileSelect(e) {
            debugger
            var files = e.target.files;
            var filesArr = Array.prototype.slice.call(files);
            filesArr.forEach(function (f) {
                storedFiles.push(f.name);
                var reader = new FileReader();
                reader.onload = function (e) {
                    debugger
                    var html = "<div><img  src=\"" + '/Uploads/k.jpg' + "\" data-file='" + f.name + "' class='selFile thumbnail' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
                    selDiv.append(html);
                }
                reader.readAsDataURL(f);
            });

        }
        function handleFileSelect1(files) {
            debugger
            var filesArr = Array.prototype.slice.call(files);
            filesArr.forEach(function (f) {
                storedFiles.push(f.name);
                var reader = new FileReader();
                reader.onload = function (e) {
                    debugger
                    var html = "<div><img  src=\"" + '/Uploads/k.jpg' + "\" data-file='" + f.name + "' class='selFile thumbnail' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
                    selDiv.append(html);
                }
                reader.readAsDataURL(f);
            });

        }
        $(document).ready(function () {
            $("#files").on("change", handleFileSelect);
            selDiv = $("#selectedFiles");
            $("#myForm").on("submit", handleForm);
            $("body").on("click", ".selFile", removeFile);
            debugger
            var obj = $("#dragandrophandler");
            obj.on('dragenter', function (e) {
                e.stopPropagation();
                e.preventDefault();
                $(this).css('border', '2px solid #0B85A1');
            });
            obj.on('dragover', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });
            obj.on('drop', function (e) {
                debugger
                $(this).css('border', '2px dotted #0B85A1');
                e.preventDefault();
                var files = e.originalEvent.dataTransfer.files;
                handleFileSelect1(files);
            });
            $(document).on('dragenter', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });
            $(document).on('dragover', function (e) {
                e.stopPropagation();
                e.preventDefault();
                obj.css('border', '2px dotted #0B85A1');
            });
            $(document).on('drop', function (e) {
                e.stopPropagation();
                e.preventDefault();
            });

        });

        function handleForm(e) {

            var items = new Array();
            e.preventDefault();
            debugger
            var data = new FormData();
            for (var i = 0, len = storedFiles.length; i < len; i++) {
                data.append('files', storedFiles[i]);
                items.push(storedFiles[i]);
            }
            var name = $("#Text1").val();
            debugger
            var Student = items;
            $.ajax({
                type: "POST",
                url: "/Demo/JqAJAX",
                data: JSON.stringify(Student),
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    debugger
                    var value = result;
                    debugger
                },
                error: function () {
                    alert("Error occured!!")
                }
            });
        }

        function removeFile(e) {
            var file = $(this).data("file");
            for (var i = 0; i < storedFiles.length; i++) {
                if (storedFiles[i].name === file) {
                    storedFiles.splice(i, 1);
                    break;
                }
            }
            $(this).parent().remove();
        }
    </script>

</body>
</html>

Sunday, 15 July 2018

How to bind data table through html using jQuery?

@{
    Layout = null;
}
<H1>Employee Details</H1>

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">

<div class="container">
    <table id="tblGrid" class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Salary</th>
                <th>Action</th>
            </tr>
        </thead>
    </table>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            url: 'http://localhost:50148/api/EmpAPI/EmployeeDetails',
            type: "GET",
            dataType: "json",
            success: function (result) {
                debugger;
             
                var htmlContent = "";
                $.each(result, function (key, item) {
                    var itemDetails = [
                                 { "ItemName": item.ID }
                    ];
                    htmlContent = htmlContent + "<tr><td>" + item.ID + "</td>" + "<td>" + item.Name + "</td>" + "<td>" + item.Salary + "</td>" + "<td>" +
                    '<a href="http://localhost:50148/api/EmpAPI/EmployeeDetails?ID=' + item.ID + '">Edit</a>' + ' ' +
                    '<a href="http://localhost:50148/api/EmpAPI/DeleteEmployee?ID=' + item.ID + '">Delete</a>' + "</td></tr>";
                });
                $("#tblGrid").append(htmlContent);

                $('#tblGrid').DataTable({
                    "pagingType": "full_numbers",
                    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
                    //"paging": false,
                    //"ordering": false,
                    //"info": false,
                    //"searching": false
                });

            },
            error: function (err) {
                alert(err.statusText);
            }
        });
    });
</script>

Monday, 21 May 2018

What is the differences among ArrayList, HashTable, List and Dictionoiry in C#? Example.

class Program
    {
        static void Main(string[] args)
        {
            List<int> li = new List<int>();
            li.Add(1);
            li.Add(2);
            li.Add(3);
            foreach (int i in li)
            {
                Console.WriteLine(i);
            }
            Dictionary<int,string> di = new Dictionary<int,string>();
            di.Add(1,"kul");
            di.Add(2, "raj");
            di.Add(3, "neha");

            foreach(KeyValuePair<int,string> ob in di)
            {
                Console.WriteLine(ob.Key +" "+ob.Value);
            }
            HashSet<int> ht = new HashSet<int>();
            ht.Add(1);
            ht.Add(2);
            ht.Add(3);
            foreach (int i in ht)
            {
                Console.WriteLine(i);
            }

            ArrayList obj = new ArrayList();
            obj.Add(1);
            obj.Add("kul");
            obj.Add("noida");
            foreach (object i in obj)
            {
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }

What is difference between List and Dictionory in C# with example?

class Program
    {
        static void Main(string[] args)
        {
            List<int> li = new List<int>();
            li.Add(1);
            li.Add(2);
            li.Add(3);
            foreach (int i in li)
            {
                Console.WriteLine(i);
            }
            Dictionary<int,string> di = new Dictionary<int,string>();
            di.Add(1,"kul");
            di.Add(2, "raj");
            di.Add(3, "neha");

            foreach(KeyValuePair<int,string> ob in di)
            {
                Console.WriteLine(ob.Key +" "+ob.Value);
            }
            Console.ReadLine();
        }

How to count character in your name using C#?

class Program
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string s = "kulshresth";
            var occurances = new Dictionary<char, int>();
            foreach (char c in s)
            {
                if (occurances.ContainsKey(c))
                    occurances[c] = occurances[c] + 1;
                else
                    occurances[c] = 1;
            }
            foreach (var entry in occurances)
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
            Console.ReadLine();
        }
    }

Monday, 8 January 2018

How to create Windows Services in C#? Example.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace ScheduledService
{
    public partial class ScheduledService : ServiceBase
    {
        Timer timer = new Timer();
        public ScheduledService()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            TraceService("start service");
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            timer.Interval = 1000;
            timer.Enabled = true;
        }
        protected override void OnStop()
        {
            timer.Enabled = false;
            TraceService("stopping service");
        }
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            TraceService("Another entry at " + DateTime.Now);
        }
        private void TraceService(string content)
        {
            FileStream fs = new FileStream(@"d:\ScheduledService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(content);
            sw.Flush();
            sw.Close();
        }
    }
}

How to check excel Date Format using C#? Example.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <style type="text/css">
        .auto-style1 {
            width: 50%;
        }
    </style>

</head>
<body>
    <form id="form1" runat="server">
 

    <table align="center" class="auto-style1">
        <tr>
            <td>
                <asp:FileUpload ID="FileUpload1" runat="server" Width="200px" />&nbsp;&nbsp;<asp:Button ID="Button1" runat="server" Style="margin-left: 0px" Text="Upload" OnClick="Button1_Click" /></td>
         
        </tr>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="ID" HeaderText="ID" HtmlEncode="False" ReadOnly="True" />
                        <asp:BoundField DataField="NAME" HeaderText="NAME" HtmlEncode="False" ReadOnly="True" />
                        <asp:BoundField DataField="JOINDATE" HeaderText="JOINDATE" HtmlEncode="False" DataFormatString="{0:d}" ReadOnly="True" />
                    </Columns>


                </asp:GridView>
            </td>

        </tr>
    </table>
      </form>
</body>
</html>
-----------------------------------------------
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel = Microsoft.Office.Interop.Excel.Application;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // processExcel("D:\\Book1.xlsx");
    }
    private void processExcel(string filename)
    {
        Application xlApp;
        Workbook xlWorkBook;
        Worksheet xlWorkSheet;

        var missing = System.Reflection.Missing.Value;

        xlApp = new ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open(filename);
        //xlWorkBook = xlApp.Workbooks.Open(filename, false, true, missing, missing, missing, true, XlPlatform.xlWindows, '\t', false, false, 0, false, true, 0);
        xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);

        Range xlRange = xlWorkSheet.UsedRange;
        Array myValues = (Array)xlRange.Cells.Value2;



        int vertical = myValues.GetLength(0);
        int horizontal = myValues.GetLength(1);

        System.Data.DataTable dt = new System.Data.DataTable();
        DateTime tempD = new DateTime();
        //if (DateTime.TryParse(myValues.GetValue(3, 3).ToString(), out tempD))
        //{

        //}
        // must start with index = 1
        // get header information
        for (int i = 1; i <= horizontal; i++)
        {
            dt.Columns.Add(new DataColumn(myValues.GetValue(1, i).ToString()));
        }

        // Get the row information
        for (int a = 2; a <= vertical; a++)
        {


            object[] poop = new object[horizontal];
            for (int b = 1; b <= horizontal; b++)
            {
                try
                {
                    poop[b - 1] = myValues.GetValue(a, b);
                    if (poop[2] != null)
                    {

                        double d = double.Parse(myValues.GetValue(a, b).ToString());
                        // DateTime conv = DateTime.FromOADate(d);
                        DateTime conv = DateTime.FromOADate(d);
                        //string date = conv.Date.ToString();
                        //string date = conv.ToShortDateString();
                        // poop[b - 1] = date;
                        poop[b - 1] = conv;
                    }
                    else
                    {
                        poop[b - 1] = myValues.GetValue(a, b);
                    }
                }
                catch (Exception ex)
                {
                    poop[b - 1] = "DateTime is not currect format !";
                }

            }
            DataRow row = dt.NewRow();
            row.ItemArray = poop;
            dt.Rows.Add(row);
        }
        //
        //foreach (DataRow dr in dt.Rows)
        //{
        //    double d = double.Parse(dr["JoinDate"].ToString());
        //    DateTime conv = DateTime.FromOADate(d);
        //    string date = conv.Date.ToString();


        //}

        // assign table to default data grid view

        GridView1.DataSource = dt;
        GridView1.DataBind();
        xlWorkBook.Close(true, missing, missing);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            Response.Write("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string FilePath = FileUpload1.PostedFile.FileName;
        //string path = @"D:\Book1.xlsx";
        // string path = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);

        processExcel(FilePath);
    }
}

How to read files data and save in directory using C#? Example.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    SqlConnection CN = new SqlConnection(@"SERVER=172.29.57.158\sql2012;Database=eMAAS;User ID=sa;Password=Mind1234");
    protected void Page_Load(object sender, EventArgs e)
    {
        Label2.Visible = false;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string ext;
        string[] allfiles = System.IO.Directory.GetFiles(TextBox1.Text, "*.*", System.IO.SearchOption.AllDirectories);
        foreach (var file in allfiles)
        {
            FileInfo info = new FileInfo(file);
           

            string name = info.Name.ToString();
            ext =info.Extension.ToString();
           
            if (ext == ".ldb" || ext == ".LDB")
            {
                ext = "Microsoft Access Record - Locking Information";
            }
            else if (ext == ".dbf" || ext == ".DBF")
            {
                ext = "DBF File";
            }
            else if (ext == ".xml" || ext == ".XML")
            {
                ext = "XML Document";
            }
            else if (ext == ".csv" || ext == ".CSV")
            {
                ext = "Microsoft Excel Comma Separated Values File";
            }
           
            else if (ext == ".CTL" || ext == ".ctl")
            {
                ext = "CTL File";
            }
            else if (ext == ".eds" || ext == ".EDS")
            {
                ext = "EDS File";
            }
            else if (ext == ".dts" || ext == ".DTS")
            {
                ext = "DTS File";
            }
            else if (ext == ".gfx" || ext == ".GFX")
            {
                ext = "GFX File";
            }
            else if (ext == ".pdf" || ext == ".PDF")
            {
                ext = "PDF File";
            }
            else if (ext == ".lnk" || ext == ".LNK")
            {
                ext = "LNK File";
            }
            else if (ext == ".txt" || ext == ".TXT")
            {
                ext = "TEXT File";
            }
            else if (ext == ".exe" || ext == ".EXE")
            {
                ext = "EXE File";
            }
            else if (ext == ".log" || ext == ".LOG")
            {
                ext = "LOG File";
            }
            else if (ext == ".dll" || ext == ".DLL")
            {
                ext = "DLL File";
            }
            else if (ext == ".gpd" || ext == ".GDP")
            {
                ext = "GPD File";
            }
            else if (ext == ".ppd" || ext == ".PPD")
            {
                ext = "PPD File";
            }
            else if (ext == ".prt" || ext == ".RPT")
            {
                ext = "PRT File";
            }
            else if (ext == ".dat" || ext == ".DAT")
            {
                ext = "DAT File";
            }
            else if (ext == ".ini" || ext == ".INI")
            {
                ext = "INI File";
            }

            else if (ext == ".tab" || ext == ".TAB")
            {
                ext = "TAB File";
            }

            else if (ext == ".rtp" || ext == ".RPT")
            {
                ext = "RPT File";
            }
            else if (ext == ".ZPP" || ext == ".zpp")
            {
                ext = "ZPP File";
            }
            else if (ext == ".BLD" || ext == ".sld")
            {
                ext = "BLD File";
            }
            else if (ext == ".zip" || ext == ".ZIP")
            {
                ext = "ZIP File";
            }
            else if (ext == ".cmp" || ext == ".CMP")
            {
                ext = "CMP File";
            }
         
            else if (ext == ".zrt" || ext == ".ZRT")
            {
                ext = "ZRT File";
            }

            else if (ext == ".rdl" || ext == ".RDL")
            {
                ext = "RDL File";
            }

            else if (ext == ".data")
            {
                ext = "DATA File";
            }

         
            else if (ext == ".DBI" || ext == ".dbi")
            {
                ext = "DBI File";
            }
            else if (ext == "")
            {
                ext = "File";
            }
            else if (ext == ".rpt" || ext == ".RPT")
            {
                ext = "RPT File";
            }
            else if (ext == ".rsv" || ext == ".RSV")
            {
                ext = "RSV File";
            }
            else if (ext == ".pfe" || ext == ".PFE")
            {
                ext = "PFE File";

            }
            else if (ext == ".sec" || ext == ".SEC")
            {
                ext = "SEC File";
            }
            else if (ext == ".als" || ext == ".ALS")
            {
                ext = "SEC File";
            }
            else if (ext == ".act" || ext == ".ACT")
            {
                ext = "ACT File";
            }
            else if (ext == ".mdb" || ext == ".MDB")
            {
                ext = "Microsoft Access Database";
            }
            else if (ext == ".csv" || ext == ".CSV")
            {
                ext = "Microsoft Excel";
            }
            else if (ext == ".vba" || ext == ".VBA")
            {
                ext = "VBA File";
            }
            else if (ext == ".ARS" || ext == ".ars")
            {
                ext = "ARS File";
            }
            else if (ext == ".AML" || ext == ".aml")
            {
                ext = "AML File";
            }
            else if (ext == ".rsv" || ext == ".RVS")
            {
                ext = "RVS File";
            }
            else if (ext == ".ARX" || ext == ".arx")
            {
                ext = "ARX File";
            }
            else if (ext == ".ARS" || ext == ".ars")
            {
                ext = "ARS File";
            }
            else if (ext == ".BIN" || ext == ".bin")
            {
                ext = "BIN File";
            }
            else if (ext == ".REE" || ext == ".ree")
            {
                ext = "REE File";
            }
            else if (ext == ".idx" || ext == ".IDX")
            {
                ext = "SQL Server Replication Snapshot Index Script";
            }
            else if (ext == ".CEL" || ext == ".CEL")
            {
                ext = "CEL File";
            }

            else if (ext == ".tmp" || ext == ".TMP")
            {
                ext = "TEP File";
            }
            else if (ext == ".ARI" || ext == ".ari")
            {
                ext = "ARI File";
            }
            else if (ext == ".ldf" || ext == ".LDF")
            {
                ext = "SQL Server Database Transaction Log File";
            }

            else if (ext == ".mdf" || ext == ".MDF")
            {
                ext = "SQL Server Database Primary Data File";
            }
            else if (ext == ".bak" || ext == ".BAK")
            {
                ext = "BAK File";
            }
            else if (ext == ".mdb" || ext == ".MDB")
            {
                ext = "Microsoft Access Database";
            }

            else if (ext == ".LDB")
            {

                ext = "Microsoft Access Record - Locking Information";
            }
            else if (ext == ".xlsx" || ext == ".xltx" || ext == ".xlt")
            {

                ext = "Microsoft Excel Worksheet";
            }

            string qry = "insert into eMAAS_Tbl_DirFileInfo (FileNames,Ext) values('" + name.Replace("'", "`").Trim() + "','" + ext.Trim() + "')";
            SqlCommand SqlCom = new SqlCommand(qry, CN);
            CN.Open();
            SqlCom.ExecuteNonQuery();
            CN.Close();
        }
        Label2.Text = "Successfully..";
        TextBox1.Text = "";
        Label2.Visible = true;
    }



    protected void Button3_Click(object sender, EventArgs e)
    {
        string qry = "truncate table eMAAS_Tbl_DirFileInfo";
        SqlCommand SqlCom = new SqlCommand(qry, CN);
        CN.Open();
        SqlCom.ExecuteNonQuery();
        CN.Close();
    }

}

Popular

Total Pageviews

Archive