RSS
 

Archive for the ‘C#’ Category

XNA User Group & Boise Code Camp

27 Feb

Boise Code Camp happened yesterday and we had an excellent turn out.

I decided to give a session on XNA game development which turned out to have more people than I expected. I was also shocked to see so many hands go up when I asked how many people used XNA already, then see almost all those hands drop when I asked if anyone launched any games.

What is it that causes people to stop making their game? There must be some reason games are not being completed. My personal opinion… and thats all it is… is that many give up on development when they get stuck on something, bored of working alone, or see their dream of a game becoming a never ending processes of jumping through hoops.

This being said I think its time for us to start an XNA user group in the Boise, Idaho area. A few of us talked after the session and are putting out feelers to see who may be interested. I would like to have at least 15-20 dedicated folks that wouldn’t mind meeting once ever month or 2. I do not want to lead this alone and feel 2-3 leaders would be best. I am going to send out an email to BSDG (Boise Development Group) and see if we get a positive response.

If you are interested in joining an XNA user group please contact me directly or reply to this post.

Also… the demo game from code camp is available for download

River Rush (Code Camp)

 
1 Comment

Posted in C#, XNA

 

Trials and Tribulations Working with XNA

02 Feb

Wow, getting a game started on your own can be a pain in the ass. The XNA forums are full of information but scattered here and there and everywhere. Building a game is more than writing lines of code. Working with XNA you must deal with Importing objects, positioning them, lighting/shading them, and once you have that figured out you may be able to write some code.

For those of us who fly solo, It’s very time consuming and extremely painful to research, build a little, research more… erase what we have done, start again, build a little, research, build, erase, build, research, research, erase, erase all, Start over… you catch my drift.

Well I am in the start over phase, I had a game going (XNA Tanks) about a year ago that I finally have time to come back to. A year later… I am a much better programmer and a new version of XNA is out so I think its time to do this game correct.

What am I going to do other than build a game? I am going to post all the questions I have and every road block I run into. Then as I solve these riddles I will post how, and why when relevant, that way when the next developer going mano-a-mano with XNA doesn’t get blown away within the first couple days.

 
2 Comments

Posted in C#, XNA

 

Render BoundingSphere in XNA 4.0

26 Jan

