Friday, December 24, 2010

Toshiba Portege M300 Drivers

modular Creating a game using C # and Tao.SDL

In previous installments I have discussed how to create the skeleton of a game using C # and Tao.SDL. The problem with this approach is to leave the entire project in a single source makes it increasingly awkward to handle when it is getting bigger, and also impossible (almost) divide work among several people.

Therefore, a reasonable alternative when the project is not very small, it is decomposed into a series classes interact.

For example, in a classic platform game, we would have a "character" that handle a number of "enemies" who attack us, "Awards" to collect, maybe "Shooter" (or weapons otherwise) with which to defend, all coordinated by a class "Game", which was responsible for the run of play, not only to repeat the loop game but to make decisions as

  • When we touch an enemy, will lose a life or part of the energy?
  • "The enemy dies too when we play?
  • When levels are changed? Do you have to collect all the prizes? "Reaching a door?
  • Is there time limit to go finish a level? "The time out or lose a life the whole game?
  • ...

addition, we may refine a little further and distinguish between a "Game" (a play session) and the whole "game" (that could also include a display screen, a credit on the authors, options to customize it .. .).

If we are practical, we might even create a class "Image", which hide the details of image manipulation with SDL , and a class "Hardware", to conceal the English names of the functions and simplify a tedious task, such as writing text. Thus, further work would cost less to carry our game to another graphics library, as Allegro. And above these helper classes could create other more versatile. For example, over "image" could create a class "ElementoGrafico" which allow animated figures (consisting of a sequence of images), which had basic checks collisions, etc.

And how can do all this? Is there any sample source? Of course, but as it would be too long to read all the sources here, you can download a sample project page "remake of Manic Miner ", hosted on Google Code.

Version 0.01 is only a basic skeleton that shows how they could be above classes, both "infrastructure" (Hardware, Image, ElementoGrafico and another for handling fonts and sounds) such as "logic game (Game Presentation , Lending, Item, Character). Later versions of this project will expand gradually to reach something that is truly "playable"


Thursday, November 4, 2010

Linsey Dawn Mckenzie Sunday Sport

Compile C # with Geany in Windows

is an interesting Geany text editor. Perhaps with fewer opportunities than others such as Notepad + +, but still very powerful and reasonably easy to use.

One of the major advantages (for my taste) vs Notepad + + is that it is easy to compile and run programs created in different programming languages \u200b\u200bwithout leaving the editor. Yes ... sometimes you have to tune it a bit:

For C #, comes preconfigured to compile with Mono , but this in Windows is less immediate than it might seem. Let's see why and how to fix it:

related settings C # is in a file called "filetypes.cs", located in the folder "data" Geany (In "C: \\ Program Files \\ Geany \\ data \\ filetypes.cs" if we do a typical installation on Windows XP). We can open that file from within Geany.

The last two lines of that file should be something like:

compiler = mcs / t: winexe "% f" / r: System, System.Drawing
run_cmd = mono "% e . exe "

The problem is that these two lines waiting to compile sources in C # using Mono, which is immediate in Linux, but it is not so trivial in Windows, because it would change the basic configuration of Windows, so folder that is Mono one of the system's search folders.

There is a simple alternative, if you have installed any version of the platform "dot net", which is almost certain if we have any Service Pack for Windows XP, or if you have a newer Windows version: can use the compiler that is included with the platform .

First we have to find it: we started our drive C (or have installed the operating system), we entered the Windows folder, and it should be a subfolder called "Microsoft.net", which in turn contains another folder called "Framework" and in it we find several subfolders, one for each version of "dot net" that we have installed:


For example, this image shows a basic version of Windows XP, which has the v1 versions .0.3705 and v1.1.4322. We go to any of those folders (preferably a recent, with a higher version number) and check if it is the compiler, a file called "CSC."

If so, we know what the full path of the compiler, something like

C: \\ WINDOWS \\ Microsoft.NET \\ Framework \\ v1.1.4322 \\ csc.exe

(no need to memorize it, you can copy and paste from the address bar of our browser).

Then we can modify the configuration two lines that interest us: to compile sufficient to indicate the previous route followed by the name of our source, and release the resulting executable will use the name of our source ending in " . exe "and:

compiler = C: \\ WINDOWS \\ Microsoft.NET \\ Framework \\ v1.1.4322 \\ csc.exe"% f "
run_cmd ="% e.exe "

