Friday, 30 March 2012

MOVE , REPLACE And DELETE Images File Dynamically In ASP.Net

Move,Copy,Save,Replace And Delete Image File Dynamically In ASP.Net


To maintain your server memory with saving files.you must sure the unused file should be deleted,means if Record updated then old file should be replace by new one,and at the time of client choosing file then it should place under temporary folder and continuously  replace old file with new file.don't worry if you didn't understand above theory.Let do it Practically.
To remind you i've already explained How To Delete File From Server  ,And here we are doing totally different things with file on server


 

1)As this is as File input- output process you must add the namespace

using System.IO;



  2)On Clicking Upload Button And Save file In Temporary Folder

protected void ButtonUpload_Click(object sender, EventArgs e)
    {

        if (FileUpload1.HasFile)
        {
           FileInfo TheFile = new FileInfo(MapPath(".") + "\\" + "itemimages/tempImages/" + "Item" + TextBoxItemCode.Text + ".jpg");
            if (TheFile.Exists)
            {
                File.Delete(MapPath(".") + "\\" + "itemimages/tempImages/" + "Item" + TextBoxItemCode.Text + ".jpg");
            }
           

            FileUpload1.SaveAs(Server.MapPath("~/itemimages/tempImages/") + "Item" + TextBoxItemCode.Text + ".jpg");
            ImageLogo.ImageUrl = "~/itemimages/tempImages/" + "Item" + TextBoxItemCode.Text + ".jpg";


        }
        else
        {
            CloseWindow = "alert('At First Browse and Select Item Image');";
            ScriptManager.RegisterStartupScript(this.up, this.up.GetType(), "CloseWindow", CloseWindow, true);
        }
    
    }







3)
TextBoxItemCode.Text:-unique name for image

"~/itemimages/tempImages/":-Path for file after clicking update button not save or update.

"~/itemimages/ItemImages/":-Path,which will finally save or updated and use to save in database.

+ "Item" +:- Just to make sure every image will save with prefix Item








4)
On save Button Click
 means
if(ButtonSave.Text=="Save")



string destinationFile ;
 string images = ImageLogo.ImageUrl;
 if (CheckBoxLogo.Checked == true)
 {
         images = "";
 }
 else
{
 string sourceFile = Server.MapPath("~/itemimages/tempImages/" + "Item" + TextBoxItemCode.Text + ".jpg");
 destinationFile = Server.MapPath("~/itemimages/ItemImages/" + "Item" + TextBoxItemCode.Text + ".jpg");
   System.IO.File.Move(sourceFile, destinationFile);

}









5)
On Update Button Click
 means
 else if(ButtonSave.Text=="Update")


string images = ImageLogo.ImageUrl;
 if (CheckBoxLogo.Checked == true)
{
       images = "";
}
  else
 {
        images = ImageLogo.ImageUrl;
         if (CheckBoxLogo.Checked == true)
         {
                            images = "";
          }
          else
          {
    string sourceFile = Server.MapPath("~/itemimages/tempImages/" + "Item" + TextBoxItemCode.Text + ".jpg");
    destinationFile = Server.MapPath("~/itemimages/ItemImages/" + "Item" + TextBoxItemCode.Text + ".jpg");
    FileInfo TheFile = new FileInfo(MapPath( "~/itemimages/ItemImages/" + "Item" + TextBoxItemCode.Text + ".jpg"));
     if (TheFile.Exists)
       {
                    File.Delete(MapPath("~/itemimages/ItemImages/" + "Item" + TextBoxItemCode.Text + ".jpg"));
         }   
         System.IO.File.Move(sourceFile, destinationFile);
                               
      }
                 

   }





6)Required TABLE With Above Code


CREATE TABLE [dbo].[tb_Item](
    [Item_Id] [bigint] IDENTITY(1,1) NOT NULL,
    [Item_Code] [varchar](100) NULL,
    [Item_Name] [varchar](200) NULL,
    [Qty] [float] NULL,
    [QtyUnit] [varchar](50) NULL,
    [InvLevel] [float] NULL,
    [Remarks] [varchar](max) NULL,
    [ItemImage] [varchar](max) NULL
)






and here is what you're lookin for

Apart From Only this I am Also Giving You Code By Which You Can Not Only Move File OVER server but can do copy paste job too,Hope you like this too.



 protected void Button_Click(object sender, EventArgs e)
    {
        string sourceFile = Server.MapPath("Data.txt");
        string destinationFile = Server.MapPath("Datacopy.txt");
        System.IO.File.Copy(sourceFile, destinationFile);
    }