There have been some changes in XNA 4.0 that prevent drawing primitives with XNA 3.1 code.
The following is a bounding sphere render class

 /// <summary>
    /// Provides a set of methods for rendering BoundingSpheres.
    /// </summary>
    public static class BoundingSphereRenderer
    {
        static VertexBuffer vertBuffer;
        static VertexDeclaration vertDecl;
        static BasicEffect effect;
        static int sphereResolution;

        /// <summary>
        /// Initializes the graphics objects for rendering the spheres. If this method isn't
        /// run manually, it will be called the first time you render a sphere.
        /// </summary>
        /// <param name="graphicsDevice">The graphics device to use when rendering.</param>
        /// <param name="sphereResolution">The number of line segments
        ///     to use for each of the three circles.</param>
        public static void InitializeGraphics(GraphicsDevice graphicsDevice, int sphereResolution)
        {
            BoundingSphereRenderer.sphereResolution = sphereResolution;

            //vertDecl = new VertexDeclaration(
            effect = new BasicEffect(graphicsDevice);
            effect.LightingEnabled = false;
            effect.VertexColorEnabled = false;

            VertexPositionColor[] verts = new VertexPositionColor[(sphereResolution + 1) * 3];

            int index = 0;

            float step = MathHelper.TwoPi / (float)sphereResolution;

            //create the loop on the XY plane first
            for (float a = 0f; a <= MathHelper.TwoPi; a += step)
            {
                verts[index++] = new VertexPositionColor(
                    new Vector3((float)Math.Cos(a), (float)Math.Sin(a), 0f),
                    Color.White);
            }

            //next on the XZ plane
            for (float a = 0f; a <= MathHelper.TwoPi; a += step)
            {
                verts[index++] = new VertexPositionColor(
                    new Vector3((float)Math.Cos(a), 0f, (float)Math.Sin(a)),
                    Color.White);
            }

            //finally on the YZ plane
            for (float a = 0f; a <= MathHelper.TwoPi; a += step)
            {
                verts[index++] = new VertexPositionColor(
                    new Vector3(0f, (float)Math.Cos(a), (float)Math.Sin(a)),
                    Color.White);
            }

            vertBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionColor), verts.Length, BufferUsage.None);
            vertBuffer.SetData(verts);
        }

        /// <summary>
        /// Renders a bounding sphere using different colors for each axis.
        /// </summary>
        /// <param name="sphere">The sphere to render.</param>
        /// <param name="graphicsDevice">The graphics device to use when rendering.</param>
        /// <param name="view">The current view matrix.</param>
        /// <param name="projection">The current projection matrix.</param>
        /// <param name="xyColor">The color for the XY circle.</param>
        /// <param name="xzColor">The color for the XZ circle.</param>
        /// <param name="yzColor">The color for the YZ circle.</param>
        public static void Render(
            BoundingSphere sphere,
            GraphicsDevice graphicsDevice,
            Matrix view,
            Matrix projection,
            Color xyColor,
            Color xzColor,
            Color yzColor)
        {
            if (vertBuffer == null)
                InitializeGraphics(graphicsDevice, 30);

            graphicsDevice.SetVertexBuffer(vertBuffer);

            effect.World =
                Matrix.CreateScale(sphere.Radius) *
                Matrix.CreateTranslation(sphere.Center);
            effect.View = view;
            effect.Projection = projection;
            effect.DiffuseColor = xyColor.ToVector3();

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                //render each circle individually
                graphicsDevice.DrawPrimitives(
                      PrimitiveType.LineStrip,
                      0,
                      sphereResolution);
                pass.Apply();
                effect.DiffuseColor = xzColor.ToVector3();
                graphicsDevice.DrawPrimitives(
                      PrimitiveType.LineStrip,
                      sphereResolution + 1,
                      sphereResolution);
                pass.Apply();
                effect.DiffuseColor = yzColor.ToVector3();
                graphicsDevice.DrawPrimitives(
                      PrimitiveType.LineStrip,
                      (sphereResolution + 1) * 2,
                      sphereResolution);
                pass.Apply();

            }

        }

        public static void Render(BoundingSphere[] spheres,
           GraphicsDevice graphicsDevice,
           Matrix view,
           Matrix projection,
           Color xyColor,
            Color xzColor,
            Color yzColor)
        {
            foreach (BoundingSphere sphere in spheres)
            {
                Render(sphere, graphicsDevice, view, projection, xyColor, xzColor, yzColor);
            }
        }

        public static void Render(BoundingSphere[] spheres,
            GraphicsDevice graphicsDevice,
            Matrix view,
            Matrix projection,
            Color color)
        {
            foreach (BoundingSphere sphere in spheres)
            {
                Render(sphere, graphicsDevice, view, projection, color);
            }
        }

        /// <summary>
        /// Renders a bounding sphere using a single color for all three axis.
        /// </summary>
        /// <param name="sphere">The sphere to render.</param>
        /// <param name="graphicsDevice">The graphics device to use when rendering.</param>
        /// <param name="view">The current view matrix.</param>
        /// <param name="projection">The current projection matrix.</param>
        /// <param name="color">The color to use for rendering the circles.</param>
        public static void Render(
            BoundingSphere sphere,
            GraphicsDevice graphicsDevice,
            Matrix view,
            Matrix projection,
            Color color)
        {
            if (vertBuffer == null)
                InitializeGraphics(graphicsDevice, 30);

            graphicsDevice.SetVertexBuffer(vertBuffer);

            effect.World =
                  Matrix.CreateScale(sphere.Radius) *
                  Matrix.CreateTranslation(sphere.Center);
            effect.View = view;
            effect.Projection = projection;
            effect.DiffuseColor = color.ToVector3();

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                //render each circle individually
                graphicsDevice.DrawPrimitives(
                      PrimitiveType.LineStrip,
                      0,
                      sphereResolution);
                graphicsDevice.DrawPrimitives(
                      PrimitiveType.LineStrip,
                      sphereResolution + 1,
                      sphereResolution);
                graphicsDevice.DrawPrimitives(
                      PrimitiveType.LineStrip,
                      (sphereResolution + 1) * 2,
                      sphereResolution);

            }

        }
    }
 
4 Comments

Posted in C#, XNA

 

Active Directory Property Names

20 Sep

lastlogoff
homemdb
badpwdcount
legacyexchangedn
givenname
logonhours
title
cn
whencreated
displayname
lastlogon
dscorepropagationdata
samaccounttype
msexchhomeservername
countrycode
objectguid
logoncount
msexchmailboxguid
authorigbl
usnchanged
objectsid
codepage
samaccountname
lastlogontimestamp
whenchanged
msexchmailboxsecuritydescriptor
homedirectory
mdbusedefaults
pwdlastset
mailnickname
homedrive
badpasswordtime
instancetype
adspath
msexchalobjectversion
primarygroupid
objectcategory
sn
objectclass
proxyaddresses
useraccountcontrol
description
distinguishedname
usncreated
textencodedoraddress
memberof
homemta
msexchuseraccountcontrol
mail
showinaddressbook
telephonenumber
accountexpires
department
scriptpath
msexchpoliciesincluded
userprincipalname
name
company

 
No Comments

