Friday, September 23, 2011

LINQ WITH DELEGATES CONCEPTS

Normal query string:
===================

static void Main(string[] args)
        {
            string[] names = { "chitharans", "naga", "ravi", "praveen", "chith", "hello", "welcome" };
            IEnumerable<string> query123 = from sss in names where sss.Length >= 4 orderby sss descending  select sss.ToUpper();
            foreach (string item in query123)
                Console.WriteLine(item);
            Console.ReadKey();
        }


Funtion  using query string:
=========================================

  static void Main(string[] args)
        {
            string[] names = { "chitharans", "naga", "ravi", "praveen", "chith", "hello", "welcome" };
            Func<string, bool> one = sss => sss.Length >= 4;
            Func<string, string> two = sss => sss;
            Func<string, string> three = sss => sss.ToUpper();
            IEnumerable<string> query123 = names.Where(one).OrderBy(two).Select(three);
          
            foreach (string item in query123)
                Console.WriteLine(item);
            Console.ReadKey();
        }

Delegates using query string:
============================

 static void Main(string[] args)
        {
            string[] names = { "chitharans", "naga", "ravi", "praveen", "chith", "hello", "welcome" };
            Func<string, bool> one = delegate(string sss)
            {
                return sss.Length>=4;
            };
            Func<string, string> two = delegate(string sss)
            {
                return sss;
            };
            Func<string, string> three = delegate(string sss)
            {
                return sss.ToUpper();
            };



           
            IEnumerable<string> query123 = names.Where(one).OrderBy(two).Select(three);
         
            foreach (string item in query123)
                Console.WriteLine(item);
            Console.ReadKey();
        }

Thursday, September 15, 2011

Creating Visual State Manager(Media Player)

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SLVSMMediaPlayer
{
    public partial class VSMPlayer1 : UserControl
    {
        public VSMPlayer1()
        {
            // Required to initialize variables
            InitializeComponent();
            Loaded +=new RoutedEventHandler(VSMPlayer1_Loaded);
        }
      
        void VSMPlayer1_Loaded(object sender, RoutedEventArgs e)
        {
          
            LayoutRoot.MouseEnter +=new MouseEventHandler(LayoutRoot_MouseEnter);
            LayoutRoot.MouseLeave += new MouseEventHandler(LayoutRoot_MouseLeave);
            button.Click += new RoutedEventHandler(button_Click);
            button1.Click += new RoutedEventHandler(button1_Click);
           
           
        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            mymedia.Pause();
        }

        void button_Click(object sender, RoutedEventArgs e)
        {
           // throw new NotImplementedException();
            mymedia.Play();
        }

        void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
        {
            //throw new NotImplementedException();
            VisualStateManager.GoToState(this,"MouseLeave", true);
        }

        void LayoutRoot_MouseEnter(object sender, MouseEventArgs e)
        {
            //throw new NotImplementedException();
            VisualStateManager.GoToState(this, "MouseEnter", true);
        }
    }
}

Thursday, September 8, 2011

Silverlight and the layout management. (Grid, Canvas, StackPanel and dock panel)






If you have done any Silverlight development, then you are familiar with the Canvas, the Grid and the StackPanel.
All 3 containers are unique in their own way. But they all have some limitations/drawbacks. Let's see:
1: The Canvas:
<Canvas Background="Blue">
   <TextBlock Height="50" Width="50" Canvas.Left="15" Canvas.Top="15" />
</Canvas>
I don't want to pixelate my items.
2: The StackPanel: 
<StackPanel>
   <TextBlock Height="50" Width="50" />
   <TextBlock Height="50" Width="50" />  
</StackPanel>
Just not rich enough to do any complex layouts.
3: The Grid:
<Grid Background="Silver">
   <Grid.ColumnDefinitions>
       <ColumnDefinition Width="*2" />
       <ColumnDefinition Width="*1" />
   </Grid.ColumnDefinitions>
   <Grid.RowDefinitions>
       <RowDefinition Height="50" />
       <RowDefinition Height="100" />
   </Grid.RowDefinitions>
   <TextBlock Height="50" Width="50" Grid.Row="1" Grid.Column="1"/>
