Tuesday, 30 July 2013

Make the color difference for Values in grid based on positive and negitive


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data Source=;Database=;User Id=sa;password=;");
            SqlCommand cmd = new SqlCommand("Select * from Employee", conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            gdv.DataSource = dr;
            gdv.DataBind();
        }

        protected void gdv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
                if (Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "empsal").ToString()) < 0)
                    e.Row.Cells[e.Row.Cells.Count - 1].ForeColor = System.Drawing.Color.Red;
                else
                    e.Row.Cells[e.Row.Cells.Count - 1].ForeColor = System.Drawing.Color.Green;
        }
    }
}

Monday, 22 July 2013

Using Label control to create looping marquee text in c# winform

public partial class FrmMarqueeText : Form
{
    private int xPos = 0, YPos = 0;

    public FrmMarqueeText()
    {
        InitializeComponent();
    }

    private void FrmMarqueeText_Load(object sender, EventArgs e)
    {

            lblText.Text = "Hello this is marquee text";
            xPos = lblText.Location.X;
            YPos = lblText.Location.Y;
            timer1.Start();


    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (xPos == 0)
        {

            this.lblText.Location = new System.Drawing.Point(this.Width, YPos);
            xPos = this.Width;
        }
        else
        {
            this.lblText.Location = new System.Drawing.Point(xPos, YPos);
            xPos -= 2;
        }
    }

Tuesday, 16 July 2013

Web Services GridEditing


SERVICE1.ASMX.CS


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using DAO;

namespace webservicetask123
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        Sample_Connection con = new Sample_Connection();
        string _connectionstring = null;
        SqlParameter[] _parameterset = null;

        public Service1()
        {
            _connectionstring = ConfigurationManager.ConnectionStrings["Developer"].ToString();
            con = new Sample_Connection(_connectionstring);
        }
        [WebMethod]
        public DataTable LoadEmp()
        {
            DataSet ds = SqlHelper.ExecuteDataset(_connectionstring, CommandType.StoredProcedure, "[practicegd]");
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
        }
        [WebMethod]
        public int insert(Details _objdetails)
        {
            _parameterset = SqlParameterCache.GetSpParameterSet(_connectionstring, "[gdinsert]");
            _parameterset[0].Value = _objdetails.EmpName;
            _parameterset[1].Value = _objdetails.EmpSal;
            _parameterset[2].Value = _objdetails.Address;
            _parameterset[3].Value = _objdetails.Email;
            int i = SqlHelper.ExecuteNonQuery(_connectionstring, CommandType.StoredProcedure, "[gdinsert]", _parameterset);
            return i;
        }
        [WebMethod]
        public int update(Details _objdetails)
        {
            _parameterset = SqlParameterCache.GetSpParameterSet(_connectionstring, "[gdupdate]");
            _parameterset[0].Value = _objdetails.EmpId;
            _parameterset[1].Value = _objdetails.EmpName;
            _parameterset[2].Value = _objdetails.EmpSal;
            _parameterset[3].Value = _objdetails.Address;
            _parameterset[4].Value = _objdetails.Email;
            int i = SqlHelper.ExecuteNonQuery(_connectionstring, CommandType.StoredProcedure, "[gdupdate]", _parameterset);
            return i;
        }
        [WebMethod]
        public int delete(int EmpId)
        {
            _parameterset = SqlParameterCache.GetSpParameterSet(_connectionstring, "[gddelete]");
            _parameterset[0].Value = EmpId;
            int i = SqlHelper.ExecuteNonQuery(_connectionstring, CommandType.StoredProcedure, "[gddelete]", _parameterset);
            return i;
        }
      }

    [Serializable]
    public class Details
    {
        int _EmpId;
        string _EmpName;
        string _EmpSal;
        string _Address;
        string _Email;

        public int EmpId
        {
            set { _EmpId = value; }
            get { return _EmpId; }
        }
        public string EmpName
        {
            set { _EmpName = value; }
            get { return _EmpName; }
        }
        public string EmpSal
        {
            set { _EmpSal = value; }
            get { return _EmpSal; }
        }
        public string Address
        {
            set { _Address = value; }
            get { return _Address; }
        }
        public string Email
        {
            set { _Email = value; }
            get { return _Email; }
        }

    }
}


AND DAO LAYER.....

 

CONSUMING 

 

