Thursday, August 27, 2009

Image loading and saving in database in WPF using VB :-

WPF image uploading :-

In many forms we need to upload an image..In WPF we have imagebox in which we can upload an image..For that code is :-

<Button Height="23" HorizontalAlignment="Right" Margin="0,100,35,0" Name="btnBrowse" VerticalAlignment="Top" Width="75">Browse</Button>

Above is the code for button which will be used for browsing file path of that image.

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnBrowse.Click
Dim ofd As New OpenFileDialog
If ofd.ShowDialog() Then
Dim fs As New FileStream(ofd.FileName, FileMode.Open)
Dim imgs As New ImageSourceConverter
Dim dat(fs.Length) As Byte
fs.Read(dat, 0, fs.Length)
fs.Close()
imgcompImage.SetValue(Image.SourceProperty, imgs.ConvertFromString(ofd.FileName.ToString()))
End If
End Sub

This code is the code which uploads image and saves it in database..For using few functions like ShowDialog() etc we need to import few namespaces as given below :-

Imports System.Windows.Media.Animation
Imports System.Windows.Navigation
Imports Microsoft.Win32
Imports System.Windows.Controls.Image
Imports System.Windows.Media.Imaging
Imports System.IO.MemoryStream

OpenFileDialog is to open a file while ShowDialog shows us the file path..SetValue function shows us the image on our page..To store image in database we read image in bytes as shown above in code and then store it in database..So now you can use image uploader in ur page..

Tuesday, August 25, 2009

WPF Toolkit Datagrid

DataGrid is part of User Interface.It is used for displaying data in tabular format.It provides sorting and editing functions. For using DataGrid in WPF

toolkit you have to first install WPF Toolkit. This Toolkit is open source. Datagrid is used for providing functions like create,update,delete,read on any data

source.Now lets start building our own WPF Application in which we will use a Datagrid....

For installing toolkit basic requirement is .Net Framework 3.5 SP1..If you have this installed on your machine you can install WPF Toolkit..For that you will

have to download WPF Toolkit (source or Binaries). You will get this here http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29117
When downloading is done run WPFToolkit.msi to install the WPFToolkit.dll and WPF Toolkit design time binaries to your Program Files folder.

When you start coding basic things which you have to do are :

1) Reference WPFToolkit.dll in your project
2) Import "Microsoft.Windows.Controls" in ur vb code.
3) In your XAML file you will have to add a new xmlns "http://schemas.microsoft.com/wpf/2008/toolkit" at the top of XAML file. Example showing this will be given

below..

Lets take a simple example of Categories table which include columns catId (Category Id), catName (Category Name), catDesc (Category Description), parcatId

(Parent Category Id) in database..From this catId is integer,catName and catDesc is string while parcatId is also integer in database but while displaying for user we

want to display it in dropdown (combobox for datagrid here) which shows catName in list but gets saved as integer in database..So lets start coding...


<Page x:Class="pgCategory"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="509" Height="409"

<Grid>
</Grid>
</Page>

This is the basic part generated when you open an XAML page..

xmlns:dd="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

These are two important things of adding references like that of toolkit without which you cant include Datagrid in your form..

Now lets see datagrid part..

<Grid.Resources>
<ObjectDataProvider x:Key="categoryDataProvider" ObjectType="{x:Type local:Categories}" MethodName="GetCategories"/>
</Grid.Resources>

Here ObjectDataProvider defines an instance of the above class as our data source which includes objecttype and methodname through which it gives data..

<dg:DataGrid AlternatingRowBackground="AliceBlue"
AutoGenerateColumns="False"
CanUserAddRows="True"
CanUserDeleteRows="True"
Height="151"
IsReadOnly="False"
ItemsSource="{Binding Path=.}"
MaxColumnWidth="500"
MinColumnWidth="50"
Name="pgCategoryDG"
RowBackground="White"
RowDetailsVisibilityMode="VisibleWhenSelected"
RowHeaderWidth="25"
SelectionUnit="FullRow"
VerticalAlignment="Bottom"
Loaded="pgCategoryDG_Loaded" MouseDoubleClick="pgCategoryDG_MouseDoubleClick">

<dg:DataGrid.Columns>
<dg:DataGridTextColumn x:Name="dgcatName" Header="Category Name" Width="100" Binding="{Binding catName}" IsReadOnly="False"/>
<dg:DataGridTextColumn x:Name="dgcatDesc" Header="Category Description" Width="125" Binding="{Binding catDesc}" IsReadOnly="false"/>
<dg:DataGridComboBoxColumn SelectedValueBinding="{Binding parcatId}" SelectedValuePath="parcatId" DisplayMemberPath="catName" ItemsSource="{Binding

Source={StaticResource categoryDataProvider}}"/>
</dg:DataGrid.Columns>
</dg:DataGrid>
<Button HorizontalAlignment="Left" Margin="165,148,0,0" Name="btnSave" Width="75" Height="23" VerticalAlignment="Top">Save</Button>

Here combobox is used for dropdown list in which parcatId is gonna be considered and catName wil be displayed..Many other properties of datagrid are mentioned

here above..Also there is a Save button which when clicked things will be saved in databse..Based on this XAML file is our vb code which is as follows :-

Imports System.Windows.Controls
Imports System.Windows.Data

Partial Public Class pgCategory

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSave.Click
Dim dtCategories As System.Data.DataTable = pgCategoryDG.DataContext
Dim dtDeleted As System.Data.DataTable
For Each r As System.Data.DataRow In dtCategories.Rows
If r.RowState = DataRowState.Modified Then
modGlobal.objInventoryService.UpdateCategories(r.Item(0), r.Item(1), r.Item(2), r.Item(3))
ElseIf r.RowState = DataRowState.Added Then
If IsDBNull(r.Item(1)) Then
MsgBox("Enter CatName!!!")
Else
If IsDBNull(r.Item(3)) Then
If IsDBNull(r.Item(2)) Then
modGlobal.objInventoryService.InsertCategory(r.Item(1), "")
Else
modGlobal.objInventoryService.InsertCategory(r.Item(1), r.Item(2))
End If
Else
If IsDBNull(r.Item(2)) Then
modGlobal.objInventoryService.InsertCategories(r.Item(1), "", r.Item(3))
Else
modGlobal.objInventoryService.InsertCategories(r.Item(1), r.Item(2), r.Item(3))
End If
End If
End If
End If
Next
dtDeleted = dtCategories.GetChanges(DataRowState.Deleted)
If Not dtDeleted Is Nothing Then
dtDeleted.RejectChanges()
For i As Integer = 0 To dtDeleted.Rows.Count - 1
modGlobal.objInventoryService.DeleteCategories(dtDeleted.Rows(i)(0))
Next
End If
dtCategories.AcceptChanges()
End Sub


Private Sub pgCategoryDG_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim a As System.Data.DataSet
a = modGlobal.objInventoryService.RetriveCategories()
pgCategoryDG.DataContext = a.Tables.Item(0)
End Sub


Public Class Categories
Public Function GetCategories() As System.Data.DataView
Dim a As System.Data.DataSet
a = modGlobal.objInventoryService.RetriveCategories()
Return a.Tables.Item(0).DefaultView
End Function
End Class

Here we have created another class called Categories which we have used for ObjectDataProvider. When form loads to display all data from database in Datagrid

we have written function Loaded. In code of Save button we have written code for inserting,deleting and updating. In that we have checked each row whether its Modified

(Update), Added (Insert), Deleted (Delete)..Based on that rowstate we can call our functions.

So this is the whole code for creating a datagrid project..I hope it will help you all to create your own Datagrid projects..I will post more blogs on Datagrid soon..

Sunday, August 16, 2009

DEVCON Event :-

Biggest event in Pune DEVCON was held on 8-9th August in Pune..This event was held in COEP,Pune..Inspite of the destruction named Swine Flu event was successfull..2 days event had a very nice grip in lectures given by speakers like Amol Vaidya,Abhishek Kant,Dhaval Faria,Dr. Nitin Paranjpe, Mayur Tendulkar, Raj Chaudhary,Sanjay Vyas,Sarang Datye, Vikram Pendse, Vic Parmar and many more..Many topics like Silverlight3,JQuery,Azure etc were covered in this event..I was managing registration desk and goodies..All enjoyed sessions also were keen for all topics..All got lot of knowledge from all sessions..Despite of swine flu thing speaker came from across India like Mumbai, Hyderabad, Bengaluru, Pune.. and lot of thanks to audience as well..thats the true spirit of community!!! Special thanks to Mahesh Mitkari and all volunteers..