</Grid>
Yes, I can define a very complex layout using the Grid. But I am still required to place my items inside "a" cell by specifying
the Grid.Row and Grid.Column attributes on each individual item. I also need to decide, how may rows and columns my page has.
This just does not feel natural.
To address this, Developer Express is working on a special LayoutControl container that will eliminate these hassles. All you have to do is specify where you want
your items placed. Left, Right, Top or Bottom.
<DockedLayoutControl x:Name="layoutItems" DockedLayoutControl.Dock="Client">
            <TextBlock Text="My Top Text" DockedLayoutControl.Dock="Left"/>
            <TextBlock Text="My Bottom Text" DockedLayoutControl.Dock="Bottom"/>
</DockedLayoutControl>
Here is a screen shot of a layout done using a DockedLayoutContro

Wednesday, September 7, 2011

Creating Stored Procedure?,Calling Stored Procedure,Inserting Data to Stored Procedure

Sample image

Introduction

There are several advantages of using stored procedures instead of standard SQL. First, stored procedures allow a lot more flexibility offering capabilities such as conditional logic. Second, because stored procedures are stored within the DBMS, bandwidth and execution time are reduced. This is because a single stored procedure can execute a complex set of SQL statements. Third, SQL Server pre-compiles stored procedures such that they execute optimally. Fourth, client developers are abstracted from complex designs. They would simply need to know the stored procedure's name and the type of data it returns.

Creating Stored Procedure?

Enterprise Manager provides an easy way to create stored procedures. First, select the database to create the stored procedure on. Expand the database node, right-click on "Stored Procedures" and select "New Stored Procedure...". You should see the following:
CREATE PROCEDURE [OWNER].[PROCEDURE NAME] AS
Substitute OWNER with "dbo" (database owner) and PROCEDURE NAME with the name of the procedure. For example:
CREATE PROCEDURE [dbo].[GetProducts] AS So far, we are telling SQL Server to create a new stored procedure with the name GetProducts. We specify the body of the procedure after the AS clause:
CREATE PROCEDURE [dbo].[GetProducts] AS SELECT ProductID, ProductName FROM Products Click on the Check Syntax button in order to confirm that the stored procedure is syntactically correct. Please note that the GetProducts example above will work on the Northwind sample database that comes with SQL Server. Modify it as necessary to suite the database you are using.
Now that we have created a stored procedure, we will examine how to call it from within a C# application

Calling Stored Procedure

A very nice aspect of ADO.NET is that it allows the developer to call a stored procedure in almost the exact same way as a standard SQL statement.

1. Create a new C# Windows Application project.

2. From the Toolbox, drag and drop a DataGrid onto the Form. Resize it as necessary.

3. Double-click on the Form to generate the Form_Load event handler. Before entering any code, add "using System.Data.SqlClient" at the top of the file.