Monday, 26 March 2012

AutoComplete Extender AJAX

Using AJAX AutoComplete Extender Sample


Basic Sample How To Get Texts From Sql Database To TextBox




SQL Query For Sample

CREATE TABLE tb_Client(
    [Client_id] [bigint] IDENTITY(1,1) NOT NULL,
    [Client_Name] [varchar](max) NULL,
   
)


.CS

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetClientList(string prefixText, int count, string contextKey)
    {
        if (count == 0)
        {
            count = 10;
        }

       
        List<string> items = new List<string>(count);

        SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["CString"]);
        SqlCommand cmd = new SqlCommand("SELECT [Client_Name],[Client_Id] FROM [dbo].[tb_Client] where Client_Name like '" + prefixText + "%'", con);
        if (con.State == ConnectionState.Closed)
            con.Open();
        cmd.CommandType = CommandType.Text;
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.HasRows)
        {
            while (dr.Read())
            {
                items.Add(dr.GetValue(0).ToString());

            }
            dr.NextResult();
        }

  

        return items.ToArray();
    }

You can also replace bit code with this to extend its performance as per your need.
           while (dr.Read())
            {
                string item =
AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["Client_Name"].ToString(), dr["Client_Id"].ToString());
                items.Add(item);

            }





.ASPX Page


<asp:TextBox ID="txtSearch" runat="server" Width = "200"></asp:TextBox>
           <asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
               BehaviorID="AutoCompleteEx"
                TargetControlID="txtSearch"
                ServiceMethod="GetClientList"
                MinimumPrefixLength="1"
                CompletionInterval="100"
                EnableCaching="true"
                CompletionSetCount="20"
                CompletionListCssClass="AutoExtender"
        CompletionListItemCssClass="AutoExtenderList"
               
               
             
                CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
                DelimiterCharacters=";, :"
                ShowOnlyCurrentWordInCompletionListItem="true" UseContextKey="True" >
    </asp:AutoCompleteExtender>



CSS (add it in head)

  <style type="text/css">
   /*AutoComplete flyout */

.autocomplete_completionListElement

    margin : 0px!important;
    background-color : inherit;
    color : windowtext;
    border : buttonshadow;
    border-width : 1px;
    border-style : solid;
    cursor : 'default';
    overflow : auto;
    height :auto;
    text-align : left;
    list-style-type : none;
}

/* AutoComplete highlighted item */

.autocomplete_highlightedListItem
{
    background-color: #ffff99;
    color: black;
    padding: 1px;
}

/* AutoComplete item */

.autocomplete_listItem
{
    background-color : window;
    color : windowtext;
    padding : 1px;
}
  .AutoExtender
        {
            font-family: Verdana, Helvetica, sans-serif;
            font-size: .8em;
            font-weight: normal;
            border: solid 1px #006699;
            line-height: 20px;
            padding: 10px;
            background-color: White;
            margin-left:10px;
        }
        .AutoExtenderList
        {
            border-bottom: dotted 1px #006699;
            cursor: pointer;
            color: Maroon;
            font-style:normal;
        }


   </style>


In last here is what you are lookin for...



To Adjust the style of Autocomplete extender genrating list you can take a view at Autocomplete Simple CSS.


you may also like.
Ajax Calender Control
Ajax Progress Bar

Tuesday, 6 March 2012

GridView With ObjectDataSource

GridView With ObjectDataSource /Insert,Update & Delete With ObjectDataSource

In this article I will show you how you can use the ObjectDataSource with the GridView control to do editing, updating, deleting and adding new records. There are several ways to perform these operations, I am using the simplest approach.



For That We Need Grid View Like Below
 <asp:GridView ID="GridView1" runat="server"
                                                DataSourceID="ObjectDataSource1"
                                 onrowcommand="GridView1_RowCommand" ShowFooter="True"
                                 AutoGenerateColumns="False" onrowupdating="GridView1_RowUpdating"
                                 onrowdeleting="GridView1_RowDeleting" onrowupdated="GridView1_RowUpdated"
                                 onrowediting="GridView1_RowEditing" DataKeyNames="Country_Id">
                                 <Columns>
                                     <asp:TemplateField>
                                         <FooterTemplate>
                                             <asp:TextBox ID="TextBoxAddName" runat="server"></asp:TextBox>
                                         </FooterTemplate>
                                         <ItemTemplate>
                                             <asp:Label ID="LabelID" runat="server" Text='<%# Bind("Country_Id") %>'></asp:Label>
                                         </ItemTemplate>
                                     </asp:TemplateField>
                                     <asp:TemplateField>
                                         <EditItemTemplate>
                                             <asp:TextBox ID="TextBoxUpdateName" runat="server" Text='<%# Bind("Country_Name") %>'></asp:TextBox>
                                         </EditItemTemplate>
                                         <FooterTemplate>
                                             <asp:Button ID="ButtonAdd" runat="server" CommandName="AddCountry"
                                                 Text="Add Country" />
                                         </FooterTemplate>
                                         <ItemTemplate>
                                             <asp:Label ID="Label2" runat="server" Text='<%# Bind("Country_Name") %>'></asp:Label>
                                         </ItemTemplate>
                                     </asp:TemplateField>
                                     <asp:CommandField ShowEditButton="True" />
                                     <asp:CommandField ShowDeleteButton="True" />
                                 </Columns>
                             </asp:GridView>