Thursday, July 23, 2009

DEVCON Event :-

The biggest event DEVCON is here once again in Pune..Its going to be held on 8-9 August 09..Industry experts speakers going to give sessions on interesting topics like .Net 4.0,Silverlight,Windows Azure,Visual Studio 2010 etc..Do not miss it :-) For FREE registration and other details visit site http://www.puneusergroup.org/events/devcon2009/

Tuesday, July 7, 2009

ADO.NET output parameter in VB

This is used to give a direction to output parameter. When we write a stored procedure and when we declare output parameter in it in which we have to store output. This output parameter we have to declare in code also. While adding this parameter in code we have to use ParameterDirection.Output.

Example : -

Stored Procedure : -

CREATE PROCEDURE [dbo].[USP_AuthenticateUsers]

@username nvarchar(255),
@password varbinary(MAX),
@userId int output,

AS
BEGIN

SET @userId=0

SELECT @userId=userId , @roleId=roleId FROM Users WHERE username=@username and [password]=@password
END


Code : -

Public Function AuthenticateUser(ByVal username As String, ByVal password As Byte(), ByVal userIPAddr As String) As structUserSession

Dim objCom As New System.Data.SqlClient.SqlCommand
objCom.CommandType = CommandType.StoredProcedure
objCom.CommandText = "USP_AuthenticateUsers"
objCom.Parameters.Add("userName", SqlDbType.NVarChar, 255).Value = username
objCom.Parameters.Add("password", SqlDbType.VarBinary, password.Length).Value = password
objCom.Parameters.Add("userId", SqlDbType.Int).Direction = ParameterDirection.Output

DB.ExecuteNonQuery(objCom)

Dim objStructUserSession As New structUserSession
objStructUserSession.userId = objCom.Parameters.Item("userId").Value

Return objStructUserSession

End Function

If Condition in SQL

If...Else statement is used to test a condition. If we have more than 1 condition we can use If...Else statement. We can also have nested If...Else statements also. We have nested If...Else statements when we have to include 1 or more If...Else statements in 1 If...Else statement. If...Else Statement in SQL is used in execution os Stored Procedures.

Syntax for simple If...Else statement is,

IF ( Condition )
BEGIN
Sql Statements
END
ELSE
BEGIN
Sql Statements
END

Syntax for nested If...Else statements is,

IF ( Condition )
BEGIN
Sql Statements
IF ( Condition )
BEGIN
Sql Statements
END
ELSE
BEGIN
Sql Statements
END
END

ELSE
BEGIN
Sql Statements
END


Example for simple If...Else statement is,

CREATE PROCEDURE [dbo].[USP_InsertUserSession]
@userId int,
@userSession nvarchar(255),
@userDate datetime,

AS
BEGIN
declare @tmpuserId int
SELECT @tmpuserId=userId from UsersSessions WHERE userId=@userId

if @tmpuserId > 0
begin
UPDATE UsersSessions SET userSession=@userSession, userDate=@userDate WHERE userId=@tmpuserId
end

else
begin
INSERT INTO UsersSessions(userId,userSession,userDate) VALUES (@userId,@userSession,@userDate)
end

Friday, June 26, 2009

TechEd on roads

Attended TechEd on roads on 21st June 09. We had sessions on Win 7 SDK, .NET 4.0,Silverlight 3.Session was from morning 10 to evening 5.30. Session was very interactive. Speakers were Dhaval Faria, Sarang Date, Vikram Pendse. I was handling registration desk. It was fun handling..

Monday, June 1, 2009

Training in MVJ college, Bangalore

Conducted 1 day training in MVJ college, Bangalore on 28th May for faculty members. Training was on basics of .net. Training included .net framework 3.5, ASP.net, ADO.net, Windows mobile etc. The training lasted from 10 am to 4 pm. Faculty members were very interactive.

