phone7

Windows Phone 7 – hacer web requests de forma simple

La célula de Mendoza esta intento buscar gente para hacer desarrollos en Windows Phone 7 y por mi cuenta (Angel) he estado haciendo algunas investigaciones.

Por naturaleza de aplicación para celular, lo mas conveniente es hacer aplicaciones que consuman datos de algún web service. A veces es difícil encontrar como hacer esto, mas cuando la plataforma es tan nueva. Acá les voy a pasar un ejemplo de como hacerlo correctamente y de forma fácil:

        public void GetXML(string url)
        {
            HttpWebRequest request = 
(HttpWebRequest)HttpWebRequest.Create(new Uri(url)); request.Headers["user-agent"] = "MSIE 7.0"; request.BeginGetResponse(new AsyncCallback(ReadCallback), request); } private void ReadCallback(IAsyncResult asynchronousResult) { HttpWebRequest request =
(HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response =
(HttpWebResponse)request.EndGetResponse(asynchronousResult); using (StreamReader streamReader =
new StreamReader(response.GetResponseStream())) { XDocument xmlDocument = XDocument.Load(streamReader); }
}

El código hace un pedido a una url especificada y cuando obtiene la respuesta va al metodo ReadCallback (si van a actualizar algún control tengan en cuenta que están trabajando en hilos diferentes). Yo en el ejemplo cree un XDocument (es la version de XmlDocument en WP7), pero pueden usar un string o lo que deseen.

Como les decia, si van a actualizar un metodo, lo mejor es usar un delegado y un evento (estos son ejemplos, no le presten atencion a los metodos y argumentos)

1) Declaramos en nuestra clase ambos:

public delegate void CharacterReceivedHandler(object sender, CharacterReceivedEventArgs e);
public event CharacterReceivedHandler CharacterReceived;

2) Disparamos el evento cuando armamos el XDocument ( o lo que recibamos):

 if(CharacterReceived != null)
      CharacterReceived(this,
new CharacterReceivedEventArgs() { Character = currentCharacter });

3)En la clase que enganchamos el metodo hacemos lo siguiente:

connector.CharacterReceived +=
new ArmoryConnector.CharacterReceivedHandler(connector_CharacterReceived);

void connector_CharacterReceived(object sender, CharacterReceivedEventArgs e) {   this.Dispatcher.BeginInvoke(delegate() {         // Update controls here
}); }

Ojala les sirva 🙂

phone7, xna

XNA – Your first Phone 7 Game in 3D !!!

Heiya guys ! I’ll post a small tutorial on how to compile your first 3d game on windows phone 7 (using the emulator).

First, you’ll need the developer tools WHICH ARE FREE !!! Get them RIGHT now:

http://www.microsoft.com/express/Phone/

Now, lets get this started. First open VS2010 and create a new Windows Game.

Camera

I’ve prepared a 3d camera suitable for a shooter. This means the camera is looking from upside down. You can feel free to use it in your projects. Here is the code:

   public static class Camera
   {
       public static Matrix World { get; private set; }
       public static Matrix View { get; set; }
       public static Matrix Projection { get; private set; }

       public static BoundingFrustum BoundingFrustum { get; private set; }

       public static Vector3 Position { get; set; }

       // needed attributes
       private static float nearClip = 1.0f;
       private static float farClip = 1000.0f;

       private static float aspectRatio = 800 / 600; // default aspect ratio
       public static float AspectRatio
       {
           get { return aspectRatio; }

           set
           {
               aspectRatio = value;
               UpdateMatrices();
           }

       }

       public static void Update()
       {
           UpdateMatrices();
       }

       public static void UpdateMatrices()
       {

           Matrix rotationMatrix = Matrix.CreateRotationX(MathHelper.ToRadians(90));
           Vector3 transformedReference = Vector3.Transform(Vector3.Forward, rotationMatrix);

           View = Matrix.CreateLookAt(Position, new Vector3(0, 0, 0), Vector3.Forward);
           Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
           World = Matrix.Identity;

           World = Matrix.Identity;

           BoundingFrustum = new BoundingFrustum(View * Projection);
       }
   }

The code is quite simple. The UpdateMatrices does all the work.  Notice I’ll I’m doing is transform the Forward vector with a 90 degrees angle. I know this is lame but I’ve choose this way to make it more graphical: In a normal FPS game you are pointing forward, if I rotate 90 degrees… well I know you get it 🙂

Note this:

Before we load the graphical device, we don’t know the viewport’s aspect ratio, so I’ve done it in a dynamic fashion, once you change the Camera’s ratio, it’ll recalculate the projection Matrix; this means you have to manually set the aspect ratio of the camera:

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            Camera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;
        }

Also ! remember to update the camera !!

Model

Here is the great part. Nothing has changed ! You can draw your models just the way you did it in the XNA 3.1 versions.

In a few steps:

  1. Declare your model
  2. Load it (notice the changes in the Content directory)
  3. Transform it
  4. Draw it

The declaration is easy, but the process to add it to the project is a little bit different. Here is a screenshoot:

loadModel

To load it, we use the same procedure as before:

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);

    // TODO: use this.Content to load your game content here
    Camera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;
    model = Content.Load<Model>("raptorxxi");
}

Here is our code to draw it (you can see the rest in the project).

/// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            // Copy any parent transforms.
            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in model.Meshes)
            {
                // This is where the mesh orientation is set, as well 
                // as our camera and projection.
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.View = Camera.View;
                    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(Vector3.Zero);
                    effect.Projection = Camera.Projection;
                }
                // Draw the mesh, using the effects set above.
                mesh.Draw();

            }

            base.Draw(gameTime);
        }

And there you go:

 final

Download the solution from HERE !!!!!