Total Pageviews

Thursday 30 August 2018

Saturday 27 February 2016

Datalist and bootstrap modal in asp.net



Pre requests - Use bootstrap CDN links

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

Objective- Add comment from bootstrap modal pop up

Write html outside datalist code

where datalist id- post_datalist

Bootstrap Modal code (we are using a asp hidden field control in modal)
------------------------------
<div class="modal fade" id="add_comment" tabindex="-1" role="dialog"
                aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="H2">Comment</h4>

                        </div>

                        <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                            <ContentTemplate>
                                <div class="modal-body" style="height: 150px;">


                                    <div class="form-group">

                                        <div class="col-xs-12">
                                            <asp:TextBox ID="comment_txt" runat="server" TextMode="MultiLine" Style="width: 100%; min-height: 90px;"></asp:TextBox>
                                            <asp:HiddenField ID="post_id" runat="server" />
                                        </div>
                                    </div>

  </div>
                                <div class="modal-footer">
                                    <asp:Label ID="Label2" Visible="false" runat="server"></asp:Label>
                                    <asp:Button ID="post_comment" runat="server" Text="Post comment" CssClass="btn btn-info" OnClick="post_comment_Click" />
                                    <button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
                                </div>

                            </ContentTemplate>
                            <Triggers>
                                <asp:AsyncPostBackTrigger ControlID="post_datalist" EventName="ItemCommand" />
                                <asp:AsyncPostBackTrigger ControlID="post_comment" EventName="Click" />
                            </Triggers>
                        </asp:UpdatePanel>
                    </div>
                </div>
            </div>


Now in code behind inside post_datalist_ItemCommand -- 


    //add_comment
        if ((e.CommandName == "comment") && (e.CommandArgument != null))
        {

            int id = Convert.ToInt32(e.CommandArgument);
            string code = Convert.ToString(id);
            post_id.Value = code;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script type='text/javascript'>");
            sb.Append("$('#add_comment').modal('show');");
            sb.Append(@"</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "CommentModalScript", sb.ToString(), false);

 }




Now when the modal opens you can write the comment and click button- here is the button click function 

    protected void post_comment_Click(object sender, EventArgs e)
    {
        string postid = post_id.Value;

        Int32 post_id_value = Convert.ToInt32(postid);
        comment_save(post_id_value); // here you can call function to save the data
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"<script type='text/javascript'>");

        sb.Append("$('#add_comment').modal('hide');");
        sb.Append(@"</script>");
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "CommentModalScript", sb.ToString(), false);
        BindParentDataList();// bind data /refresh

    }

Friends pending request,confirm request & friends list table in MSSQL

Create Two tables

User(id, Username)

Friends(friend_one ,friend_two,status)

Here status 01 and 2 values references to Pending Friend RequestConfirm Friend Request and You

Add friend

INSERT INTO friends
(friend_one,friend_two) 
VALUES 
(@user_id,@
friend_id);

Confirm friend

