Asp.net & Sql server fundas with Rajat Jaiswal

December 21, 2009

File Download in asp.net in 5 minutes

Filed under: Asp.net — indiandotnet @ 6:20 pm
Tags: , ,

Hello friends,

It’s almost 2 week that I did not post any article friends sorry for that busy in some other high priority task. Today we will work on how to download a file with asp.net which exists in database.

So friends here we go.

Let us suppose we have a table of document in which we keep document in binary format. Suppose the table structure is as follows.
lngId
strFileName
strDescription
strContentType
binDocumentFile

Now what we have to do is by passing just lngId we will download the file or open in browser.
The code for doing this so simple.
Which I mention below

Dim sqlcon as New Sqlconnection(strConnectionString)
Sqlcon.open()
Dim ds as new dataset
Dim sqlcmd as new sqlcommand
Sqlcmd.connection =sqlcon
Sqlcmd.commandType = commandtype.storeprocedure
Sqlcmd.commandtext = “proc_getDocumentById”
Sqlcmd.parameters.add(“@lngId”,intDocumentId) ‘int documented is lngID of document
Dim sda as new sqldataAdapter
Sda.selectCommand = sqlcmd
Sda.fill(ds)

If ds Is Nothing = False AndAlso ds.tables(0).rows.count >0 Then
Dim dr As dataRow = ds.tables(0).Rows(0)
Context.Response.Clear()
Context.Response.ContentType = dr (“DOCTYPE”).ToString()
Dim intLength As Integer = DirectCast(dr (“DOCDATA”), Byte()).Length()
Context.Response.AddHeader(“Content-Disposition”, “inline;filename=” & dr (“DOCNAME”))
‘ Context.Response.AddHeader(“Content-Disposition”, “attachment;filename=” & dr (“DOCNAME”))
Context.Response.AddHeader(“content-length”, intLength)
Context.Response.AddHeader(“Pragma”, “public”)
Context.Response.AddHeader(“Cache-Control”, “public”)
Context.Response.CacheControl = “public”
Context.Response.BinaryWrite(DirectCast(dr(“DOCDATA”), Byte()))
Context.Response.End()
dR = nothing
end If
Ds = nothing
Sqlcmd = nothing
Sqlcon = nothing
Sda = nothing

Now the main important point here is content – disposition, and content type
Content type is basically type of content which we are going to download like, JPEG, word, text, etc
And content disposition describe that whether you want download the file or open in browser.
If you want to open in browser then use “inline” and if you want to download then use “attachment” in disposition setting.

So in this way we easily download and kind of file.
If you feel any kind of suggestion, discussions feel free to contact.

Thanks & Esteemed Regards
Rajat Jaiswal

December 2, 2009

Host your site with me in free

Filed under: Asp.net — indiandotnet @ 5:17 pm
Tags: , , ,

Hello friends Here are some free hosting services which I prefer to use. I would like to share this with you so that you will also create your account on this and use free services of hosting from this hosting units.

1) Web Host for Asp :-

 

 2) Brinskter :-

 

3) 7 Host:-

 \

Other than this there are some other services which provide free asp.net hosting like aspspider.net. So enjoy your work with this.
Thanks &
regards
Rajat Jaiswal

November 29, 2009

Create Multilevel Grid in 5 Minutes in 5 easy steps

Filed under: Asp.net — indiandotnet @ 4:57 am
Tags: ,