Posted in C#

 

Return JSON from Web Services, Capture with jQuery

17 Jul

Many times now I have banged my head against the keyboard because I can’t get JSON to return correctly from my web service… Or is it the other way around? Is my service setup correctly but my Ajax call breaking things… Hopefully this can help people that were in my situation.

I have seen many people using a JSON serializer in their code. This is not normally necessary since WebServices should have the cabapility to serialize your object directly. Now lets get started… Your Web Service should look something like this.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService] //Make sure this is uncommented
public class MyWebService: System.Web.Services.WebService
{
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)] //This line is optional!
        public string MyJSONString()
        {
            return "MyJSONString!";
        }

        [WebMethod]
        public List<KeyValuePair<int, string>> MyJSONList(string sample)
        {
            return new List<KeyValuePair<int,string>>(){
                new KeyValuePair<int,string>(0,"MyValue1"),
                new KeyValuePair<int,string>(1,"MyValue2"),
                new KeyValuePair<int,string>(2,"MyValue3"),
                new KeyValuePair<int,string>(3,"MyValue4"),
                new KeyValuePair<int,string>(4,"MyValue5"),
            };

        }
}

Once you have that ready to go, and it looks like this you should be able to make an AJax call to return it as JSON. This is were a lot of people get caught up. You can’t use Jquery’s built in getJSON for reasons unknown to me webservices can only return JSON with a POST not a GET so here is a sample call that works for me. First the string, then the more advanced list.

 $.ajax({
    type: "POST",
    url: "http://localhost/WebServices/MyWebService.asmx/MyJSONString",
    data: "{}", //This is the KEY, Send in an empty object as the data
    contentType: "application/json; charset=utf-8", //this must be added in order to request json
    dataType: "json", //as well as this.
    success: function (data) {
        alert(data.d); //Should = "MyJSONString!"
    }
 });

Now the List, sometimes things get tricky here because as you can see the method requires a string as a parameter. This string needs to be sent in the Data… but remember we have to have a json object in the Data field. so we must send our parameters as a certain way… ‘{sample:value}’ just like that, if there are more you just add a comma ‘{sample:value, arg2:value}’.

 $.ajax({
    type: "POST",
    url: "http://localhost/WebServices/MyWebService.asmx/MyJSONList",
    data: '{sample:"' + myVar +'"}', //This is the KEY if you require arguments
    contentType: "application/json; charset=utf-8", //this must be added in order to request json
    dataType: "json", //as well as this.
    success: function (data) {
        alert(data.d); //Should = "[object],[object],etc"
    }
 });

using FireBug you can see the results of the query

As you can see web services adds a d to the json object… not sure why, but it does. Therefore you might not be able to implement this directly into a plugin that isn’t expecting the d you will have to modify it and then pass it back into the plugin.
But if you are having issues let me know… I’m more than happy to help.

 
 

Quick Serialization of an Object in C#

23 Jun

Sometimes I just post code snippets for myself.

Serializing 2 objects