Enter the following code:
private void Form1_Load(object sender, System.EventArgs e) {
SqlConnection conn = new SqlConnection("Data
Source=localhost;Database=db_first;Integrated Security=SSPI"
);
SqlCommand command = new SqlCommand("GetProducts", conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds, "Products");
this.dg_Data.DataSource = ds;

this.dg_Data.DataMember = "Products";

Inserting Data to Stored Procedure

Using other SQL statements such as INSERT, UPDATE or DELETE follow the same procedure. First, create a stored procedure that may or may not accept parameters, and then call the stored procedure from within the code supply the necessary values if parameters are needed. The following example illustrates how to insert a new user in a users table that has a username and password field.
Sql Server Code
CREATE PROCEDURE [dbo].[InsertUser] (
@Username varchar(50), @Password varchar(50)
)
AS INSERT INTO Users VALUES(@Username, @Password)


C# code
string username = Username.Text // get username from user string //
password = Password.Text // get password from user

SqlConnection conn = new SqlConnection"
DataSource=localhost;Database=db_First;Integrated Security=SSPI"
);
SqlCommand command = new SqlCommand("InsertUser", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Username", SqlDbType.VarChar).Value = username;
command.Parameters.Add("@Password", SqlDbType.VarChar).Value = password;
conn.Open(); int rows = command.ExecuteNonQuery();
conn.Close();
First, we retrieve the username and password information from the user. This information may be entered onto a form, through a message dialog or through some other method. The point is, the user specifies the username and password and the applicaton inserts the data into the database. Also notice that we called the ExecuteNonQuery() method of the Connection object. We call this method to indicate that the stored procedure does not return results for a query but rather an integer indicating how many rows were affected by the executed statement. ExecuteNonQuery() is used for DML statements such as INSERT, UPDATE and DELETE. Note that we can test the value of rows to check if the stored procedure inserted the data successfully.
<code>if (rows == 1) {
MessageBox.Show("Create new user SUCCESS!");
}
else {
MessageBox.Show("Create new user FAILED!"); }
We check the value of rows to see if it is equal to one. Since our stored procedure only did one insert operation and if it is successful, the ExecuteNonQuery() method should return 1 to indicate the one row that was inserted. For other SQL statements, especially UPDATE and DELETE statements that affect more than one row, the stored procedure will return the number of rows affected by the statement.

Conclusion

Stored procedures offer developers a lot of flexibility with many features not available using standard SQL. ADO.NET allows us to use stored procedures in our applications seamlessly. The combination of these two allows us to create very powerful appliations rapidly.
enjoyyyyyyyyyyyyyyyyyyyyyyyyyy

insert values to database throw sp with c# coding..

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;
using System.Data.SqlClient;

namespace Wininsert
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


            string Phcname = textBox1.Text;
            string Chcname = textBox2.Text;
            string Location = textBox3.Text;
            string Address = textBox4.Text;
            try
            {
                SqlConnection sqlcon = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ilink;Data Source=.");
                   SqlCommand Cmd = new SqlCommand("Employeedetails", sqlcon);
                    Cmd.CommandType = CommandType.StoredProcedure;
                    Cmd.Parameters.Add("@Phcname", SqlDbType.VarChar).Value = textBox1.Text;
                    Cmd.Parameters.Add("@Chcname", SqlDbType.VarChar).Value = textBox2.Text;
                    Cmd.Parameters.Add("@Location", SqlDbType.VarChar).Value = textBox3.Text;
                    Cmd.Parameters.Add("@Address", SqlDbType.VarChar).Value = textBox4.Text;
                sqlcon.Open();
                int rows = Cmd.ExecuteNonQuery();
                if (rows == 1)
                {
                    MessageBox.Show("created successfully");


                }
                else
                {
                    MessageBox.Show("creation failed");
                }
               //Cmd.ExecuteNonQuery();
                sqlcon.Close();

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
   

       
public  string Employeedetails { get; set; }}
    }

Thursday, September 1, 2011

// Source Code for saving the image file into the database//


public void OnUpload(Object sender, EventArgs e)
{
  // Create a byte[] from the input file

  int len = Upload.PostedFile.ContentLength;
  byte[] pic = new byte[len];
  Upload.PostedFile.InputStream.Read (pic, 0, len);
  // Insert the image and comment into the database

  SqlConnection connection = new
  SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=i ndia");
  try
  {
    connection.Open ();
    SqlCommand cmd = new SqlCommand ("insert into Image "
    + "(Picture, Comment) values (@pic, @text)", connection);
    cmd.Parameters.Add ("@pic", pic);
    cmd.Parameters.Add ("@text", Comment.Text);
    cmd.ExecuteNonQuery ();
  }
  finally
  {
  connection.Close ();
  }
}

Primary and Foreign key using table.

use chitharans
create table NewBusiness1
(
businessid int identity(2010,10) not null,
businessname varchar(20) not null,
companyname varchar(20) not null,
startingdate datetime not null,
endingdate datetime not null

CONSTRAINT [PK_ NewBusiness1] PRIMARY KEY CLUSTERED
(
    [businessid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO