Total Pageviews

Tuesday 6 October 2015

Dropzone with multiple files in asp.net(upload)

Scripts
--------

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <link rel="stylesheet" href="http://localhost:1202/code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />

    
    <script src="Jquery/bootstrap.min.js"></script>
    <link href="Jquery/bootstrap.min.css" rel="stylesheet" />



    <script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
    <link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css" />


  <script>
        Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element

            autoDiscover: false,
            addRemoveLinks: true,

            // The configuration we've talked about above
            autoProcessQueue: false,
            uploadMultiple: true,
            parallelUploads: 20,
            url: "fileupload.ashx",
            addRemoveLinks: true,
            maxFiles: 5,
            maxFilesize: 5,
            dictDefaultMessage: "Drag or click to add photos",

            // The setting up of the dropzone
            init: function () {
                var myDropzone = this;

                // First change the button to actually tell Dropzone to process the queue.
                this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
                    // Make sure that the form isn't actually being sent.
                    e.preventDefault();
                    e.stopPropagation();
                    myDropzone.processQueue();
                });

                // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
                // of the sending event because uploadMultiple is set to true.
                this.on("sendingmultiple", function (file, xhr, formData) {
                    // Gets triggered when the form is actually being sent.
                    // Hide the success button or the complete form.



                    formData.append('title', $("input[name=title]").val());

       

                });
                this.on("successmultiple", function (files, response) {
                    alert(response);
                });
                this.on("errormultiple", function (files, response) {
                    // Gets triggered when there was an error sending the files.
                    // Maybe show form again, and notify user of error
                });
            }

        }
    </script>



fileupload.aspx
------------------



    <form id="my-awesome-dropzone" class="dropzone">

        <div>
            <input type="text" name="title" placeholder="Title"  />
          
            <button id="submit-all" type="submit" class="button3" style="cursor: pointer">Post</button>
        </div>


        <div>

            <div class="dropzone-previews" style="border: 1px dashed blue;"></div>

        </div>

   


    </form>



fileupload.ashx
---------------------

<%@ WebHandler Language="C#" Class="fileupload" %>

using System;
using System.Web;
using System.IO;

public class agoodthing : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");


       HttpFileCollection files = context.Request.Files;
       
        for (int i = 0; i < files.Count; i++)
        {

       
            string title = context.Request["title"];
           
           
            string photo_name = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
            HttpPostedFile file = files[i];

            //string fileExtension = file.ContentType;
            string photo_box_id = photo_name  ;

            string fname = context.Server.MapPath("~/dump/" +photo_box_id+ file.FileName);


          
            file.SaveAs(fname);
            //context.Response.Write( title );
        }

     
    }

    public bool IsReusable {
        get {
            return false;
        }
    }


}

Monday 5 October 2015

How to use dropzone and cropper in asp.net






Include scripts (inside head tag and get bootstrap links from getbootstrap.com)
--------------------
 <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <link rel="stylesheet" href="http://localhost:1202/code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />

    <script src="Jquery/bootstrap.min.js"></script>
    <link href="Jquery/bootstrap.min.css" rel="stylesheet" />



    <link href="https://cdn.rawgit.com/fengyuanchen/cropper/v0.11.1/dist/cropper.min.css" rel="stylesheet">
    <script src="https://cdn.rawgit.com/fengyuanchen/cropper/v0.11.1/dist/cropper.min.js"></script>

    <script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
    <link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css" />

//Script for dropzone
-------------------------
<script>

        $(document).ready(function () {
            Dropzone.autoDiscover = false;
            //Simple Dropzonejs
            $("#dZUpload").dropzone({
                url: "profile_pic.ashx",
                addRemoveLinks: true,
                maxFiles: 1,
                maxFilesize: 5,

                //previewsContainer: "#previews",

                dictDefaultMessage: "Drag or click to add profile image",


                success: function (file, response) {
                    var imgName = response;
                    file.previewElement.classList.add("dz-success");
                    console.log('Successfully uploaded :' + imgName);



                    var imgName = response;
                    d = new Date();
                    $("#imgcrop").attr("src", "");

                    $(".photo_to_crop1").attr("src", "dump_images/" + imgName + "?" + d.getTime());



                    $("#img_name").attr("value", imgName);



                    intialize();
                },
                error: function (file, response) {
                    file.previewElement.classList.add("dz-error");
                },

                sending: function (file, xhr, formData) {



                    formData.append('name', $("input[name=name]").val());



                },
                complete: function (response) {

                }



            });
        });
    </script>