Default Source

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="webservicetaskconsuming._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="EmpId" ShowFooter="true"
    AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" Width="82px"
    AutoGenerateColumns="false" onrowcancelingedit="GridView1_RowCancelingEdit"
        onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" >
    <Columns>
    <asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="true" />
   
    <asp:TemplateField HeaderText="EmpName">
    <ItemTemplate>
    <%#Eval("EmpName") %>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtEmpName" runat="server" Text='<%#Eval("EmpName")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFooterName" runat="server"></asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
   
    <asp:TemplateField HeaderText="EmpSal">
    <ItemTemplate>
    <%#Eval("EmpSal") %>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtEmpSal" runat="server" Text='<%#Eval("EmpSal")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFooterSal" runat="server"></asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
   
   <asp:TemplateField HeaderText="Address">
    <ItemTemplate>
    <%#Eval("Address") %>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtAddress" runat="server" Text='<%#Eval("Address")%>'></asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFooterAddress" runat="server"></asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
   
   <asp:TemplateField HeaderText="Email">
   <ItemTemplate>
   <%#Eval("Email") %>
   </ItemTemplate>
   <EditItemTemplate>
<asp:TextBox ID="txtEmail" runat="server" Text='<%#Eval("Email") %>'></asp:TextBox>
   </EditItemTemplate>
   <FooterTemplate>
   <asp:TextBox ID="txtFooterEmail" runat="server"></asp:TextBox>
   </FooterTemplate>
   </asp:TemplateField>
  <asp:TemplateField HeaderText="Insert">
  <FooterTemplate>
  <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btninsert"/>
  </FooterTemplate>
  </asp:TemplateField>
    </Columns>
   
    </asp:GridView>
    <asp:Label ID="lblMsg" runat="server"></asp:Label>
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit"
        onclick="btnSubmit_Click" />
    <br />
    <asp:GridView ID="GridView2" runat="server"
            >
    </asp:GridView>

        U can send these details to ur mail<br />

    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>
</body>
</html>










 

DEFAULT.ASPX.CS

 

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.Data.SqlClient;
using System.Drawing;
using System.Configuration;
using System.Net.Mail;
using System.Text;
using System.IO;
namespace webservicetaskconsuming
{
    public partial class _Default : System.Web.UI.Page
    {

