C# Data Sync

Saturday, January 24, 2009

You'll notice the flash menu on the right hand side of this blog column. I wanted a menu that could sort my posts into categories. I could not find one that blogger offered so I decided to do what any self respecting coder does...I made my own!
Blogger offers an RSS feed of my blog, so I read that into flash and did some fancy formatting with xml so that it would sort all my posts into two categories:
  • Flash
  • C#
Then I ran into a crossdomain.xml issue. You see, Blogger doesn't allow any domains to in the crossdomain.xml, so my flash menu was done for.....or was it?
I thought, well I'll just write a C# console app that reads my blogs rss feed, saves it as an xml file, then calls another function that logs into my ftp server, posts the newly updated xml file and then closes its streams. It took maybe a few hours to figure out the code and piece it together, but it works great!

Now any time I make a new blog post, I just run the .exe on my computer and it updates the xml file that my flash menu (over on the right) points to, and that new blog post is instantly catagorized and loaded into the menu! FREAKIN SWEET!

and the function that does it, thanks to google and some of my own modification:

static void UploadToFTP()
{
Console.WriteLine("Uploading to FTP");
string filename = "data.xml";
FileInfo fileInf = new FileInfo(filename);

FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://domain_name_or_ip/folder_name/" + filename));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
request.UseBinary = true;
request.KeepAlive = false;
request.ContentLength = fileInf.Length;

int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();

try
{
// Stream to which the file to be upload is written
Stream strm = request.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);

// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();

Console.WriteLine("File Uploaded Successfully!");
Console.WriteLine("Closing streams...");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ": Upload Error");
System.Threading.Thread.Sleep(3000);
}
}

1 comments:

Daryl said...

You should check out Hanselman's post on using a Syntax Highlighter

http://www.hanselman.com/blog/BestCodeSyntaxHighlighterForSnippetsInYourBlog.aspx

Post a Comment