UPDATE friends
SET status="1"
WHERE 
(friend_one=@user_id OR friend_two=
@user_id
AND 
(friend_one=@friend_id OR friend_two=@
friend_id);

Checking friend

SELECT 'friend_one','friend_two','status' FROM friends
WHERE
(friend_one=@user_id OR friend_two=@user_id)
AND
(friend_one=@user_id OR friend_two=@user_id)

List friends

SELECT * FROM user U
LEFT JOIN Friends F
ON U.id = F.friend_two
WHERE F.friend_one = 1 and status=1
UNION
SELECT * FROM user U
LEFT JOIN friends F
ON U.id = F.friend_one
WHERE F.friend_two = 1 and status=1

Monday 25 January 2016

Bootstrap confirm dialog in asp.net server control

Objective : We use here a html control and server control to activate a confirmation dialog(Bootstrap modal)

<!DOCTYPE html>

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



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



    <script>

        $(document).ready(function () {
            $('a[data-confirm]').click(function (ev) {
                var href = $(this).attr('href');
                if (!$('#dataConfirmModal').length) {

                    $('body').append('<div id="dataConfirmModal" class="modal fade" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header" style="background: orange; color: white;"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body" style="background: white;"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
                }
                $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
                $('#dataConfirmOK').attr('href', href);
                $('#dataConfirmModal').modal({ show: true });
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">

        <a href="delete.cfm" data-confirm="Are you sure you want to delete?">Delete</a>

        <asp:LinkButton ID="LinkButton1" runat="server" data-confirm="Are you sure you want to delete?" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>


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

    </form>
</body>
</html>


Code Behind
-----------------
protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Write("ok");
    }

Friday 22 January 2016

Submit form data without files in dropzone on button click



Objective:
------------
 Form data and image file submitted at button click or Form data is submitted without image file on button click.

Dropzone:
-------------
 https://rawgit.com/enyo/dropzone/master/dist/dropzone.js

Prerequisites:
---------------
Dropzone Js file corrections(Check out my post below for corrections )

http://aspdotnetcake.blogspot.in/2016/01/dropzone-js-corrections.html

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="js/dropzone.js"></script>


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


Script code:
------------------

<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: "db_save.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, formData) {
                    // Make sure that the form isn't actually being sent.
                    e.preventDefault();
                    e.stopPropagation();

                    if (myDropzone.getQueuedFiles().length > 0) {
                        myDropzone.processQueue();
                    }

                    else

                    {

                        alert("hi"); //Testing it with alert
                     
                        myDropzone.uploadFiles([]);


                     
                    }

                 
                });






                // 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());

                    formData.append('desc', $("textarea[name=description]").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>


HTMLin aspx
-------------------

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

        <div>
            <input type="text" name="title" placeholder="Title"  />
            <textarea name="description" aria-valuetext="" style="cursor: pointer; width: 100%;" placeholder="Description" ></textarea></br>
            <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>

        <%--<input id="username" type="text" name="username" value="akash" style="display: none;" />--%>

        <input id="username" type="text" name="username" value="<% =ServerValue %>" style="display: none;" />


    </form>


db_save.ashx
------------------------

 string constring = ConfigurationManager.ConnectionStrings["xxxxx_mdf"].ConnectionString;







        //HttpFileCollection files = context.Request.Files;

        string user = string.Empty;

        string xx= string.Empty;
        string xx= string.Empty;
        string xx= string.Empty;
        string xxxx= string.Empty;
        string xxx= string.Empty;
        string xx= string.Empty;
        string xx= string.Empty;
        string xx= string.Empty;
        string xx= string.Empty;
        string xx= string.Empty;
        string xxxx= string.Empty;
        int photos_count = 0;

        user = context.Request["username"];

        post_desc = context.Request["desc"];



        string title = context.Request["title"];

   




        string dirFullPath = HttpContext.Current.Server.MapPath("~/pictures/");
        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)
        {
         
         
            string id = string.Empty;

            id = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");

            HttpPostedFile file = context.Request.Files[s];
            //  int fileSizeInBytes = file.ContentLength;
            string fileName = file.FileName;
            string fileExtension = file.ContentType;
            context.Response.Write(status);

            if (!string.IsNullOrEmpty(fileName))
            {

                context.Response.Write(status);

                fileExtension = Path.GetExtension(fileName);
                Guid g = Guid.NewGuid();
                str_image = g + numFiles.ToString() + fileExtension;



                string image_path = HttpContext.Current.Server.MapPath("~/pictures/") + str_image;
                file.SaveAs(image_path);

                Stream streamfile = file.InputStream;
                //context.Response.Write(pathToSave_100);


                //Start of post data

                post_title = context.Request["title"];

                post_title = post_title.Substring(0, post_title.IndexOf(','));


                event_photo_path = "pictures/" + str_image;
                event_photoname = file.FileName;
                event_photoid = "xxx" + DateTime.Now.ToString();
                event_photo_ext = fileExtension;
                photo_hide_code = "0";
                photo_username = "";
                event_timestamp = DateTime.Now.ToString();
                int event_like_count = 0;

                photos_count = photos_count + 1;

                //DB for photos


                if (event_photoname != "")
                {


                    try
                    {
                        {

                            using (SqlConnection con = new SqlConnection(constring))
                            {
                                using (SqlCommand cmd = new SqlCommand("insert into db_save values (@xxxx,@xxxxx,@xxxx,@xxxx)", con))
                                {

                                    cmd.Parameters.AddWithValue("@xxx", );
                                    cmd.Parameters.AddWithValue("@xxx", );

                                    cmd.Parameters.AddWithValue("@xxx", );
                                    cmd.Parameters.AddWithValue("@xxx", );
                             
                                    con.Open();
                                    cmd.ExecuteNonQuery();
                                    con.Close();
                                    status = "ok";
                                    context.Response.Write(status);

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

                        context.Response.Write(ex);
                    }
                    finally
                    {

                    }//try catch complete

                }//if event_photoname-->complete




            }//if filename exists -->complete

       

         



        }//For each complete


// If no image write code here below



   

Dropzone Js corrections

Please correct the Dropzone js file

Updated by below redline
------------------------------------------

for (i = _m = 0, _ref5 = files.length - 1; 0 <= _ref5 ? _m <= _ref5 : _m >= _ref5; i = 0 <= _ref5 ? ++_m : --_m) {
          // formData.append(this._getParamName(i), files[i], files[i].name);

          if (typeof files[i] != "undefined") {
              formData.append(this._getParamName(i), files[i], files[i].name);
          } else {
              formData.append(this._getParamName(i), files[i], "");
          }


      }



and this redline
-------------------------------

 xhr.onload = (function(_this) {
        return function(e) {
          var _ref;
          if (files[0] && files[0].status === Dropzone.CANCELED) {
            return;
          }
          if (xhr.readyState !== 4) {
            return;
          }

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;
        }
    }


}