shake demo

Click to shake the box.

Tuesday 3 February 2015

BACK UP & RESTORE SQL SERVER DB USING C# ASP.NET

//aspx Page
 <div> 
            <table cellpadding="10" cellspacing="10" style="border: solid 10px red; background-color: Skyblue;" 
                width="90%" align="center"> 
                <tr> 
                    <td style="height: 35px; background-color: Yellow; font-weight: bold; font-size: 16pt; 
                        font-family: Times New Roman; color: Red" align="center"> 
                        Backup/Restore SQL Server DataBase 
                    </td> 
                </tr> 
                <tr> 
                    <td align="center"> 
                        <asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label> 
                    </td> 
                </tr> 
                <tr> 
                    <td align="center"> 
                        <asp:Button ID="btnBackup" runat="server" Text="Backup DataBase" OnClick="btnBackup_Click" /> 
                    </td> 
      
                </tr>  
                  <tr> 
                    <td align="center"> 
                        <asp:Button ID="btnrestore" runat="server" Text="Restore DataBase" OnClick="btnrestore_Click" /> 
                    </td> 
      
                </tr> 
            </table> 
        </div>

//Codebehind Page
using System.IO;

 //global var
  string strQuery = string.Empty;
        string backupDIR = "D:\\BackupDB";
        SqlConnection con = new SqlConnection();
        SqlCommand sqlcmd = new SqlCommand();


 protected void btnBackup_Click(object sender, EventArgs e)
        {
            con.ConnectionString = @"Server=REFLEXIRP\SQLEXPRESS;database=testdb;uid=sa;password=sasa@123;";

            if (!Directory.Exists(backupDIR))
            {
                Directory.CreateDirectory(backupDIR);
            }
            try
            {
                string[] pdfFiles = Directory.GetFiles("D:\\BackupDB\\", "*.bak");
                string str = pdfFiles[0].ToString();
                if (str!=null)
                {
                    Array.ForEach(Directory.GetFiles(@"D:\\BackupDB\\", "*.bak"), File.Delete);
                    con.Open();
                    sqlcmd = new SqlCommand("backup database testdb to disk='" + backupDIR + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", con);
                    sqlcmd.ExecuteNonQuery();
                    con.Close();
                    lblError.Text = "Backup database successfully";
                }

            }
            catch (Exception ex)
            {
                lblError.Text = "Error Occured During DB backup process !<br>" + ex.ToString();
            }
        }  
        protected void btnrestore_Click(object sender, EventArgs e)
        {         

            string[] pdfFiles = System.IO.Directory.GetFiles("D:\\BackupDB\\", "*.bak");           
            string str = pdfFiles[0].ToString();
            con.ConnectionString = @"Server=REFLEXIRP\SQLEXPRESS;database=testdb;uid=sa;password=sasa@123;";         
            con.Open();
            sqlcmd = new SqlCommand("USE MASTER RESTORE DATABASE testdb FROM DISK =   '" + str + "' WITH REPLACE", con);

            sqlcmd.ExecuteNonQuery();
            con.Close();        

            lblError.Text = "Restored database successfully";

        }
       

Wednesday 24 December 2014

ASP TOOLTIP ELIPSIS-

 

Option 1:

To trim text and show ellipsis to the cells of a column in gridview, use a TemplateField with a label and use CSS3's text-overflow option. Then in the 'ToolTip' property of the label field, add code to bind the field with the value from data source as shown below.
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
    <Columns>
     <asp:TemplateField HeaderText ="Product_Review">
           <ItemTemplate>
                 <div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width:100px">
                      <asp:Label ID="review" runat="server" Text='<%# Bind("Product_Review") %>' Tooltip='<%#Bind("Product_Review")%>'></asp:Label>
                 </div>
           </ItemTemplate>
           <HeaderStyle Wrap="false" Width="100" HorizontalAlign="Left" />
           <ItemStyle Wrap="false" Width="100"></ItemStyle>
     </asp:TemplateField>
    </Columns>
</asp:GridView>
 
 

Option 2:

Use the same logic to trim text and show ellipsis, use gridview's RowDataBound event to display tooltip. Here we find the label control and use its text value to display tooltip.

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false">
   <Columns>
       <asp:TemplateField HeaderText ="Product_Review" HeaderStyle-ForeColor="Orange">
                <ItemTemplate>
                    <div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width:100px">
                        <asp:Label ID="review" runat="server" Text='<%# Bind("Product_Review") %>'></asp:Label>
                    </div>
                </ItemTemplate>
                <HeaderStyle Wrap="false" Width="100" HorizontalAlign="Left" />
                <ItemStyle Wrap="false" Width="100"></ItemStyle>
        </asp:TemplateField>
    </Columns>
</asp:GridView> 
Codebehind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
   {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           Label lblReview = (Label)e.Row.FindControl("review");
           string tooltip = lblReview.Text;
           e.Row.Cells[4].Attributes.Add("title", tooltip);
       }
   }

 Sample output is shown below,






 

SQL Server query to delete objects

declare @n char(1)
set @n = char(10)

declare @stmt nvarchar(max)

-- tables
select @stmt = isnull( @stmt + @n, '' ) +
    'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables

-- stored procedures
select @stmt = isnull( @stmt + @n, '' ) +
    'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures


-- check constraints
select @stmt = isnull( @stmt + @n, '' ) +
'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + ']    drop constraint [' + name + ']'
from sys.check_constraints

-- functions
select @stmt = isnull( @stmt + @n, '' ) +
    'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )

-- views
select @stmt = isnull( @stmt + @n, '' ) +
    'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views

-- foreign keys
select @stmt = isnull( @stmt + @n, '' ) +
    'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys



-- user defined types
select @stmt = isnull( @stmt + @n, '' ) +
    'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1


exec sp_executesql @stmt


===============================
select how many records in a table

CREATE TABLE  #rowcount (tablename varchar(128), records_in_table int)

EXEC sp_MSforeachtable
 @command1 = 'Insert into #rowcount select ''?'',
              count(*) from ?',
 @whereand = 'and o.name like ''c%''',
 @postcommand = 'SELECT * from #rowcount'

DROP TABLE  #rowcount

LOCK PC using C# code

using System.Runtime.InteropServices;


 public partial class Trends : System.Web.UI.Page
    {
[DllImport("user32.dll")]
        public static extern void LockWorkStation();

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
            }
        }

public static void LockScreen()
        {
            LockWorkStation();
        }
        protected void btnLockPC_Click(object sender, EventArgs e)
        {

            LockScreen();
       
        }
}

Friday 21 November 2014

C# Evaluate Expression- Mathematical calculation

<asp:TextBox ID="txtEquation" runat="server" MaxLength="50"></asp:TextBox>
                    <asp:Button ID="calculate" runat="server" Text="Calculate" OnClick="calculate_Click" />
                    <asp:Label ID="lblResult" runat="server" Text="0"></asp:Label>

 private object EvaluateExpression(string eqn)
        {
            DataTable dt = new DataTable();
            var result = dt.Compute(eqn, string.Empty);
            return result;
        }

        protected void calculate_Click(object sender, EventArgs e)
        {
            try
            {
                string result = Convert.ToString(EvaluateExpression(txtEquation.Text.Trim()));
                lblResult.Text = "Result: " + String.Format(result, "#.##");
                lblResult.ForeColor = Color.Green;
            }
            catch (Exception ex)
            {
                lblResult.Text = "Oops!! error occured: " + ex.Message.ToString();
                lblResult.ForeColor = Color.Red;
            }
        }

OutPut is:


Disable Browser Back Button

// Add below js code on master page or any .js file
<%-- Code for browswer back button disable start from here --%>
   
    <script type="text/javascript" language="javascript">

        function changeHashOnLoad() {
            window.location.href += '#';
            setTimeout('changeHashAgain()', '50');
        } 12438.00

        function changeHashAgain() {
            window.location.href += '1';
        }

        var storedHash = window.location.hash;
        window.setInterval(function () {
            //          if (window.location.hash != storedHash) {
            window.onhashchange = function () { window.location.hash = storedHash; }
            window.location.hash = storedHash;

        }, 50);
        window.onload = changeHashOnLoad;
        window.location.hash = "no-back-button";
        window.location.hash = "Again-no-back-button"; //for google chrome
        // window.onhashchange = function () { window.location.hash = "no-back-button"; }
        window.history.forward(1);
        history.go(1);
    </script>
    <%-- end Code for browswer back button disable --%>

Tuesday 14 October 2014

aspx Textbox Search from sql server database (like google search):

aspx Textbox Search from sql server (like google search):
----------------------------------------------------------------------------------------------------

  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

aspx page code:
 -------------------------------
           <script language="javascript" type="text/javascript">
            $(function () {
                $('#<%=txtcustname.ClientID%>').autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: "enquiry.aspx/GetCompanyName",
                            data: "{ 'customer':'" + request.term + "'}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {
                                response($.map(data.d, function (item) {
                                    return { value: item }
                                }))
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                alert(textStatus);
                            }
                        });
                    }
                });
            });
</script>

<asp:TextBox ID="txtcustname" runat="server"  CssClass="textboxAuto" ></asp:TextBox>

C# CodeBehibd
-------------------------

 [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<string> GetCompanyName(string customer)
        {
            mainclass objmc = new mainclass();
            List<string> result = new List<string>();
            using (SqlCommand cmd = new SqlCommand("select name from customer where name LIKE @SearchText+'%'", objmc.con))
            {
                objmc.con.Open();
                cmd.Parameters.AddWithValue("@SearchText", customer);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["name"].ToString());
                }
                return result;
            }
        }

DEMO: