Search This Blog

Friday, October 21, 2011

Inserting and Retrieving images from SQL Server Database using C#

Database
1.Create a database named TestImage
2.create a table called test_table holding two columns id_image(datatype: nvarchar[50]) and pic(datatype: image). 
Front End 


1.create a new project in visual studio
2.select windows application, language c# and name it as TestImage

3. drop two labels, a textbox, a combo box, three buttons and two picture boxes on your win form as shown below

4.
The first picture box will only displays the image you are going to save in your database    providing some id in   the textbox (I used this to just recall the image from database) once      an image is loaded on the clicking      event of Store button we are going to insert that         image with provided ID into the database and the combo box will load itself with all   available IDs in our database. By selecting an id we and clicking Retrieve the respective image will be shown in the second picture box. 
5.double click the button.It will create a button click event.
Here declare a global string
string imagename;
a data adapter
SqlDataAdapter empadap1;
and a dataset
DataSet dset;
you will also require to use System.IO and System.Data.SqlClient
using System.IO;
 
using System.Data.SqlClient;

now we need to create a method to insert our image into the database and second method to retrieve all images. I named the method inserting my image into the database as update() and to retrieve my images I named my method as connection(). Now update() uses filestream to convert the image into binary data since image datatype in SQL Server 2005 use to store binary data in its image datatype. While connection() simply convert that binary data to an image using identical technique for us. Code for both the methods is:
private void updatedata()
{
 
//use filestream object to read the image.
 
//read to the full length of image to a byte array.
 
//add this byte as an oracle parameter and insert it into database.
 
try
{
 
//proceed only when the image has a valid path
 
if (imagename != "")
{
 
FileStream fs;
 
fs = new FileStream(@imagename, FileMode.Open, FileAccess.Read);
 
//a byte array to read the image
 
byte[] picbyte = new byte[fs.Length];
 
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
 
fs.Close();
 
//open the database using odp.net and insert the data
 
string connstr = @"Data Source=.;Initial Catalog=TestImage;
                Persist Security Info=True;User ID=sa";
 
SqlConnection conn = new SqlConnection(connstr);
 
conn.Open();
 
string query;
 
query = "insert into test_table(id_image,pic) values(" + 
textBox1.Text + "," + " @pic)";
 
SqlParameter picparameter = new SqlParameter();
 
picparameter.SqlDbType = SqlDbType.Image;
 
picparameter.ParameterName = "pic";
 
picparameter.Value = picbyte;
 
SqlCommand cmd = new SqlCommand(query, conn);
 
cmd.Parameters.Add(picparameter);
 
cmd.ExecuteNonQuery();
 
MessageBox.Show("Image Added");
 
cmd.Dispose();
 
conn.Close();
 
conn.Dispose();
 
Connection();
 
}
 
}
 
catch (Exception ex)
{
 
MessageBox.Show(ex.Message);
 
}
 
}
 
//----------------------------------------
 
private void Connection()
{
 
//connect to the database and table
 
//selecting all the columns
 
//adding the name column alone to the combobox
 
try
{
 
string connstr = @"Data Source=.;Initial Catalog=TestImage;

            Persist Security Info=True;User ID=sa";
 
SqlConnection conn = new SqlConnection(connstr);
 
conn.Open();
 
empadap1 = new SqlDataAdapter();
 
empadap1.SelectCommand = new SqlCommand("SELECT * FROM test_table"

            , conn);
 
dset = new DataSet("dset");
 
empadap1.Fill(dset);
 
DataTable dtable;
 
dtable = dset.Tables[0];
 
comboBox1.Items.Clear();
 
foreach (DataRow drow in dtable.Rows)
{
 
comboBox1.Items.Add(drow[0].ToString());
 
comboBox1.SelectedIndex = 0;
 
}
 
}
 
catch (Exception ex)
{
 
MessageBox.Show(ex.Message);
 
}
 
}
now double click the Load button and write the code lines:

try
{
 
FileDialog fldlg = new OpenFileDialog();
 
//specify your own initial directory
 
fldlg.InitialDirectory = @":D\";
 
//this will allow only those file extensions to be added
 
fldlg.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
 
if (fldlg.ShowDialog() == DialogResult.OK)
{
 
imagename = fldlg.FileName;
 
Bitmap newimg = new Bitmap(imagename);
 
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
 
pictureBox1.Image = (Image)newimg;
 
}
 
fldlg = null;
 
}
 