//Script for cropper
-----------------------

    <script>



        function intialize() {

            var imageURL = $(".photo_to_crop1").attr("src");
            var imageBox = $('.photo_to_crop');


            var options = {
                aspectRatio: 1,

                movable: true,
                zoomable: true,
                responsive: true,
                center: true,
                scalable: true,
                crop: getcroparea
            };

            if (imageURL != null) {
                console.log("It's not empty, building dedault box!");
                var DefaultCropBoxOptionObj = {
                    height: 25,
                    width: 25
                };
                console.log(DefaultCropBoxOptionObj);
                imageBox.cropper(options);
                imageBox.cropper('setData', DefaultCropBoxOptionObj);
                imageBox.cropper('replace', imageURL);

            }
        }


        function getcroparea(c) {
            $('#hdnx').val(parseInt(c.x));
            $('#hdny').val(parseInt(c.y));
            $('#hdnw').val(parseInt(c.width));
            $('#hdnh').val(parseInt(c.height));
            $('#hdnr').val(parseInt(c.rotate));
            $('#hdnsx').val(parseInt(c.scaleX));
            $('#hdnsy').val(parseInt(c.scaleY));
        };




    </script>




cropper.aspx
-------------------

<form id="form1" runat="server">

        <div id="dZUpload" class="dropzone">
            <div class="dz-default dz-message">

                <p style="font-family: 'Open Sans'">Drop a photo here or click to add profile photo</p>
            </div>
        </div>
        <div>
            <input id="username" type="text" name="name" value="<% =ServerValue %>" style="display: none;" />

            <img id="img1" alt="sample image" src="" class="photo_to_crop1" style="display: none;" />
              <div style="padding-bottom: 5px; padding-top: 5px; width: 300px">

                <img id="imgcropped" runat="server" visible="false" class="img-responsive" />

                <h5>
                    <asp:Label ID="my_ad_err_lbl" runat="server" Text=""></asp:Label></h5>
            </div>
            <div class="container cropcontainer">
                <img id="imgcrop" alt="sample image" src="" class="photo_to_crop" />
                <input type="text" style="display: none" id="img_name" name="img_name" value="user.png" />
            </div>

            <input type="hidden" id="hdnx" runat="server" />
            <input type="hidden" id="hdny" runat="server" />
            <input type="hidden" id="hdnw" runat="server" />
            <input type="hidden" id="hdnh" runat="server" />
            <input type="hidden" id="hdnr" runat="server" />
            <input type="hidden" id="hdnsx" runat="server" />
            <input type="hidden" id="hdnsy" runat="server" />

            <asp:Button ID="btncrop" runat="server" OnClick="btncrop_Click" Text="Crop and Save" CssClass="button3" OnClientClick="reload()" />
            <asp:Button ID="save_original" runat="server" OnClick="btnsave_original_Click" Text="Save original" CssClass="button3" OnClientClick="reload()" Style="display: none;" />
            <asp:Button ID="pic_delete" runat="server" OnClick="btndelete_Click" Text="Delete Photo" OnClientClick="deletepic()" CssClass="button3" />

          




        </div>



    </form>


Code behind
----------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using Image = System.Drawing.Image;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;

public partial class cropper : System.Web.UI.Page
{

