Total Pageviews

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.

Sunday, 5 July 2015

Beautiful alert box for asp.net button click

http://www.jqueryscript.net/demo/Stylish-jQuery-Notification-Alert-Plugin-Smart-Alert/quick-start/



Download link- http://www.jqueryscript.net/download/Stylish-jQuery-Notification-Alert-Plugin-Smart-Alert.zip
Code:
--------
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"></script>

    <link href="css/alert.css" rel="stylesheet" />
    <link href="css/theme.css" rel="stylesheet" />
    <script src="Jquery/alert.js"></script>

 <script language="javascript">
                function ConfirmRemoveDialog() {
                    //If validation failed    
                    $.alert.open('confirm', 'Lorem ipsum dolor sit amet');
                    return false;

                    //If validation passed in that case return true.
                }
    </script>

 <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick ="return ConfirmRemoveDialog();" />


You can also call from code behind

  protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage","ConfirmRemoveDialog();", true);
    }

Thursday, 2 April 2015

Responsive gridview

Create div and inside gridview in html

Open css file or style tag

Add media query to decrease the width of screen.
eg:-

<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
</head>

CSS
---------------
<style>

#grid_div{
width:500px;
overflow:scroll;
}

@media only screen and (min-width:150px) and (max-width:600px) {
#grid_div{
width:150px;
overflow:scroll;
}
}
</style>

JQUERY
------------------
Download 2 jquery files

a) jquery-1.11.2.min.js
b) footable.js

 <script src="Jquery/jquery-1.11.2.min.js"></script>
   <script src="Jquery/footable.js"></script>

    <script type="text/javascript">
        $(function () {
            $('#<%=church_gridview.ClientID %>').footable({
                  breakpoints: {

                      phone: 150,
                      tablet: 640

                  }
              });
          });
    </script>

HTML
------------
<div id="grid_div">

 <asp:GridView ID="church_gridview" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="church_sqldatasource" PageSize="3" CssClass="footable" AllowPaging="True">
                <Columns>
                 
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="return confirm('Are you sure you?');"
                                CommandName="Delete" CausesValidation="false">Delete</asp:LinkButton>

                        </ItemTemplate>
                   
                     
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton="True" CausesValidation="false" />
                    <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
                    <asp:BoundField DataField="church_name" HeaderText="church_name" SortExpression="church_name" />
                    <asp:BoundField DataField="church_address" HeaderText="church_address" SortExpression="church_address" />
                    <asp:BoundField DataField="church_ph" HeaderText="church_ph" SortExpression="church_ph" />
                    <asp:BoundField DataField="church_email" HeaderText="church_email" SortExpression="church_email" />
                    <asp:BoundField DataField="church_website" HeaderText="church_website" SortExpression="church_website" />
                    <asp:BoundField DataField="District" HeaderText="District" SortExpression="District" />
                </Columns>
            </asp:GridView>

</div>


Code Behind
--------------------
protected void Page_Load(object sender, EventArgs e)
    {
     
        if (!IsPostBack)
        {
            gridview_bind_responsive();
        }

    }


    public void gridview_bind_responsive()
    {

        church_gridview.DataBind();
        church_gridview.UseAccessibleHeader = true;
        church_gridview.HeaderRow.TableSection = TableRowSection.TableHeader;

        TableCellCollection cells = church_gridview.HeaderRow.Cells;
        cells[0].Attributes.Add("data-hide", "expand");
        cells[1].Attributes.Add("data-class", "expand");
        cells[2].Attributes.Add("data-hide", "phone,tablet");

        cells[3].Attributes.Add("data-hide", "expand");
        cells[4].Attributes.Add("data-hide", "phone,tablet");
     
     
        cells[8].Attributes.Add("data-hide", "phone,tablet");
        cells[7].Attributes.Add("data-hide", "phone,tablet");
        cells[6].Attributes.Add("data-hide", "phone,tablet");
        cells[5].Attributes.Add("data-hide", "phone,tablet");

    }

Wednesday, 1 April 2015

Add javascript alert to asp.net button

Method: 1
-----------------
 <script> 
function alert_me() {
            return confirm('Hello!');
        }

 </script>

 <asp:Button ID="Button4"  OnClientClick="alert_me()"
                Text="Click Me" runat="server" />
            <br />



Method: 2
-----------------
<asp:Button ID="Button5"  OnClientClick="return confirm('are you sure?')"
                Text="Click Me" runat="server" />

Sunday, 29 March 2015

Page Numbers to Datalist in dynamic


No . of results for your filter coding is not shown here,but u can add from querying it.
No css is shown in this coding.
HTML
-----------

<div id="m_right_panel">
                 
                        <div>
                            <table>
                                <tr>
                                    <td>
 <asp:Label ID="m_page_lbl" runat="server" Text="Page:" Visible="False" CssClass ="font_class"></asp:Label></td>
                                    <td>
  <asp:Repeater ID="rptPager" runat="server">
             <ItemTemplate>
<asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
               </ItemTemplate>
    </asp:Repeater>
                                    </td><td></td>
                                    <td style ="text-align :center ;">
  <asp:Label ID="m_search_result_lbl" runat="server" Text="" CssClass ="font_class"></asp:Label></td>
                                </tr>
                            </table>

                        </div>
                    <div id="meeting_datalist_div">
    <asp:DataList ID="meeting_datalist" runat="server" RepeatDirection="Horizontal"  ShowFooter="False" ShowHeader="False" CellPadding="10"  RepeatLayout="Flow"    HorizontalAlign="Left" Width="100%" >
                           <ItemStyle Height ="100%" />
                            <ItemTemplate >
                                <div style="margin:10px;padding:10px;height:320px">
                             
                                 <table id="meetings_tbl" >
                                    <tr>
                                        <td style="text-align: center">

  <asp:Label ID="Label4" runat="server" Text='<% #Bind("title")%>'></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>

                                        <td style ="text-align :center;">
  <asp:Image ID="Image1" runat="server" ImageUrl='<% #Bind("imageurl")%>' Width="180px" Height="180px" />

                                        </td>
                                    </tr>
                                    <tr>
                                        <td >

  <asp:Label ID="Label5" runat="server" Text="Ministries:"></asp:Label>

 <asp:Label ID="Label2" runat="server" Text='<% #Bind("ministries")%>'></asp:Label>

                                        </td>
                                    </tr>
                                    <tr>
                                        <td>

  <asp:Label ID="Label6" runat="server" Text="Comments:"></asp:Label>

   <asp:Label ID="comments_lbl" runat="server" Text='<% #Bind("comments")%>'></asp:Label>

                                        </td>
                                    </tr>
                                    <tr>
                                        <td>

  <asp:Label ID="Label8" runat="server" Text="Meeting starts on:"></asp:Label>

       <asp:Label ID="Label9" runat="server" Text='<% #Bind("meeting_start_dt")%>'></asp:Label></td>
                                    </tr>
                                    <tr>
                                        <td>

  <asp:Label ID="Label7" runat="server" Text="Posted date:"></asp:Label>

 <asp:Label ID="posted_lbl" runat="server" Text='<% #Bind("posted_date")%>'></asp:Label></td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                    </tr>
                                </table>

                                    </div>
                            </ItemTemplate>
                        </asp:DataList>
                  </div>
             

            </div>


STORED PROCEDURE
------------------------------

CREATE PROCEDURE [dbo].[GetCustomersPageWise]
      @PageIndex INT = 1
      ,@PageSize INT = 10
      ,@RecordCount INT OUTPUT,
 @from_dt varchar(50),
 @to_dt varchar(50),
 @district varchar(100)
AS
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
      (
            ORDER BY [id] ASC
      )AS RowNumber
      ,[title]
      ,[ministries]
      ,[comments]
  ,[meeting_start_dt]
   ,[posted_date]
,[imageurl]
     INTO #Results
      FROM [customer_post_ad] where district=@district  and meeting_start_dt between @from_dt  and @to_dt order by title
 
      SELECT @RecordCount = COUNT(*)
      FROM #Results
       
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
 
      DROP TABLE #Results
END



CODE-BEHIND
-----------------------

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;

string con = ConfigurationManager.ConnectionStrings["prayermeeting_mdf"].ConnectionString;
private int PageSize = 2;

 protected void meeting_search_btn_Click(object sender, EventArgs e)
    {

        this.GetCustomersPageWise(1);
  }


private void GetCustomersPageWise(int pageIndex)
    {
        string constring = ConfigurationManager.ConnectionStrings["prayermeeting_mdf"].ConnectionString;

        string district = m_district_ddl.SelectedItem.Text.ToString();
        string from_dt = m_frm_dt.Text;
        string to_dt = m_to_dt.Text;
        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("GetCustomersPageWise", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                cmd.Parameters.AddWithValue("@PageSize", PageSize);
                cmd.Parameters.AddWithValue("@district", district);
                cmd.Parameters.AddWithValue("@from_dt", from_dt );
                cmd.Parameters.AddWithValue("@to_dt", to_dt);
                cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4);
                cmd.Parameters["@RecordCount"].Direction = ParameterDirection.Output;
                con.Open();
                IDataReader idr = cmd.ExecuteReader();
                meeting_datalist.DataSource = idr;
                meeting_datalist.DataBind();
                idr.Close();
                con.Close();
                int recordCount = Convert.ToInt32(cmd.Parameters["@RecordCount"].Value);
                this.PopulatePager(recordCount, pageIndex);
                m_page_lbl.Visible = true;

                m_search_result_lbl.Text  = "No. of results for your filter: "+recordCount ;
            }
        }
    }