catch (System.ArgumentException ae)
{
 
imagename = " ";
 
MessageBox.Show(ae.Message.ToString());
 
}
 
catch (Exception ex)
{
 
MessageBox.Show(ex.Message.ToString());
 
}
Now double click Store button and call the update () method to insert selected image into the database.
updatedata();
the update method itself calls connection() therefore combo box will be filled with IDs of images exits in database, one can use the connection method in anyway the person likes.
Finally double click Retrieve button and write
DataTable dataTable = dset.Tables[0];
 
//if there is an already an image in picturebox, then delete it
 
if (pictureBox2.Image != null)
{
 
pictureBox2.Image.Dispose();
 
}
 
//using filestream object write the column as bytes and store 
        it as an image
 
FileStream FS1 = new FileStream("image.jpg", FileMode.Create);
 
foreach (DataRow dataRow in dataTable.Rows)
{
 
if (dataRow[0].ToString() == comboBox1.SelectedItem.ToString())
{
 
byte[] blob = (byte[])dataRow[1];
 
FS1.Write(blob, 0, blob.Length);
 
FS1.Close();
 
FS1 = null;
 
pictureBox2.Image = Image.FromFile("image.jpg");
 
pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
 
pictureBox2.Refresh();
 
}
 
}


Friday, August 5, 2011

AJAX ModalPopup Demonstration

The ModalPopup extender allows a page to display content to the user in a "modal" manner which prevents the user from interacting with the rest of the page. The modal content can be any hierarchy of controls and is displayed above a background that can have a custom style applied to it. When displayed, only the modal content can be interacted with; clicking on the rest of the page does nothing. When the user is done interacting with the modal content, a click of an OK/Cancel control dismisses the modal content and optionally runs custom script. The custom script will typically be used to apply whatever changes were made while the modal mode was active. If a postback is required, simply allow the OK/Cancel control to postback and the page to re-render. You can also absolutely position a modal popup by setting the X and Y properties. By default it is centered on the page, however if just X or Y is specified then it is centered vertically or horizontally.
ModalPopup Properties



The control above is initialized with this code. The display on the modal popup element is set to none to avoid a flicker on render. The italic properties are optional:
<ajaxToolkit:ModalPopupExtender ID="MPE" runat="server"
    TargetControlID="LinkButton1"
    PopupControlID="Panel1"
    BackgroundCssClass="modalBackground" 
    DropShadow="true" 
    OkControlID="OkButton" 
    OnOkScript="onOk()"
    CancelControlID="CancelButton" 
    PopupDragHandleControlID="Panel3" />
  • TargetControlID - The ID of the element that activates the modal popup
  • PopupControlID - The ID of the element to display as a modal popup
  • BackgroundCssClass - The CSS class to apply to the background when the modal popup is displayed
  • DropShadow - True to automatically add a drop-shadow to the modal popup
  • OkControlID - The ID of the element that dismisses the modal popup
  • OnOkScript - Script to run when the modal popup is dismissed with the OkControlID
  • CancelControlID - The ID of the element that cancels the modal popup
  • OnCancelScript - Script to run when the modal popup is dismissed with the CancelControlID
  • PopupDragHandleControlID - The ID of the embedded element that contains the popup header/title which will be used as a drag handle
  • X - The X coordinate of the top/left corner of the modal popup (the popup will be centered horizontally if not specified)
  • Y - The Y coordinate of the top/left corner of the modal popup (the popup will be centered vertically if not specified)
  • RepositionMode - The setting that determines if the popup needs to be repositioned when the window is resized or scrolled.

AJAX AutoComplete Demonstration

AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup panel to display words that begin with the prefix typed into the textbox.
AutoComplete Properties :
The textbox is linked with an AutoCompleteExtender which is initialized with this code. Theitalic properties are optional:



<ajaxToolkit:AutoCompleteExtender 
    runat="server" 
    ID="autoComplete1" 
    TargetControlID="myTextBox"
    ServiceMethod="GetCompletionList"
    ServicePath="AutoComplete.asmx"
    MinimumPrefixLength="2" 
    CompletionInterval="1000"
    EnableCaching="true"
    CompletionSetCount="20" 
    CompletionListCssClass="autocomplete_completionListElement" 
    CompletionListItemCssClass="autocomplete_listItem" 
    CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
    DelimiterCharacters=";, :"
    ShowOnlyCurrentWordInCompletionListItem="true">
        <Animations>
            <OnShow> ... </OnShow>
            <OnHide> ... </OnHide>
        </Animations>