Training in Ambedkar Institute of Technology, Bangalore

Conducted 1 day training in Ambedkar Institute of Technology, Bangalore on 2nd May for faculty members. Training was on basics of .net. Training included .net framework 3.5, ASP.net, ADO.net, Windows mobile etc. The training lasted from 10 am to 4 pm. Faculty members were very interactive.

Friday, May 1, 2009

What is Web Service?

Web Services are just like functions. We can define web service as a collection of functions which can be recalled. The description of this function calls is defined in a XML file called WSDL (Web Services Description Language). Functions are recalled through SOAP (Simple Object Access Protocol). This SOAP uses HTTP for transmission. XML is the basis for Web services. It provides a language which can be used between different platforms and programming language and still express complex messages and functions.So basically Web Services use XML to code and decode data and SOAP to transport it. Web Services are platform independent. They are also independent for the programming language. With Web Servics, Win 2k servers can be connected with UNIX servers.

Sunday, April 26, 2009

What is WCF?

WCF...Windows Communication Foundation..
* Its a programming framework used to build application that inter-communicate.
* Its code name is 'Indigo'. It was released in December-2006.
* WCF uses SOAP (Simple Object Access Protocol) messages between two processes. But while communicating with a non-WCF process, XML-based encoding is used for the SOAP messages.
* A WCF service is composed of 3 parts :
1) Service class that implements service to be provided.
2) host environment to host service.
3) one or more endpoints to which clients will connect.

Use of WCF :
* Because WCF can communicate using Web services, interoperability with other platforms that also support SOAP, such as the leading J2EE-based application servers, is straightforward.
* We can also configure and extend WCF to communicate with Web services using messages not based on SOAP, for example, simple XML formats like RSS.
* WCF helps provide reliability, security, and transactions when communicating with any platform.
* It is designed to interoperate well with the non-WCF applications.

Thursday, April 2, 2009

Session in Cummins college of engineering for Women

We took 1 day session and 2 days workshop on 27-28 February and 1st March in Cummins college of engineering for Women. Session was held for 2nd and 3rd year girls. In session we covered an introduction to .net,asp.net and ado.net.

Many girls attended the session. 4 staff members also attended the session. MSPs Sonali, Shrishti, Shaizeen also were involved in our session.

Thursday, January 29, 2009

What is Silverlight?

Silverlight is a combination of different technology into a single development platform that allows you to select tools and the programming language you want to use. Its a programmable web-browser plugin. It has features such as animation,vector ggraphics and audio-video playback.Its a cross-browser i.e. it works with all versions of all browsers to have existed since the web began. It can be implemented and inter-operated on multiple computer platforms. It aims to compete with Adobe Flash and presentation components of AJAX. It also computes with Sun Microsystems' JavaFX, which was launched few days after Silverlight. Silverlight supports Windows Media Audio and Video (WMA, WMV7–9) and VC-1, as well as MP3 audio. It is being designed to work in conjunction with XAML and is scriptable with JavaScript. Silverlight can also be used to create Windows Sidebar gadgets for Windows Vista. Silverlight exposes a Downloader object which can be used to download content, like scripts, media assets or other data, as may be required by the application.
For more information visit http://www.silverlight.net/

Monday, January 12, 2009

GridView AutoGenerateColumns

Till now we know that gridview generates autocolumns..But I wanted to get only 1 column in gridview..For that i found a solution that there is 1 property of gridview named as AutoGenerateColumns which is by default true.We just have to make it false so that we can manually generate columns how much we want..
Example as shown below..

< asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
< Columns>
< asp:BoundField DataField="quest" HeaderText="Questions" SortExpression="Questions" />
< asp:TemplateField>
< ItemTemplate>
< asp:Label ID="lblSelect" runat="server"> < a href="showOptions.aspx?qid=< %# Eval("QuesId") %> "> Select< /a> < /asp:Label>
< /ItemTemplate>
< /asp:TemplateField>
< /Columns>

< /asp:GridView>


Welcome to Ketaki's blog

Hello all..Welcome to my blog..Get ready to learn lot about technologies like .net etc..