Hello Friends ,
Today we will create multilevel grid in simplest manner. So here I go.
Here for example I am taking northwind database and our requirment is to determine Category & its products.
Means category is parent and product is chid.Now here are some basic steps just follow it and you will get hierachical grid.
Step 1:- Drag drop a dataGrid on page and define column according to your need.
  @@asp:DataGrid ID=”dgCategoryParent” runat=”server” AutoGenerateColumns=”False$$
            @@Columns$$
                @@asp:BoundColumn DataField=”CategoryId” Visible=”false”@@ @@/asp:BoundColumn$$
                @@asp:TemplateColumn$$
                    @@HeaderTemplate$$
                       @@table border=”1″ width=”100%”$$
                            @@tr$$
                                @@td width=”1″$$    @@/td$$
                                @@td$$  Category  @@/td$$
                                @@td$$Description @@/td$$
                            @@/tr$$
                        @@/table$$
                    @@/HeaderTemplate$$
                    @@ItemTemplate$$
                        @@table border=”1″ width=”100%”$$
                            @@tr$$ @@td width=”1″$$ @@asp:Button ID=”btnTest” runat=”server” Text=”+” /$$
                                @@/td$$td$$
                                    @@asp:Label ID=”lblCategory” runat=”server” Text=’@@%# DataBinder.Eval(Container, “DataItem.CategoryName”) %$$’$$ @@/asp:Label$$
                                @@/td$$
                                @@td$$
                                    @@asp:Label ID=”lblDescription” runat=”server” Text=’@@%# DataBinder.Eval(Container, “DataItem.Description”) %$$’$$@@/asp:Label$$
                                @@/td$$
                            @@/tr$$
                            @@tr$$
                                @@td colspan=”3″$$
                                    @@asp:DataGrid ID=”dgProductChild” runat=”server” AutoGenerateColumns=”false” CellPadding=”4″
                                        ForeColor=”#333333″ GridLines=”Both” $$
                                        @@FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” /$$
                                        @@EditItemStyle BackColor=”#999999″ /$$
                                        @@SelectedItemStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ /$$
                                        @@PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” /$$
                                        @@AlternatingItemStyle BackColor=”White” ForeColor=”#284775″ /$$
                                        @@ItemStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ /$$
                                        @@Columns$$
                                            @@asp:BoundColumn DataField=”productName” HeaderText=”Product”$$@@/asp:BoundColumn$$
                                            @@asp:BoundColumn DataField=”UnitPrice” HeaderText=”Unit price”$$@@/asp:BoundColumn$$
                                            @@asp:BoundColumn DataField=”Quantityperunit” HeaderText=”Quantity per unit”$$@@/asp:BoundColumn$$
                                        @@/Columns$$
                                    @@/asp:DataGrid$$
                                @@/td$$
                            @@/tr$$
                        @@/table$$
                    @@/ItemTemplate$$
                @@/asp:TemplateColumn$$
            @@/Columns$$
            @@HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” /$$
        @@/asp:DataGrid$$

Step 2:-
Now step 2 is to bindGrid for this we have wrote following code.
Remember here we just binding our first data which is related to parent means “Category”

Dim sqlcon As New SqlConnection(strCONNECTIONSTRING)
sqlcon.Open()
Dim sqlcmd As New SqlCommand
sqlcmd.CommandText = "SELECT categoryId,categoryName,description FROM categories"
sqlcmd.CommandType = CommandType.Text
sqlcmd.Connection = sqlcon
Dim ds As New DataSet
Dim sda As New SqlDataAdapter
sda.SelectCommand = sqlcmd
sda.Fill(ds)
Me.dgCategoryParent.DataSource = ds
Me.dgCategoryParent.DataBind()
sqlcon.Close()
sqlcon = Nothing

Step 3:- Now as we now there is row data Bound event on this event our action is to bind
So just find the child control ” product DataGrid ” and bind it. As shown below

 Protected Sub dgCategoryParent_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgCategoryParent.ItemDataBound
Try
Dim blnBind As Boolean = False
Select Case e.Item.ItemType
Case ListItemType.Item
blnBind = True
Case ListItemType.AlternatingItem
blnBind = True
Case Else
blnBind = False
End Select
If blnBind = True Then
Dim intId As Integer = e.Item.Cells(0).Text
Dim MyGrid As DataGrid
Dim mybtn As Button
mybtn = CType(e.Item.FindControl("btnTest"), Button)
MyGrid = CType(e.Item.FindControl("dgProductChild"), DataGrid)
If MyGrid Is Nothing = False AndAlso mybtn Is Nothing = False Then
mybtn.Attributes.Add("Onclick", "javascript: return myvisiblity('" & mybtn.ClientID & "','" & MyGrid.ClientID & "')")
Me.pvtBindProductForCategory(intId, MyGrid)
End If