</ajaxToolkit:AutoCompleteExtender>
    
  • TargetControlID - The TextBox control where the user types content to be automatically completed
  • ServiceMethod - The web service method to be called. The signature of this method must match the following:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] GetCompletionList(string prefixText, int count) { ... }
    Note that you can replace "GetCompletionList" with a name of your choice, but the return type and parameter name and type must exactly match, including case.
  • ServicePath - The path to the web service that the extender will pull the word\sentence completions from. If this is not provided, the service method should be a page method.
  • ContextKey - User/page specific context provided to an optional overload of the web method described by ServiceMethod/ServicePath. If the context key is used, it should have the same signature with an additional parameter named contextKey of type string:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] GetCompletionList(
        string prefixText, int count, string contextKey) { ... }
    Note that you can replace "GetCompletionList" with a name of your choice, but the return type and parameter name and type must exactly match, including case.
  • UseContextKey - Whether or not the ContextKey property should be used. This will be automatically enabled if the ContextKey property is ever set (on either the client or the server). If the context key is used, it should have the same signature with an additional parameter named contextKey of type string (as described above).
  • MinimumPrefixLength - Minimum number of characters that must be entered before getting suggestions from the web service.
  • CompletionInterval - Time in milliseconds when the timer will kick in to get suggestions using the web service.
  • EnableCaching - Whether client side caching is enabled.
  • CompletionSetCount - Number of suggestions to be retrieved from the web service.
  • CompletionListCssClass - Css Class that will be used to style the completion list flyout.
  • CompletionListItemCssClass - Css Class that will be used to style an item in the AutoComplete list flyout.
  • CompletionListHighlightedItemCssClass - Css Class that will be used to style a highlighted item in the AutoComplete list flyout.
  • DelimiterCharacters - Specifies one or more character(s) used to separate words. The text in the AutoComplete textbox is tokenized using these characters and the webservice completes the last token.
  • FirstRowSelected - Determines if the first option in the AutoComplete list will be selected by default.
  • ShowOnlyCurrentWordInCompletionListItem - If true and DelimiterCharacters are specified, then the AutoComplete list items display suggestions for the current word to be completed and do not display the rest of the tokens.
  • Animations - Generic animations for the AutoComplete extender. See the Using Animations walkthrough and Animation Reference for more details.
    • OnShow - The OnShow animation will be played each time the AutoComplete completion list is displayed. The completion list will be positioned correctly but hidden. The animation can use <HideAction Visible="true" /> to display the completion list along with any other visual effects.
    • OnHide - The OnHide animation will be played each time the AutoComplete completion list is hidden.

Thursday, July 21, 2011

*FREE* Download of MSDN Library For Visual Studio 2008 SP1

*FREE* Download of MSDN Library For Visual Studio 2008 SP1

Dot net interview questions and answers

1.              How many weg.configs can an application have?
 An application can have any number of web.config files but each file in a separate folder.
 if an application has 5 folders then the application can have 5 web.config files in the folders + 1    web.config file in root directory
2.            Differences between application and session?
  Application state does not change for end user
  session state is create for every user


3.             What are the 2 types of polymorphism supports in .NET?
 Compile time and run time polymorphism


4.             Explain a class access specifies and method access specifies?
 There is 5 access specifies
public
protected
private
internal
protected internal


5.             Explain virtual function and its usage.
>> it’s tell compiler that this method might be override


6.             How do you implement inhetance in .NET?
>> in c# using :
in Vb inhertans


7.             If I want to override a method 1 of class A and this class B then how do you declared
class B : A
{
public override method1()
{}
}
8.             Explain friend and protected friend?
 friend == this type of members is available for all classs those are in same assembly
 protected friend == same assembly classs and drive classs can able to access this type of members

9.             Explain multiple and multi_level inheritance in .NET?
 multiple == class A : intehert interface1,interface2
multi_level == class A {}
class B : A {}
class c : B {}


10.           What is isPostback property?
 it’s check this page is load first time .It is using to avoid round trips to the server..

11.            Diff b/w DataGrid and GridView?
The great advantage of the GridView over the DataGrid is its support for code-free scenarios. Using
the GridView, you can accomplish many common tasks, such as paging and selection, without writing
any code. With the DataGrid, you were forced to handle events to implement the same features.


12.          what is abstrat class ?
 The abstract class cannot be inherited when the abstract keyword is specified to the destined class