        santhosh.Service1 _objgrid = new santhosh.Service1();
        santhosh.Details _objdetails = new santhosh.Details();
        DataTable _dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                TextBox1.Focus();
                gridbind();
                ViewState["sample"] = (DataTable)GridView1.DataSource;


            }


        }
        public void gridbind()
        {
            _dt = _objgrid.LoadEmp();
            GridView1.DataSource = _dt;
            GridView1.DataBind();
        }


        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            GridView1.EditIndex = -1;
            gridbind();

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            gridbind();
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            TextBox txtEmpName = (TextBox)(GridView1.Rows[GridView1.EditIndex].FindControl("txtEmpName"));
            TextBox txtEmpSal = (TextBox)(GridView1.Rows[GridView1.EditIndex].FindControl("txtEmpSal"));
            TextBox txtAddress = (TextBox)(GridView1.Rows[GridView1.EditIndex].FindControl("txtAddress"));
            TextBox txtEmail = (TextBox)(GridView1.Rows[GridView1.EditIndex].FindControl("txtEmail"));
            _objdetails.EmpId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            _objdetails.EmpName = txtEmpName.Text;
            _objdetails.EmpSal = txtEmpSal.Text;
            _objdetails.Address = txtAddress.Text;
            _objdetails.Email = txtEmail.Text;
            int i = _objgrid.update(_objdetails);
            if (i > 0)
            {
                lblMsg.Text = "UpDated Sucessfully";

            }
            else
            {
                lblMsg.Text = "Updation Falied";
            }
            GridView1.EditIndex = -1;
            gridbind();
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int EmpId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
            int i = _objgrid.delete(EmpId);
            if (i > 0)
            {
                lblMsg.Text = "deleted Successfully";
            }
            else
            {
                lblMsg.Text = "deletion failed";
            }
            GridView1.EditIndex = -1;
            gridbind();
        }
        protected void btninsert(object sender, EventArgs e)
        {
            TextBox txtFooterName = (TextBox)(GridView1.FooterRow.FindControl("txtFooterName"));
            TextBox txtFooterSal = (TextBox)(GridView1.FooterRow.FindControl("txtFooterSal"));
            TextBox txtFooterAddress = (TextBox)(GridView1.FooterRow.FindControl("txtFooterAddress"));
            TextBox txtFooterEmail = (TextBox)(GridView1.FooterRow.FindControl("txtFooterEmail"));
            _objdetails.EmpName = txtFooterName.Text;
            _objdetails.EmpSal = txtFooterSal.Text;
            _objdetails.Address = txtFooterAddress.Text;
            _objdetails.Email = txtFooterEmail.Text;
            int i = _objgrid.insert(_objdetails);
            if (i > 0)
            {
                lblMsg.Text = "Inserted Successfully";
            }
            else
            {
                lblMsg.Text = "Insertion failed";
            }
            GridView1.EditIndex = -1;
            gridbind();
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            _dt = (DataTable)ViewState["sample"];
            //_dt = _objgrid.LoadEmp();
            GridView2.DataSource = _dt;
            GridView2.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            string to =TextBox1.Text;
            string From = "rajshekarsanthosh@gmail.com";
            string subject = "Required info";
            string Body = "sir ,<br> Got the Output <br><br>";
            Body += GridViewToHtml(GridView2); //Elaborate this function detail later
            Body += "<br><br>Regards,<br>Santhosh";
            bool send = send_mail(to, From, subject, Body);//Elaborate this function detail later
            if (send == true)
            {
                string CloseWindow = "alert('Mail Sent Successfully!');";
                ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
            }
            else
            {
                string CloseWindow = "alert('Problem in Sending mail...try later!');";
                ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
            }
        }
        public bool send_mail(string to, string from, string subject, string body)
        {
            MailMessage msg = new MailMessage(from, to);
            msg.Subject = subject;
            AlternateView view;
            SmtpClient client;
            StringBuilder msgText = new StringBuilder();
            msgText.Append(" <html><body><br></body></html> <br><br><br>  " + body);
            view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");


            msg.AlternateViews.Add(view);
            client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.Credentials = new System.Net.NetworkCredential("rajshekarsanthosh@gmail.com", "raj123456");
            client.EnableSsl = true; //Gmail works on Server Secured Layer
            client.Send(msg);
            bool k = true;
            return k;
        }
        private string GridViewToHtml(GridView gv)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gv.RenderControl(hw);
            return sb.ToString();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {

        }

    }
}

Disable Back Button after Logout

  <script type = "text/javascript" >
        function disableBackButton() {
            window.history.forward();
        }
        setTimeout("disableBackButton()", 0);
     
</script>

Add this in masterpage

Text As WaterMark

DEFAULT.ASPX


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StringToImage.aspx.cs" Inherits="StringToImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Enter Text:
       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
       
       Enter WaterMark Text:  <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
       File Name:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
       <asp:Button ID="btnConvert" runat="server" OnClick="Button1_Click" Text="Covert" /><br />
         
        <asp:Image ID="Image1" runat="server" />

       <br />
    
    </div>
    </form>
</body>
</html>


DEFAULT.ASPX.CS


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Configuration;
using System.Text;
using System.Drawing.Drawing2D;

public partial class StringToImage : System.Web.UI.Page
{
    //string FileName = "MyImage";
    //string FontName = "Arial";
    //Color FontColor = Color.BlueViolet;
    //Color BackColor = Color.Red;
    //int Height = 250;
    //int Width = 50;
    //Color objColor;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string Text = TextBox1.Text;
        Color FontColor = Color.Black;
        Color BackColor = Color.Yellow;
        string FontName = "Times New Roman";
        int FontSize = 14;
        int Height = 200;
        int Width = 200;
        string FileName = TextBox3.Text;
        Bitmap objBitmap = new Bitmap(Width, Height);
        Graphics objGraphics = Graphics.FromImage(objBitmap);
        Color objColor;
        Font objFont = new Font(FontName, FontSize);
        PointF objPoint = new PointF(5f, 5f);
        SolidBrush objBrushForeColor = new SolidBrush(FontColor);
        SolidBrush objBrushBackColor = new SolidBrush(BackColor);
        objGraphics.FillRectangle(objBrushBackColor, 0, 0, Width, Height);
        objGraphics.DrawString(Text, objFont, objBrushForeColor, objPoint);
        //string From = ConfigurationManager.AppSettings["FromPath"].ToString();
        //string To = ConfigurationManager.AppSettings["ToPath"].ToString();
        string FromPath = @"C:\Documents and Settings\rajasekhary\Desktop\newfolder\TextAsWaterMark\Web\Image\" + FileName + ".GIF";
        ///string ToPath = @To + FileName + ".JPG";
        objBitmap.Save(FromPath, ImageFormat.Gif);
        //Image1.ImageUrl ="~/Questions/Original/" + FileName + ".JPG";
        string mainImage = @"C:\Documents and Settings\rajasekhary\Desktop\newfolder\TextAsWaterMark\Web\Image\" + FileName + ".GIF";
        ImageSetting(TextBox2.Text, "", mainImage);
        Image1.ImageUrl = "~/Image/" + FileName + "_new" + ".GIF";
    }
    void ImageSetting(string wmText, string wmImage, string mainImage)
    {
        byte[] imageBytes = null;
        if (File.Exists(mainImage))
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(mainImage);
            Graphics graphic;
            if (image.PixelFormat != PixelFormat.Indexed && image.PixelFormat != PixelFormat.Format8bppIndexed && image.PixelFormat != PixelFormat.Format4bppIndexed && image.PixelFormat != PixelFormat.Format1bppIndexed)
            {
                // Graphic is not a Indexed (GIF) image
                graphic = Graphics.FromImage(image);
            }
            else
            {
                /* Cannot create a graphics object from an indexed (GIF) image.
                 * So we're going to copy the image into a new bitmap so
                 * we can work with it. */
                Bitmap indexedImage = new Bitmap(image);
                graphic = Graphics.FromImage(indexedImage);

                // Draw the contents of the original bitmap onto the new bitmap.
                graphic.DrawImage(image, 0, 0, image.Width, image.Height);
                image = indexedImage;
            }
            graphic.SmoothingMode = SmoothingMode.AntiAlias & SmoothingMode.HighQuality;

            //Text Watermark properties
            Font myFont = new Font("Arial", 26, FontStyle.Bold);
            SolidBrush brush = new SolidBrush(Color.FromArgb(70, Color.Red));
            SizeF textSize = new SizeF();
            if (wmText != "")
                textSize = graphic.MeasureString(wmText, myFont);

            //Image Watermark
            System.Drawing.Image ig = null;
            if (wmImage != "")
                ig = System.Drawing.Image.FromFile(wmImage);

            //Code by me
            float y = (image.Height / 2) - (textSize.Height / 2);
            float x = (image.Width / 2) - (textSize.Width / 2);
            PointF pointF = new PointF(x, y);
            graphic.DrawString(wmText, myFont, brush, pointF);

            // Write the text watermark and image watermark across the main image.
            /*for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    PointF pointF = new PointF(x, y);
                    if (wmText != "")
                    {
                        graphic.DrawString(wmText, myFont, brush, pointF);
                        x += Convert.ToInt32(textSize.Width);
                    }
                    if (wmImage != "")
                    {
                        graphic.DrawImage(ig, pointF);
                        x += Convert.ToInt32(ig.Width);
                    }
                }
                if (wmText != "")
                    y += Convert.ToInt32(textSize.Height);
                if (wmImage != "")
                    y += Convert.ToInt32(ig.Height);
            }*/
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // save image in memoryStream with it format which get it from GetImageFormat function
                image.Save(memoryStream, GetImageFormat(mainImage));
                imageBytes = memoryStream.ToArray();
            }
            graphic.Dispose();
        }
        //Image1.ImageUrl="
        MemoryStream ms = new MemoryStream(imageBytes);
        System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
        //save new image and rename it;
        returnImage.Save(mainImage.Insert(mainImage.LastIndexOf("."), "_new"));
        ms.Dispose();
        returnImage.Dispose();
    }

    //Bitmap ConvertStringToImage(string inputString)
    //{
        
    //    Bitmap b = new Bitmap(250, 50);

    //    Font f = new Font("Arial", 15F);
    //    PointF objPoint = new PointF(5f, 5f);

    //    Graphics g = Graphics.FromImage(b);

    //    SolidBrush whiteBrush = new SolidBrush(Color.BlueViolet);
    //    SolidBrush blackBrush = new SolidBrush(Color.Red);

    //    RectangleF canvas = new RectangleF(0, 0, 250, 50);

    //    g.FillRectangle(whiteBrush, canvas);
    //    g.DrawString(inputString, f, blackBrush, canvas);
    //    b.Save(@"E:\" + FileName + ".GIF", ImageFormat.Gif);
    //    return b;
    //}

    ImageFormat GetImageFormat(String path)
    {
        switch (Path.GetExtension(path).ToLower())
        {
            case ".bmp": return ImageFormat.Bmp;
            case ".gif": return ImageFormat.Gif;
            case ".jpg": return ImageFormat.Jpeg;
            case ".png": return ImageFormat.Png;
            default: return null;
        }
    }
}