End If

Catch ex As Exception
Throw ex
End Try
End Sub

 

Step 4:- more over if you want collapse property than add a button on main row and apply java script on it. see below function for it

myvisiblity(str, gridId) { var myBtn1 = document.getElementById(str) var mygrid1 = document.getElementById(gridId); if (myBtn1.value == "+") { mygrid1.style.display = 'none'; myBtn1.value = "-"; } else { mygrid1.style.display = 'block'; myBtn1.value = "+"; } return false; }
You will find a collasible datagrid.

Step 5 : here is your final output


I hope you understand the startegy here.

You can download code at
Enjoy programming!

Thanks & Esteemed Regards
Rajat Jaiswal

November 15, 2009

How to improve AJAX page Speed with 5 easy steps

Filed under: Asp.net, ajax — indiandotnet @ 12:27 pm
Tags: ,

Hello friends,

Many times we face the Ajax speed problem. Our AJAX page is very slow.

So here I am with  five valuable tips checkout if it helps you some where. 

1)      EnablePartialRendering:-

 Make enable partial rendering = true in script manager

Its syntax is as shown below

“<asp:ScriptManager ID=”scm” runat=”server”  EnablePartialRendering =”true”   >”

It enable partial rendering so use does n’t have to wait a long for page.

Remember its useful only when you have multiple panel update. 

2)      Script Refrence Profiler dll:-

This is one of the most important DLL by which you can imporve your page performance.

Its simple in use you have to do just drag and drop Script refrence profiler in Div. Then run the page it will give you all refrence Scripts.

As shown below fig.

 ScriptRefrence1

 Just copy this and page in script tag of Script manager as shown below.

<asp:ScriptManager ID=”scm” runat=”server”  EnablePartialRendering =”true”   >

    <Scripts>

<asp:ScriptReference path=”../Includes/Scripts/System.Web.Extensions/1.0.61025.0/MicrosoftAjax.js”/>

</script>

</asp:scriptManager> 

3)      Script Mode=”Release”:- 

Try to make script mode always release for better performance.

You have to do following setting

<asp:ScriptManager ID=”scm” runat=”server”  ScriptMode =”Release”>

 4)      LoadScriptBeforeUI=”false”:-

This should be false for better result. When you do this then screen comes fast.

 5)      Composite Script:-

 If you are using Asp.net 3.5 with service pack 1 then there will be a nice tag which is called Composite script tag.

By the name its clear that it composite all the script its syntax is as follows.

<asp:ScriptManager ID=”scm” runat=”server”  ScriptMode =”Release”>

<CompositeScript ScriptMode =”Release”>

     <Scripts>

        <asp:ScriptReference Name=”MicrosoftAjax.js” ScriptMode=”Auto” Path=”../Includes/Scripts/System.Web.Extensions/1.0.61025.0/MicrosoftAjax.js”>

        </asp:ScriptReference>

        <asp:ScriptReference Name=”MicrosoftAjax.debug.js” ScriptMode=”Auto” Path=”../Includes/Scripts/System.Web.Extensions/1.0.61025.0/MicrosoftAjax.debug.js”>

        </asp:ScriptReference>

        </script>

</compositeScript>

 If you find any error related size then just concentrate on following link its very good to solve that kind of problem.

http://bellouti.wordpress.com/2008/09/14/combining-javascript-files-with-ajax-toolkit-library/

 So ,friends in this way we improve our AJAX Page.

I hope you like this so enjoy AJAX.

 Thanks

Rajat Jaiswal

November 14, 2009

Some useful Terminology (acronyms)

Filed under: Ado.net Data Services, Asp.net, Astoria, JUERY, LINQ, MVC, WCF, WPF, XML, ajax — indiandotnet @ 5:22 am
Tags: , , , ,

