Asp. NET interactive bitmap Form design (9)

Source: Internet
Author: User
Tags control characters empty inheritance soap printable characters visual studio
Asp.net| Interaction | Design passes status between page and request
For the application to work, it needs to be able to maintain the state between requests and pass the status to the drawing page, as shown below.

There are several ways to maintain and deliver state. If your application is a strict single-page application (as in previous applications), you can use view state, where the data is encoded to be stored in the hidden input field of the Web page.

But our image controls are drawing on separate pages, so we need something more flexible. The best choice is the cookie and session state. Session state is flexible, but requires server resources. Browsers can keep cookies, but their size is very limited.

Page_Load
Page_Load is invoked after the Page object is created and before all event handlers are run. So the Page_Load method is the ideal place to load persistent data. If no data is found, the new data is created. The following are the relevant code:


Private Sub Page_Load (ByVal sender as System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Randomgen = ViewState ("Randomgen")
If Randomgen is nothing Then Randomgen = New Random ()
' One of the options: Get a drawing list using session state
' (Saved in page_unload)
' (note: Require state storage on the server)
Drawinglist = Session ("Drawinglist")
If drawinglist is nothing Then drawinglist = New dshapelist ()
' Select two: From the cookie in the user's browser
' Retrieve drawing status
' (Note: No server storage is required, but some users will disable cookies)
' (Note the second: Cookies are not automatically deserialized!) :( )
' Note three: Use cookies to limit the number of shapes that can be drawn
' Dim drawingListCookie as HttpCookie
' drawingListCookie = Request.Cookies ("drawinglist")
' If drawingListCookie is nothing Then
' drawinglist = New dshapelist ()
' Else
' Drawinglist = _
' Serialhelper.deserializefrombase64string (_
' Drawinglistcookie.value)
' End If
End Sub

First, we try to load the random number generator state from the view state. If present, the stored value is used. If it does not exist, a new Random object is created.

Next, we try to load the drawing list from the session state. Similarly, if a drawing list does not exist, a new empty list is created.

View state and session state automatically serialize our objects if needed. View state is always serialized, so you can represent the encoded string that is hidden in the input field for the browser. Session state is serialized when it is stored in the database or passed between servers, but is not serialized if the application is running on a single server (for example, when testing on a development machine).

The annotated code attempted to load a drawing list from a cookie. Note that processing cookies is much more complicated than working with view or session state. The first is that it cannot be serialized automatically. To serialize to a string, we wrote the helper function in a new class, as follows:


Public Shared Function Deserializefrombase64string (_
ByVal base64string as String) as Object
Dim Formatter as New BinaryFormatter ()
Dim bytes () as Byte = Convert.frombase64string (base64string)
Dim Serialmemorystream as New MemoryStream (bytes)
Return formatter. Deserialize (Serialmemorystream)
End Function


The Dr. GUI uses a binary formatter and converts to a printable base 64 string because neither SOAP nor XML formatter is applicable to this application. We must convert from a pure binary representation to a base 64 string to avoid potential problems with controlling characters in a string because of simple copying of bytes. The base 64 string uses a single character-A-Z, A-Z, 0-9, +, or/(a total of 64 or 2^6 characters) to represent every six bits in a binary string. So four characters represent three bytes--the first character represents six bits in the first byte, the second character represents the last two digits of the first byte, and the second word The first four digits of the section, and so on. Similarly, using the base 64 string is key to limiting the string to printable characters, which avoids potential problems with any control characters.

The XML formatter does not serialize private data--and the Dr. GUI does not intend to add public access to the private data in the drawing list. The SOAP formatter does not have this restriction, but it does not serialize the empty list for deserialization. Instead, it writes nothing to the data stream for an empty list, so that an exception is thrown when an attempt is made to deserialize. (Dr. The GUI thinks this is a mistake. )

The Dr. GUI prefers to serialize in a readable XML format, but because neither XML serialization formatter can complete this work, the binary formatter is eventually selected and converted to a base 64 string.

Page_Unload
Page_Unload is called before it destroys a Page object (including any contained data), so it is an ideal place to permanently place important data so that we can take it out in the future from Page_Load (or from the Page_Load of the image).

Therefore, we save the data in Page_Unload and retrieve the data from the Page_Load. Strange as it may be, it is true.

Here's the code for Page_Unload:

Private Sub page_unload (ByVal sender as Object, _
ByVal e As System.EventArgs) _
Handles Mybase.prerender
ViewState ("randomgen") = Randomgen
' One of the options: writing session state
Session ("drawinglist") = Drawinglist

' Option two: Write a cookie. You must write code to serialize.
' Note: Using cookies will limit the number of shapes you can draw!
' Dim drawingliststring as String =
' Serialhelper.serializetobase64string (drawinglist)
' Response.Cookies.Add (New HttpCookie ("Drawinglist", _
' Drawingliststring)
End Sub



This code is slightly simpler because we don't have to see whether the state already exists in the view or session-state object, but simply write it unconditionally.

Similarly, view state and session state can automatically serialize itself, while cookies cannot, so we need to do it ourselves. The Dr. GUI writes the following helper function (in a separate class), as shown in the following code:


Public Shared Function serializetobase64string (ByVal o as Object) _
As String
Dim Formatter as New BinaryFormatter ()
Dim Serialmemorystream as New MemoryStream ()
Formatter. Serialize (Serialmemorystream, O)
Dim bytes () as Byte = Serialmemorystream.toarray ()
Return convert.tobase64string (bytes)
End Function

Drawing in a separate page
As mentioned earlier, the drawing is done on a separate page. The following is the code for the page:


Private Sub Page_Load (ByVal sender as System.Object, _
ByVal e as System.EventArgs) Handles MyBase.Load
Dim Drawinglist as DShapeList
' Get one of the drawing list options: Use Session state ...
Drawinglist = Session ("Drawinglist")
If drawinglist is nothing Then drawinglist = New dshapelist ()

' Get drawing list option two: Use cookies ...
' (See the homepage code for more comments)
' Dim drawingListCookie as HttpCookie
' drawingListCookie = Request.Cookies ("drawinglist")
' If drawingListCookie is nothing Then
' drawinglist = New dshapelist ()
' Else
' Drawinglist = _
' Serialhelper.deserializefrombase64string (_
' Drawinglistcookie.value)
' End If

Response.ContentType = "Image/gif"
Dim BitMap as New bitMap (368, 376)
Dim g as Graphics = Graphics.fromimage (BITMAP)
Try
G.clear (Color.White)
Drawinglist.drawlist (g)
Bitmap.save (Response.outputstream, Imageformat.gif)
Finally
G.dispose ()
Bitmap.dispose ()
End Try
End Sub


First, we get the drawing list from the session state or cookie. (This part of the code is similar to the Page_Load method above.) )

