Thursday, February 18, 2010

How to add a new Blogger post with labels from C#

First download and install Google API from here:
http://code.google.com/p/google-gdata/downloads/list

Add a reference to "Google Data API Core Library",
and use the following function:


public static bool AddPost(string title, string bodyHTML, string[] labels)
{
    Service service = new Service("blogger", "<program name>");
    service.Credentials = new GDataCredentials("<username>", "<password>");
    AtomEntry newPost = new AtomEntry();
    newPost.Title.Text = title;
    newPost.Content = new AtomContent();
    newPost.Content.Content = bodyHTML;
    newPost.Content.Type = "html";
    foreach (string label in labels)
    {
        AtomCategory cat = new AtomCategory();
        cat.Scheme = new Uri("http://www.blogger.com/atom/ns#");
        cat.Term = label;
        newPost.Categories.Add(cat);
    }
    AtomEntry response = null;
    try
    {
        response = service.Insert(new Uri("<uri>"), newPost);
    }
    catch (GDataRequestException exception)
    {
        if (exception.ResponseString == "Blog has exceeded rate limit or otherwise requires word verification for new posts")
        {
            return false;
        }
        else
        {
            throw exception;
        }
    }
    if (response == null)
    {
        throw new Exception("Something went wrong");
    }
    return true;
}

Note what you need to replace:
Also note the marked yellow line. It took me some nasty googling time to find it. You must put it for the labels to work.

Blogger like search box

I copied the Blogger search box and added the following features:
  • It shows the current search keywords after you invoked the search (by parsing the URL)
  • It has a border that becomes gray when mouse is on the box
  • It has a faded string when not in focus, and it disappears when in focus
Take a look:
http://ycouriel-archive.blogspot.com/
(It's on the sidebar)

This is actually the first time I'm using HTML, JavaScript and CSS.
So I hope the code won't be that embarrassing:

<div id="b-navbar2">
<form style="display: inline;" method="get" action="http://ycouriel-archive.blogspot.com/search" id="searchthis">
<div id="b-query-box" style="width: 193.7px;" >
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<style type="text/css">
#b-navbar2{
white-space:nowrap;color:#fff;height:29px;border-bottom:1px solid #024;background:transparent;font-size:13px;font-family:Arial,Sans-serif
}
#b-navbar2 #b-query-box{
background-color:#fff;margin:0 .5em 0 0;border:1px solid transparent;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;padding:0 .3em
}
#b-navbar2 #b-query-box:hover{
border:1px solid #999999;
}
#b-navbar2 #b-query-icon{
display:block;width:13px;height:13px;cursor:pointer;cursor:hand;background:url(http://img1.blogblog.com/img/navbar/icons_orange.png) no-repeat 0 0
}
#b-navbar2 #b-query-icon:hover{
background:url(http://img1.blogblog.com/img/navbar/icons_orange.png) no-repeat -13px 0
}
#b-navbar2 #b-query{
font-size:13px;color:#000;background-color:transparent;border:none;margin:0
}
</style>
<td valign="middle">
<input type="text" title="Search" style="width: 180px; color: #999999;" tabindex="3" name="q" id="b-query" onblur="if (this.value == '') {this.value = 'Search...'; this.style.color='#999999';}" onfocus="if(this.value == 'Search...') {this.style.color='#000000';this.value = '';}" value="Search...">
</td>
<td valign="right" style="width: 15px;">
<a title="Search this blog" onclick="document.getElementById(&quot;searchthis&quot;).submit();" id="b-query-icon"></a></td></tr></tbody></table></div></form>
<script language="JavaScript">
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function decode(encoded) {
    return decodeURIComponent(encoded.replace(/\+/g, " "));
}

var q = gup("q");
if (q != "") {
    var lmnt = document.getElementById("b-query");
    lmnt.value = decode(q);
    lmnt.style.color = "#000000";
}
</script>

Thursday, January 21, 2010

My upgrades to XNA 2D beginners tutorial