Of course, other options of Geany that seem comfortable to me are:

  • In Edit / Preferences / Editor / Indent: width 4 or 2, but always filled with spaces instead of Tabs.
  • In Edit / Preferences / Editor / Display: marker of activated long lines in column 80, to keep out of position when you print, if I use old sources or from other programmers, who may use the tab character instead of spaces also mark the option "Show white space."
  • I also find it convenient to change tabs to spaces automatically and spaces are erased at the end of each line Once you save a file, which you can get from Edit / Preferences / Files
For changes to be effective, we can exit the editor and re-enter or use the "Reload Settings" menu ( This serves the appearance, not to the "new compiler" for fonts in C #, for that we do need to leave the editor and reopen it.)

Happy coding! ;-)


(All this is tested with version 0.19.1 on Windows XP and Windows 7)

Saturday, October 23, 2010

What's The Black Boogers By Cat's Nose

The game loop

SDL
A source can be difficult to read, and even more if not structured, but has all the logic in "Main" and grows arbitrarily. So, it is often preferable to create our own functions that would hide a bit: Functions as "Initialize", "CargarImagen", "ComprobarTeclas", "DibujarImagenes", etc.

A "classic game loop" would look like this:
  • Checked events (keystrokes, mouse clicks and movement, use joystick ...) Move
  • game elements (a character, enemies, backgrounds mobile) Check
  • collisions game elements (which may involve loss lives or energy, earn points, etc)
  • Draw all items on the screen in its current state
  • Pause at the end of each "frame" for the speed of the game is the same on any computer, and, step, to help multi-tasking operating system.

therefore create these functions, along with other assistants to initialize the system, draw a hidden screen image, write text on the screen hidden ... The result could be:



 
/*---------------------------*/
/ * sdl05.cs * /
/ * * /
/ * Fifth approach * /
/ * SDL * /
/ * * /
/ * For Nacho Cabanes * /
/*----------------
-----------*/
using Tao.Sdl;
using System; / / For IntPtr (pointer images, etc)