We then set the ContentType of the response stream being written to a GIF image.

Next, we're going to do something really wonderful: create a bitmap in the size you want (in this case, the same size as in a Windows forms application).

We then get a Graphics object associated with the bitmap, clear the object, and draw our list in it.

The following steps are important: Next, we write the image content in GIF format to the response stream (that is, the browser). We set this response type to ensure that the browser interprets the image correctly, and then sends bits of the image. (The. NET Framework makes this operation fairly simple.) In the original Windows GDI era, only plotting on the bitmap was very painful! )

Another important step is to remember to clean the Graphics and Bitmap objects-and use try/finally to clean up the object even if an exception occurs.

Hey! There are so many steps. But in order for this application to run as a asp.net application, it is worthwhile-and, better still, this application does not need to rely on client-side scripting.

Give it a try!


If you have. NET at hand, the best way to learn it is to try it. If not, please find a way to get it. If you spend about one hours a week on Dr. NET, you will already be a. NET Framework expert before you know.

Start with you--and invite your friends!
As the first person to learn new technology, it must feel good, but if sharing with friends is more fun! To enjoy more fun, invite friends to study. NET!

The attempt should be made ...
First try the code given here. Some of these are excerpts from large programs, and creating programs around these snippets can have a good effect. (You can also use the code provided by the Dr. GUI, if necessary.) ) to ponder the code.

Add a few different shapes to the drawing program, including fill and unfilled shapes. Note: Although we did not convert it, the classes that were added might exist in different assemblies from other files (and thus different executables). This means that the language of the class you are adding can even be different from the other classes. You will be more convinced when you read and try the necessary work related to it.

Please add some methods to the class here and try to change the user interface. Make a lovely CAD applet of your own.

Use inheritance, Abstract/mustinherit classes, interfaces, and polymorphism in the projects you choose. When the class family has many common parts, using inheritance works best. If the class does not have many common parts, but the function is similar, then use the interface is the best effect.

Try writing your own drawing application with asp.net. Note that if you are able to run the. NET Framework, you can run the asp.net on your own computer with Microsoft Internet Information Server (IIS)-No server! The Dr. GUI thinks it's great to create and test WEB applications on portable computers using only standard operating systems and free. NET Framework. (but is the Dr. GUI still inclined to use visual Studio, or at least visual Basic or Microsoft Visual C #?) Standard Edition. ) Look at it! No Server Required! You don't even need an Internet connection! (You can try it on the extended version of Brand J ...) )



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.