try
{
	BinaryFormatter bf = new BinaryFormatter();
	using (Stream output = File.OpenWrite("File.txt")){
		bf.Serialize(output, object1);
		bf.Serialize(output, object2);
	}
}
catch (Exception ex)
{
	MessageBox.Show("Unable to save the file\r\n" + ex.Message,
	"File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

De-serializing the file

try
{
	BinaryFormatter bf = new BinaryFormatter();
	using (Stream output = File.OpenRead(openDialog.FileName)){
		object1 = (object1)bf.Deserialize(output);
		object2  = (object2)bf.Deserialize(output);
	}
}
catch (Exception ex)
{
	MessageBox.Show("Unable to read the file\r\n" + ex.Message,
	"File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
 
No Comments

Posted in C#

 

Read Web Page

17 May

Simple C# method to grab a webpage and read its contents… The following is used to get an external IP address easily…


System.Net.WebClient myWebClient = new System.Net.WebClient();

using( System.IO.Stream myStream = myWebClient.OpenRead("http://www.geekpedia.com/ip.php")){

System.IO.StreamReader myStreamReader = new System.IO.StreamReader(myStream);

string IP = myStreamReader.ReadToEnd();

}
 
No Comments

Posted in C#

 

TanksXNA

05 May

The TanksXNA game is good enough for an initial release, I need to add a Bugs board so people can add bugs they find there.

Anyways without further ado here it is

The XNA redistributable is required in order to run the game, a check is coming later for that.

TanksXNA

Redistributable

 
3 Comments

Posted in C#, XNA

 

Working With BackgroundWorker Part 2: Populating Treeviews

14 Apr

I ran into an issue the other day populating a Treeview with a bunch of data that took quite some time to retrieve. The problem wasn’t populating the tree, it was waiting for the data to come back, then populating the tree all at once that was bothering me. No one wants to wait forever for the treeview to become available. I figured a backgroundworker would be extremely useful at a time like this…

Let’s start by creating a simple method called PopulateTree and generating a BackgroundWorker… Make sure you generate the missing methods


private void PopulateTreeView()

{

BackgroundWorker bw = new BackgroundWorker();

bw.WorkerReportsProgress = true;

bw.WorkerSupportsCancellation = false;

bw.DoWork += new DoWorkEventHandler(bw_DoWork);

bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);

bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

You should already have a TreeView added to the Form. Lets just call it treeView1 for now. What we will do is populate the treeview with nodes 0 – a given number passed into the bw_DoWork method


//continuing inside the PopulateTreeView method

bw.RunWorkerAsync(10000);

}

//Now inside of our bw_DoWork method

void bw_DoWork(object sender, DoWorkEventArgs e)

{

//This is where the work you want the backgroundworker to do will be preformed

//DO NOT UPDATE THE GUI FROM HERE!

//The sender is the Background worker that called this Do Work

//Lets safely cast the backgroundwoker to bw

BackgroundWorker bw = sender as BackgroundWorker;

//The argument passed in is the number we want to count to.

int countTo = int.Parse(e.Argument.ToString());

//Loop through the numbers adding each one to the listview

for (int i = 1; i < countTo; i++)

{

//Calculate the percentage of numbers gone through

double percentComplete = (double) i / countTo) * 100;

//Report our progress

//This is where we tell the UI to update

//Lets pass the percentage and the number we want to add to the listview

bw.ReportProgress((int)percentComplete,i);

//Found it best to sleep for 1ms so the ui can update itself.

System.Threading.Thread.Sleep(1);

}

}

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

//This is where progress from the bw will be handled

//You CAN update the UI from this method.

int progressComplete = e.ProgressPercentage;

//this is the number to add to the TreeView

int number = (int)e.UserState;

treeView1.Nodes.Add(number.ToString());

}

So, basically what we did here was boxed up an int and sent it through background workers ReportProgress method and unboxed that number inside the ProgressChanged method, then added it to our listview.

This is the proper way to update the UI from a backgroundworker. What’s great is we are not limited to sending a single object through the report progress, we could send a collection or even any object through that… Part III will show an example of something more complex. This is a good start though.

Download Source BackgroundWorkers Populate Treeview

 
No Comments

Posted in C#, Threading

 

Working with BackgroundWorkers Part 1

24 Mar

One of the first things I attempted in C# was threading. Being tired of my vbscript and javascript applications freezing, I decided to learn all I could about it. Learning threading led to my first C# application and a major headache… until I ran into the eBook “Threading in C#” by Joseph Albahari. If you want to learn threading go here download the book and read it cover to cover. I swear it’s the best thing you will do.

After writing a complex program full of threads and issues I stumbled upon the windows control backgroundWorker. I then cussed aloud and removed about 75% of my old code and replaced it with this wonderful control. That’s what inspired me to post this today. I am going to go over the windows background worker and explain a few of the do’s and don’ts that will hopefully save a few headaches. I have limited time so it’s going to be done in parts. Part 1 consists of a basic overview.

Let’s get started.

BackgroundWorker bw = new BackgroundWorker;

The above code will create a background worker, or you can simple drag and drop one onto your windows form.

The background worker consists of Three events that you will handle, these events are the bread and butter to the background worker. They are as follows.

bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
return bw;

We now need to add the event methods.

void bw_DoWork(object sender, DoWorkEventArgs e){
//This is where the work you want the backgroundworker
//to do will be preformed

//DO NOT UPDATE THE GUI FROM HERE!

}

The DoWork method is where the background worker will do all of the work. .Net is smart and will launch the DoWork method in a seperate thread making threading simple, there is no need to implement your own threading! That being said… This DoWork method is being ran on a different thread! that means you Can’t update the user interface from this method, don’t try it, don’t even think about doing it! you will however and you will see what happens. Updating the UI needs to be done differently, and we will get to that.

The next method ProgressChanged

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)

{       //This is where progress from the bw will be handled

//You CAN update the UI from this method.

}

Yes, this is where you can update the user interface, It’s not as easy as you would like it I know but that’s the sad truth of threading. However you would be amazed at how easy the BackgroundWorker makes it compared to conventional threading.

The final Event is WorkCompleted

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

//Cleanup anything

//Update the UI if needed.

}

Here you cleanup everything you need to and update the UI if needed. Very straightforward.
What have we learned up until now? Not much except the 3 major events and the law “DO NOT UPDATE THE UI FROM THE DOWORK METHOD”

Part II contains an a working example.

 
No Comments

Posted in C#, Threading