Hello friends,
Cheers!
Here I am with some useful terminology and these acronyms are generally used now days in broad way take a look.
1) ESB : Enterprise Service Bus
2) POX : Plain OLD XML
3) REST: Representational State Transfer
4) SOAP: Simple Object Access Protocol
5) RIA : Rich Internet Application
6) XML : Extensible Markup Language
7) JASON: Java Script Object Notation
8) DOM : Document Object Modeling
9) XAML : Extensible Application Markup Language
10) LINQ : Language Integrated Query
11) RSS: Really Simple Syndication
12) WCF: Windows Communication Foundation
13) WF: Windows Foundation
14) WPF: Windows Presentation Foundation
15) AJAX: Asynchronous Java script and XML
16) XLST: Extensible Style Sheet Language Transformation
17) INDIGO: Code name of Microsoft windows Communication foundation Technology
18) OSLO: Code name of Microsoft Modeling Technology
19) SOA: Service Oriented Architecture
20) ORCAS: dot net 3.5 Version called ORCAS
21) AVALON: code name of Microsoft Windows Presentation foundation Technology
22) Azure: Microsoft new Operation system Related to Cloud computing
23) Astoria : Code name of Ado.net Data services

I hope you people like it.
Enjoy life with dot net.

Your host
Rajat Jaiswal

November 8, 2009

WPF Windows Persentaion Foundation with me PART- II

Filed under: Asp.net, Silverlight, WPF — indiandotnet @ 12:35 pm
Tags: , , ,

Hello friends,
In this session we are going to take a look how do we connect a silver light application with database.
So here I would like to say that there are basically 4 options by which you can handle database in silver light application.
1) WCF for Silver light
2) Ado.net Data Services
3) Web services
4) RIA Services (need to explore more)

Here I will explain how to connect your WPF Silver light application with database using well know Web service.
It’s easy and I think we all already work on some part of Web services.

So let’s start with it.
We have added a silver light navigation project. In navigation silver light project part we have added 2 new pages employee, register page.
Employee page is for show employee list,And register page is for register employee.


Just see project structure as below.

projectPhoto

And In web part we have added a new web service with name my services.
Whose functionality to save, updates, Delete, and read all employee record.
As shown in below fig.

MyWebService

Now our next step is how to integrate this web service with silver light.
For this we add a services reference in our navigation project with the help of Add services reference menu as shown below.

AddServices

Now you can rename name space according to your choice.

If you do not get any error in referencing then till now you are ok with your work.
Now our next step is calling web method in our pages.
Here I am taking first page which is employee list
We are calling web method which returns all employee lists so here we go.

Private Sub EmployeePage_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Try
Dim myBinding As New ServiceModel.BasicHttpBinding()
Dim myEndPoint As New ServiceModel.EndpointAddress(New Uri(“http://localhost/MyTest/MyWebService.asmx”, UriKind.Absolute))
Dim proxy As New MyWebServiceSoapClient(myBinding, myEndPoint)
proxy.pub_ReadAllDataAsync()
AddHandler proxy.pub_ReadAllDataCompleted, AddressOf proxy_ReadAllEmployeeCompleted

Catch ex As Exception

End Try
End Sub

Private Sub proxy_ReadAllEmployeeCompleted(ByVal sender As Object, ByVal e As myService.pub_ReadAllDataCompletedEventArgs)
Try
Me.myGrid.ItemsSource = e.Result
Catch ex As Exception
Me.HeaderText.Text = ex.InnerException.Message.ToString
End Try
End Sub

Now things to remember here
1) Dim myBinding As New ServiceModel.BasicHttpBinding()
Its shows the binding is http binding
2) Dim myEndPoint As New ServiceModel.EndpointAddress(New Uri(“http://localhost/MyTest/MyWebService.asmx”, UriKind.Absolute))
Here the path can be absolute or relative.

3) Next you have to call web method like we have call here proxy.pub_ReadAllDataAsync()
4) once we have call the method asyncronously then we have to make a event handler like we have create here

AddHandler proxy.pub_ReadAllDataCompleted, AddressOf proxy_ReadAllEmployeeCompleted

5) when the asyncronous method is complete we have to take result complete argument and covert according to our requirement.
I have just bind the result to datagrid and get below screen.
Just see below.

employeeList

So friends in this way we can call web service in a Silverlight application.

Still we can use DataServices, RIA services, and WCF services for data manipulation application.

