<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Crows Programming</title>
	<atom:link href="http://www.crowsprogramming.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.crowsprogramming.com</link>
	<description>Computer Programming and Random Blurbs</description>
	<lastBuildDate>Tue, 08 Dec 2009 05:44:52 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>SDL &amp; OpenGL Game with C++ &#8211; Part II</title>
		<link>http://www.crowsprogramming.com/archives/117</link>
		<comments>http://www.crowsprogramming.com/archives/117#comments</comments>
		<pubDate>Tue, 08 Dec 2009 05:39:32 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=117</guid>
		<description><![CDATA[ Parts in the Series 

 Part I  &#8211; Getting Started 
 Part II &#8211; Drawing a Quad 

 Rendering a Quad with OpenGL and SDL
Ok, so if we are going to program a video game then we need to draw something with OpenGL. 
That being said, last time we left off with a [...]]]></description>
			<content:encoded><![CDATA[<h3> Parts in the Series </h3>
<ul>
<li><a href="http://www.crowsprogramming.com/archives/104"> Part I  &#8211; Getting Started </a></li>
<li><a href="http://www.crowsprogramming.com/archives/117"> Part II &#8211; Drawing a Quad </a></li>
</ul>
<h3> Rendering a Quad with OpenGL and SDL</h3>
<p>Ok, so if we are going to <b>program a video game</b> then we need to <b>draw something with OpenGL</b>. </p>
<p>That being said, last time we left off with a basic framework for creating a game with SDL. If you haven’t read it <a href="http://www.crowsprogramming.com/archives/104"> then you should check out part 1 here</a> because we’ll be building off of that. This time around the goal is simply to get something rendering on the screen with OpenGL. So with that in mind here is the road map for what I wanted to accomplish:</p>
<ul>
<li> Render a single quad </li>
<li> Render a textured quad </li>
</ul>
<p>As you can see I am going to keep it simple for now. I’ll throw in the ability to swap textures at runtime as well just to keep it interesting.</p>
<p>The game so far will look a little something like this:<br />
<a href="http://www.crowsprogramming.com/wp-content/uploads/2009/12/Figure1.png"><br />
<img src="http://www.crowsprogramming.com/wp-content/uploads/2009/12/Figure1-Thumb.png" /><br />
</a></p>
<h2> Drawing a Square With SDL </h2>
<p>First on the list is to render a single quad. But, before you do anything make sure you add the OpenGL libraries to your project. You can accomplish that by going into the linker section of the project settings and adding <i>opengl32.lib</i> and <i>glu32.lib</i> to the additional dependencies section, just as we did for the SDL libraries in <a href="http://www.crowsprogramming.com/archives/104"> Part I</a>. </p>
<p>I am just going to start out showing you the new main function and then we will go through it step by step. So here ya go!</p>
<p><span id="more-117"></span></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// graphics properties</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">int</span> width <span style="color: #339933;">=</span> <span style="color: #0000dd;">640</span><span style="color: #339933;">;</span>        <span style="color: #666666; font-style: italic;">// width of the game window </span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">int</span> height <span style="color: #339933;">=</span> <span style="color: #0000dd;">480</span><span style="color: #339933;">;</span>       <span style="color: #666666; font-style: italic;">// height of the game window</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">float</span> fov <span style="color: #339933;">=</span> <span style="color:#800080;">45.0f</span><span style="color: #339933;">;</span>      <span style="color: #666666; font-style: italic;">// field of view (degrees)</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">float</span> nearClip <span style="color: #339933;">=</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// near clip plane (don't set to zero)</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">float</span> farClip <span style="color: #339933;">=</span> <span style="color:#800080;">100.0f</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// far clip plane</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// initialize SDL</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> SDL_Init<span style="color: #009900;">&#40;</span> SDL_INIT_VIDEO <span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
              fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to initialize SDL. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
              exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// set desired OpenGL attributes prior to selecting a video mode</span>
	SDL_GL_SetAttribute<span style="color: #009900;">&#40;</span> SDL_GL_DEPTH_SIZE<span style="color: #339933;">,</span> <span style="color: #0000dd;">16</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// use 16 bits for depth buffer</span>
	SDL_GL_SetAttribute<span style="color: #009900;">&#40;</span> SDL_GL_DOUBLEBUFFER<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// enable double buffering</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// create an OpenGL surface/window</span>
	SDL_Surface <span style="color: #339933;">*</span>screen <span style="color: #339933;">=</span> SDL_SetVideoMode<span style="color: #009900;">&#40;</span>width<span style="color: #339933;">,</span> height<span style="color: #339933;">,</span> <span style="color: #0000dd;">32</span><span style="color: #339933;">,</span> SDL_OPENGL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> screen <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
              fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to set video mode. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
              exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// initialize OpenGL</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> SetupOpenGL<span style="color: #009900;">&#40;</span> width<span style="color: #339933;">,</span> height<span style="color: #339933;">,</span> fov<span style="color: #339933;">,</span> nearClip<span style="color: #339933;">,</span> farClip<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fprintf<span style="color: #009900;">&#40;</span> stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to setup OpenGL.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// main game loop</span>
	bool done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span>done <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		RenderScene<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> ProcessInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
			done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	SDL_Quit<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The variable declarations on lines 4-8 just control the graphical properties of the application. They’re pretty self-explanatory. You can change the width or height and so on. </p>
<p>Next up you’ll see that the code to initialize the video mode (lines 17-27) has been changed. SDL gives us certain attributes that can modify the behavior of OpenGL, <i>but</i> these changes <i>only</i> take place after a call to SDL_SetVideoMode. In this case we’re telling SDL that we would like OpenGL to use a 16-bit depth buffer and to use double buffering when rendering (actively draws to an off screen surface, not the screen). Note that technically we should check the value of these attributes after the SDL_SetVideoMode call to ensure that they were set successfully. You could (and technically should) do this with the correct calls to SDL_GL_GetAttribute. You’ll also notice that the flags parameter for SDL_SetVideoMode now uses SDL_OPENGL instead of SDL_SWSURFACE since we are specifying that we want to use OpenGL for drawing.</p>
<p>Following the setting of the video mode I make a call to SetupOpenGL which is going to configure OpenGL for the application. I’ll detail this function shortly. The last major change to the code is the addition of RenderScene in the main loop. This is the function that will actually draw the game on the screen. Everthing should seem pretty straight forward.</p>
<h2>Configuring OpenGL</h2>
<p>So now I am going to show you SetupOpenGL. The entire purpose of this function is simply to setup things with respect to OpenGL that we won&#8217;t be changing again or that need a known initial state. It&#8217;s pretty simple stuff.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> SetupOpenGL<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> width<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> height<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> fov<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> nearClip<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> farClip <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	glClearColor<span style="color: #009900;">&#40;</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #993333;">float</span> ar <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>GLfloat<span style="color: #009900;">&#41;</span>width <span style="color: #339933;">/</span> height<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// display aspect ratio</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// setup projection matrix</span>
	glMatrixMode<span style="color: #009900;">&#40;</span>GL_PROJECTION<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	glLoadIdentity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	gluPerspective<span style="color: #009900;">&#40;</span>fov<span style="color: #339933;">,</span> ar<span style="color: #339933;">,</span> nearClip<span style="color: #339933;">,</span> farClip<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// setup model view matrix</span>
	glMatrixMode<span style="color: #009900;">&#40;</span>GL_MODELVIEW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>			
	glLoadIdentity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// setup depth buffer</span>
	glClearDepth<span style="color: #009900;">&#40;</span><span style="color:#800080;">1.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	glEnable<span style="color: #009900;">&#40;</span>GL_DEPTH_TEST<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	glDepthFunc<span style="color: #009900;">&#40;</span>GL_LEQUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
&nbsp;
	<span style="color: #666666; font-style: italic;">// misc. GL settings</span>
	glHint<span style="color: #009900;">&#40;</span>GL_PERSPECTIVE_CORRECTION_HINT<span style="color: #339933;">,</span> GL_NICEST<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	glShadeModel<span style="color: #009900;">&#40;</span>GL_SMOOTH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	glViewport<span style="color: #009900;">&#40;</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> width<span style="color: #339933;">,</span> height <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here I do some basic setup work:</p>
<ul>
<li> Setup the projection matrix with gluPerspective </li>
<li> Set the view matrix to identity</li>
<li> Setup the depth buffer</li>
<li> Setup some various GL settings such as the shade model</li>
<li> And finally setup the viewport</li>
</ul>
<p>If that looks like gably gook to you then you should check out the <a href="http://www.opengl.org/documentation/red_book/">the OpenGL Red Book</a>. The 3D transformation pipeline, matrix math, etc is a vast subject and beyond the scope of this post.</p>
<h2> Render Scene </h2>
<p>Next let’s look at the render scene function.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">void</span> RenderScene<span style="color: #009900;">&#40;</span> <span style="color: #993333;">void</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// render everything for the current frame</span>
&nbsp;
	glClear<span style="color: #009900;">&#40;</span> GL_COLOR_BUFFER_BIT <span style="color: #339933;">|</span> GL_DEPTH_BUFFER_BIT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	glMatrixMode<span style="color: #009900;">&#40;</span> GL_MODELVIEW <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	glLoadIdentity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// move off center so the quad is visible</span>
	glTranslatef<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color: #339933;">-</span><span style="color:#800080;">5.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// draw quad as red</span>
	glColor3f<span style="color: #009900;">&#40;</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// render the quad</span>
	glBegin<span style="color: #009900;">&#40;</span>GL_QUADS<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
		glVertex3f<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				
		glVertex3f<span style="color: #009900;">&#40;</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				
		glVertex3f<span style="color: #009900;">&#40;</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				
		glVertex3f<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>			
	glEnd<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// update display</span>
	SDL_GL_SwapBuffers<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>So this function will be called every frame to draw the entire screen or &#8220;scene&#8221;. In this example, it’s simply drawing a red quad on the screen. What’s happening should be clear. First the framebuffer is cleared to get rid of the last scene. Then the identity matrix is loaded into the view matrix so that we are in the center of our world. After that the &#8220;camera&#8221; is positioned slightly to the left and back a little so the quad is nice and visible. Also, remember OpenGL uses a <a href="http://en.wikipedia.org/wiki/Cartesian_coordinate_system"> right handed system </a> so to move the camera back we move along the negative z-axis. Moving on, the active color is then set to red and the quad is drawn vertex by vertex inside the glBegin/glEnd calls. Note that we are not culling back faces so we don’t worry about vertex winding order. Finally a call to SDL_GL_SwapBuffers is made so that the output can be seen. You should see a nice pretty red square.</p>
<h2> ProcessInput </h2>
<p>The ProcessInput function is responsible for reacting to input events like key presses. Basically it’s the same code from the last example moved into its own little function. It returns true to indicate that the user has indicated he would like to exit the game. Here is the code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="c" style="font-family:monospace;">bool ProcessInput<span style="color: #009900;">&#40;</span> <span style="color: #993333;">void</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// runs the input processing loop</span>
	<span style="color: #666666; font-style: italic;">// returns true if any input has requested the application to exit</span>
&nbsp;
	SDL_Event evt<span style="color: #339933;">;</span>
	bool exitFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// check for events generated from SDL</span>
	<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> SDL_PollEvent<span style="color: #009900;">&#40;</span> <span style="color: #339933;">&amp;</span>evt <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">type</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">case</span> SDL_QUIT<span style="color: #339933;">:</span>
			exitFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">case</span> SDL_KEYUP<span style="color: #339933;">:</span>
			<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">sym</span> <span style="color: #339933;">==</span> SDLK_ESCAPE <span style="color: #009900;">&#41;</span>
				exitFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> exitFlag<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h2> Complete Code Listing </h2>
<p>Ok, that was great fun. Now, behold the entire code listing!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;windows.h&gt;</span>
&nbsp;
<span style="color: #339933;">#include &lt;gl\gl.h&gt;</span>
<span style="color: #339933;">#include &lt;gl\glu.h&gt;</span>
&nbsp;
<span style="color: #339933;">#include &lt;sdl.h&gt;</span>
<span style="color: #339933;">#include &lt;sdl_opengl.h&gt;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// function prototypes</span>
<span style="color: #993333;">int</span> SetupOpenGL<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> width<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> height<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> fov<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> nearClip<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> farClip <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #993333;">void</span> RenderScene<span style="color: #009900;">&#40;</span> <span style="color: #993333;">void</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
bool ProcessInput<span style="color: #009900;">&#40;</span> <span style="color: #993333;">void</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// graphics properties</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">int</span> width <span style="color: #339933;">=</span> <span style="color: #0000dd;">640</span><span style="color: #339933;">;</span>        <span style="color: #666666; font-style: italic;">// width of the game window </span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">int</span> height <span style="color: #339933;">=</span> <span style="color: #0000dd;">480</span><span style="color: #339933;">;</span>       <span style="color: #666666; font-style: italic;">// height of the game window</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">float</span> fov <span style="color: #339933;">=</span> <span style="color:#800080;">45.0f</span><span style="color: #339933;">;</span>      <span style="color: #666666; font-style: italic;">// field of view (degrees)</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">float</span> nearClip <span style="color: #339933;">=</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// near clip plane (don't set to zero)</span>
	<span style="color: #993333;">const</span> <span style="color: #993333;">float</span> farClip <span style="color: #339933;">=</span> <span style="color:#800080;">100.0f</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// far clip plane</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// initialize SDL</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> SDL_Init<span style="color: #009900;">&#40;</span> SDL_INIT_VIDEO <span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to initialize SDL. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// set desired OpenGL attributes prior to selecting a video mode</span>
	SDL_GL_SetAttribute<span style="color: #009900;">&#40;</span> SDL_GL_DEPTH_SIZE<span style="color: #339933;">,</span> <span style="color: #0000dd;">16</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// use 16 bits for depth buffer</span>
	SDL_GL_SetAttribute<span style="color: #009900;">&#40;</span> SDL_GL_DOUBLEBUFFER<span style="color: #339933;">,</span> <span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// enable double buffering</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// create an OpenGL surface/window</span>
	SDL_Surface <span style="color: #339933;">*</span>screen <span style="color: #339933;">=</span> SDL_SetVideoMode<span style="color: #009900;">&#40;</span>width<span style="color: #339933;">,</span> height<span style="color: #339933;">,</span> <span style="color: #0000dd;">32</span><span style="color: #339933;">,</span> SDL_OPENGL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> screen <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
		fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to set video mode. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// initialize OpenGL</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> SetupOpenGL<span style="color: #009900;">&#40;</span> width<span style="color: #339933;">,</span> height<span style="color: #339933;">,</span> fov<span style="color: #339933;">,</span> nearClip<span style="color: #339933;">,</span> farClip<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		fprintf<span style="color: #009900;">&#40;</span> stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to setup OpenGL.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// main game loop</span>
	bool done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span>done <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		RenderScene<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> ProcessInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
			done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	SDL_Quit<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">int</span> SetupOpenGL<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> width<span style="color: #339933;">,</span> <span style="color: #993333;">int</span> height<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> fov<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> nearClip<span style="color: #339933;">,</span> <span style="color: #993333;">float</span> farClip <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	glClearColor<span style="color: #009900;">&#40;</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #993333;">float</span> ar <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>GLfloat<span style="color: #009900;">&#41;</span>width <span style="color: #339933;">/</span> height<span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// display aspect ratio</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// setup projection matrix</span>
	glMatrixMode<span style="color: #009900;">&#40;</span>GL_PROJECTION<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	glLoadIdentity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	gluPerspective<span style="color: #009900;">&#40;</span>fov<span style="color: #339933;">,</span> ar<span style="color: #339933;">,</span> nearClip<span style="color: #339933;">,</span> farClip<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// setup model view matrix</span>
	glMatrixMode<span style="color: #009900;">&#40;</span>GL_MODELVIEW<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>			
	glLoadIdentity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// setup depth buffer</span>
	glClearDepth<span style="color: #009900;">&#40;</span><span style="color:#800080;">1.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	glEnable<span style="color: #009900;">&#40;</span>GL_DEPTH_TEST<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
	glDepthFunc<span style="color: #009900;">&#40;</span>GL_LEQUAL<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
&nbsp;
	<span style="color: #666666; font-style: italic;">// misc. GL settings</span>
	glHint<span style="color: #009900;">&#40;</span>GL_PERSPECTIVE_CORRECTION_HINT<span style="color: #339933;">,</span> GL_NICEST<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	glShadeModel<span style="color: #009900;">&#40;</span>GL_SMOOTH<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	glViewport<span style="color: #009900;">&#40;</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> width<span style="color: #339933;">,</span> height <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #993333;">void</span> RenderScene<span style="color: #009900;">&#40;</span> <span style="color: #993333;">void</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// render everything for the current frame</span>
&nbsp;
	glClear<span style="color: #009900;">&#40;</span> GL_COLOR_BUFFER_BIT <span style="color: #339933;">|</span> GL_DEPTH_BUFFER_BIT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	glMatrixMode<span style="color: #009900;">&#40;</span> GL_MODELVIEW <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	glLoadIdentity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// move off center so the quad is visible</span>
	glTranslatef<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #339933;">,</span> <span style="color: #339933;">-</span><span style="color:#800080;">5.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// draw quad as red</span>
	glColor3f<span style="color: #009900;">&#40;</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// render the quad</span>
	glBegin<span style="color: #009900;">&#40;</span>GL_QUADS<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>						
		glVertex3f<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				
		glVertex3f<span style="color: #009900;">&#40;</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				
		glVertex3f<span style="color: #009900;">&#40;</span> <span style="color:#800080;">1.0f</span><span style="color: #339933;">,-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>				
		glVertex3f<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,-</span><span style="color:#800080;">1.0f</span><span style="color: #339933;">,</span> <span style="color:#800080;">0.0f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>			
	glEnd<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// update display</span>
	SDL_GL_SwapBuffers<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
bool ProcessInput<span style="color: #009900;">&#40;</span> <span style="color: #993333;">void</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// runs the input processing loop</span>
	<span style="color: #666666; font-style: italic;">// returns true if any input has requested the application to exit</span>
&nbsp;
	SDL_Event evt<span style="color: #339933;">;</span>
	bool exitFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// check for events generated from SDL</span>
	<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> SDL_PollEvent<span style="color: #009900;">&#40;</span> <span style="color: #339933;">&amp;</span>evt <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">type</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">case</span> SDL_QUIT<span style="color: #339933;">:</span>
			exitFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">case</span> SDL_KEYUP<span style="color: #339933;">:</span>
			<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">sym</span> <span style="color: #339933;">==</span> SDLK_ESCAPE <span style="color: #009900;">&#41;</span>
				exitFlag <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
			<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> exitFlag<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h2> Wrap Up </h2>
<p>Well, now we can at least draw something on the screen. I wanted to do textures on this post but it is already getting pretty lengthy. So, next time we will texture map the quad and work another step closer to having some kind of game programmed.</p>
<p>Have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/117/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>SDL &amp; OpenGL Game with C++ &#8211; Part I</title>
		<link>http://www.crowsprogramming.com/archives/104</link>
		<comments>http://www.crowsprogramming.com/archives/104#comments</comments>
		<pubDate>Mon, 23 Nov 2009 07:22:01 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Game Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=104</guid>
		<description><![CDATA[ Parts in the Series 

 Part II &#8211; Drawing a Quad 

 Getting Started 
 I think I&#8217;ve spent too many late nights playing multiplayer Modern Warfare 2 and now I feel the need to build a small game of some kind. Game programming is fun, and although I’ve never done it professionally, I [...]]]></description>
			<content:encoded><![CDATA[<h3> Parts in the Series </h3>
<ul>
<li><a href="http://www.crowsprogramming.com/archives/117"> Part II &#8211; Drawing a Quad </a></li>
</ul>
<h2> Getting Started </h2>
<p> I think I&#8217;ve spent too many late nights playing multiplayer Modern Warfare 2 and now I feel the need to build a small game of some kind. Game programming is fun, and although I’ve never done it professionally, I have dabbled with it as a hobby for many years. I’ll be documenting my progress here over time via a number of different postings. Maybe some of you will find it useful as a reference or small SDL tutorial or game programming tutorial. That being said, time to get to work!</p>
<p>I have no idea what type of game to build yet so the first thing to do is just get the basic framework setup. I&#8217;ll be using C++ for this game project. I thought about using C# and <a href="http://creators.xna.com">XNA</a> but I need to dust off my C++. For the graphics system I decided to use OpenGL. This is mostly because I am familiar with it and didn&#8217;t want the extra overhead of boilerplate setup stuff associated with DirectX. I just want to get something going quickly. For the rest of the stuff needed (audio, input, etc) I am going to use SDL. SDL is a great tool to get things up and running fast and it easily interfaces with OpenGL. I am also thinking about putting in some UI stuff using <a href="http://www.cegui.org.uk">CEGUI (Crazy Eddie&#8217;s GUI System).</a></p>
<h2>SDL Setup Prerequisites</h2>
<p>Before we get started you’ll want to make sure you have the SDL development libraries (I am using version 1.2.14). You can find them on the SDL website: <a href="http://www.libsdl.org">http://www.libsdl.org.</a> The ones I used specifically are:</p>
<ul>
<li>Runtime &#8211; <a href="http://www.libsdl.org/release/SDL-1.2.14-win32.zip">http://www.libsdl.org/release/SDL-1.2.14-win32.zip</a></li>
<li>Library (Visual Studio 2008) &#8211; <a href="http://www.libsdl.org/release/SDL-devel-1.2.14-VC8.zip">http://www.libsdl.org/release/SDL-devel-1.2.14-VC8.zip</a></li>
</ul>
<p><span id="more-104"></span></p>
<h2> Creating the Project </h2>
<p>Ok enough talk, let&#8217;s get started. You&#8217;ll need to create a new project and correctly configure it to use the SDL library. Fire up Visual Studio and create a new C/C++ console project. In the project wizard, <i>uncheck</i> the &#8220;Using Precompiled Header&#8221; option and <i>check</i> the &#8220;empty project&#8221; option. Now, add a new file and call it <b>main.cpp</b>.</p>
<p>In the Solution Explorer, right click your project and select properties. Open the C/C++ settings and select the general property page. Under the item &#8220;additional include directories&#8221; enter the path to the SDL SDK header files (i.e. C:\YourSDLDir\SDL-1.2.14\include).</p>
<p>Now, drop down to the Code Generation page and under &#8220;Runtime Library&#8221; select &#8220;Multi-threaded DLL&#8221;.  If you try to link with the debug build of the runtime you’ll see a nice error message like this one:</p>
<p><i>warning LNK4098: defaultlib &#8216;msvcrt.lib&#8217; conflicts with use of other libs; use /NODEFAULTLIB:library</i></p>
<p>This is because the SDL runtime is <b>not</b> a debug build. I couldn&#8217;t find a debug build on the SDL website so I guess if you want one you have to build it from source.</p>
<p>That takes care of the C/C++ settings so now let&#8217;s do the linker settings. Under the linker settings select the general page. Under additional library directories enter the path to the lib directory for your SDL SDK (i.e. C:\YourSDLDIR\SDL-1.2.14\lib). On the input page 2 files need to be listed as additional dependencies.</p>
<ul>
<li> SDL.lib</li>
<li> SDLmain.lib</li>
</ul>
<p>Also, make sure you grab SDL.dll from the SDK and put it in your debug folder along side the executable you build.</p>
<p>And that’s it! Go ahead and compile your application to make sure you set everything up correctly.</p>
<h2>Basic SDL Usage</h2>
<p>Next we will fill out main.cpp to get a basic SDL skeleton application running. Start out by including the SDL header file.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;sdl.h&gt;</span></pre></div></div>

<p>Now add the main function:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, an interesting thing to note here is that’s not really your normal main function. It’s not even the main entry point into your application. SDL redefines main using a <i>#define to SDL_main</i>. This also means that you cannot change the function signature as you normally could for a main function. SDL_main just does some basic housekeeping/setup stuff on behalf of SDL.</p>
<h2> SDL Initialization </h2>
<p>Next up we need to initialize the SDL system. This is accomplished via SDL_Init. Go ahead and add the following to your main function.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> SDL_Init<span style="color: #009900;">&#40;</span> SDL_INIT_VIDEO <span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
   fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to initialize SDL. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This will initialize SDL and the video subsystem. If it fails, it will print an error message to the standard error stream. Since we have a console app, this information will be printed directly to the console. Note the usage of SDL_GetError. This is a great tool to help determine why an SDL function call failed. It simply returns a pointer to a null-terminated string containing a description of the <b>last</b> failure.</p>
<p>The next thing to do is setup a video mode. This will give us a window and a drawing surface so we can actually render game content to the screen. Add the following code after the SDL_Init block.</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">SDL_Surface <span style="color: #339933;">*</span>screen <span style="color: #339933;">=</span> SDL_SetVideoMode<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">640</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">480</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">32</span><span style="color: #339933;">,</span> SDL_SWSURFACE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> screen <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
   fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to set video mode. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This will get us a window and a surface to draw on that’s 640&#215;480 with 32 bits per pixel. The video surface will be created in system memory as opposed to say video memory thanks to the SDL_SWSURFACE flag. That&#8217;s ok for now. Also note that you could create the application in fullscreen mode by specifying SDL_FULLSCREEN for the last parameter.</p>
<p>Now we&#8217;re going to add the main game loop. Game loops can get pretty complicated but we will keep it simple here. For now we only need to check user input. So let&#8217;s add the following code now.</p>
<h2> Game Loop &#038; Event Processing </h2>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">SDL_Event evt<span style="color: #339933;">;</span>
bool done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span>done <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> SDL_PollEvent<span style="color: #009900;">&#40;</span> <span style="color: #339933;">&amp;</span>evt <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">type</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">case</span> SDL_QUIT<span style="color: #339933;">:</span>
		  done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
		  <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">case</span> SDL_KEYUP<span style="color: #339933;">:</span>
		  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">sym</span> <span style="color: #339933;">==</span> SDLK_ESCAPE <span style="color: #009900;">&#41;</span>
		       done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
		  <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
                  <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Ok, so what&#8217;s going on here is that for every trip through the game loop we are emptying the SDL event queue and processing the events. SDL stores all kinds of events for us such as key presses, mouse movement, and joystick input. In this case, we want to know if the user wants to quit the application (SDL_QUIT) or if the user presses the escape key (SDL_KEYUP). In both cases we simply set <i>done</i> to true to signal the main loop to bail. SDL_Event is a union with all kinds of interesting structures in it. You should have a look at it in the SDL documentation.</p>
<p>The last thing that needs to happen is to shutdown the application. We can accomplish that with a simple call to SDL_Quit.</p>
<p>So, without further ado, here is the complete skeletal SDL game code that simply creates a 640&#215;480 window and waits for the user to press escape or close the window.</p>
<h2> Full Code Listing</h2>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;sdl.h&gt;</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span> <span style="color: #993333;">int</span> argc<span style="color: #339933;">,</span> <span style="color: #993333;">char</span> <span style="color: #339933;">**</span>argv<span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	SDL_Event evt<span style="color: #339933;">;</span>
	bool done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// initialize SDL</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> SDL_Init<span style="color: #009900;">&#40;</span> SDL_INIT_VIDEO <span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #0000dd;">1</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
            fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to initialize SDL. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// create a software surface/window</span>
	SDL_Surface <span style="color: #339933;">*</span>screen <span style="color: #339933;">=</span> SDL_SetVideoMode<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">640</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">480</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">32</span><span style="color: #339933;">,</span> SDL_SWSURFACE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> screen <span style="color: #339933;">==</span> <span style="color: #000000; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
            fprintf<span style="color: #009900;">&#40;</span>stderr<span style="color: #339933;">,</span> <span style="color: #ff0000;">&quot;Failed to set video mode. [%s]<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> SDL_GetError<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            exit<span style="color: #009900;">&#40;</span><span style="color: #0000dd;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// main game loop</span>
	<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span>done <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">// check for events generated from SDL</span>
		<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span> SDL_PollEvent<span style="color: #009900;">&#40;</span> <span style="color: #339933;">&amp;</span>evt <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">type</span> <span style="color: #009900;">&#41;</span>
			<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">case</span> SDL_QUIT<span style="color: #339933;">:</span>
				done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
				<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> SDL_KEYUP<span style="color: #339933;">:</span>
				<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">sym</span> <span style="color: #339933;">==</span> SDLK_ESCAPE <span style="color: #009900;">&#41;</span>
					done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
				<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
				<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
			<span style="color: #009900;">&#125;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	SDL_Quit<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h2>Fun Stuff to Try</h2>
<p>So, here&#8217;s some fun stuff to try to understand a little more about making things happen in SDL.<br />
Try adding this snippet of code to see how to fill or clear the screen (SDL surface) with a different color. Before the main game loop add this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">Uint32 color1 <span style="color: #339933;">=</span> SDL_MapRGB<span style="color: #009900;">&#40;</span>screen<span style="color: #339933;">-&gt;</span>format<span style="color: #339933;">,</span> <span style="color: #208080;">0x00</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x00</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xFF</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Uint32 color2 <span style="color: #339933;">=</span> SDL_MapRGB<span style="color: #009900;">&#40;</span>screen<span style="color: #339933;">-&gt;</span>format<span style="color: #339933;">,</span> <span style="color: #208080;">0x00</span><span style="color: #339933;">,</span> <span style="color: #208080;">0xFF</span><span style="color: #339933;">,</span> <span style="color: #208080;">0x00</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Uint32 currentColor <span style="color: #339933;">=</span> color1<span style="color: #339933;">;</span></pre></div></div>

<p>And, your SDL_KEYUP processing code in your main loop should look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">case</span> SDL_KEYUP<span style="color: #339933;">:</span>
   <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">sym</span> <span style="color: #339933;">==</span> SDLK_ESCAPE <span style="color: #009900;">&#41;</span>
      done <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">true</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">else</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">sym</span> <span style="color: #339933;">==</span> SDLK_SPACE <span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#123;</span>
      currentColor <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> currentColor <span style="color: #339933;">==</span> color1 <span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> color2 <span style="color: #339933;">:</span> color1<span style="color: #339933;">;</span>
      SDL_FillRect<span style="color: #009900;">&#40;</span> screen<span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">NULL</span><span style="color: #339933;">,</span> currentColor<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      SDL_UpdateRect<span style="color: #009900;">&#40;</span>screen<span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">,</span> <span style="color: #0000dd;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
   <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now, every time your press the space key the screen color will alternate between green and blue.</p>
<p>Another thing you can do is when processing the key stroke is display the character pressed in the console window. You can do that like this:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #b1b100;">case</span> SDL_KEYDOWN<span style="color: #339933;">:</span>
   <span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span> <span style="color: #ff0000;">&quot;KEYDOWN: %c<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> evt.<span style="color: #202020;">key</span>.<span style="color: #202020;">keysym</span>.<span style="color: #202020;">unicode</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span></pre></div></div>

<p>But you have to remember to enable Unicode support within SDL. Do that with a call to <i>SDL_EnableUNICODE(1)</i> in the initialization code prior to the main game loop.</p>
<h2> What Next? </h2>
<p>Well that’s it for now. You now have a basic game setup using SDL. It also shows some basic ways to manipulate the screen and process SDL events. Next time I am going to start integrating OpenGL and get something fun on the screen. </p>
<p>If you have any questions or comments let me know. See ya next time!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/104/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Runtime Scripting in .Net</title>
		<link>http://www.crowsprogramming.com/archives/99</link>
		<comments>http://www.crowsprogramming.com/archives/99#comments</comments>
		<pubDate>Thu, 01 Oct 2009 04:49:40 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=99</guid>
		<description><![CDATA[The ability to ship source code with your product that can be compiled or interpreted at runtime is a very valuable asset.  Video games do this all the time with things like AI allowing the end-user to easily mod the game. In compiled languages like C++, this technique is highly advantageous as it allows [...]]]></description>
			<content:encoded><![CDATA[<p>The ability to ship source code with your product that can be compiled or interpreted at runtime is a very valuable asset.  Video games do this all the time with things like AI allowing the end-user to easily mod the game. In compiled languages like C++, this technique is highly advantageous as it allows you to avoid the costly compile-link cycle for every small change to a source file. This is also helpful in an environment where creating a new build, generating the installer, and deploying it is overkill or difficult to achieve. In this article we will examine how you can achieve this from .Net programs consuming a C# or VB.Net script.  I’ll refer to this as &#8220;scripting&#8221;, even though an unambiguous definition of a &#8220;script&#8221; is somewhat difficult to nail down.</p>
<p>Using a C# or VB script from a .Net language is actually very simple. The basic idea is to read in a source file, which could come from the network or disk, and compile it into a temporary assembly on file or IL in memory. Then you can instantiate types from the script file and use them just as easily as any other types already defined. Normally the hard part in this process is locating and invoking the proper compiler. Luckily, we can compile IL code using a CodeDomProvider like CSharpCodeProvider. And, since these types are part of the .Net framework we know they are available on the end-user PC! Life is great eh?</p>
<p>Ok, so first make sure you have referenced the following namespaces:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.CodeDom.Compiler</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.CSharp</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.VisualBasic</span><span style="color: #008000;">;</span></pre></div></div>

<p>Next you need to setup the compiler parameters. These are simply the options given to the compiler such as whether to create the resulting assembly in memory or if debug information should be included in the generated code. You can do this with the CompilerParameters type. Here is an example for creating an in memory assembly with debug information:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> CompilerParameters cparams <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CompilerParameters<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
 cparams.<span style="color: #0000FF;">GenerateInMemory</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
 cparams.<span style="color: #0000FF;">IncludeDebugInformation</span> <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
 cparams.<span style="color: #0000FF;">CompilerOptions</span> <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot; /debug:pdbonly&quot;</span><span style="color: #008000;">;</span>
&nbsp;
 cparams.<span style="color: #0000FF;">TreatWarningsAsErrors</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
 cparams.<span style="color: #0000FF;">GenerateExecutable</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span></pre></div></div>

<p>You would also want to add any references that your code needs using CompilerParameters. ReferencedAssemblies. So, after you have the compiler options set you need to actually invoke the C# or Visual Basic compiler. You do this by creating a CodeDomCompiler of the appropriate type:</p>
<p>VBCodeProvider – for Visual Basic<br />
CSharpCodeProvider – for C Sharp</p>
<p>Then you can use the provider to compile an assembly like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">CodeDomProvider provider <span style="color: #008000;">=</span> CSharpCodeProvider<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
CompilerResults result <span style="color: #008000;">=</span> provider.<span style="color: #0000FF;">CompileAssemblyFromFile</span><span style="color: #000000;">&#40;</span>cparams, script<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Where cparams are your compiler parameters and result is well, your results. Within results you will find out if the compilation was successful or generated warnings. It will also give you access to the resulting assembly. You can check for errors using results.Errors.HasErrors and reference the assembly with results.CompiledAssembly.</p>
<p><span id="more-99"></span></p>
<p>Now that you have a compiled assembly in memory, there is one last issue to address. How do you instantiate types from the assembly? The easiest way to attack the problem is to create an interface that your application can access and derive a type from that interface in your script. I’ve created a full example below (explained in code comments) to illustrate the technique I am talking about.</p>
<h2> C# Example </h2>
<h3> Main application &#8211; Script.cs</h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.CodeDom.Compiler</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.CSharp</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Microsoft.VisualBasic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ScriptingExample
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Script
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> LoadedType LoadScript<span style="color: #008000;">&lt;</span>LoadedType<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> script, <span style="color: #FF0000;">string</span> referenceString<span style="color: #000000;">&#41;</span> where LoadedType<span style="color: #008000;">:</span><span style="color: #FF0000;">class</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// this will load/compile the script source file, &quot;script&quot;, and return a type of LoadedType</span>
            <span style="color: #008080; font-style: italic;">// it is assumed that a type of &quot;LoadedType&quot; is defined in the script</span>
            <span style="color: #008080; font-style: italic;">// the referenceString is a comma delimited string identifying all references needed by the script</span>
            <span style="color: #008080; font-style: italic;">// e.g. &quot;System.dll,System.Windows.Forms.dll&quot;</span>
            <span style="color: #008080; font-style: italic;">// either the VB or C# compiler will be invoked, based upon the file extenstion .vb or .cs</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// try and compile the script</span>
            CompilerParameters cparams <span style="color: #008000;">=</span> CreateCompilerParameters<span style="color: #000000;">&#40;</span>referenceString<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            CompilerResults results <span style="color: #008000;">=</span> CompileScript<span style="color: #000000;">&#40;</span>script, cparams<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// check for errors</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>results.<span style="color: #0000FF;">Errors</span>.<span style="color: #0000FF;">HasErrors</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">string</span> e <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>CompilerError error <span style="color: #0600FF;">in</span> results.<span style="color: #0000FF;">Errors</span><span style="color: #000000;">&#41;</span>
                    e <span style="color: #008000;">+=</span> <span style="color: #000000;">&#40;</span>error.<span style="color: #0000FF;">ErrorText</span> <span style="color: #008000;">+</span> Environment.<span style="color: #0000FF;">NewLine</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ERROR IN SCRIPT: &quot;</span> <span style="color: #008000;">+</span> Environment.<span style="color: #0000FF;">NewLine</span> <span style="color: #008000;">+</span> e<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// find the &quot;exported&quot; type to load</span>
            LoadedType scriptObject <span style="color: #008000;">=</span> FindScriptObject<span style="color: #008000;">&lt;</span>LoadedType<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>results.<span style="color: #0000FF;">CompiledAssembly</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>scriptObject <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;CAN'T LOAD SCRIPT, TARGET TYPE NOT IMPLEMENTED IN SCRIPT.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                <span style="color: #0600FF;">return</span> scriptObject<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> CompilerResults CompileScript<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> script, CompilerParameters cparams<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// compiles the script using the specified parameters</span>
            <span style="color: #008080; font-style: italic;">// either the VB or C# compiler will be invoked, based upon the file extenstion .vb or .cs</span>
            CodeDomProvider provider <span style="color: #008000;">=</span> GetCompiler<span style="color: #000000;">&#40;</span>script<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            CompilerResults result <span style="color: #008000;">=</span> provider.<span style="color: #0000FF;">CompileAssemblyFromFile</span><span style="color: #000000;">&#40;</span>cparams, script<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> result<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        CodeDomProvider GetCompiler<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> script<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// returns the correct compiler to use based on the file extension of the script</span>
            <span style="color: #FF0000;">string</span> extension <span style="color: #008000;">=</span> Path.<span style="color: #0000FF;">GetExtension</span><span style="color: #000000;">&#40;</span>script<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>extension <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;.vb&quot;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> VBCodeProvider<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>extension <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;.cs&quot;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> CSharpCodeProvider<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;UNKNOWN SCRIPT TYPE&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> LoadedType FindScriptObject<span style="color: #008000;">&lt;</span>LoadedType<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>Assembly assembly<span style="color: #000000;">&#41;</span> where LoadedType <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// attempts to locate the type &quot;LoadedType&quot; within the assembly that was created from the &quot;script&quot;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Type t <span style="color: #0600FF;">in</span> assembly.<span style="color: #0000FF;">GetTypes</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>LoadedType<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">IsAssignableFrom</span><span style="color: #000000;">&#40;</span>t<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #0600FF;">return</span> Activator.<span style="color: #0000FF;">CreateInstance</span><span style="color: #000000;">&#40;</span>t<span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">as</span> LoadedType<span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #0600FF;">default</span><span style="color: #000000;">&#40;</span>LoadedType<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> CompilerParameters CreateCompilerParameters<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> referenceString<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// creates compiler parameters to generate an in memory assembly, with debug</span>
            <span style="color: #008080; font-style: italic;">// symbols if this is a debug build</span>
            <span style="color: #008080; font-style: italic;">// the referenceString is a comma delimited string identifying all references needed by the script</span>
            CompilerParameters cparams <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CompilerParameters<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            cparams.<span style="color: #0000FF;">GenerateInMemory</span> <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080;">#if DEBUG</span>
                <span style="color: #008080; font-style: italic;">// create debug symbols if this is a debug build</span>
                cparams.<span style="color: #0000FF;">IncludeDebugInformation</span> <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
                cparams.<span style="color: #0000FF;">CompilerOptions</span> <span style="color: #008000;">+=</span> <span style="color: #666666;">&quot; /debug:pdbonly&quot;</span><span style="color: #008000;">;</span>
            <span style="color: #008080;">#endif</span>
&nbsp;
            cparams.<span style="color: #0000FF;">TreatWarningsAsErrors</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
            cparams.<span style="color: #0000FF;">GenerateExecutable</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span> 
&nbsp;
            <span style="color: #008080; font-style: italic;">// seperate reference string</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> references <span style="color: #008000;">=</span> referenceString.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">','</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> reference <span style="color: #0600FF;">in</span> references<span style="color: #000000;">&#41;</span>
                cparams.<span style="color: #0000FF;">ReferencedAssemblies</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>reference<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> cparams<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3> App Showing How to Use Script.cs </h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.ComponentModel</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Data</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Drawing</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Linq</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ScriptingExample
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// we have to define an interface so we know how to &quot;talk&quot; to</span>
    <span style="color: #008080; font-style: italic;">// the script, that is, there must be a type that we *know* the</span>
    <span style="color: #008080; font-style: italic;">// script implements so we can call methods on it</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> MyScript
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">void</span> Execute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">partial</span> <span style="color: #FF0000;">class</span> Form1 <span style="color: #008000;">:</span> Form
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> Form1<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            InitializeComponent<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Form1_Load<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// just populate the combo box with all &quot;scripts&quot; located in the directory &quot;Scripts&quot;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> file <span style="color: #0600FF;">in</span> Directory.<span style="color: #0000FF;">GetFiles</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Scripts&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                comboBox1.<span style="color: #0000FF;">Items</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>file<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>comboBox1.<span style="color: #0000FF;">Items</span>.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
                comboBox1.<span style="color: #0000FF;">SelectedIndex</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
            <span style="color: #000000;">&#123;</span>
                button1.<span style="color: #0000FF;">Enabled</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
                comboBox1.<span style="color: #0000FF;">Enabled</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> button1_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// load the script, which contains a type that implements MyScript</span>
            <span style="color: #008080; font-style: italic;">// and call the execute method on it</span>
            Script s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Script<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// these are the references the script will need, we must reference this executable</span>
            <span style="color: #008080; font-style: italic;">// because the script needs to see the MyScript data type</span>
            <span style="color: #008080; font-style: italic;">// this is just a sample, in a real application such types would be defined in an assembly dll</span>
            <span style="color: #008080; font-style: italic;">// that is shared between the app consuming the script and the script itself</span>
            <span style="color: #FF0000;">string</span> references <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;System.dll,System.Windows.Forms.dll,&quot;</span> <span style="color: #008000;">+</span> Directory.<span style="color: #0000FF;">GetCurrentDirectory</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\\</span>ScriptingExample.exe&quot;</span><span style="color: #008000;">;</span>
&nbsp;
            MyScript script <span style="color: #008000;">=</span> s.<span style="color: #0000FF;">LoadScript</span><span style="color: #008000;">&lt;</span>MyScript<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>comboBox1.<span style="color: #0000FF;">SelectedItem</span> <span style="color: #0600FF;">as</span> <span style="color: #FF0000;">string</span>, references<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            script.<span style="color: #0000FF;">Execute</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3> A VB and C# Script</h3>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Windows.Forms</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> ScriptingExample.<span style="color: #0000FF;">Scripts</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CSharpScript <span style="color: #008000;">:</span> MyScript
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Execute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;I AM A C# SCRIPT&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="vbnet" style="font-family:monospace;"><span style="color: #0600FF;">Imports</span> System
<span style="color: #0600FF;">Imports</span> System.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>
<span style="color: #0600FF;">Imports</span> System.<span style="color: #0000FF;">Text</span>
<span style="color: #0600FF;">Imports</span> System.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Forms</span>
&nbsp;
<span style="color: #0600FF;">Namespace</span> ScriptingExample.<span style="color: #0000FF;">Scripts</span>
    <span style="color: #FF8000;">Public</span> <span style="color: #0600FF;">Class</span> VBScript
        <span style="color: #0600FF;">Implements</span> MyScript
        <span style="color: #FF8000;">Public</span> <span style="color: #0600FF;">Sub</span> Execute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">Implements</span> MyScript.<span style="color: #0000FF;">Execute</span>
            MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;I AM A VB SCRIPT!!&quot;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #0600FF;">End</span> <span style="color: #0600FF;">Sub</span>
    <span style="color: #0600FF;">End</span> <span style="color: #0600FF;">Class</span>
<span style="color: #0600FF;">End</span> <span style="color: #0600FF;">Namespace</span></pre></div></div>

<h2>Conclusion</h2>
<p>And that&#8217;s it! A very simple technique that can be used in many interesting ways. I&#8217;ve included a link to a Visual Studio project containing an implementation using the above information. The project can be found <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/09/scriptingexample.zip"> here </a> As always, let me know if you have any questions or ideas!</p>
<p>See ya next time!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/99/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using Ini Files In C#</title>
		<link>http://www.crowsprogramming.com/archives/95</link>
		<comments>http://www.crowsprogramming.com/archives/95#comments</comments>
		<pubDate>Thu, 16 Jul 2009 23:26:32 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=95</guid>
		<description><![CDATA[An Initialization, or Ini file, is a common text based file format commonly used on the Windows platform. Today its mostly been succeeded in favor of XML files for application configuration and persisting user data. Never the less, these files still exist and are in use by many applications. In this post, we will explore [...]]]></description>
			<content:encoded><![CDATA[<p>An Initialization, or <b>Ini</b> file, is a common text based file format commonly used on the Windows platform. Today its mostly been succeeded in favor of XML files for application configuration and persisting user data. Never the less, these files still exist and are in use by many applications. In this post, we will explore how to work with Ini files via C#.</p>
<p>The structure of an Ini file is very simple and straight forward. You have three primary types of information: sections, parameters, and values. They look like this:</p>
<p>[SectionA]<br />
Parameter1=value1<br />
Parameter2=value2</p>
<p>[SectionB]<br />
Parameter1=value1</p>
<p>Below we will create a class to read this data from a file. Keep in mind as you look at this C# Ini file implementation that this is just one way to do it. You could for example, create a much more concise solution using regular expressions, etc.</p>
<h2>Parsing the Data</h2>
<p>The first thing we should do if figure out how to get the data from the Ini file. We could read in all the text and manually parse the file; however there is an easier approach. The Win32 API contains a function called <i>GetPrivateProfileString</i> that we can use specifically for this task. We can use it to directly obtain the sections, parameters, and values. For a more detailed description of the GetPrivateProfileString function, check out <a href="http://msdn.microsoft.com/en-us/library/ms724353%28VS.85%29.aspx">this link on MSDN</a>.</p>
<p>To use GetPrivateProfileString in C#, we need only reference it using the <i>DLLImport</i> attribute with the correct function signature.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Kernel32.dll&quot;</span>, EntryPoint <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;GetPrivateProfileStringW&quot;</span>, SetLastError <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span>, CharSet <span style="color: #008000;">=</span> CharSet.<span style="color: #0000FF;">Unicode</span>, ExactSpelling <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span>, CallingConvention <span style="color: #008000;">=</span> CallingConvention.<span style="color: #0000FF;">StdCall</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> <span style="color: #FF0000;">int</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> lpAppName,
                                                         <span style="color: #FF0000;">string</span> lpKeyName,
                                                         <span style="color: #FF0000;">string</span> lpDefault,
                                                         <span style="color: #000000;">&#91;</span><span style="color: #0600FF;">In</span>, <span style="color: #0600FF;">Out</span><span style="color: #000000;">&#93;</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> lpReturnString,
                                                         <span style="color: #FF0000;">int</span> nSize,
                                                         <span style="color: #FF0000;">string</span> lpFilename<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2> Reading from an Ini File</h2>
<p>First, to make our job a little easier we will wrap the call to GetPrivateProfileString with our own method so that we can handle all of the details. Here is the wrapper:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> appName, <span style="color: #FF0000;">string</span> keyName, <span style="color: #FF0000;">string</span> defaultName, <span style="color: #FF0000;">string</span> inifile<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// the file inifile should exist as it's validated in the class constructor, however GetPrivateProfileString does not lock the file hence it could be locked or deleted by</span>
            <span style="color: #008080; font-style: italic;">// another process between calls to this method</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// used to tell if we successfully read all requested data from the file </span>
            <span style="color: #008080; font-style: italic;">// from MSDN:</span>
            <span style="color: #008080; font-style: italic;">//  If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.</span>
            <span style="color: #008080; font-style: italic;">//  If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.</span>
            <span style="color: #FF0000;">int</span> sizeReadOffset <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>appName <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> keyName <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">:</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// try and read the entire amount of data from the ini file</span>
            <span style="color: #FF0000;">int</span> sizeRead <span style="color: #008000;">=</span> Kernel32.<span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #000000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if unable to read all of the data because the buffer is to small, increase the size and try again, but only allow memory to increase up to _readBufferMaxSize</span>
            <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>sizeRead <span style="color: #008000;">&gt;=</span> _readBufferSize <span style="color: #008000;">-</span> sizeReadOffset<span style="color: #000000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #000000;">&#40;</span>_readBufferSize <span style="color: #008000;">&lt;</span> _readBufferMaxSize<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _readBufferSize <span style="color: #008000;">+=</span> <span style="color: #FF0000;">512</span><span style="color: #008000;">;</span>
                _readBuffer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span>_readBufferSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
                sizeRead <span style="color: #008000;">=</span> Kernel32.<span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #000000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if memory consumption exceeded _readBufferMaxSize then we have a problem</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_readBufferSize <span style="color: #008000;">&gt;=</span> _readBufferMaxSize<span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> FileLoadException<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniLoad&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// the buffer returned from GetPrivateProfileString will be null terminated C-strings followed by a double null at the end - so split the strings on the nulls</span>
            <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> sep <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
            sep<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">'<span style="color: #008080; font-weight: bold;">\0</span>'</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">string</span> s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#40;</span>_readBuffer, <span style="color: #FF0000;">0</span>, sizeRead<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> result <span style="color: #008000;">=</span> s.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span>sep, StringSplitOptions.<span style="color: #0000FF;">RemoveEmptyEntries</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> result<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Here, the MSDN terminology refers to what I call a section as an appName and what I refer to as a paramter as a keyName.</p>
<p>This method has a lot going on but is very easy to use. To get an array of strings containing all of the section names you simply say:<br />
<span id="more-95"></span></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, filename<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And, to get an array of all parameter names for a particular section you would say:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span>sectionName, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, inifileName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And finally, to get a parameter value you could say:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span>sectionName, parameterName, <span style="color: #0600FF;">null</span>, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And the value is stored in the first element of the returned array.</p>
<h2>Putting it All Together</h2>
<p>So now we can put together a simple class encapsulating the above functionality. You can use this class as follows:</p>
<p>Given an Ini file:</p>
<p>[SectionA]<br />
Parameter1=value1<br />
Parameter2=value2</p>
<p>[SectionB]<br />
Parameter1=value1</p>
<p>You could,</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">            INIFile file <span style="color: #008000;">=</span>  <span style="color: #008000;">new</span> INIFile<span style="color: #000000;">&#40;</span>Directory.<span style="color: #0000FF;">GetCurrentDirectory</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> Path.<span style="color: #0000FF;">DirectorySeparatorChar</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;MyInifile.ini&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">string</span> a1 <span style="color: #008000;">=</span> file<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;SectionA&quot;</span>,<span style="color: #666666;">&quot;Parameter1&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// returns &quot;value1&quot;</span>
            <span style="color: #FF0000;">string</span> a2 <span style="color: #008000;">=</span> file<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;SectionA&quot;</span>,<span style="color: #666666;">&quot;Parameter2&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// returns &quot;value2&quot;</span>
&nbsp;
            <span style="color: #FF0000;">string</span> b1 <span style="color: #008000;">=</span> file<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;SectionB&quot;</span>, <span style="color: #666666;">&quot;Parameter1&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// returns &quot;value1&quot;</span></pre></div></div>

<p>Have fun playing with it. You could easily add the ability to write new sections and parameters as well. If you make some changes, find some bugs, or just plain find it useful let me know. I am always interested.</p>
<p>Here is the complete code listing for the class. You can <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/07/inifile.cs">download it here</a> or just copy and paste it.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Contains native Win32 API methods found in Kernel32. </span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> Kernel32
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Retrieves a string from the specified section in an initialization file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpAppName&quot;&gt;The name of the section containing the key name. If this parameter is NULL, the GetPrivateProfileString function copies all section names in the file to the supplied buffer.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpKeyName&quot;&gt;The name of the key whose associated string is to be retrieved. If this parameter is NULL, all key names in the section specified by the lpAppName parameter are copied to the buffer specified by the lpReturnedString parameter.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpDefault&quot;&gt;A default string. If the lpKeyName key cannot be found in the initialization file, GetPrivateProfileString copies the default string to the lpReturnedString buffer. If this parameter is NULL, the default is an empty string, &quot;&quot;.</span>
        <span style="color: #008080; font-style: italic;">///                         &lt;para&gt;Avoid specifying a default string with trailing blank characters. The function inserts a null character in the lpReturnedString buffer to strip any trailing blanks.&lt;/para&gt;&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpReturnString&quot;&gt;A pointer to the buffer that receives the retrieved string.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;nSize&quot;&gt;The size of the buffer pointed to by the lpReturnedString parameter, in characters.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;lpFilename&quot;&gt;The name of the initialization file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The return value is the number of characters copied to the buffer, not including the terminating null character.&lt;/returns&gt;</span>
        <span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Kernel32.dll&quot;</span>, EntryPoint <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;GetPrivateProfileStringW&quot;</span>, SetLastError <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span>, CharSet <span style="color: #008000;">=</span> CharSet.<span style="color: #0000FF;">Unicode</span>, ExactSpelling <span style="color: #008000;">=</span> <span style="color: #0600FF;">true</span>, CallingConvention <span style="color: #008000;">=</span> CallingConvention.<span style="color: #0000FF;">StdCall</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> <span style="color: #FF0000;">int</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> lpAppName,
                                                         <span style="color: #FF0000;">string</span> lpKeyName,
                                                         <span style="color: #FF0000;">string</span> lpDefault,
                                                         <span style="color: #000000;">&#91;</span><span style="color: #0600FF;">In</span>, <span style="color: #0600FF;">Out</span><span style="color: #000000;">&#93;</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> lpReturnString,
                                                         <span style="color: #FF0000;">int</span> nSize,
                                                         <span style="color: #FF0000;">string</span> lpFilename<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
&nbsp;
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Represents the &lt;i&gt;common&lt;/i&gt; INI file format consisting of parameter-value pairs grouped by sections.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> INIFile
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region Nested Types</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">enum</span> CaseSensitiviy
        <span style="color: #000000;">&#123;</span>
            CaseInsensitive,
            CaseSensitive
        <span style="color: #000000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Properties</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Provides the string value of parameter belonging to the specified section. The section and parameter must exist.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section the parameter belongs to.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;parameterName&quot;&gt;The name of the parameter containing the value.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.ArgumentException&quot;&gt;Thrown if either the section or parameter name do not exist.&lt;/exception&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The value of the parameter.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">string</span> sectionName, <span style="color: #FF0000;">string</span> parameterName<span style="color: #000000;">&#93;</span>
        <span style="color: #000000;">&#123;</span>
            get
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_sections.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span>sectionName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_sections<span style="color: #000000;">&#91;</span>sectionName<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span>parameterName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                        <span style="color: #0600FF;">return</span> _sections<span style="color: #000000;">&#91;</span>sectionName<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#91;</span>parameterName<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
                    <span style="color: #0600FF;">else</span>
                        <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniFile&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
                <span style="color: #0600FF;">else</span>
                    <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniFile&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Specifies what case sensitivity mode is being used when looking up section and parameter names.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">public</span> CaseSensitiviy CaseSensitivity
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _caseSensitivity<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Events</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Constructors</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Loads the specified INI file. By default, all searches for section and parameter names will be case sensitive.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;The file name and path to the INI file. If this parameter does not contain a full path to the file, the method will search the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.IO.FileNotFoundException&quot;&gt;Thrown if filename could not be found and doesn't exist in the Window directory.&lt;/exception&gt;</span>
        <span style="color: #0600FF;">public</span> INIFile<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> filename<span style="color: #000000;">&#41;</span> <span style="color: #008000;">:</span>
            <span style="color: #0600FF;">this</span><span style="color: #000000;">&#40;</span>filename, CaseSensitiviy.<span style="color: #0000FF;">CaseSensitive</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Loads the specified INI file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;The file name and path to the INI file. If this parameter does not contain a full path to the file, the method will search the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sensitivity&quot;&gt;Specifies if letter case should be accounted for when looking up section and parameter names.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.IO.FileNotFoundException&quot;&gt;Thrown if filename could not be found and doesn't exist in the Window directory.&lt;/exception&gt;</span>
        <span style="color: #0600FF;">public</span> INIFile<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> filename, CaseSensitiviy sensitivity<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// make sure the file exists, directly, or in the Windows directory</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>File.<span style="color: #0000FF;">Exists</span><span style="color: #000000;">&#40;</span>filename<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>File.<span style="color: #0000FF;">Exists</span><span style="color: #000000;">&#40;</span>Path.<span style="color: #0000FF;">Combine</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">ExpandEnvironmentVariables</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;%WinDir%&quot;</span><span style="color: #000000;">&#41;</span>, filename<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> FileNotFoundException<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// save local state</span>
            _caseSensitivity <span style="color: #008000;">=</span> sensitivity<span style="color: #008000;">;</span>
            _readBufferSize <span style="color: #008000;">=</span> _readBufferDefaultSize<span style="color: #008000;">;</span>
            _readBuffer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span>_readBufferSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// read all section names</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, filename<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// the data is stored in a dictionary, we must tell it if case sensitivity is important</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_caseSensitivity <span style="color: #008000;">==</span> CaseSensitiviy.<span style="color: #0000FF;">CaseInsensitive</span><span style="color: #000000;">&#41;</span>
                _sections <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span>StringComparer.<span style="color: #0000FF;">CurrentCultureIgnoreCase</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                _sections <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// now, read in all parameters and values for each section name we located</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> s <span style="color: #0600FF;">in</span> raw<span style="color: #000000;">&#41;</span>
                ReadSection<span style="color: #000000;">&#40;</span>filename, s, _sections<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Public Methods</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Checks to see if a given section exists in the Ini file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The section name to check for.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;True if the section exists, false if not.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> DoesSectionExist<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> sectionName<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> _sections.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span>sectionName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Checks to see if a given parameter exists for a section.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section containing the parameter.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;parameterName&quot;&gt;The name of the parameter to check for.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;True if the parameter exists, false if not.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> DoesParameterExist<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> sectionName, <span style="color: #FF0000;">string</span> parameterName<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>DoesSectionExist<span style="color: #000000;">&#40;</span>sectionName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">return</span> _sections<span style="color: #000000;">&#91;</span>sectionName<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span>parameterName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                <span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Private Methods</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Reads all parameters and values for a given section within the Ini file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;inifile&quot;&gt;The ini file to read from.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section to read.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;storage&quot;&gt;A dictionary containing an entry for the section that will be populated with the resulting parameters/values.&lt;/param&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> ReadSection<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> inifile, <span style="color: #FF0000;">string</span> sectionName, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;&gt;</span> storage<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// create the parameter/value dictionary for the section entry</span>
            <span style="color: #008080; font-style: italic;">// it is assumed that the callers logic created/validated storage[sectionName] -- we will not check again here</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_caseSensitivity <span style="color: #008000;">==</span> CaseSensitiviy.<span style="color: #0000FF;">CaseInsensitive</span><span style="color: #000000;">&#41;</span>
                storage<span style="color: #000000;">&#91;</span>sectionName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>StringComparer.<span style="color: #0000FF;">CurrentCultureIgnoreCase</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                storage<span style="color: #000000;">&#91;</span>sectionName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span>sectionName, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// now read in the values for the parameters that we found</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> s <span style="color: #0600FF;">in</span> raw<span style="color: #000000;">&#41;</span>
                ReadParameter<span style="color: #000000;">&#40;</span>inifile, sectionName, s, storage<span style="color: #000000;">&#91;</span>sectionName<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Reads the value of a parameter in a given section within the Ini file.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;inifile&quot;&gt;The ini file to read from.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;sectionName&quot;&gt;The name of the section containing the parameter.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;parameterName&quot;&gt;The name of the parameter to read.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;storage&quot;&gt;The dictionary that the parameter value will be written to.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;System.ArgumentException&quot;&gt;Thrown if more than 1 value is associated with a single parameter.&lt;/exception&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> ReadParameter<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> inifile, <span style="color: #FF0000;">string</span> sectionName, <span style="color: #FF0000;">string</span> parameterName, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> storage<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// get the param value</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> raw <span style="color: #008000;">=</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span>sectionName, parameterName, <span style="color: #0600FF;">null</span>, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// store the resulting value, if more than 1 value comes back for the parameter throw an exception, not sure how to parse that scenario</span>
            <span style="color: #008080; font-style: italic;">// if no values come back just use an empty string by default</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>raw.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniFile&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>raw.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
                storage<span style="color: #000000;">&#91;</span>parameterName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
                storage<span style="color: #000000;">&#91;</span>parameterName<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> raw<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Wrapper around the Win32 function GetPrivateProfileString to make it nicer and more robust.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;appName&quot;&gt;The name of the section containing the key name. If this parameter is null, all section names will be returned.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;keyName&quot;&gt;The name of the key whose associated string is to be retrieved. If this parameter is null, all key names in the section will be returned.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;defaultName&quot;&gt;A default string. If the keyName key cannot be found in the initialization file, GetPrivateProfileString copies the default string to the </span>
        <span style="color: #008080; font-style: italic;">///                           returned value. If this parameter is null, the default is an empty string, &quot;&quot;.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;inifile&quot;&gt;The path and file name of the INI file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;An array of string containing either section names, parameter names, or values corresponding to appName and keyName.&lt;/returns&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;FileLoadException&quot;&gt;&lt;/exception&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> GetPrivateProfileString<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> appName, <span style="color: #FF0000;">string</span> keyName, <span style="color: #FF0000;">string</span> defaultName, <span style="color: #FF0000;">string</span> inifile<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// the file inifile should exist as it's validated in the class constructor, however GetPrivateProfileString does not lock the file hence it could be locked or deleted by</span>
            <span style="color: #008080; font-style: italic;">// another process between calls to this method</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// used to tell if we successfully read all requested data from the file </span>
            <span style="color: #008080; font-style: italic;">// from MSDN:</span>
            <span style="color: #008080; font-style: italic;">//  If neither lpAppName nor lpKeyName is NULL and the supplied destination buffer is too small to hold the requested string, the string is truncated and followed by a null character, and the return value is equal to nSize minus one.</span>
            <span style="color: #008080; font-style: italic;">//  If either lpAppName or lpKeyName is NULL and the supplied destination buffer is too small to hold all the strings, the last string is truncated and followed by two null characters. In this case, the return value is equal to nSize minus two.</span>
            <span style="color: #FF0000;">int</span> sizeReadOffset <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>appName <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> keyName <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">?</span> <span style="color: #FF0000;">1</span> <span style="color: #008000;">:</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// try and read the entire amount of data from the ini file</span>
            <span style="color: #FF0000;">int</span> sizeRead <span style="color: #008000;">=</span> Kernel32.<span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #000000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if unable to read all of the data because the buffer is to small, increase the size and try again, but only allow memory to increase up to _readBufferMaxSize</span>
            <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>sizeRead <span style="color: #008000;">&gt;=</span> _readBufferSize <span style="color: #008000;">-</span> sizeReadOffset<span style="color: #000000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #000000;">&#40;</span>_readBufferSize <span style="color: #008000;">&lt;</span> _readBufferMaxSize<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _readBufferSize <span style="color: #008000;">+=</span> <span style="color: #FF0000;">512</span><span style="color: #008000;">;</span>
                _readBuffer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span>_readBufferSize<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
                sizeRead <span style="color: #008000;">=</span> Kernel32.<span style="color: #0000FF;">GetPrivateProfileString</span><span style="color: #000000;">&#40;</span>appName, keyName, defaultName, _readBuffer, _readBufferSize, inifile<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// if memory consumption exceeded _readBufferMaxSize then we have a problem</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_readBufferSize <span style="color: #008000;">&gt;=</span> _readBufferMaxSize<span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> FileLoadException<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ErrorBadIniLoad&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// the buffer returned from GetPrivateProfileString will be null terminated C-strings followed by a double null at the end - so split the strings on the nulls</span>
            <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> sep <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
            sep<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">'<span style="color: #008080; font-weight: bold;">\0</span>'</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">string</span> s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#40;</span>_readBuffer, <span style="color: #FF0000;">0</span>, sizeRead<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> result <span style="color: #008000;">=</span> s.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span>sep, StringSplitOptions.<span style="color: #0000FF;">RemoveEmptyEntries</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> result<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080;">#region Fields</span>
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Stores the sections from the Ini file. The section name is the key. The value is another dictionary containing the parameter values, keyed on the parameter name.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">private</span> IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;&gt;</span> _sections<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Determines if case is ignored or not when referencing section and parameter names.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">private</span> CaseSensitiviy _caseSensitivity<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Holds the information from the last read of the ini file. The buffer is overwritten with sections, parameters, or values on each call to GetPrivateProfileString.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> _readBuffer<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The size, in bytes, of _readBuffer.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">int</span> _readBufferSize<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The starting size of _readBuffer, in bytes.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">int</span> _readBufferDefaultSize <span style="color: #008000;">=</span> <span style="color: #FF0000;">1024</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The maximum size _readBuffer is allowed to grow to in order to hold all information obtained from GetPrivateProfileString.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">int</span> _readBufferMaxSize <span style="color: #008000;">=</span> <span style="color: #FF0000;">4096</span><span style="color: #008000;">;</span>
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/95/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>I&#8217;m Back</title>
		<link>http://www.crowsprogramming.com/archives/91</link>
		<comments>http://www.crowsprogramming.com/archives/91#comments</comments>
		<pubDate>Thu, 16 Jul 2009 02:58:14 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=91</guid>
		<description><![CDATA[Hey guys, sorry I&#8217;ve been away for a bit. I&#8217;ll try and respond to your questions, especially those over on the C# dynamic web service page.
I&#8217;ll be adding a whole lot of new content as well. If anyone has any suggestions on a topic feel free to leave them for me.
See Ya!!
]]></description>
			<content:encoded><![CDATA[<p>Hey guys, sorry I&#8217;ve been away for a bit. I&#8217;ll try and respond to your questions, especially those over on the <a href="http://www.crowsprogramming.com/archives/66">C# dynamic web service page</a>.</p>
<p>I&#8217;ll be adding a whole lot of new content as well. If anyone has any suggestions on a topic feel free to leave them for me.</p>
<p>See Ya!!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/91/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Accessing the System Task Bar in C#</title>
		<link>http://www.crowsprogramming.com/archives/88</link>
		<comments>http://www.crowsprogramming.com/archives/88#comments</comments>
		<pubDate>Sun, 10 May 2009 06:56:18 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=88</guid>
		<description><![CDATA[In this post I’ll show you how to access the system taskbar and obtain information like its location, size, etc. You may find yourself needing to do something like this if you had a &#8220;popup&#8221; window for instance that is always supposed to &#8220;pop up&#8221; from the system tray. This is a common feature in [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I’ll show you how to access the system taskbar and obtain information like its location, size, etc. You may find yourself needing to do something like this if you had a &#8220;popup&#8221; window for instance that is always supposed to &#8220;pop up&#8221; from the system tray. This is a common feature in many of today’s applications; however the task bar may be docked somewhere other than the bottom of the screen or maybe even on a different monitor in a multi-monitor setup.</p>
<h2>The Taskbar is an APPBAR</h2>
<p>First, the task bar is considered an appbar (or <a href="http://msdn.microsoft.com/en-us/library/cc144177(VS.85).aspx">desktop application toolbar</a>) albeit with some special restrictions. Being an appbar we can talk to it with the Win32 API function <i><b>SHAppBarMessage</b></i>. SHAppBarMessage allows us to send a message to the system to get or set information about a registered appbar. The necessary C# definitions to access the function are as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>StructLayout<span style="color: #000000;">&#40;</span>LayoutKind.<span style="color: #0000FF;">Sequential</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">struct</span> RECT
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> left<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> top<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> right<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> bottom<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>StructLayout<span style="color: #000000;">&#40;</span>LayoutKind.<span style="color: #0000FF;">Sequential</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">struct</span> APPBARDATA
<span style="color: #000000;">&#123;</span>
<span style="color: #0600FF;">public</span> Int32 cbSize<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> IntPtr hWnd<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> Int32 uCallbackMessage<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> ABEdge uEdge<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> RECT rc<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">public</span> IntPtr lParam<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">enum</span> ABMsg
<span style="color: #000000;">&#123;</span>
ABM_NEW <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
      ABM_REMOVE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
      ABM_QUERYPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
      ABM_SETPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
      ABM_GETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span>,
      ABM_GETTASKBARPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>,
      ABM_ACTIVATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">6</span>,
      ABM_GETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">7</span>,
      ABM_SETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">8</span>,
      ABM_WINDOWPOSCHANGED <span style="color: #008000;">=</span> <span style="color: #FF0000;">9</span>,
      ABM_SETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">enum</span> ABEdge
<span style="color: #000000;">&#123;</span>
ABE_LEFT <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
      ABE_TOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
      ABE_RIGHT <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
      ABE_BOTTOM <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #FF0000;">enum</span> ABState
<span style="color: #000000;">&#123;</span>
ABS_MANUAL <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
      ABS_AUTOHIDE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
      ABS_ALWAYSONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
      ABS_AUTOHIDEANDONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;shell32.dll&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> IntPtr SHAppBarMessage<span style="color: #000000;">&#40;</span>ABMsg dwMessage, <span style="color: #000000;">&#91;</span><span style="color: #0600FF;">In</span>, <span style="color: #0600FF;">Out</span><span style="color: #000000;">&#93;</span> <span style="color: #0600FF;">ref</span> APPBARDATA pData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Using SHAppBarMessage</h2>
<p>In order to use SHAppBarMessage we must first fill out the APPBAR struct with at least the cbSize and hWnd members. For hWnd we need to get the handle to the system taskbar window. It just so happens that you can use the FindWindow API function with a system class name of &#8220;Shell_TrayWnd&#8221; to get the required handle. Of course, to the best of my knowledge the class name &#8220;Shell_TrayWnd&#8221; is not a &#8220;documented&#8221; part of the Win32 system therefore it could change with any Windows release. However, I think it’s probably a safe bet to rely on it given the number of applications in the field that already do. Without further ado, some code to get the size of the task bar.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;user32.dll&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> IntPtr FindWindow<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> lpClassName, <span style="color: #FF0000;">string</span> lpWindowName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
APPBARDATA appBar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> APPBARDATA<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
appBar.<span style="color: #0000FF;">hWnd</span> <span style="color: #008000;">=</span> FindWindow<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Shell_TrayWnd&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
appBar.<span style="color: #0000FF;">cbSize</span> <span style="color: #008000;">=</span> Marshal.<span style="color: #008000;">SizeOf</span><span style="color: #000000;">&#40;</span>appBar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #000000;">System</span>.<span style="color: #0000FF;">IntPtr</span> ret <span style="color: #008000;">=</span> SHAppBarMessage<span style="color: #000000;">&#40;</span>ABMsg.<span style="color: #0000FF;">ABM_GETTASKBARPOS</span>, <span style="color: #0600FF;">ref</span> appBar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Size s <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Size<span style="color: #000000;">&#40;</span>appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">right</span> <span style="color: #008000;">-</span> appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">left</span>, appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">bottom</span> <span style="color: #008000;">-</span> appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">top</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Simple right?</p>
<h2>Modifying the Taskbar</h2>
<p>Remember earlier I said the system taskbar is not quite like a normal appbar? Well it’s special in that you can’t really change any of its properties like its size or position. This makes sense as you wouldn’t just want any program you install to play with the users taskbar; it’s sort of like an invasion of privacy. I’ve seen claims around the Internet that this can be pulled off in application code, which may be true prior to Vista; however I’ve tried all kinds of tricks based on SHAppBarMessage and can’t change the taskbar properties under Vista. Do you know how this can be done or if it’s even possible? I have found that you can change the task bar state. That is, you can toggle between &#8220;autohide&#8221; mode and &#8220;always on top&#8221; mode.</p>
<h2>Example Taskbar Code</h2>
<p>So, here is a little class I’ve put together to wrap the SHAppBarMessage functionality. I really haven&#8217;t paid attention to error handling or anything with it so if you use this you would need to address that.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Runtime.InteropServices</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Drawing</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> TaskbarInfoExample
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Provides methods for obtaining and modifying information for the system taskbar.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #FF0000;">class</span> TaskBar
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region Native API</span>
        <span style="color: #008080; font-style: italic;">// The native API functions/enums/structs needed to access taskbar info</span>
        <span style="color: #008080; font-style: italic;">// consult MSDN for more detailed information about them</span>
        <span style="color: #000000;">&#91;</span>StructLayout<span style="color: #000000;">&#40;</span>LayoutKind.<span style="color: #0000FF;">Sequential</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">struct</span> RECT
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> left<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> top<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> right<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> bottom<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>StructLayout<span style="color: #000000;">&#40;</span>LayoutKind.<span style="color: #0000FF;">Sequential</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">struct</span> APPBARDATA
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">public</span> Int32 cbSize<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> IntPtr hWnd<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> Int32 uCallbackMessage<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> ABEdge uEdge<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> RECT rc<span style="color: #008000;">;</span>
            <span style="color: #0600FF;">public</span> IntPtr lParam<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">enum</span> ABMsg
        <span style="color: #000000;">&#123;</span>
            ABM_NEW <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
            ABM_REMOVE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
            ABM_QUERYPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
            ABM_SETPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
            ABM_GETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span>,
            ABM_GETTASKBARPOS <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>,
            ABM_ACTIVATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">6</span>,
            ABM_GETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">7</span>,
            ABM_SETAUTOHIDEBAR <span style="color: #008000;">=</span> <span style="color: #FF0000;">8</span>,
            ABM_WINDOWPOSCHANGED <span style="color: #008000;">=</span> <span style="color: #FF0000;">9</span>,
            ABM_SETSTATE <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">enum</span> ABEdge
        <span style="color: #000000;">&#123;</span>
            ABE_LEFT <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
            ABE_TOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
            ABE_RIGHT <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
            ABE_BOTTOM <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">enum</span> ABState
        <span style="color: #000000;">&#123;</span>
            ABS_MANUAL <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
            ABS_AUTOHIDE <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
            ABS_ALWAYSONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
            ABS_AUTOHIDEANDONTOP <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;shell32.dll&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> IntPtr SHAppBarMessage<span style="color: #000000;">&#40;</span>ABMsg dwMessage, <span style="color: #000000;">&#91;</span><span style="color: #0600FF;">In</span>, <span style="color: #0600FF;">Out</span><span style="color: #000000;">&#93;</span> <span style="color: #0600FF;">ref</span> APPBARDATA pData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #000000;">&#91;</span>DllImport<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;user32.dll&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">extern</span> IntPtr FindWindow<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> lpClassName, <span style="color: #FF0000;">string</span> lpWindowName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Represents the edge of the screen the task bar is docked to.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">enum</span> TaskBarEdge
        <span style="color: #000000;">&#123;</span>
            Left <span style="color: #008000;">=</span> ABEdge.<span style="color: #0000FF;">ABE_LEFT</span>,
            Top <span style="color: #008000;">=</span> ABEdge.<span style="color: #0000FF;">ABE_TOP</span>,
            Right <span style="color: #008000;">=</span> ABEdge.<span style="color: #0000FF;">ABE_RIGHT</span>,
            Bottom <span style="color: #008000;">=</span> ABEdge.<span style="color: #0000FF;">ABE_BOTTOM</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// The states the task bar can be in.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #000000;">&#91;</span>Flags<span style="color: #000000;">&#93;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">enum</span> TaskBarState
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
            <span style="color: #008080; font-style: italic;">/// No autohide, not always top</span>
            <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
            None <span style="color: #008000;">=</span> ABState.<span style="color: #0000FF;">ABS_MANUAL</span>,
&nbsp;
            <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
            <span style="color: #008080; font-style: italic;">/// Hides task bar when mouse exits task bar region</span>
            <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
            AutoHide <span style="color: #008000;">=</span> ABState.<span style="color: #0000FF;">ABS_AUTOHIDE</span>,
&nbsp;
            <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
            <span style="color: #008080; font-style: italic;">/// Taskbar is always on top of other windows</span>
            <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
            AlwaysTop <span style="color: #008000;">=</span> ABState.<span style="color: #0000FF;">ABS_ALWAYSONTOP</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the location, in screen coordinates of the task bar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The taskbar location.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Point GetTaskBarLocation<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> GetTaskBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> Point<span style="color: #000000;">&#40;</span>appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">left</span>, appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">top</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the size, in pixels of the task bar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The taskbar size.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> Size GetTaskBarSize<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> GetTaskBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> Size<span style="color: #000000;">&#40;</span>appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">right</span> <span style="color: #008000;">-</span> appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">left</span>, appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">bottom</span> <span style="color: #008000;">-</span> appBar.<span style="color: #0000FF;">rc</span>.<span style="color: #0000FF;">top</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the edge of the screen that the task bar is docked to.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TaskBarEdge GetTaskBarEdge<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> GetTaskBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>TaskBarEdge<span style="color: #000000;">&#41;</span>appBar.<span style="color: #0000FF;">uEdge</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets the current state of the taskbar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TaskBarState GetTaskBarState<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> CreateAppBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>TaskBarState<span style="color: #000000;">&#41;</span>SHAppBarMessage<span style="color: #000000;">&#40;</span>ABMsg.<span style="color: #0000FF;">ABM_GETSTATE</span>, <span style="color: #0600FF;">ref</span> appBar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Sets the state of the task bar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;state&quot;&gt;The new state.&lt;/param&gt;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> SetTaskBarState<span style="color: #000000;">&#40;</span>TaskBarState state<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> CreateAppBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            appBar.<span style="color: #0000FF;">lParam</span> <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>IntPtr<span style="color: #000000;">&#41;</span>state<span style="color: #008000;">;</span>
&nbsp;
            SHAppBarMessage<span style="color: #000000;">&#40;</span>ABMsg.<span style="color: #0000FF;">ABM_SETSTATE</span>, <span style="color: #0600FF;">ref</span> appBar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets an APPBARDATA struct with valid location,size,and edge of the taskbar.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> APPBARDATA GetTaskBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> CreateAppBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #000000;">System</span>.<span style="color: #0000FF;">IntPtr</span> ret <span style="color: #008000;">=</span> SHAppBarMessage<span style="color: #000000;">&#40;</span>ABMsg.<span style="color: #0000FF;">ABM_GETTASKBARPOS</span>, <span style="color: #0600FF;">ref</span> appBar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> appBar<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Creats an APPBARDATA struct with its hWnd member set to the task bar window.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> APPBARDATA CreateAppBarData<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            APPBARDATA appBar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> APPBARDATA<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            appBar.<span style="color: #0000FF;">hWnd</span> <span style="color: #008000;">=</span> FindWindow<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Shell_TrayWnd&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            appBar.<span style="color: #0000FF;">cbSize</span> <span style="color: #008000;">=</span> Marshal.<span style="color: #008000;">SizeOf</span><span style="color: #000000;">&#40;</span>appBar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> appBar<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3>That’s All!</h3>
<p>That’s all I’ve got for now. I have included a little demo app you can download to demonstrate the class. You can find that <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/05/taskbarinfoexample.zip">here </a>Basically it just allows you to modify the task bar state and shows you all of its properties.</p>
<p>Hope you found this useful and saved yourself some time!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/88/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Launching and Viewing Processes in C#</title>
		<link>http://www.crowsprogramming.com/archives/83</link>
		<comments>http://www.crowsprogramming.com/archives/83#comments</comments>
		<pubDate>Wed, 15 Apr 2009 05:23:19 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=83</guid>
		<description><![CDATA[You can launch a new process from a C# application by using the Process class located in the System.Diagnostics namespace. The Process class also allows you to obtain a collection of all running processes on the system.
How to Launch a New Process
Starting a process is really easy.

Process.Start&#40; &#34;Notepad.exe&#34; &#41;;

And that’s it. If Notepad.exe exists on [...]]]></description>
			<content:encoded><![CDATA[<p>You can launch a new process from a C# application by using the Process class located in the System.Diagnostics namespace. The Process class also allows you to obtain a collection of all running processes on the system.</p>
<h2>How to Launch a New Process</h2>
<p>Starting a process is really easy.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Process.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot;Notepad.exe&quot;</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And that’s it. If Notepad.exe exists on your system then it will start. Make sure that if you do not specify a complete path then the name you do present is available in your environment path. You can wait for the newly created process to terminate as well.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Process p <span style="color: #008000;">=</span> Process.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span> <span style="color: #666666;">&quot;Notepad.exe&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
p.<span style="color: #0000FF;">WaitForExit</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Keep in mind that WaitForExit will block the calling thread. If you don’t want that behavior considering launching the new process on a thread of its own. You can also use the ProcessStartInfo class to pass information to the Start method. This example launches the new process on a thread from the thread pool via an anonymous method. Remember to include System.Threading.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// launch the program / process on a new thread from the thread pool</span>
ThreadPool.<span style="color: #0000FF;">QueueUserWorkItem</span><span style="color: #000000;">&#40;</span> <span style="color: #000000;">&#40;</span>WaitCallback<span style="color: #000000;">&#41;</span><span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> state<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    ProcessStartInfo psi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ProcessStartInfo<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Notepad.exe&quot;</span>, <span style="color: #666666;">&quot;&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    Process p <span style="color: #008000;">=</span> Process.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span>psi<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    p.<span style="color: #0000FF;">WaitForExit</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Passing Arguments to the New Process</h2>
<p>You can also pass arguments to a new process. The next example will launch Notepad and tell it to open the file MyFile.txt.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ProcessStartInfo psi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ProcessStartInfo<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Notepad.exe&quot;</span>, <span style="color: #666666;">@&quot;C:\My\Path\MyFile.txt&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Process p <span style="color: #008000;">=</span> Process.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span>psi<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2> Launching a Document and Setting the Verb</h2>
<p>There are some other interesting things you can do with the Process class. For instance, instead of specifying a file name in Process.Start like we did above with Notepad.exe, we could specify a file or document. The method would then open that file with the registered default application for that type of file. You can also specify a verb that is associated with that file type. A verb represents an action that is associated with that file type. So, if I wanted to launch the default application for a .txt file and have that file printed I could do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ProcessStartInfo psi <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ProcessStartInfo<span style="color: #000000;">&#40;</span><span style="color: #666666;">@&quot;C:\My\Path\MyFile.txt&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
psi.<span style="color: #0000FF;">Verb</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;print&quot;</span><span style="color: #008000;">;</span>
&nbsp;
Process p <span style="color: #008000;">=</span> Process.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span>psi<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
p.<span style="color: #0000FF;">WaitForExit</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Listing All Running Processes</h2>
<p>The last thing I want to show you is how easy it is to view a list of all processes running on the system with C#. Assuming you have a ListBox name listbox1, the following code fragment would add an entry to the ListBox with the name of each process running on the system.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Process<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> processes <span style="color: #008000;">=</span> Process.<span style="color: #0000FF;">GetProcesses</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span> Process process <span style="color: #0600FF;">in</span> processes <span style="color: #000000;">&#41;</span>
   listBox1.<span style="color: #0000FF;">Items</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span> process.<span style="color: #0000FF;">ProcessName</span> <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Well, that’s it for today. Hope this information comes in handy for some of you!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/83/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How To Get Screen Shot Capture in C#</title>
		<link>http://www.crowsprogramming.com/archives/78</link>
		<comments>http://www.crowsprogramming.com/archives/78#comments</comments>
		<pubDate>Mon, 13 Apr 2009 06:36:10 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=78</guid>
		<description><![CDATA[It’s often necessary to programmatically get a screen shot of the desktop and save it to a file. This is pretty easy with C#; we can create a simple method that will save an image of whatever is on the screen or desktop.
Saving a Bitmap Image of the Screen
First make sure you include the System.Drawing.Imaging [...]]]></description>
			<content:encoded><![CDATA[<p>It’s often necessary to programmatically get a screen shot of the desktop and save it to a file. This is pretty easy with C#; we can create a simple method that will save an image of whatever is on the screen or desktop.</p>
<h2>Saving a Bitmap Image of the Screen</h2>
<p>First make sure you include the System.Drawing.Imaging namespace. Now, all we really have to do is create a new bitmap and use the CopyFromScreen method of the bitmaps Graphics device.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Saves a screen capture in the specified image format to a file.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> SaveScreenShot<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> filename, ImageFormat format<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
        Bitmap screenShot <span style="color: #008000;">=</span> CaptureScreenShot<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  	screenShot.<span style="color: #0000FF;">Save</span><span style="color: #000000;">&#40;</span>filename, format<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Saves a picture of the screen to a bitmap image.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The saved bitmap.&lt;/returns&gt;</span>
<span style="color: #0600FF;">private</span> Bitmap CaptureScreenShot<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
 	<span style="color: #008080; font-style: italic;">// get the bounding area of the screen containing (0,0)</span>
        <span style="color: #008080; font-style: italic;">// remember in a multidisplay environment you don't know which display holds this point</span>
    	Rectangle bounds <span style="color: #008000;">=</span> Screen.<span style="color: #0000FF;">GetBounds</span><span style="color: #000000;">&#40;</span>Point.<span style="color: #0000FF;">Empty</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	<span style="color: #008080; font-style: italic;">// create the bitmap to copy the screen shot to</span>
   	Bitmap bitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Bitmap<span style="color: #000000;">&#40;</span>bounds.<span style="color: #0000FF;">Width</span>, bounds.<span style="color: #0000FF;">Height</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	<span style="color: #008080; font-style: italic;">// now copy the screen image to the graphics device from the bitmap</span>
   	<span style="color: #0600FF;">using</span> <span style="color: #000000;">&#40;</span>Graphics gr <span style="color: #008000;">=</span> Graphics.<span style="color: #0000FF;">FromImage</span><span style="color: #000000;">&#40;</span>bitmap<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
   	<span style="color: #000000;">&#123;</span>
       	   gr.<span style="color: #0000FF;">CopyFromScreen</span><span style="color: #000000;">&#40;</span>Point.<span style="color: #0000FF;">Empty</span>, Point.<span style="color: #0000FF;">Empty</span>, bounds.<span style="color: #0000FF;">Size</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   	<span style="color: #000000;">&#125;</span>
&nbsp;
  	<span style="color: #0600FF;">return</span> bitmap<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>And that’s really all there is to capturing a screen shot. You can save it to whatever file you would like and in any of the image formats supported by ImageFormat such as PNG or JPEG. Keep in mind if your working in a multidisplay environment you’ll want to be careful which display your targeting. Or perhaps you may want a huge image of all the desktop displays.</p>
<p>You can use the above code simply by calling the SaveScreenShot method with a file name and image format to save to:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//save screen shot in PNG image format</span>
SaveScreenShot<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;MyScreenShot.png&quot;</span>, ImageFormat.<span style="color: #0000FF;">Png</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>With a really small change you can modify the above code to save a screen shot of an arbitrary control instead of the entire desktop display.</p>
<h2>Saving a Screen Capture of a Control</h2>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Saves a screen capture of the specified control to a file.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;control&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;filename&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> SaveControlShot<span style="color: #000000;">&#40;</span>Control control, <span style="color: #FF0000;">string</span> filename, ImageFormat format<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   	Bitmap controlShot <span style="color: #008000;">=</span> CaptureControlShot<span style="color: #000000;">&#40;</span>control<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   	controlShot.<span style="color: #0000FF;">Save</span><span style="color: #000000;">&#40;</span>filename, format<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Gets a bitmap image of the specified control.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;control&quot;&gt;&lt;/param&gt;</span>
<span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
<span style="color: #0600FF;">private</span> Bitmap CaptureControlShot<span style="color: #000000;">&#40;</span>Control control<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// get control bounding rectangle</span>
     	Rectangle bounds <span style="color: #008000;">=</span> control.<span style="color: #0000FF;">Bounds</span><span style="color: #008000;">;</span>
&nbsp;
   	<span style="color: #008080; font-style: italic;">// create the new bitmap that holds the image of the control</span>
     	Bitmap bitmap <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Bitmap<span style="color: #000000;">&#40;</span>bounds.<span style="color: #0000FF;">Width</span>, bounds.<span style="color: #0000FF;">Height</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   	<span style="color: #008080; font-style: italic;">// copy controls image data to the bitmaps graphics device</span>
    	<span style="color: #0600FF;">using</span> <span style="color: #000000;">&#40;</span>Graphics gr <span style="color: #008000;">=</span> Graphics.<span style="color: #0000FF;">FromImage</span><span style="color: #000000;">&#40;</span>bitmap<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
    	<span style="color: #000000;">&#123;</span>
        	gr.<span style="color: #0000FF;">CopyFromScreen</span><span style="color: #000000;">&#40;</span>control.<span style="color: #0000FF;">Location</span>, Point.<span style="color: #0000FF;">Empty</span>, bounds.<span style="color: #0000FF;">Size</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     	<span style="color: #000000;">&#125;</span>
&nbsp;
    	<span style="color: #0600FF;">return</span> bitmap<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>And you can use this just as easily as the previous screen capture method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// if &quot;this&quot; is a control, like a form</span>
SaveControlShot<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span>, <span style="color: #666666;">&quot;MyControlShot.png&quot;</span>, ImageFormat.<span style="color: #0000FF;">Png</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And there you have it, an example of simple methods for saving a screen shot or an image of a control. I Hope you find this helpful.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/78/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Introduction to Multithreading in C#</title>
		<link>http://www.crowsprogramming.com/archives/71</link>
		<comments>http://www.crowsprogramming.com/archives/71#comments</comments>
		<pubDate>Thu, 09 Apr 2009 00:34:18 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=71</guid>
		<description><![CDATA[This article is a very basic introductory tutorial for using multiple threads in C#. I’ll explain what threads are, why you would want to use them, and how to use them. I’ll also show you several examples for creating threads, killing threads, etc.
What’s a Thread?
A computer program is generally very linear. That is, you have [...]]]></description>
			<content:encoded><![CDATA[<p>This article is a very basic introductory tutorial for using multiple threads in C#. I’ll explain what threads are, why you would want to use them, and how to use them. I’ll also show you several examples for creating threads, killing threads, etc.</p>
<h2>What’s a Thread?</h2>
<p>A computer program is generally very linear. That is, you have a sequence of instructions that get executed one after another in an orderly and predictable fashion. This scenario only affords you one path of execution. Threads allow you to execute multiple paths of code simultaneously. Now, <i>simultaneously</i> in this case does not necessarily mean <i>physically</i> at the same time. Both your operating system and processor must support this for that to be true. Threads are not particular to C#; most modern programming languages such as Visual Basic.Net support the concept of threads.</p>
<h2>So Why Do I Need Multiple Threads?</h2>
<p>Threading is handy because many programming tasks are asynchronous. That is, I can start the task and go on about my business and when that task is finished it can let me know and I can take action. An example of this would be downloading files from a remote location. I can start downloading three files and when the first is finished I can process it while the others continue to download.</p>
<p>There are numerous other reasons. Consider for instance a long task like sorting a million numbers. If I start that task on the thread that runs the GUI then I couldn’t update my user interface which means I couldn’t respond to user requests like button clicks.</p>
<p>Ok, lets move on to an example of creating a new thread via C#.</p>
<h2>Creating a Thread with C#</h2>
<p>Creating a thread is easy; we make use of the Thread object from the System.Threading namespace. When we create the thread we must pass it a ParameterizedThreadStart  or ThreadStart delegate. This will be the method that gets invoked on the new thread – it’s the starting point. New threads begin life in a stopped state. To make it run we call the Thread.Start method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread myThread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>MyThreadFunction<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
myThread.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> MyThreadFunction<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;HI&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Congratulations, you’ve created your first thread that runs in parallel with your main thread.</p>
<h2> Passing an Argument to the New Thread</h2>
<p>You can easily pass an argument to the thread like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Thread myThread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>MyThreadFunction<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
myThread.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;HELLO WORLD&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> MyThreadFunction<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> x<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span>x <span style="color: #0600FF;">as</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Keep in mind that this is not the best way to pass data to the thread. Since Thread.Start accepts only an object this is not very type safe. Image if we didn’t pass a string or the object didn’t have a ToString method. The best way to accomplish this would be to encapsulate your thread function in a class with data members you could set ahead of time.</p>
<h2> Waiting for a Thread to Stop</h2>
<p>Now that we have our thread up and running, we may at some point wish to wait for it to complete. This is accomplished with the Thread.Join method. Here is an example for Thread.Join:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">myThread <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Thread<span style="color: #000000;">&#40;</span>MyThreadFunction<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
myThread.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;HELLO WORLD&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
myThread.<span style="color: #0000FF;">Join</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;ALL DONE!&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//-elsewhere</span>
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> MyThreadFunction<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> x<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   MessageBox.<span style="color: #0000FF;">Show</span><span style="color: #000000;">&#40;</span>x <span style="color: #0600FF;">as</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>When the first piece of code executes it will create a new thread that will begin running in MyThreadFunction. After calling myThread.join that thread will go to sleep and stop executing until MyThreadFunction returns. This will happen after you dismiss the message box. Finally, when MyThreadFunction exits and the thread is destroyed, the original thread will continue execution at the next statement and pop its message box.</p>
<p>One thing to watch out for is what happens if the thread function never returns meaning the thread never dies. In this situation you can specify a timeout value in Thread.Join. The method will block for a predetermined amount of time waiting for the thread to terminate. If the thread did not terminate then Thread.Join would return false.</p>
<h2>Stopping a Thread</h2>
<p>Stopping a thread is simple. You call Thread.Abort on the thread you wish to stop.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">myThread.<span style="color: #0000FF;">Abort</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>This will cause a ThreadAbortException to be raised on the thread you are trying to stop. Now this <i>usually</i> stops the thread. It’s possible that the thread can abort your abort and continue living. There are a few other circumstances that can prevent the thread from aborting.</p>
<h2>Sharing Variables</h2>
<p>When you have two or more threading running it’s possible that they could be executing at the same time. This can create problems when both threads are trying to read/write to the same variable. You have to synchronize thread access to shared variables. There are many synchronization primitives available to you in C# via the .Net Framework Library such as AutoResetEvent, Monitor, and Mutex. This is a big subject so I will defer it till another post.</p>
<p>Along those same lines here’s a tip: If you create secondary threads they cannot modify controls on your GUI. Only the thread that created a control can modify its properties. You will generate the dreaded <i>illegal cross thread exception</i>. <a href="http://www.crowsprogramming.com/archives/18">I’ve already posted a brief work around for this problem</a></p>
<p>So that’s it for my C# threading tutorial. Now you know the basics of how to create a thread, how to kill a thread, how to wait for a thread, and some general threading principles. This is a big subject and I’ve hardly done it justice with this little bit of writing. If there are sufficient interests, I will elaborate on some more advance multithreading techniques that are applicable in all .Net languages – not just C#. I’ll leave you with a small incomplete pro and con list about using multiple threads.</p>
<h3>Advantages of Multithreading</h3>
<ul>
<li> Improved performance – Multiple threads can execute concurrently.</li>
<li> Streamline application logic – Some tasks are easier to conceptualize this way</li>
<li> Improves responsiveness of an application – GUI still works under heavy load.</li>
</ul>
<p></p>
<h3>Disadvantages of Multithreading</h3>
<ul>
<li> Hard to write and debug – Nuff said!!</li>
<li> Performance impact from synchronizing access to shared variables</li>
<li> There is a limit to how many threads an operating system can handle efficiently</li>
<li> Context switching between threads can hurt performance</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/71/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C# &#8211; Dynamically Invoke Web Service At Runtime</title>
		<link>http://www.crowsprogramming.com/archives/66</link>
		<comments>http://www.crowsprogramming.com/archives/66#comments</comments>
		<pubDate>Wed, 08 Apr 2009 06:42:42 +0000</pubDate>
		<dc:creator>crow</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.crowsprogramming.com/?p=66</guid>
		<description><![CDATA[Web services have become an integral part of the communications between software over a network. There are a lot of ugly details behind how they work but thankfully C# hide a lot of those gory details. What you need to know is that there is a web service description (WSDL) that describes the available services [...]]]></description>
			<content:encoded><![CDATA[<p>Web services have become an integral part of the communications between software over a network. There are a lot of ugly details behind how they work but thankfully C# hide a lot of those gory details. What you need to know is that there is a web service description (WSDL) that describes the available services and the data types they use (via XML). </p>
<p>You can use the WSDL to create types in C# that can communicate with the web service. There are a couple of ways that you can do this. You can generate a proxy class using the WSDL utility in the .NET SDK and add it to your project. You can also download the WSDL file at runtime, create the proxy class, compile it into an assembly, and execute the methods on it. This allows you to dynamically invoke methods from a web service that aren’t known at build time and is the approach I will explore today.</p>
<h2> Step 1 – Obtain a ServiceDescriptionImporter</h2>
<p>We want to create a ServiceDescriptionImporter object that we can use to generate the web service proxy class.  We have to pass to it the WSDL location which is an XML document.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">XmlTextReader xmlreader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlTextReader<span style="color: #000000;">&#40;</span>“MyWebService” <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;?wsdl&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
ServiceDescription serviceDescription <span style="color: #008000;">=</span> ServiceDescription.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span>xmlreader<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// build an importer, that assumes the SOAP protocol, client binding, and generates properties</span>
ServiceDescriptionImporter descriptionImporter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ServiceDescriptionImporter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
descriptionImporter.<span style="color: #0000FF;">ProtocolName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Soap&quot;</span><span style="color: #008000;">;</span>
descriptionImporter.<span style="color: #0000FF;">AddServiceDescription</span><span style="color: #000000;">&#40;</span>serviceDescription, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
descriptionImporter.<span style="color: #0000FF;">Style</span> <span style="color: #008000;">=</span> ServiceDescriptionImportStyle.<span style="color: #0000FF;">Client</span><span style="color: #008000;">;</span>
descriptionImporter.<span style="color: #0000FF;">CodeGenerationOptions</span> <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Xml</span>.<span style="color: #0000FF;">Serialization</span></span>.<span style="color: #0000FF;">CodeGenerationOptions</span>.<span style="color: #0000FF;">GenerateProperties</span><span style="color: #008000;">;</span></pre></div></div>

<h2> Step 2 – Compile an Assembly from the importer</h2>
<p>Now that we have the ServiceDescriptionImporter we need to use it to compile a proxy assembly that we can use to communicate with the web service. The assembly will exist in the users’ temporary folder.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// a namespace and compile unit are needed by importer</span>
CodeNamespace <span style="color: #008080;">codeNamespace </span><span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CodeNamespace<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
CodeCompileUnit codeUnit <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CodeCompileUnit<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
codeUnit.<span style="color: #0000FF;">Namespaces</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>codeNamespace<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
ServiceDescriptionImportWarnings importWarnings <span style="color: #008000;">=</span> descriptionImporter.<span style="color: #0000FF;">Import</span><span style="color: #000000;">&#40;</span>codeNamespace, codeUnit<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>importWarnings <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">// no warnings</span>
<span style="color: #000000;">&#123;</span>
     <span style="color: #008080; font-style: italic;">// create a c# compiler</span>
     CodeDomProvider compiler <span style="color: #008000;">=</span> CodeDomProvider.<span style="color: #0000FF;">CreateProvider</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;CSharp&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// include the assembly references needed to compile</span>
     <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> references <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;System.Web.Services.dll&quot;</span>, <span style="color: #666666;">&quot;System.Xml.dll&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
     CompilerParameters parameters <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CompilerParameters<span style="color: #000000;">&#40;</span>references<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// compile into assembly</span>
     CompilerResults results <span style="color: #008000;">=</span> compiler.<span style="color: #0000FF;">CompileAssemblyFromDom</span><span style="color: #000000;">&#40;</span>parameters, codeUnit<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
     <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>CompilerError oops <span style="color: #0600FF;">in</span> results.<span style="color: #0000FF;">Errors</span><span style="color: #000000;">&#41;</span>
     <span style="color: #000000;">&#123;</span>
          <span style="color: #008080; font-style: italic;">// trap these errors and make them available to exception object</span>
          <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Compilation Error Creating Assembly&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     <span style="color: #000000;">&#125;</span>
&nbsp;
     <span style="color: #008080; font-style: italic;">// all done....</span>
     <span style="color: #0600FF;">return</span> results.<span style="color: #0000FF;">CompiledAssembly</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">else</span>
<span style="color: #000000;">&#123;</span>
     <span style="color: #008080; font-style: italic;">// warnings issued from importers, something wrong with WSDL</span>
     <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Invalid WSDL&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h2>Step 3 – Execute Methods from the Web Service</h2>
<p>Finally we have an assembly built from the web service description and now we can invoke methods from it just like any other ordinary assembly we might use. To accomplish this we must use reflection to discover the correct method.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #FF0000;">object</span> obj <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">webServiceAssembly</span>.<span style="color: #0000FF;">CreateInstance</span><span style="color: #000000;">&#40;</span>serviceName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
Type type <span style="color: #008000;">=</span> obj.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>T<span style="color: #000000;">&#41;</span>type.<span style="color: #0000FF;">InvokeMember</span><span style="color: #000000;">&#40;</span>methodName, BindingFlags.<span style="color: #0000FF;">InvokeMethod</span>, <span style="color: #0600FF;">null</span>, obj, args<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>And there you have it, dynamic invocation of web service methods at runtime. Using this technique you can invoke methods from any arbitrary web service at runtime.</p>
<p>Here is a full example class for dynamically invoking a web service method in C#.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.CodeDom</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.CodeDom.Compiler</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web.Services</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web.Services.Description</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web.Services.Discovery</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Xml</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> DynamicWebExample
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> WebServiceInvoker
    <span style="color: #000000;">&#123;</span>
        Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, Type<span style="color: #008000;">&gt;</span> availableTypes<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Text description of the available services within this web service.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> AvailableServices
        <span style="color: #000000;">&#123;</span>
            get<span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">services</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Creates the service invoker using the specified web service.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;webServiceUri&quot;&gt;&lt;/param&gt;</span>
        <span style="color: #0600FF;">public</span> WebServiceInvoker<span style="color: #000000;">&#40;</span>Uri webServiceUri<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">services</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// available services</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">availableTypes</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, Type<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// available types</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// create an assembly from the web service description</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">webServiceAssembly</span> <span style="color: #008000;">=</span> BuildAssemblyFromWSDL<span style="color: #000000;">&#40;</span>webServiceUri<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// see what service types are available</span>
            Type<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> types <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">webServiceAssembly</span>.<span style="color: #0000FF;">GetExportedTypes</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// and save them</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Type type <span style="color: #0600FF;">in</span> types<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                services.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>type.<span style="color: #0000FF;">FullName</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                availableTypes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>type.<span style="color: #0000FF;">FullName</span>, type<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Gets a list of all methods available for the specified service.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;serviceName&quot;&gt;&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> EnumerateServiceMethods<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> serviceName<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> methods <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">availableTypes</span>.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span>serviceName<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Service Not Available&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">else</span>
            <span style="color: #000000;">&#123;</span>
                Type type <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">availableTypes</span><span style="color: #000000;">&#91;</span>serviceName<span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #008080; font-style: italic;">// only find methods of this object type (the one we generated)</span>
                <span style="color: #008080; font-style: italic;">// we don't want inherited members (this type inherited from SoapHttpClientProtocol)</span>
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>MethodInfo minfo <span style="color: #0600FF;">in</span> type.<span style="color: #0000FF;">GetMethods</span><span style="color: #000000;">&#40;</span>BindingFlags.<span style="color: #0000FF;">Instance</span> <span style="color: #008000;">|</span> BindingFlags.<span style="color: #0600FF;">Public</span> <span style="color: #008000;">|</span> BindingFlags.<span style="color: #0000FF;">DeclaredOnly</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    methods.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>minfo.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">return</span> methods<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Invokes the specified method of the named service.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;typeparam name=&quot;T&quot;&gt;The expected return type.&lt;/typeparam&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;serviceName&quot;&gt;The name of the service to use.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;methodName&quot;&gt;The name of the method to call.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;args&quot;&gt;The arguments to the method.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The return value from the web service method.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">public</span> T InvokeMethod<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span> <span style="color: #FF0000;">string</span> serviceName, <span style="color: #FF0000;">string</span> methodName, <span style="color: #0600FF;">params</span> <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args <span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// create an instance of the specified service</span>
            <span style="color: #008080; font-style: italic;">// and invoke the method</span>
            <span style="color: #FF0000;">object</span> obj <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">webServiceAssembly</span>.<span style="color: #0000FF;">CreateInstance</span><span style="color: #000000;">&#40;</span>serviceName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Type type <span style="color: #008000;">=</span> obj.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>T<span style="color: #000000;">&#41;</span>type.<span style="color: #0000FF;">InvokeMember</span><span style="color: #000000;">&#40;</span>methodName, BindingFlags.<span style="color: #0000FF;">InvokeMethod</span>, <span style="color: #0600FF;">null</span>, obj, args<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Builds the web service description importer, which allows us to generate a proxy class based on the </span>
        <span style="color: #008080; font-style: italic;">/// content of the WSDL described by the XmlTextReader.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;xmlreader&quot;&gt;The WSDL content, described by XML.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;A ServiceDescriptionImporter that can be used to create a proxy class.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">private</span> ServiceDescriptionImporter BuildServiceDescriptionImporter<span style="color: #000000;">&#40;</span> XmlTextReader xmlreader <span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// make sure xml describes a valid wsdl</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>ServiceDescription.<span style="color: #0000FF;">CanRead</span><span style="color: #000000;">&#40;</span>xmlreader<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Invalid Web Service Description&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// parse wsdl</span>
            ServiceDescription serviceDescription <span style="color: #008000;">=</span> ServiceDescription.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span>xmlreader<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// build an importer, that assumes the SOAP protocol, client binding, and generates properties</span>
            ServiceDescriptionImporter descriptionImporter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ServiceDescriptionImporter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            descriptionImporter.<span style="color: #0000FF;">ProtocolName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Soap&quot;</span><span style="color: #008000;">;</span>
            descriptionImporter.<span style="color: #0000FF;">AddServiceDescription</span><span style="color: #000000;">&#40;</span>serviceDescription, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            descriptionImporter.<span style="color: #0000FF;">Style</span> <span style="color: #008000;">=</span> ServiceDescriptionImportStyle.<span style="color: #0000FF;">Client</span><span style="color: #008000;">;</span>
            descriptionImporter.<span style="color: #0000FF;">CodeGenerationOptions</span> <span style="color: #008000;">=</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Xml</span>.<span style="color: #0000FF;">Serialization</span></span>.<span style="color: #0000FF;">CodeGenerationOptions</span>.<span style="color: #0000FF;">GenerateProperties</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> descriptionImporter<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Compiles an assembly from the proxy class provided by the ServiceDescriptionImporter.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;descriptionImporter&quot;&gt;&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;An assembly that can be used to execute the web service methods.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">private</span> Assembly CompileAssembly<span style="color: #000000;">&#40;</span>ServiceDescriptionImporter descriptionImporter<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">// a namespace and compile unit are needed by importer</span>
            CodeNamespace <span style="color: #008080;">codeNamespace </span><span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CodeNamespace<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            CodeCompileUnit codeUnit <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CodeCompileUnit<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            codeUnit.<span style="color: #0000FF;">Namespaces</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>codeNamespace<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            ServiceDescriptionImportWarnings importWarnings <span style="color: #008000;">=</span> descriptionImporter.<span style="color: #0000FF;">Import</span><span style="color: #000000;">&#40;</span>codeNamespace, codeUnit<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>importWarnings <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">// no warnings</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// create a c# compiler</span>
                CodeDomProvider compiler <span style="color: #008000;">=</span> CodeDomProvider.<span style="color: #0000FF;">CreateProvider</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;CSharp&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #008080; font-style: italic;">// include the assembly references needed to compile</span>
                <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> references <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">&quot;System.Web.Services.dll&quot;</span>, <span style="color: #666666;">&quot;System.Xml.dll&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
                CompilerParameters parameters <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CompilerParameters<span style="color: #000000;">&#40;</span>references<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #008080; font-style: italic;">// compile into assembly</span>
                CompilerResults results <span style="color: #008000;">=</span> compiler.<span style="color: #0000FF;">CompileAssemblyFromDom</span><span style="color: #000000;">&#40;</span>parameters, codeUnit<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>CompilerError oops <span style="color: #0600FF;">in</span> results.<span style="color: #0000FF;">Errors</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">// trap these errors and make them available to exception object</span>
                    <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Compilation Error Creating Assembly&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #000000;">&#125;</span>
&nbsp;
                <span style="color: #008080; font-style: italic;">// all done....</span>
                <span style="color: #0600FF;">return</span> results.<span style="color: #0000FF;">CompiledAssembly</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// warnings issued from importers, something wrong with WSDL</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Invalid WSDL&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// Builds an assembly from a web service description.</span>
        <span style="color: #008080; font-style: italic;">/// The assembly can be used to execute the web service methods.</span>
        <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;webServiceUri&quot;&gt;Location of WSDL.&lt;/param&gt;</span>
        <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;A web service assembly.&lt;/returns&gt;</span>
        <span style="color: #0600FF;">private</span> Assembly BuildAssemblyFromWSDL<span style="color: #000000;">&#40;</span>Uri webServiceUri<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>webServiceUri.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> Exception<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Web Service Not Found&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            XmlTextReader xmlreader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlTextReader<span style="color: #000000;">&#40;</span>webServiceUri.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;?wsdl&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            ServiceDescriptionImporter descriptionImporter <span style="color: #008000;">=</span> BuildServiceDescriptionImporter<span style="color: #000000;">&#40;</span>xmlreader<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF;">return</span> CompileAssembly<span style="color: #000000;">&#40;</span>descriptionImporter<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> Assembly webServiceAssembly<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span> services<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This C# class can be easily used to invoke web service methods:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">WebServiceInvoker invoker <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WebServiceInvoker<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Uri<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;http://localhost/services/test.php&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">string</span> service <span style="color: #008000;">=</span> “MyService”<span style="color: #008000;">;</span>
<span style="color: #FF0000;">string</span> method <span style="color: #008000;">=</span> “MyMethod”<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> “arg1”, “arg2” <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #FF0000;">string</span> result <span style="color: #008000;">=</span> invoker.<span style="color: #0000FF;">InvokeMethod</span><span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>service, method, args<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>I’ve put together an example application that you can download to evaluate the class. It allows you to invoke methods from a web service entered on the GUI and see the return value. <a href="http://www.crowsprogramming.com/wp-content/uploads/2009/04/dynamicwebexample.zip">You can download it here.</a></p>
<p>
<img src="http://www.crowsprogramming.com/wp-content/uploads/2009/04/dynamicwebservice.png" /></p>
<p>I hope you find this useful and if you have any questions or comments be sure to leave them here.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.crowsprogramming.com/archives/66/feed</wfw:commentRss>
		<slash:comments>57</slash:comments>
		</item>
	</channel>
</rss>