private void PopulatePager(int recordCount, int currentPage)
    {
        List<ListItem> pages = new List<ListItem>();
        int startIndex, endIndex;
        int pagerSpan = 5;

        //Calculate the Start and End Index of pages to be displayed.
        double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
        int pageCount = (int)Math.Ceiling(dblPageCount);
        startIndex = currentPage > 1 && currentPage + pagerSpan - 1 < pagerSpan ? currentPage : 1;
        endIndex = pageCount > pagerSpan ? pagerSpan : pageCount;
        if (currentPage > pagerSpan % 2)
        {
            if (currentPage == 2)
            {
                endIndex = 5;
            }
            else
            {
                endIndex = currentPage + 2;
            }
        }
        else
        {
            endIndex = (pagerSpan - currentPage) + 1;
        }

        if (endIndex - (pagerSpan - 1) > startIndex)
        {
            startIndex = endIndex - (pagerSpan - 1);
        }

        if (endIndex > pageCount)
        {
            endIndex = pageCount;
            startIndex = ((endIndex - pagerSpan) + 1) > 0 ? (endIndex - pagerSpan) + 1 : 1;
        }

        //Add the First Page Button.
        if (currentPage > 1)
        {
            pages.Add(new ListItem("First", "1"));
        }

        //Add the Previous Button.
        if (currentPage > 1)
        {
            pages.Add(new ListItem("<<", (currentPage - 1).ToString()));
        }

        for (int i = startIndex; i <= endIndex; i++)
        {
            pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
        }

        //Add the Next Button.
        if (currentPage < pageCount)
        {
            pages.Add(new ListItem(">>", (currentPage + 1).ToString()));
        }

        //Add the Last Button.
        if (currentPage != pageCount)
        {
            pages.Add(new ListItem("Last", pageCount.ToString()));
        }
        rptPager.DataSource = pages;
        rptPager.DataBind();
    }


 protected void Page_Changed(object sender, EventArgs e)
    {
        int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
        this.GetCustomersPageWise(pageIndex);
    }

Responsive datalist change the list on fly / screen width





<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<head>

CSS
-------
church_display_tbl {
        width: 100%;
        height: 100px;
        padding-left: 5px;
        float: left;
    }

    #church_data_div {
      height:445px;
      overflow :scroll ;
    }

 

    #church_tbl {
        margin-top: 40px;
        width: 210px;
        height: 150px;
        font-size: 13px;
     
        float: left;

    }

@media only screen and (min-width:150px) and (max-width:600px) {

    #church_data_div {
      height:150px;
      overflow :scroll ;
    }
}

 


HTML
----------

   <div id="church_data_div">
           
                    <table>
                        <tr>
                            <td>
 <asp:DataList ID="church_datalist" runat="server" RepeatDirection="Horizontal"  ShowFooter="False" ShowHeader="False" CellPadding="5"  RepeatLayout="Flow"    HorizontalAlign="Left" Width="100%">

                                    <ItemStyle Height ="100%" />

                                     <ItemTemplate>
                                          <div style="margin:2px;padding:2px;height:100px">
                                        <table id="church_tbl">

                                            <tr>
                                                <td>
    <asp:Label ID="Label1" runat="server" Text="Church Name:"></asp:Label></td>
                                                <td>
   <asp:Label ID="Label2" runat="server" Text='<% #Bind("church_name")%>'></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td>
 <asp:Label ID="Label7" runat="server" Text="Ph:"></asp:Label></td>
                                                <td>
       <asp:Label ID="Label8" runat="server" Text='<% #Bind("church_ph")%>'></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td>
          <asp:Label ID="Label3" runat="server" Text="Address:"></asp:Label></td>
                                                <td>
        <asp:Label ID="Label4" runat="server" Text='<% #Bind("church_address")%>'></asp:Label></td>
                                            </tr>
                                            <tr>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td>
                  <asp:Label ID="Label5" runat="server" Text="District:"></asp:Label></td>
                                                <td>
         <asp:Label ID="Label6" runat="server" Text='<% #Bind("district")%>'></asp:Label></td>
                                            </tr>
                                        </table>
                                              </div>
                                    </ItemTemplate>
                                </asp:DataList>
                            </td>
                        </tr>
                    </table>
           
            </div>