Object DataSource Like Below
 <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
                                 SelectMethod="select" InsertMethod="AddCountry" UpdateMethod="UpdateCountry" DeleteMethod="DeleteUser" TypeName="ControlPanel.selection">
                             </asp:ObjectDataSource>

Three Methods In Class File(Class File Under App_Code)
    public void AddCountry(string CountryName)
    {

    }

    public void UpdateCountry(string update,int uniqueid)
    {
   
    }
    public void DeleteUser(int id)
    {
  
    }



Which we will Further Fill By
 public void AddCountry(string CountryName)
    {

        SqlCommand cmd = new SqlCommand("insert into tb_Country values(@CountryName)", con);
        cmd.Parameters.AddWithValue("@CountryName", CountryName);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

    }

    public void UpdateCountry(string update,int uniqueid)
    {
        SqlCommand cmd = new SqlCommand("update tb_Country set Country_Name=@CountryN where Country_Id=@CID", con);

        cmd.Parameters.AddWithValue("@CountryN", update);
        cmd.Parameters.AddWithValue("@CID", uniqueid);
        con.Open();
        cmd.ExecuteNonQuery();

        con.Close();
    }
    public void DeleteUser(int id)
    {
        SqlCommand cmd = new SqlCommand("Delete from tb_Country where Country_Id=@CID", con);
        cmd.Parameters.AddWithValue("@CID", id);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

Here Is The Script Of The TABLE

CREATE TABLE [dbo].[tb_Country](
    [Country_Id] [int] IDENTITY(1,1) NOT NULL,
    [Country_Name] [varchar](50) NULL
)

Now To Explain You Below Are Two Images Will Tell You Why For What Code Is Going





Download Source From Here

Saturday, 3 March 2012

Ajax Progress Bar In ASP.Net

Ajax Progress Bar In ASP.Net

Till your code execution is in process if you require progress bar to show then here is a sample for you.


Like this Progress Bar...





So Start With A Basic Step...
1)Now Add This Code To Your .ASPX Page



 <div><asp:scriptmanager runat="server"></asp:scriptmanager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">

        <Triggers>

            <asp:PostBackTrigger ControlID="btnUpload" />

        </Triggers>

        <ContentTemplate>

            <br />

            <asp:FileUpload ID="myFile" runat="server" />

            <asp:Label ID="lblMsg" runat="server"></asp:Label>           

            <br />

            <asp:Button ID="btnUpload" runat="server" Text="Upload"

                OnClick="UploadFile" OnClientClick="javascript:showWait();"/>          

            <br />

            <asp:UpdateProgress ID="UpdateProgress1" runat="server"

                AssociatedUpdatePanelID="UpdatePanel1">

                <ProgressTemplate>

                    <asp:Label ID="lblWait" runat="server" BackColor="#507CD1"

                        Font-Bold="True" ForeColor="White"

                        Text="Please wait ... Uploading file"></asp:Label>

                    <img alt="" src="progress.gif" />

                </ProgressTemplate>

            </asp:UpdateProgress>

        </ContentTemplate>

    </asp:UpdatePanel>
    </div>



Now look at your Design Page.It will look like below one










2)Add this javascript code at your header part of .ASPX Page.
<script language="javascript" type="text/javascript">

function showWait()

{

    if ($get('myFile').value.length > 0)

    {

        $get('UpdateProgress1').style.display = 'block';

    }

}

</script>




3)Now check your button click event with break points you'll see till the execution is under process your progress bar will remain visible.









4)Finally you'll get this kind of progress bar at the time of your execution taking long time


    


Download Sample From Here

                                                                               you may also like 

Print Only Grid View in ASP.net

ASP.net How to Print Only GridView < div id ="gridviewDiv" >   < asp:GridView ID ="gridViewToPri...