Hope in next few chapter we will take this example and work on it.

That’s all friends, thanks for reading the article.

Happy programming!

Thanks
Rajat

November 1, 2009

WPF Windows Persentaion Foundation with me PART- I

Filed under: Asp.net, Silverlight, WPF — indiandotnet @ 9:43 am
Tags: , ,

Hello friends,

Today we will discuss one of the most popular technologies which are silver light.
Before going forward you have some query in your mind. As I have so we will first solve that. See following questions.
1. What is Silver light?
Answer: – Silver Light is programmable web browser plug in, that enable feature such like vector graphics, animation and audio, video play back. It provide cross browser compatibility.
Its main aim to provide RIA (Rich Internet Application).Its Consistency with WPF (Windows Presentation Foundation). XAML (extensible Application Markup Language) is base of Silver light.
Its main use to provide end user a rich web application experience
Silver light basically used for RIA (Rich Internet Application) and with help of it we can make user friendly and all browser supported web sites.

2. What is XAML?
Answer: – XAML is core of Windows Presentation foundation. Its full form is Extensible Application Markup Language it’s just like a xml language with certain fixed tags. Like canvas, rectangle, grid etc…

3) From where I can download toolkit?
Answer: – We can download silver light 3.0 toolkits from http://www.silverlight.net site which is official site.

Here I will explain basic example of silver light. We are going to make a simple add 2 integer programs. I know you all aware of this but I started this for step by step progress in silver light.
For this you have to first install 3.0.
Once you have installed silver light 3.0 you will get following projects in asp.net new project window. Just select silver light application in this.

NewProject

Once you have selected this then next screen comes up for the web site or web application selection. As shown below. I have selected web application.

SilverlightOption

After selecting web application project you will get 2 projects in your solution explorer one is for silver light in which there will be .XAML file. And another one is web application which is used to call XAML file in the compile format which is called XAP.

ProjectExplore
Now we start our actual work of making 2 digit sums in silver light application
For this we have to select mainPage.xaml.
In this XAML page we have to put all the control which is requiring like textbox, label or Text Block and button.
Suppose we have to add a TextBlock in page then see below lines

 Here x:Name is like id in our ASPX page it should be unique. Grid.Row = 0 and grid.column =0 shows position in grid.

Now similarly if you want to add a label and Textbox and button then
You have to follow below code.
<dataInput:Label x:Name=”lblResult” Grid.Row=”3″ Grid.ColumnSpan=”2″ HorizontalAlignment=”Center”></dataInput:Label>

<TextBox x:Name=”txtSecond” Width=”100″ HorizontalAlignment=”Left” Grid.Row=”1″ Grid.Column=”1″></TextBox >

< Button Name=”btnAdd” Content=”Add” Click=”btnAdd_Click” Width=”100″Grid.Row=”2″ Grid.ColumnSpan=”2″ HorizontalAlignment = “Center” >
</Button >
So the main this which you have to concentrate for alignment, colors.
In Next post we will come up with some solid project base & tool kit understanding.

till than  happy programming.

Thanks
Rajat

October 31, 2009

Nice utilities for Web Developer

Filed under: Asp.net, JUERY — indiandotnet @ 12:18 pm
Tags: , , ,

Hello friends,

Today I come up with some useful list which help you in web development and good news is that its all free.
1) “FIREBUG” :-
Basically “FIREBUG” is add in for FireFox. It’s a great utility helps a lot to design web pages. As a developer I am mostly intrested in programming not designing.But this utility help me in solving designing issues. With the help of it you can manage designing ,CSS issues.
You can download this from https://addons.mozilla.org/en-US/firefox/addon/1843
2) Web Development Helper:-
This one is another useful utitly for web developer to improve performance. Its basically help you to determine which page taking how much time to response.It also help other area also like script finding. It has dom Inspector also. You can take help of this tool in various way.
You can download this from http://projects.nikhilk.net/WebDevHelper
3) Deep Zoom composer:- If you are working on Silverlight also then you can use Deep Zoom composer.it has very nice feature for images.
You can dowload this from http://www.microsoft.com/downloads/details.aspx?familyid=457b17b7-52bf-4bda-87a3-fa8a4673f8bf&displaylang=en