{public class Game
short anchoPantalla = 800;
short altoPantalla = 600;
bool finished = false;
short x = 400;
short y = 300;
short anchoImagen = 50;
short altoImagen = 50;
Sdl.SDL_Event event;
numkeys int;
byte [] keys;
pantallaOculta IntPtr, IntPtr
tipoDeLetra;
IntPtr image;

void initialize () {

bitsColor int = 24 int flags = Sdl.SDL_HWSURFACE
which is cut off the screen hidden

Sdl.SDL_Rect rect2 = new Sdl.SDL_Rect (0.0, (short) anchoPantalla, (short) altoPantalla)
Sdl.SDL_SetClipRect (pantallaOculta, ref rect2)

/ / Load an image
image = SdlImage.IMG_Load (personaje.png ");
if (image == IntPtr.Zero) {
System.Console.WriteLine (" Image does not exist: personaje.png! ") ;
Environment.Exit (4);


} / / And a font in size 18
SdlTtf.TTF_OpenFont tipoDeLetra = ("FreeSansBold.ttf" 18);
if (tipoDeLetra == IntPtr.Zero) {
System.Console.WriteLine ("Font does not exist: FreeSansBold.ttf!");
Environment.Exit (5);

}}

void
comprobarTeclas ()

{/ / Check
Sdl.SDL_PollEvent events (out event);
keys = Sdl.SDL_GetKeyState (out numkeys)

/ / Let's see if you've pressed a cursor arrow
if (keys [ Sdl.SDLK_UP] == 1)
and -= 2;
if (keys [Sdl.SDLK_DOWN] == 1) y + =
2;
if (keys [Sdl.SDLK_LEFT] == 1)
x -= 2;
if (keys [Sdl.SDLK_RIGHT] == 1)
x + = 2;
if (keys [Sdl.SDLK_ESCAPE] = = 1)
finished = true;}



comprobarColisiones void () {

/ / Still not check collisions with enemies
/ / or with obstacles}



moverElementos void () {

/ / Not yet There is no single element that moves}


dibujarElementos void () {

/ / Clear screen Sdl.SDL_Rect
origin = new Sdl.SDL_Rect (0.0,
anchoPantalla, altoPantalla)
Sdl.SDL_FillRect (pantallaOculta, ref origin, 0);

/ / Draw the image in its new coordinates
dibujarImagenOculta (image, x, y, anchoImagen, altoImagen)

/ / Write the text, image
escribirTextoOculta ("Sample Text"
/ * Coordinates * / 200.100,
/ * Colors * / 50, 50, 255,
tipoDeLetra
)

/ / show the hidden display
Sdl.SDL_Flip (pantallaOculta)



} void pausaFotograma ()

{/ / Wait 20 ms
System.Threading.Thread.Sleep (20);}



void dibujarImagenOculta (IntPtr image, short x, short and short
wide short height) {
Sdl.SDL_Rect
origin = new Sdl.SDL_Rect (0, 0, width, height);
Sdl.SDL_Rect Sdl.SDL_Rect dest = new (x, y, width, height);
Sdl.SDL_BlitSurface ( image, ref origin pantallaOculta, ref dest);}



escribirTextoOculta void (string text,
short x, short and byte r, byte g, byte b, IntPtr source)

{/ / Create an image from the text
Sdl.SDL_Color color = new Sdl.SDL_Color (r, g, b) = SdlTtf.TTF_RenderText_Solid
textoComoImagen IntPtr (
font, text, color )
if (textoComoImagen == IntPtr.Zero) {
System.Console.WriteLine ("I can not render the text");
Environment.Exit (6);}

dibujarImagenOculta (textoComoImagen, x, y, (short) (800-x), (short) (600-y));}



partidaTerminada bool ()

{return finished;



} private static void Main () {
Game
j = new Game ();
j.inicializar ();

/ / game loop do {

j.comprobarTeclas ();
j.moverElementos ();
j.comprobarColisiones ();
j.dibujarElementos ();
j.pausaFotograma ();
} while (! j.partidaTerminada ());

/ / Finally, close SDL
Sdl.SDL_Quit () ;



}}





Tuesday, October 19, 2010

Sample Letter Of Offer Beauty Therapist

PNG and JPG images

know
display images in BMP format
from a program in C # that use Tao.Sdl. But the images in this format take up much space, and do not allow advanced features such as transparency (although one could imitate). If we use images in modern formats such as JPG or PNG, we need only include a few more DLL files and make a small change in the program.




The new files you need are: SDL_image.dll (the principal), libpng13.dll (PNG Image), zlib1.dll (Auxiliary above) and jpeg.dll (if you want to use JPG images).


SdlImage.IMG_Load image = ("personaje.png");

Wednesday, October 13, 2010

Discount Platypus Flossers

Tao.SDL TTF fonts with SDL and C #

If we write text using TrueType fonts (the standard in Windows and Linux), the changes are not large:
We must include the DLL file in the folder called SDL_ttf.DLL our program executable and the TTF file for each type font you want to use.
 We must declare a new data that will be our font, the generic type "IntPtr" 
tipoDeLetra IntPtr;

SdlTtf also need to initialize after basic initialization of SDL: SdlTtf.TTF_Init ();


Then prepare the font you want to use, indicating which file from TTF and what size:


/ / A font in size 18
 SdlTtf.TTF_OpenFont tipoDeLetra = ("FreeSansBold.ttf", 18); 
if (tipoDeLetra == IntPtr.Zero) {
System.Console.WriteLine ("Type nonexistent letter: FreeSansBold.ttf! ");
Environment.Exit (5);}

 
Then we can create an image from a phrase


/ / And create an image from the text
Sdl.SDL_Color colorAzulIntenso = new Sdl.SDL_Color (50, 50, 255);
 string text = "Sample text"; 
textoComoImagen IntPtr = SdlTtf.TTF_RenderText_Solid (
tipoDeLetra text, colorAzulIntenso)

if (textoComoImagen == IntPtr.Zero) {
System.Console.WriteLine ("I can not render the text");
Environment.Exit (6);}



And we could draw that image anywhere on the screen, like any other image:
 

/ / Write the text, image source = new Sdl.SDL_Rect
(0.0, anchoPantalla, altoPantalla)
dest = new Sdl.SDL_Rect (200,100, anchoPantalla, altoPantalla)
Sdl.SDL_BlitSurface (textoComoImagen, ref origin
pantallaOculta, ref dest);


As this way of working can be cumbersome, soon we will improve, creating a class "source" that we hide all these details and allow us to easily write text.


Sunday, October 10, 2010

Restoril Small Quantity

C #: An image that moves with the keyboard


We have seen the basics of how
display images on screen using C # and SDL
. 



A second more detailed example could afford to move the character with the arrow keys at a rate of 50 frames per second, so (you have the following comments the source):


/ * Example SDL
access from C # (2), using Tao.SDL
By Nacho Cabanes
* /


 
using Tao. Sdl

;


using System;

/ / For IntPtr (pointer images, etc)
public class Sdl02
{

private static

void
Main
( ) { short anchoPantalla =
800 ;


short altoPantalla = 600 ;
int bitsColor = 24 ;

int flags = Sdl . SDL_HWSURFACE Sdl
. SDL_DOUBLEBUF ( anchoPantalla , altoPantalla , bitsColor , flags
) ;

/ / indicate that it is cut to leave the hidden display

Sdl. SDL_Rect rect2
= new Sdl. SDL_Rect ( 0 , 0 ,

( short )
anchoPantalla ,
(
short
) altoPantalla ) ;
Sdl


.
SDL_SetClipRect ( pantallaOculta , ref
rect2 ) ; / / Load an image IntPtr image ; image = Sdl. SDL_LoadBMP ( "personaje.bmp" ) ; if ( image = = IntPtr .
Zero
) { System. Console. WriteLine (

"Image does not exist!"
)
;

Environment. Exit ( 4) ;
} / / Part repetitive bool finished = false ; short x = 400

; short and = 300 ; short anchoImagen =
50 ; short altoImagen = 50 ;

SDL .
SDL_Event event
;
int numkeys ;
byte [ ]

keys ; of
{ / / Check event Sdl. SDL_PollEvent

( out event ) ; keys
= Sdl. SDL_GetKeyState ( out numkeys
) ;

/ / Let's see if you've pressed a cursor arrow if ( keys [
Sdl
. SDLK_UP
]
= 1 =
) y - = 2 ;
if ( keys [ Sdl . SDLK_DOWN ]


= 1 =
) + y = 2 ; if ( keys [ Sdl .
SDLK_LEFT
] = 1 =
) x - = 2 ; if ( keys [ Sdl .
SDLK_RIGHT
] = =
1) x + = 2 ; if ( keys [Sdl .
SDLK_ESCAPE
] = =
1) finished = true ; / / Clear screen Sdl. SDL_Rect origin = new SDL.

SDL_Rect ( 0, 0
, anchoPantalla , altoPantalla ) ; SDL. SDL_FillRect ( pantallaOculta , ref

origin, 0)


;
/ / Draw in their new home coordinates = new Sdl. SDL_Rect ( 0 , 0 ,
anchoImagen
, altoImagen ) ;
Sdl. SDL_Rect dest = new Sdl. SDL_Rect ( x , and ,

anchoImagen ,
altoImagen
) ; Sdl. SDL_BlitSurface ( image, ref origin, pantallaOculta , ref dest ) ;

/ / show the screen Sdl hidden . SDL_Flip ( pantallaOculta ) ;
/ / And wait 20 ms
System. Threading . Thread . Sleep
( 20) ;
} while (

!
finished )
; / / Finally, close SDL Sdl . SDL_Quit (

)
; } } the differences with the previous source are:
When initializing, we add a new option, Sdl.SDL_FULLSCREEN, so that the "game" to run full screen instead of on window. We use a loop

"do ... while" to repeat until you press the ESC key. SDL_Event is the type of data used to check the "events", such as keystrokes or mouse, or using the joystick. With SDL_PollEvent forcing them to look at what events are pending analysis. SDL_GetkeyState get an array that gives us the current status of each key. Then we can look each of these keys by accessing the array with the key name in English as well: keys [Sdl.SDLK_RIGHT] SDL_FillRect fills a rectangle with some color. It's an easy way to clear the screen or part of it.

Monday, September 13, 2010

How Does Wrestling In The Marines Work

Games with C # using SQLite

SDL is a library known to carry games which is available for various operating systems and allowing both draw pictures and check the keyboard, mouse or joystick, and play sounds.

Tao.SDL is an adaptation of this library, which allows using it from C #. It can be downloaded from http://www.mono-project.com/Tao
SDL is a library not particularly easy, and neither has just Tao.SDL, so the following sources can be difficult to understand, although very basic tasks. Therefore, it is often preferable to "hide" the details of creating our own classes SDL "Hardware", "Picture" etc. We will do later, but for now v masters to see a first example, basic but complete, showing how to enter graphics mode, upload an image, draw on the screen, wait five seconds and return to the operating system. Following comment the main source functions.

/ * Example SDL
access from C # (1), using Tao.SDL
By Nacho Cabanes * /


using Tao. Sdl

;
  • using System;
  • / / For IntPtr (pointer images, etc)

public class Game

private static void

Main

(

)



{
 



short

width = 800


; short
high = 600 ;

bitsColor int = 24

;

int flags = ( Sdl. SDL_HWSURFACE Sdl . SDL_Init (
Sdl. SDL_INIT_EVERYTHING
)

; pantallaOculta = Sdl. SDL_SetVideoMode
( wide, high ,

bitsColor , flags ) ;
/ / Indicates what is cut out of the hidden display Sdl. SDL_Rect rect2 = new Sdl. SDL_Rect ( 0 , 0
,
(

short
) width, ( short ) high )

; Sdl.
SDL_SetClipRect ( pantallaOculta
, ref rect2 )
;
/ / Load an image
IntPtr image;

image
=
Sdl
. SDL_LoadBMP (
"personaje.bmp" ) ; if ( image = = IntPtr . Zero ) { System. Console. WriteLine ( "Image does not exist!" ) ;

Environment. Exit ( 4) ;

}
/ / Draw the image

short x = 400 ; short and = 300
; Sdl. SDL_Rect origin = new Sdl. SDL_Rect ( 0

, 0 , wide, high ) ; Sdl.
SDL_Rect dest = Sdl new . SDL_Rect ( x ,
and
,
wide, high

)
; Sdl. SDL_BlitSurface (
image, ref origin, pantallaOculta , ref dest

) ; / / show the hidden display Sdl . SDL_Flip ( pantallaOculta ) ; / / and wait 5 seconds System. Threading

. Thread . Sleep (5000 ) ; / / Finally, close SDL SDL . SDL_Quit (

) ; } }

Some basic ideas:

·
SDL_Init is the initialization routine, which goes into graphics mode, with a screen width and height, a certain amount of colors and some additional options. · SDL_Rect type defines a "rectangle" from its origin (y) its width and height, and is used in many operations.

·
SDL_SetClipRect indicates the trimming (clipping) the size of the screen, so you do not have to worry about if we draw an image in part (or entirely) outside the visible screen. · SDL_LoadBMP load a BMP format image (if you only use SDL "pure", we can not use other types that allow smaller sizes, such as JPG, or transparency, such as PNG). The type of data you get is an "IntPtr" (which Daeman no details), and how to check if you really manage to upload the image is looking at whether the value obtained is IntPtr.Zero (and if so, could not have been loaded) or another (and then the image would have read without problems.) · SDL_BlitSurface dumps a rectangle (SDL_Rect) over another, and use it to foresee all the hidden images on a screen, and then dump all this hidden from the display screen visible, thus avoids flicker (a technique known as "double buffer"). ·


SDL_Flip hidden dumps that screen display visible (the final step of this "double buffering").
· pause For we have not used any function of SDL, but Thread.Sleep, which we discussed in the section on timing. ·
SDL_Quit releases resources (which usually would from a destructor).






To compile this example using Mono, we:

·

Enter (or copy and paste) the source.

·

in the same folder Copy the DLL files (Tao.Sdl.Dll and SDL.Dll) and images (in this case, "personaje.bmp").

·

Compile with:

sdl01.cs mcs / r: Tao.Sdl.dll

And if we use Visual Studio or SharpDevelop, we that: ·

Create a draft of the console application. " ·

Replace our main program for this. ·

Tao.Sdl.Dll Copy the file to the Fonts folder and add it to your project references (usually by pressing the right mouse button in the view of the project and choosing classes "Add Reference").

·

Copy executable folder (typically bin / debug) DLL files (Tao.Sdl.Dll and SDL.Dll) and images (in this case, "personaje.bmp"). ·

Compile and test.

If we will not use compressed images (PNG or JPG) or TTF fonts, and sounds in MP3 format or additional drawing functions (lines, boxes, circles, etc). not need any additional DLL. can download the source and executable, the DLL and a sample character, here:

Http://www.nachocabanes.com/fich/descargar.php?nombre=csharp_sdl_01.zip

Sunday, July 4, 2010

8 Month Old With Chesty Cough

SDL,

We have seen how to display data in a SQLite database from C #, both from console as using Windows Forms and basic components such as TextBox and ListView.

If we simply a "grid" similar to those of spreadsheets, which can modify and add data, there is a simple way to get it: from the visual editor added a DataGridView to our form and connect to our table SQLiteDataAdapter using a DataSet and a DataTable.

appearance would this

And the source would be essentially the same as above, but the function responsible for updating the list of cities would look like:

1:

private void ActualizarListaCiudades (

) 2: {

3: connection = 4 :

new SQLiteConnection 5: (

"Data Source = personal.sqlite, Version = 3; New = False; Compress = True;" )

;

6:

connection. Open

(

)

;

7:
8:

/ / launch the consultation and prepare to read data structure
9:

string query =

"select * from city "
;

10:


11:
   / / Data Adapter, DataSet and Table   12:    SQLiteDataAdapter  db = new      SQLiteDataAdapter   (   
consultation, connection )
;

13: DataSet ds = new DataSet
( ) ; 14: ds
. Reset ( ) ; 15: DataTable dt

= new DataTable
(
)
; 16: db
.

Fill (ds )
;
17: 18: / / Assign the DataTable the first table (cities) 19: / / and show it in the DataGridView 20:
dt = ds
. Tables [ 0 ] ;
21: dataGridView1.DataSource dt = ; 22: 23: / / And we can close the connection 24:

connection. Close ( ) ; 25:
}

Friday, June 25, 2010

What Does Fungus Look Like

DataGridView C # and SQLite with C # on Windows Forms

After seeing how to create a console application in C # to create a database with SQLite, save data and read, we'll see how to do something similar in an application "window" using Windows Forms.

components is done using "normal" rather than the defaults that allow access to databases. We will have a main window that displays the current data in a ListView, and includes a button to add new data:

button "Add" show a second form which will ask the data:

We can do this by following these steps (in Visual C # 2008): Create a new project, which is a "Windows Forms Application" In the main window, add a ListView and a button. Customize ListView using the properties tab, so you have two columns (one for code and one for the name), and as a display mode ("View") have the "details" ("Details" .) Creating a second window from the "Project" in the "Add Windows Form." Add to that window two TextBox for the text that the user entered, along with explanatory text for the Label and a button to confirm. Add the DLL file to your project references (in the window of "Solution Explorer" by right clicking on "References" and selecting the file System.Data.SQLite.DLL from the "Browse" tab.) complete source code of the project. As the code, the two key parts are the part that reads the data to populate the ListView and releasing the auxiliary window, making it what the user type and then enter that data.

The filling in the ListView (which is called the end of the constructor, and after the introduction of new data) could be:

1:
private void ActualizarListaCiudades ( ) 2: {

3: connection
= 4: new

SQLiteConnection
5:
(

"Data Source = personal.sqlite, Version = 3; New = False; Compress = True;"
)

;

6:

connection. Open
(
)
  • ;
  • 7:
  • 8:
  • lstCiudades
  • . Items
. Clear

(

)


;


  9:    10:    / / launch the consultation and prepare to read data structure   11: query string       = "select * from city"   ; 
12: SQLiteCommand cmd = new

SQLiteCommand (
consultation, connection
) ; 13: SQLiteDataReader data Cmd = .

ExecuteReader ( ) ; 14: / / read data repeatedly 15:

while ( data. Read ( ) )

16: {

17: string code = Convert
. ToString (
data [0 ] ) ; 18: string name = Convert .

ToString ( data [1 ] ) ;
19:
/ / And show
20: ListViewItem item = new ListViewItem ( code) ; 21:

item. SubItems . Add
( name) ; 22: lstCiudades . Items . Add (item )

; 23: } 24: connection. Close ( ) ;
25: }

And adding other data would be like: 1: private void InsertarDatos
( string code, string name ) 2: { 3:
4:
insertion string; / / Order of insertion, in SQL 5: cmd SQLiteCommand ; / / Command SQLite 6:
7: connection =
8: new SQLiteConnection 9: ( "Data Source = personal.sqlite, Version = 3, New = False; Compress = True; " )

; 10:
connection. Open

(


)
   ;     11:    12:        try 13: {     
14: insertion = "INSERT INTO city"

+
15: "VALUES ('" + + code
"','" + name +
"');" ;

16:
cmd = new

SQLiteCommand
( insertion,
connection ) ; 17: cmd . ExecuteNonQuery (

) ; 18: } 19:

catch (Exception e
) 20:

{21: MessageBox . Show
( 22: "Unable to insert. Possibly a code is repeated" , 23: "Notice" )

; 24: } 25: connection. Close ( )
; 26: } So the complete action on the button "Add" would be something like

1:
private void btAnadir_Click ( object sender, EventArgs e )
2: {
3: ventanaAnadir . Clean (

) ;
4: ventanaAnadir . ShowDialog ( )
;
5: InsertarDatos ( ventanaAnadir . GetCodigo ( )

, ventanaAnadir .
getName (



)
   )    ;      6:  ActualizarListaCiudades   (   )    
; 7:

} And here you can download the project, with the two sources, the DLL and executable files: csharp_sqlite2.zip

Sunday, June 13, 2010

Email Confidentiality Statement Example

SQLite from C #

SQLite is a database manager, which allows querying using SQL language, and that can be included as part of a program in C or C + +, just including an additional DLL file ... or even that, because it really is a library that can be "embedded" as part of the program. Since C # can not use the SQLite DLL directly, but through others like System.Data.Sqlite.Dll, which can be found in
http://sqlite.phxsoftware.com/ With the DLL, along with the original SQLite, we do programs in C # that allow us to access databases and are easy to distribute. SQLite can be found in http://www.sqlite.org/ We will see a small example of creating a database, how to enter data and display it. First we see the fragments of code, then a full source, then how to compile and test it, and eventually will include the full download, with source, executable and DLLs. To connect to the database, we would create an object of type "SQLiteConnection" connection = new SQLiteConnection ("Data Source = personal.sqlite, Version = 3; New = True; Compress = True , ");
conexion.Open ();
To create and modify queries, create an object of type SQLiteCommand and run it with" ExecuteNonQuery () ": creation string = "CREATE TABLE city" + "(code VARCHAR (2) PRIMARY KEY, name VARCHAR (30 ));"; SQLiteCommand cmd = new SQLiteCommand (creation, connection); cmd.ExecuteNonQuery (); If it is a query that returns data itself (a "select"), use "ExecuteReader ()" and read data repeatedly with "while (datos.Read ())" string query = "select * from city"; SQLiteCommand cmd = new SQLiteCommand (query, conn); SQLiteDataReader data = cmd.ExecuteReader (); / / read data while repeatedly (Datos.Read ()) { string code = Convert.ToString (data [0]); string name = Convert.ToString (data [1]); / / And show Console.WriteLine ("Code : {0}, Name: {1} ", code, name);} In the" ExecuteNonQuery ", we can check the amount of data involved, so we can help you discover errors: quantity = cmd.ExecuteNonQuery (); if (amount \u0026lt;1) Console.WriteLine ("Could not insert");

Still, many types of errors, and a duplicate key, may cause an exception and jumps to interrupt the program, it would be advisable to include insertion orders within a "try ... catch" In any case, at the end of the connection should close access to Database: conexion.Close ();
The full source can be: / / Example of accessing SQLite from C #


/ / Nacho Cabanes, June 2010



using System;

using System. IO

;


using System
.
Data

.

SQLite
 ;   


//Utilizamos la DLL




public
   

class

pruebaSQLite01

{


  
static

SQLiteConnection conexion

;





private


static


 void 

CrearBBDDSiNoExiste

(



)




 

{if





(
 !  File 
.

Exists (

"personal.sqlite" )
) {
/ / Create the connection to the database. / / The Source Data File contains the path of the database connection

= new

SQLiteConnection ( "Data Source = personal.sqlite, Version = 3; New = True; Compress = True;"
) ;
connection. Open
(
) ; / / Create the first table creation string = "CREATE TABLE city"

+ ( code VARCHAR (2) PRIMARY KEY, name VARCHAR (30)); "
; SQLiteCommand cmd = new SQLiteCommand ( creation, connection ) ;
cmd.
ExecuteNonQuery (
)
;
/ / Create the second table creation

= "CREATE TABLE person" + ( code VARCHAR (2) PRIMARY KEY, name VARCHAR (30), " + " codigoCiudad VARCHAR (2)); " ;

cmd = new SQLiteCommand ( creation, connection
)

;
cmd.
ExecuteNonQuery ( )

; } else { / / Create the connection to the database.
/ / The Source Data File contains the path of the database connection = new SQLiteConnection
(
"Data Source = personal.sqlite, Version = 3, New = False; Compress = True; "

)
;
connection. Open
( )
; }}
private static void
InsertarDatos ( ) {

insertion string;
/ / Order of insertion, in SQL SQLiteCommand
cmd;

/ / SQLite Command

int
amount ;
/ / Result: The amount of data
try { insertion
= "INSERT INTO city" + " VALUES ('t', 'Toledo'); " ; cmd = new

SQLiteCommand (
insertion, connection
)

; cmd = amount . ExecuteNonQuery ( )

;
if
( amount \u0026lt;
1)
Console.
WriteLine ( "Could not insert" )

;

insertion
= "INSERT INTO city" +
"VALUES ('a', 'Alicante');" ;
cmd = new SQLiteCommand
( insertion, connection ) ; amount cmd = .

ExecuteNonQuery ( ) ; if (
amount \u0026lt; 1 ) Console. WriteLine (

"Could not insert" ) ; insertion = "INSERT INTO person"

+ "VALUES (' j ',' John ',' t '); " ;
cmd = new SQLiteCommand

( insertion, connection ) ; amount cmd = .
ExecuteNonQuery ( ) ; if (

amount \u0026lt; 1) Console. WriteLine (
"Could not insert" ) ; insertion = "INSERT INTO person"


+ "VALUES ('p', 'Pepe', 't');" ;
cmd = new SQLiteCommand
( insertion, connection ) ; amount cmd = .

ExecuteNonQuery ( ) ; if (
amount \u0026lt; 1) Console. WriteLine (

"Could not insert" ) ; }

catch (Exception e
) {

Console. WriteLine ( "Could not insert" ) ; Console.
WriteLine ( "Possibly a code is repeated" ) ; Console.

WriteLine ( "Error found: {0}" , and . Message )
; } }

private
static void MostrarCiudades ( )
{
/ / launch the consultation and prepare to read data structure string query = "select * from city" ; SQLiteCommand cmd = new

SQLiteCommand ( consultation, connection ) ;
SQLiteDataReader data = cmd . ExecuteReader ( ) ; / / read data repeatedly

while (
data.
Read
( ) ) {string code = Convert
.
ToString (
data [
0 ] )
; string name = Convert . ToString ( data [1

] ) ; / / And show
Console.
WriteLine (
"Code: {0}, Name: {1}" , code, name ) ; }

}
private static void MostrarPersonas ( ) {

/ / launch the consultation and prepare the structure for reading data query string = "select * from person" ; SQLiteCommand cmd = new SQLiteCommand ( consultation,
connection )

;
SQLiteDataReader data = cmd . ExecuteReader (
) ; / / read data repeatedly
while
(
data.
Read

( ) ) {string code = Convert
. ToString (

data [0
] )
; string name = Convert . ToString ( data [1

] ) ; / / And show
Console.
WriteLine (
"Code: {0}, Name: {1}" , code, name ) ; }

}
private static void MostrarCiudadesYPersonas ( ) {

/ / launch the consultation and prepare to read data structure string query = "persona.nombre select a city. name " +" from person town " + " where persona.codigoCiudad = ciudad.Codigo " ; SQLiteCommand cmd = new
SQLiteCommand

(
consultation , connection ) ; SQLiteDataReader data = cmd
. ExecuteReader ( )
;

/ / read data repeatedly

while ( data. Read ( ) )
{

nombrePersona string Convert
=
.
ToString (
data [0
] )

; string Convert nombreCiudad = . ToString ( data [1
] ) ; / / And show
Console.

WriteLine (
"{0} lives at {1}" , nombrePersona , nombreCiudad ) ;
} }
private static void CerrarBBDD ( ) {

connection. Close ( ) ; } public
static

void
Main ( ) {
Console . WriteLine ( "Accediendo..." )
;

CrearBBDDSiNoExiste (

) ; Console. WriteLine ( "Adding data ..." )
;

InsertarDatos ( ) ; Console.
WriteLine (
"city data"

) ; MostrarCiudades ( ) ;

Console.
WriteLine ( "data people" ) ; MostrarPersonas (
) ; Console.

WriteLine ( "data people and cities," ) ; MostrarCiudadesYPersonas (
) ; CerrarBBDD (
) ; } }

To compile this source, we include "System.Data . SqLite.dll "within the project references. This would be done from within the visual environment if we use tools like Visual Studio or SharpDevelop, or by adding the / r option if you compile from the command line, for example using Mono: gmcs pruebaSQLite.cs / r: System.Data. SqLite.dll
And here you can download the source, the DLL and executable files: csharp_sqlite.zip