I used a XNA 2D beginners tutorial and changed it to a more generic and flexible code.
I also added explosions and sound.
The new classes I created can be used for any 2D XNA game.
The tutorial is here: http://creators.xna.com/en-US/education/gettingstarted/bg2d/chapter1Explanations and demo of explosions: http://creators.xna.com/en-US/sample/particle
The demo project with the new classes: http://www.megaupload.com/?d=NEMV4EF3
Screenshot:


Most of the code can't be figured from the screenshot.
I created some generic classes to represent static objects, moving objects, particles, and particles systems. I wrote the most important things about some classes:
  • class GameObject2 : DrawableGameComponent
    • Represents a static 2D object
    • Has the following additional properties:
      • Texture
      • Position
      • Center
      • Rotation
      • Scale
      • DestinationRectangle
      • CenterPosition
      • Active
      • SourceRectangle
      • Color
      • Effects
      • LayerDepth
      • SpriteBlendMode
    • Has 8 different constructors for different purposes
    • Overrides Draw() method


  • class MovingGameObject2 : GameObject2
    • Represents an 2D object that moves
    • Has the following additional properties:
      • Velocity
      • Acceleration
      • RotationSpeed
      • TimeSinceInit
    • Overrides Update() method
    • class Particle2 : MovingGameObject2
      • Represents a 2D particle like in an explosion
      • Has a Lifetime property
      • Overrides Update() method
    • abstract class ParticleSystem2 : GameObject2
      • Represents a 2D particle system that can be used for explosions, smoke etc.
      • Has the following protected parameters:
        • rangeParticlesPerEffect
        • rangeVelocity
        • rangeAcceleration
        • rangeRotation
        • rangeRotationSpeed
        • rangeScale
        • rangeLifetime
      • Each new particle gets a random value for each parameter from its range
      • Overrides Draw() and Update() methods

      Tuesday, January 5, 2010

      How to restore Visual Studio .sln file icon

      I merely tried to associate .sln file type with the IDE so Windows 7 taskbar will remember my recent projects and I could access them with right click. I ended up reinstalling Visual Studio. This was after I tried to fix it in registry, just to find out Windows 7 has a different mechanism for file types associations. The big frustration was I could not find the icons themselves to put them on the registry. Visual Studio has a "Restore File Associations" feature. It doesn't fix the icons! Reinstalling after deleting all related registry values didn't work either! After a couple of hours where I visited sites like Ways Bill Gates Should Die, and Googling a lot I found the solution:

      1. Right click a .sln file
      2. Click "Open with..."
      3. Click "Browse..."
      4. Go to "Program Files\Common Files\microsoft shared\MSEnv"
      5. Choose "VSLauncher.exe"
      6. Click "Open"
      7. Check "Always use the selected program to open this kind of file"
      8. Click "OK"

      Tuesday, December 29, 2009

      C# Clipboard in Console Application

      In C# accessing the Clipboard suppose to be easy, but you'll find out it doesn't work in the normal way.
      Here is a small note from MSDN that I missed at first:

      The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.
      So, in a Console application, use this function:

      Code:
      public static object GetClipboardData()
      {
          object ret = null;
          ThreadStart method = delegate()
          {
              System.Windows.Forms.IDataObject dataObject = Clipboard.GetDataObject();
              if (dataObject != null && dataObject.GetDataPresent(DataFormats.Text))
              {
                  ret = dataObject.GetData(DataFormats.Text);
              }
          };
          if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
          {
              Thread thread = new Thread(method);
              thread.SetApartmentState(ApartmentState.STA);
              thread.Start();
              thread.Join();
          }
          else
          {
              method();
          }
          return ret;
      }

      Saturday, December 26, 2009

      Step-by-Step Math

      Have you ever given up working on a math problem because you couldn’t figure out the next step? Wolfram|Alpha can guide you step by step through the process of solving many mathematical problems, from solving a simple quadratic equation to taking the integral of a complex function.

      From here:
      http://blog.wolframalpha.com/2009/12/01/step-by-step-math/

      Example:
      http://www.wolframalpha.com/input/?i=integrate+x+Sqrt[1-Sqrt[x]]