    string con = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
    public string ServerValue = String.Empty;
    public string photo_loc = String.Empty;
    public string db_photo_name = String.Empty;
    public string db_photo_loc = String.Empty;
    public string db_photo_ext = String.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Request.Cookies["userdata"] != null)
        {
            HttpCookie login = Request.Cookies["userdata"];
            string user = login["username"];

            ServerValue = user;

            //load_profile_pic();

        }

    }


    protected void btncrop_Click(object sender, EventArgs e)
    {
        try
        {

            //string photo_path = imgcrop.Src;

            string photo_name = Request.Form["img_name"];

            string fname = photo_name;
            string fpath = Path.Combine(Server.MapPath("~/dump_images"), fname);
            Image oimg = Image.FromFile(fpath);
            Rectangle cropcords = new Rectangle(
            Convert.ToInt32(hdnx.Value),
            Convert.ToInt32(hdny.Value),
            Convert.ToInt32(hdnw.Value),
            Convert.ToInt32(hdnh.Value)
            

            
            );
            string cfname, cfpath;
            Bitmap bitMap = new Bitmap(cropcords.Width, cropcords.Height, oimg.PixelFormat);
            Graphics grph = Graphics.FromImage(bitMap);
            grph.DrawImage(oimg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), cropcords, GraphicsUnit.Pixel);
            cfname = "crop_" + fname;
            cfpath = Path.Combine(Server.MapPath("~/profile_images"), cfname);
            bitMap.Save(cfpath);
            imgcropped.Visible = true;
            imgcropped.Src = "~/profile_images/" + cfname;
            db_photo_loc = "profile_images/" + cfname;
            db_photo_name = cfname;





            string id = db_photo_name;

            //UPDATE THE IMAGE IN DB
            try
            {


                SqlConnection conn = new SqlConnection(con);
                SqlCommand sqlcomm = new SqlCommand(" write your query for update", conn);
                conn.Open();
                sqlcomm.ExecuteNonQuery();
                conn.Close();
                my_ad_err_lbl.Text = "Profile photo cropped and saved.";


                if (my_ad_err_lbl.Text == "Done")
                {


                }

            }
            catch (Exception ex)
            {
                my_ad_err_lbl.Text = ex.Message;


            }
            finally
            {

            }



        }
        catch (Exception ex)
        {
            throw ex;
        }
    }



    protected void btndelete_Click(object sender, EventArgs e)
    {

        delete_photo();
    }


    public void delete_photo()
    {


        //DELETE THE IMAGE BEFORE UPDATE
        try
        {
            SqlConnection conn = new SqlConnection(con);
            conn.Open();
            SqlCommand cmd = new SqlCommand("  write your query to delete    '", conn);
            SqlDataReader dr = cmd.ExecuteReader();


            while (dr.Read())
            {
                string imageurl = dr["profile_img_loc"].ToString();
                string imageFilePath = HttpContext.Current.Server.MapPath("~/" + imageurl);
                System.IO.File.Delete(imageFilePath);

            }
        }
        catch (Exception ex)
        {
            my_ad_err_lbl.Text = ex.Message;
        }
        finally
        {

        }


    }

    protected void btnsave_original_Click(object sender, EventArgs e)
    {
        string id = db_photo_name;

        //UPDATE THE IMAGE IN DB
        try
        {


         

        }
        catch (Exception ex)
        {
           


        }
        finally
        {

        }

    }
}


profile_pic.ashx
---------------------
<%@ WebHandler Language="C#" Class="profile_pic" %>