Show Richtextbox selected word in messagebox in winforms..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       private string RichWordOver(RichTextBox rch, int x, int y)
        {
       
            int pos = rch.GetCharIndexFromPosition(new Point(x, y));
            if (pos <= 0) return "";

       
            string txt = rch.Text;

            int start_pos;
            for (start_pos = pos; start_pos >= 0; start_pos--)
            {
             
                char ch = txt[start_pos];
                if (!char.IsLetterOrDigit(ch) && !(ch=='_')) break;
            }
            start_pos++;
            int end_pos;
            for (end_pos = pos; end_pos < txt.Length; end_pos++)
            {
                char ch = txt[end_pos];
                if (!char.IsLetterOrDigit(ch) && !(ch == '_')) break;
            }
            end_pos--;

         
            if (start_pos > end_pos) return "";
            return txt.Substring(start_pos, end_pos - start_pos + 1);
        }

     
        private void rchText_MouseMove(object sender, MouseEventArgs e)
        {
            MessageBox.Show(RichWordOver(rchText, e.X, e.Y));
        }
   
    }
}
           

Friday, 12 July 2013

Create Database Schema Diagram in SQL Server

Create Database Schema Diagram in SQL Server

Introduction

Here I will explain how to create database schema diagram in SQL Server 2008.

Description
 
In previous articles I explained 
Insert values in identity column in SQL ServerCheck if string contains specific word in SQLSQL Query to read xml fileSQL Query to get duplicate records countSQL Query to convert lower case to upper case and many articles relating to SQL ServerjQueryJavaScript. Now I will explain how to create database schema diagram in SQL Server 2008.

To create database schema diagram in SQL Server 2008 you need to follow below steps

1. First open SQL Server Management Studio and connect to the database for which you need to generate schema diagram in object explorer

2. Now expand your database by click on + icon in left side. Once Database expand you have option Database Diagrams like as shown below   

3. Now right click on Database Diagram -à now select New Database Diagram and click on it that will be like as shown below

4. Now one new window will open in that select required tables to generate diagram or select all the tables to generate diagram. Once you select tables click Add button.

5. You can change the view of tables by right click on it and select Table View option.

6. Once everything done click on PrtScn button and paste it in paint to generate image.

what is stored procedure in Sql server | what are the advantages of using stored procedures in sql server


A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

Advantages of using stored procedures

a)    a) Stored procedure allows modular programming. 

You can create the procedure once, store it in the database, and call it any number of times in your program. 

b)    b) Stored Procedure allows faster execution. 

If the operation requires a large amount of SQL code is performed repetitively, stored procedures can be faster. They are parsed and optimized when they are first executed, and a compiled version of the stored procedure remains in memory cache for later use. This means the stored procedure does not need to be reparsed and reoptimized with each use resulting in much faster execution times. 

c)     c) Stored Procedure can reduce network traffic. 

An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.

d)    d) Stored procedures provide better security to your data

Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly.

In SQL we are having different types of stored procedures are there

a)    System Stored Procedures
b)    User Defined Stored procedures
c)    Extended Stored Procedures

System Stored Procedures:

System stored procedures are stored in the master database and these are starts with a sp_ prefix. These procedures can be used to perform variety of tasks to support sql server functions for external application calls in the system tables 

Ex: sp_helptext [StoredProcedure_Name]

User Defined Stored Procedures:

User Defined stored procedures are usually stored in a user database and are typically designed to complete the tasks in the user database. While coding these procedures don’t use sp_ prefix because if we use the sp_ prefix first it will check master database then it comes to user defined database

Extended Stored Procedures:

Extended stored procedures are the procedures that call functions from DLL files. Now a day’s extended stored procedures are depreciated for that reason it would be better to avoid using of Extended Stored procedures.