So just dowload & use this tools and improve your code.

Happy programming!

Thanks …
Your host
Rajat

October 25, 2009

How to change VS.NET 2008 IDE colorful and make it attractive in 5 minutes?

Filed under: Asp.net — indiandotnet @ 5:41 pm

Hello friends,
I know you are some time bored by same IDE. So here I am helping you out to make your IDE environment colorful as shown below fig.

IDE

Microsoft gives you full hands on IDE Environment to make your IDE attractive and enjoy dot net programming.
So for this you have to follow below steps.
1) Go to tool –> import and export Setting

1
2) Select the option as shown below.

2
3) In next step you can save your existing IDE Settings as shown below fig.

3
4)in next step just browse your require IDE settings (all the IDE settings has extension “VSSettings”) Like “rajat.vsSettings” just browse the file and click on finish button and what you will see is amazed cool coloful VS IDE.

4
I have attached some of the files just rename them with .vsSettings.

1) Colourful black

2) IndianTouch

3)RajatSpecial

Remember to rename this doc file to “.VsSettings”

Just use the wizard and you will get attractive IDE.
So enjoy colorful programming and IDE.
Make your coding colorful.

Thanks & regards
Rajat Jaiswal

October 4, 2009

Basic Threading with dotnet

Filed under: Asp.net — indiandotnet @ 1:04 pm
Tags: , ,

Hello friends,
Some time I really scared when I listen threading, but when I dive in threading pool its really fun and interesting also.
As per my knowledge what ever I got by learning from different books and web sites I will give you some basic knowledge which you will use and enjoy.
So first thing is what is threading? So here we go. When we talk about multi tasking, multi processing then threading word comes in action. Suppose you have a agile code which will run on a button click but the problem is when user click the button its hang up user screen for a while but you want user screen to be free and allow user to do some other task which he wants. Or similar thing in code also.
In this situation you require threading. It will improve user interaction and performance of your code also.

So start with basic the base class in dot net for threading is System.Threading

I will just write a code how to start a thread so it will much better to understand.

Suppose on button click we want to create a thread which will count number
Private Sub btnStartThread_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartThread.Click

Dim myThread As Threading.Thread = New System.Threading.Thread(New Threading.ThreadStart(AddressOf Me.pvt_NumberCounter))
myThread.Start()
MsgBox(“Next statement after thread!!!!”, MsgBoxStyle.Critical, “Rajat”)

End Sub

In the above lines what we are doing we are creating a delegate for a method which pvt_NumberCounter which count the number and assign it to mythread object.
Then to start thread or to activate thread we wrote mythread.start()
Which make thread active. Method pvt_NumberCounter() get in action.
While after mythread.start() statement message box also execute.
Means controls remain in start thread button.

In this way the thread can start.
There are some states of thread which will call thread state by which we can know what is the current position or state of a thread. For understanding thread you must understand thread state. Go through below fig and table.

ThreadStates

Action

ThreadState

A thread is created within the common language runtime.

Unstarted

A thread calls Start

Running

The thread starts running.

Running

The thread calls Sleep

WaitSleepJoin

The thread calls Wait on another object.

WaitSleepJoin

The thread calls Join on another thread.

WaitSleepJoin

Another thread calls Interrupt

Running

Another thread calls Suspend

SuspendRequested

The thread responds to a Suspend request.

Suspended

Another thread calls Resume

Running

Another thread calls Abort

AbortRequested

The thread responds to a Abort request.

Stopped

A thread is terminated.

Stopped

 

 

 

 

 

 

 

Now your mind has one question we started Thread, we have seen thread state but how to kill a thread explicitly I know you are very destructive mind : D but it was also in my mind so here is simple property which we have to use.
Which is Abort(). Sounds interesting.
You can kill a thread explicitly by thread.abort() statement.
So friends its over for me for this article i will bring some more stuff later on.
till then keep programming, keep visiting.
Thanks
Rajat

Next Page »

Blog at WordPress.com.