using System;
using System.Web;
using System.IO;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public class profile_pic : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {


        string con = ConfigurationManager.ConnectionStrings["prayermeeting_mdf"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(con);
        context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        
        
        
        
        
        context.Response.ContentType = "text/plain";
            string dirFullPath = HttpContext.Current.Server.MapPath("~/profile_images/");
            string[] files;
            int numFiles;
            files = System.IO.Directory.GetFiles(dirFullPath);
            numFiles = files.Length;
            numFiles = numFiles + 1;
            string str_image = "";
            foreach (string s in context.Request.Files)
            {
                HttpPostedFile file = context.Request.Files[s];
              //  int fileSizeInBytes = file.ContentLength;
                
                
                string fileName = file.FileName;
                
                
                string fileExtension = file.ContentType;
                if (!string.IsNullOrEmpty(fileName))
                {

                    fileExtension = Path.GetExtension(fileName);


                    if (fileExtension == ".jpeg" || fileExtension == ".JPEG" || fileExtension == ".png" || fileExtension == ".PNG" || fileExtension == ".jpg" || fileExtension == ".JPG")
                    {
                        string user = context.Request["name"];
                        //context.Response.Write("your username: " + user + fileExtension);




                     

                        string profile_pic_id = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");

                        str_image = profile_pic_id + user + fileExtension;


                       
                        
                        string id=profile_pic_id + user;

                        string pathToSave = HttpContext.Current.Server.MapPath("~/dump_images/") + str_image;
                        

                        //context.Response.Write(str_image);

                        string loc = "dump_images/" + str_image;


                        //DELETE THE IMAGE BEFORE UPDATE
                  
                        
                        //SAVE THE IMAGE
                        file.SaveAs(pathToSave);



                        // UPDATE THE IMAGE IN DB
                   
                    
                    }
                    
                    
                    
                }
            } 
            context.Response.Write(str_image);
    }
    
    public bool IsReusable {
        get {
            return false;
        }
    }

Saturday 26 September 2015

Autocomplete for a input text box with update panel

SCRIPT
----------

 <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>


      <script>
        $(document).keypress(function (event) {
            if (event.keyCode == 13) {
                $("#<%= pm_search_btn.ClientID%>").click();
            }
        });
    </script>

   <script type="text/javascript">

       $(document).ready(function () {
           SearchText_m();
       });

       //On UpdatePanel Refresh.
       var prm = Sys.WebForms.PageRequestManager.getInstance();
       if (prm != null) {
           prm.add_endRequest(function (sender, e) {
               if (sender._postBackSettings.panelsToUpdate != null) {
                   SearchText_m();
               }
           });
       };
       function SearchText_m() {
           $(".autosuggest").autocomplete({
               source: function (request, response) {
                   $.ajax({
                       type: "POST",
                       contentType: "application/json; charset=utf-8",
                       url: "meetings.aspx/GetAutoCompleteData",
                       data: "{'search_txt':'" + document.getElementById('txtSearch').value + "'}",
                       dataType: "json",
                       success: function (data) {
                           response(data.d);
                       },
                       error: function (result) {
                           alert("Error");
                       }
                   });
               }
           });
       }

    </script>


HTML (meetings.aspx)
--------

 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

  <asp:UpdatePanel ID="UpdatePanel1"
                        UpdateMode="Conditional"
                        runat="server">
                        <ContentTemplate>

<input type="text" id="txtSearch" placeholder="Search..." class="autosuggest" name="pm_search_txt" />

 <span style="display:none">

 <asp:Button ID="pm_search_btn" runat="server" Text="Button" OnClick="pm_search_btn_Click" />
       </span>

         </ContentTemplate>
                    </asp:UpdatePanel>



Code Behind
---------------

using System.Web.Services;  


 [WebMethod]

    public static List<string> GetAutoCompleteData(string search_txt)
    {
        List<string> result = new List<string>();
        string conn = ConfigurationManager.ConnectionStrings["meeting_mdf"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conn))
        {
            using (SqlCommand cmd = new SqlCommand(" select top 10 ministry from (select DISTINCT  ministry from customer_ad )  as tb1 where  ministry  LIKE '%'+@SearchText+'%'", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", search_txt);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["ministry "].ToString());
                }
                return result;
            }
        }
    }


Now you can get data
 protected void pm_search_btn_Click(object sender, EventArgs e)
{

}


Friday 25 September 2015

How to save a video in folder after upload in asp.net

In aspx file
---------------

using System;
using System.Web;
using System.IO;


file.SaveAs(Server.MapPath("~/videos/") + file.FileName);
Stream streamfile = file.InputStream;


OR

In ashx file
---------------

using System;
using System.Web;
using System.IO;


  HttpPostedFile file = null;

        if (context.Request.Files.Count > 0)
        {
            file = context.Request.Files[0];
            file.SaveAs(HttpContext.Current.Server.MapPath("~/videos/") + file.FileName);
            Stream streamfile = file.InputStream;
        }

Dynamic video gallery +flowplayer + Bootstrap modal + Asp.net

We will display a dynamic video gallery from database to datalist and on clicking a video, a bootstrap modal (pop up window) will display the video, also we will add a jquery to stop video on close.


SCRIPT (Jquery+Flowplayer+Bootstrap)
--------
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

      <script src="//releases.flowplayer.org/6.0.3/flowplayer.min.js"></script>
    <link rel="stylesheet" href="//releases.flowplayer.org/6.0.3/skin/minimalist.css">



 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>



  //Stop video
   <script>
 
        $('body').on('hidden.bs.modal', '.modal', function () {
            $('video').trigger('pause');
       
        });
    </script>


(also u can try to stop video option 2:  

  <script>

        $('body').on('hidden.bs.modal', '.modal', function () {
           jQuery('.modalid video').attr("src", jQuery(".modalid video").attr("src"));
     
        });
    </script>

)

HTML (Datalist with flowplayer and bootstrap modal)
---------
<asp:DataList ID="test_datalist" runat="server" RepeatDirection="Horizontal" RepeatColumns="4" CellPadding="10" RepeatLayout="Table" HeaderStyle-VerticalAlign="Top">
                            <ItemStyle Height="100%" HorizontalAlign="Center" />
                            <ItemTemplate>
                           <div class="test_first_div" style="padding-left: 2px;">
                         <div class="videobox" style="margin: 0 auto; width: 99%;">
                       <div style="float: left;width:100%;">
                       <div style="text-align: center; width: 100%; height: 40px; padding-top: 5px;">
                                                <span></span>
 <asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("Name") %>' CssClass="linkbtn2"></asp:LinkButton>

                          </div>

                           

                                           
                                        
      <a class="btn btn-info btn-lg" data-toggle="modal" data-target='<%# "#" + Eval("id") %>' >
        <img src="Images/Testimonies_poster.png"   style="width:100%"/>
    </a>

                                            <!-- Modal -->

  <div id='<%# Eval("id") %>' class="modal fade modalid" role="dialog">
                                                <div class="modal-dialog">

                                                    <!-- Modal content-->
                                             <div class="modal-content">
                                      <div class="modal-header">
                                   <button type="button" class="close" data-dismiss="modal">&times;</button>
                                                            <h4 class="modal-title">Modal Header</h4>
                                                        </div>
                                                        <div class="modal-body" style="height:400px;">
                                                            <div class="videoplayer" style="">
 <div class="flowplayer" data-ratio="0.4167" data-poster="Images/Testimonies_poster.png">
                         <video poster=" width="300" height="400">

                                                      <source src='<%# Eval("location") %>' type='video/mp4' />
                                                       <source src='<%# Eval("location") %>' type='video/webm' />
                                                        <source src='<%# Eval("location") %>' type='video/ogg' />
                                                          <source src='<%# Eval("location") %>' type='video/flv' />
                                                                    </video>
                                                                </div>
                                                            </div>
                                                        </div>
                                                       
                                                    </div>

                                                </div>
                                            </div>
                                           
          

                                            <div style="text-align: left; width: 100%; height: 40px;">
                                                <span>Category :</span>
            <asp:Label ID="LinkButton3" runat="server" Text='<%# Eval("category") %>'></asp:Label>
                                                <br />
                                                <span>Posted on :</span>
  <asp:Label ID="LinkButton2" runat="server" Text='<%# Eval("Posted_date") %>'></asp:Label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </ItemTemplate>

                        </asp:DataList>




You can now code behind to get data 

like Id,Name,videolocation,posted date etc .. and bind to datalist.

 test_datalist.DataSource = idr;

 test_datalist.DataBind();

Friday 11 September 2015

Call a javascript after update panel in asp.net

  <script>
        ///<summary>
        ///  This will fire on initial page load,
        ///  and all subsequent partial page updates made
        ///  by any update panel on the page
        ///</summary>
        function pageLoad() {


            $(document).ready(function () {
                $(function myFunction() {



                    //then load the JavaScript file
                    $.getScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
                    $.getScript('http://lab.iamrohit.in/js/location.js');


                });
            });


        }
</script>

Thursday 30 July 2015

Http 500 error on file upload

Problem- On local machine file upload works but on server it is giving me http 500 error.

Solution:- Check folder permissions and make it write ,read,delete for anonymous users on hosting server.

Also in coding use input stream after upload.

using System.IO;

   file = context.Request.Files[0];
                string filename = file.FileName;


                //Upload video code
                string a = filename.Trim();
          

  file.SaveAs(HttpContext.Current.Server.MapPath("~/videos/") + a);
                Stream streamfile = file.InputStream;

Saturday 25 July 2015

Grab a image from a video with ffmpeg

Download ffmpeg.exe and paste it in ffmpeg folder

And

Write the code in

Codebehind
-----------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;

public partial class Videoframe : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

       //Put the ffmpeg.exe into the source folder.

//Write the following code to grab thumbnail from the wmv video file into jpg file.

//Path for Video file

        string InputFile = Server.MapPath ("~\\videos\\TestimonyDeafMinistry.mp4");

//Path for Image (jpg) file

        string ThumbnailsPath = Server.MapPath("~\\videos\\testimage.jpg");

System.Diagnostics.Process proc = new System.Diagnostics.Process();

proc.EnableRaisingEvents = false;

//Select ffmpeg.exe

proc.StartInfo.FileName = Page.MapPath("~\\ffmpeg\\ffmpeg.exe");

//Pass the argument

// You can see the text in Red color below:

// First one is the frame and second is the size of the image

proc.StartInfo.Arguments = " -i \"" + InputFile + "\"  -an -ss 00:00:03 -s 400*300  -vframes 1 -f image2 -vcodec mjpeg \"" + ThumbnailsPath + "\"";

//Start the Process

proc.Start();

    }
}

Tuesday 21 July 2015

Simple and easy file upload with jquery in asp.net forms(with progress bar)

 normal_fileupload.aspx
------------------------------------------
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <style>
        body {
            padding: 30px;
        }

        form {
            display: block;
            margin: 20px auto;
            background: #eee;
            border-radius: 10px;
            padding: 15px;
        }

        .progress {
            position: relative;
            width: 400px;
            border: 1px solid #ddd;
            padding: 1px;
            border-radius: 3px;
        }

        .bar {
            background-color: #3599fa;
            width: 0%;
            height: 20px;
            border-radius: 3px;
        }

        .percent {
            position: absolute;
            display: inline-block;
            top: 0px;
            left: 48%;
            ;
            font-family: 'Open Sans';
        }
    </style>




<body>

    <form id="Form1" action="Upload.ashx" method="post" enctype="multipart/form-data" runat="server">
        <input id="test_title" type="text" placeholder="Title" />
          <select id="category" class="droplist_style4">
            <option id="C" value="C">-Select-</option>
            <option id="M" value="Ministry Testimony">Ministry Testimony</option>
            <option id="P" value="Personal Testimony">Personal Testimony</option>
            <option id="F" value="Family Testimony">Family Testimony</option>
            <option id="O" value="Others Testimony">Others Testimony</option>
            <option id="W" value="Worship video Song">Worship video Song</option>
            <option id="ME" value="Church Message">Church Message</option>
        </select>

        <input type="file" name="myfile[]" multiple=""><br>
        <input type="submit" value="Upload File to Server">
        <asp:Label ID="user_lbl" runat="server" Text="akash"></asp:Label>
     

    </form>
    <div class="progress">
        <div class="bar" style="width: 100%;"></div>
        <div class="percent">0%</div>
    </div>

    <div id="status"></div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
    <script>
        function validate(formData, jqForm, options) {
       
            if ($("#test_title").val() == "") {
                alert('Please enter a value for title');
                return false;
            }
            if ($("#category").val() == "C") {
                alert('Please select Category');
                return false;
            }

            for (var i = 0; i < formData.length; i++) {
                if (!formData[i].value) {
                    alert('Please select file');
                    return false;

                }
                else {

                }
            }
            //alert('Both fields contain values.');
        }




        (function () {

            var bar = $('.bar');
            var percent = $('.percent');
            var status = $('#status');
            $('.bar').width(0);



            $('form').ajaxForm({
                requiredFields: ["title_text"],
                beforeSubmit: validate,
                contentType: "application/json; charset=utf-8",
                data: { 'Id': '10000', 'title': $("#title_text").val() },

                dataType: "json",
                beforeSend: function (data) {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);

                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                    //console.log(percentVal, position, total);
                },
                success: function (data) {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                    $("#status").html(data);
                    alert(data);
                },
                complete: function (xhr) {
                    status.html(xhr.responseText);
                },
                beforeSerialize: function (form, options) {
                    options.data = {
                        user: $("#<%=user_lbl.ClientID%>").text(),
                    video_name: $("#test_title").val(),
                    category: $("#category").val(),
                    B: true
                };
            }
        });

    })();


    </script>
</body>

Upload.ashx
----------------
<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.IO;

public class Upload2 : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
     



        HttpPostedFile file = null;

        if (context.Request.Files.Count > 0)
        {
            file = context.Request.Files[0];
            file.SaveAs(HttpContext.Current.Server.MapPath("~/videos/") + file.FileName);
            Stream streamfile = file.InputStream;

            string id = context.Request["Id"];
            string user = context.Request["user"];
         
            string video_name = context.Request["video_name"];
            string category = context.Request["category"];
            //string id = "akash";

            string extension;
            string filename = file.FileName;
            extension = Path.GetExtension(filename);


            context.Response.Write( " File name : " + filename + "</br>" + " Category : " + category + "</br>" + " video name:" + video_name + "</br>" + " user:" + user);
        }
           
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

web.config
--------------

 <system.web>

    <httpRuntime maxRequestLength="1048576" executionTimeout="99999" />
    <compilation targetFramework="4.0" defaultLanguage="c#" />
    <customErrors mode="Off" />
    <sessionState timeout="120" />

  </system.web>

<location path="Upload.ashx" >
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
   
    </system.web>
  </location>
 <appSettings>
    <add key="FolderPath" value="videos" />
  </appSettings>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
    <validation validateIntegratedModeConfiguration="false" />
 
  </system.webServer>

Tuesday 14 July 2015

How to upload video or images with progress bar in asp.net (Using Uploadify)


Dowload uploadify

http://www.uploadify.com/download/

SCRIPT
------------

   <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <link href="css/uploadify.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
    <script src="js/jquery.uploadify-3.1.js" type="text/javascript"></script>


Get input and dropdownlist values, before that validate the controls and check file types

Validation and click action to upload
-------------------------------------------------------

<script type="text/javascript">
        $(document).ready(

          function () {
              $("#test_upload_btn").click(function () {


                  if ($("#test_title").val() != "" && $("#category").val() != "C") {




                      $(function () {

                          $("#test_file_upload").uploadify('upload');

                      });
                  }

                  if ($("#test_title").val() == "") {


                      $("#test_title").css('border', '1px solid red');

                  }
                  else {
                      $("#test_title").css('border', '1px solid blue');
                  }
                  if ($("#category").val() == "C") {


                      $("#category").css('border', '1px solid red');

                  }
                  else {
                      $("#category").css('border', '1px solid blue');
                  }



              });

          });



        $(document).ready(

                function () {

                    $(".test_file_upload").uploadify(
         {
             'swf': 'js/uploadify.swf',
             'uploader': 'Upload.ashx',
             'cancelImg': 'js/uploadify-cancel.png',

             'auto': false,
             'multi': false,
             'buttonText': 'Select File',
             'fileDesc': 'Image Files',
             'fileExt': '*.jpg;*.png;*.gif;*.bmp;*.jpeg',
             'queueSizeLimit': 10,
             'sizeLimit': 4000000,
             'folder': 'videos',
             'method': 'post',
             'onUploadStart': function (file) {

                 var user = $("#<%=user_lbl.ClientID%>").text();
                 var video_name = $("#test_title").val();
                 var category = $("#category").val();


                 var formData = { 'user_name': user, 'video_name': video_name, 'category': category }

                 $("#test_file_upload").uploadify("settings", "formData", formData);
             },
             'onUploadSuccess': function (file, data, response) {
                 alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
             },
             'onUploadComplete': function () { refreshRightSide() }
         });

                });
    </script>


HTML
-----------
    <input id="test_title" type="text" placeholder="Please enter title" class="textbox4" />
                               <select id="category">
                                        <option id="C" value="C">-Select-</option>
                                        <option id="M" value="Ministry ">Ministry Testimony</option>
                                        <option id="P" value="Personal ">Personal Testimony</option>
                               
                                    </select>
 <input type="file" name="file_upload" id="test_file_upload" class="test_file_upload" />

  <input id="test_upload_btn" type="button" value="Upload and save" class="button3" />
 <span style="display: none;">
   <asp:Label ID="user_lbl" runat="server" Text="akash"></asp:Label>
</span>

upload.ashx
-----------------------

<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.IO;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public class Upload : IHttpHandler {
 
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];

            string savepath = "";
            string tempPath = "";
            tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
            savepath = context.Server.MapPath(tempPath);
            string filename = postedFile.FileName;
            if (!Directory.Exists(savepath))
                Directory.CreateDirectory(savepath);

            postedFile.SaveAs(savepath + @"\" + filename);
            context.Response.Write(tempPath + "/" + filename);
            context.Response.StatusCode = 200;



            //Upload video code
            string loc = "/videos/" + filename;
            string user = context.Request["user_name"];
            string video_name = context.Request["video_name"];
            //context.Request["user"];
            string file_size = postedFile.ContentLength.ToString();
            double m = Convert.ToDouble(file_size);
            double result = m / 1024;
            string catagory = context.Request["category"];
            file_size = Convert.ToString(result);  //Result in kilobytes
            FileInfo fi = new FileInfo(postedFile.FileName);
            string video_extension_type = fi.Extension;



            //Upload video link to db
            SqlConnection sqlconn = new SqlConnection("Data Source=akash\\SQLEXPRESS;Initial Catalog=prayermeetings;Integrated Security=True");
            SqlCommand sqlcomm = new SqlCommand("video_upload", sqlconn);
            sqlcomm.CommandType = CommandType.StoredProcedure;
            sqlcomm.Parameters.Add("@video_name", SqlDbType.VarChar, 200).Value = video_name;
            sqlcomm.Parameters.Add("@video_location", SqlDbType.VarChar, 500).Value = loc;
            sqlcomm.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = user;
            sqlcomm.Parameters.Add("@category", SqlDbType.VarChar, 50).Value = catagory;
            sqlcomm.Parameters.Add("@video_size", SqlDbType.VarChar, 10).Value = file_size;
            sqlcomm.Parameters.Add("@video_extension_type", SqlDbType.VarChar, 20).Value = video_extension_type;
            sqlconn.Open();
            sqlcomm.ExecuteNonQuery();
            sqlconn.Close();




            context.Response.Write("1");

         
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
            context.Response.Write("0");
        }
    }







 
    public bool IsReusable {
        get {
            return false;
        }
    }
}


Web.config(Size in bytes)
--------------------
 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Monday 13 July 2015

Selected checkbox in gridview is not working on server but working on local machine

Problem:- when i click delete button for selected checkbox in gridview it is not working on server but working on local machine.


Solution:- In web hosting check permissions for folders,if your gridview contains images.Check mark delete permission in hosting for anonymous.


For deleting images from server folder you need to put permissions to delete.