What is the Difference Between a DTO and a POCO?

First off, I’m not the authority on DTOs, POCOs, object oriented architecture, or really anything now that I stop to think about it.  However, I do use a DTO / POCO centric architecture whenever I can and there’s at least one former client of mine who is now saddled with an entity class named DevicePoco (there was already a Device entity object that followed the Active Record pattern, otherwise I would never have named an object XXXPoco). When my client saw the new object with the crazy name in their BAL, their first reaction was of course to ask “What the heck is a POCO?”  Not too long ago I was at a Visual Studio User Group meeting where the question of POCOs and how they are different from DTOs came up.  The presenter, who quite honestly is a much better developer than me, stated confidently that POCOs and DTOs are the same thing.  I immediately clamped both hands over my mouth to keep from screaming “They are not!”.  So, there seems to be a lack of good information in the .Net community about what these objects are.  I’m going to try and clarify the issue.

What is a Data Transfer Object (DTO)?

Normally this is where I would say Wikipedia defines a DTO as...  Unfortunately, the current Wikipedia definition is pretty awful except for the line:  

“The difference between Data Transfer Objects and Business Objects or Data Access Objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).”

That’s the key concept.  A DTO stores data.  It has no methods (behaviors) other than accessors and mutators which are just used to get and set data.  Why make an object that simple? Because they make a great, lightweight, strongly typed data container when you want to move data from your DAL to your BAL or between the umpteen layers in your n-tier architecture.  Below is the code for the PersonDTO that I’ve been using in many of my recent posts. You’ll notice that it really does nothing except store data.

public class PersonDTO : DTOBase
{
public Guid PersonGuid { get;set; }
public int PersonId { get; set; }
public DateTime UtcCreated { get; set; }
public DateTime UtcModified { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string Nickname { get; set; }
public string PhoneMobile { get; set; }
public string PhoneHome { get; set; }
public string Email { get; set; }
public string ImAddress { get; set; }
public int ImType { get; set; }
public int TimeZoneId { get; set; }
public int LanguageId { get; set; }
public string City { get; set; }
public string State { get; set; }
public int ZipCode { get; set; }

// Constructor
// No parameters and all value types are intialized to the
// null values defined in CommonBase.
public PersonDTO()
{
PersonGuid = Guid_NullValue;
PersonId = Int_NullValue;
UtcCreated = DateTime_NullValue;
UtcModified = DateTime_NullValue;
Name = String_NullValue;
Nickname = String_NullValue;
PhoneMobile = String_NullValue;
PhoneHome = String_NullValue;
Email = String_NullValue;
ImAddress = String_NullValue;
ImType = Int_NullValue;
TimeZoneId = Int_NullValue;
LanguageId = Int_NullValue;
City = String_NullValue;
State = String_NullValue;
ZipCode = Int_NullValue;
IsNew = true;
}
}

So, to sum up, a DTO is just a collection of properties (or data members).  It has no validation, no business logic, no logic of any kind.  It’s just a simple, lightweight data container used for moving data between layers.


So What’s a POCO?


A POCO is not a DTO.  POCO stands for Plain Old CLR Object, or Plain Old C# Object.  It’s basically the .Net version of a POJO, Plain Old Java Object.  A POCO is your Business Object.  It has data, validation, and any other business logic that you want to put in there.  But there’s one thing a POCO does not have, and that’s what makes it a POCO.  POCOs do not have persistence methods.  If you have a POCO of type Person, you can’t have a Person.GetPersonById() method, or a Person.Save() method.  POCOs contain only data and domain logic, no persistence logic of any kind.  The term you’ll hear for this concept is Persistence Ignorance (PI).  POCOs are Persistence Ignorant. 


Below is the code for my BAL.Person class which is a POCO.  You’ll notice that it contains no persistence logic of any kind, just data and validation methods.  You’ll also notice that I don’t recreate a bunch of accessors and mutators for my person data.  That would clutter up my Person class, plus they would be redundant since they’ve already been defined in PersonDTO.  Instead I just have a single property named Data that is of type PersonDTO.  This approach makes getting and saving a person really easy.  When getting a person, I just get a PersonDTO from my DAL and then set person.Data = personDTO.  When saving, my save methods all take a PersonDTO as a parameter so I can just use my person.Data property for that as well.

public class Person : BALBase
{
// Data
// This property exists for all BAL objects, and it is
// set to the DTO type for this entity. This is the
// mechanism that we use to implement "has a" inheritance
// instead of "is a" inheritance.
public PersonDTO Data { get; set; }

// Person - default constructor
public Person() { this.Data = new PersonDTO(); }

// Person - takes a DTO
public Person(PersonDTO dto) { this.Data = dto; }

// Validate
public override List<ValidationError> Validate()
{
// Call all validation functions
Val_Name();
Val_Email();
Val_Password();
Val_TimeZone();
Val_City();
Val_State();
Val_ZipCode();
Val_ImType();

// If the ValidationErrors list is empty then
// we passed validation.
return this.ValidationErrors;
}

// Validation Methods:
// There are only 2 requirements on validation methods.
// - They must handle adding a Validation Error to the
// ValidationErrors list if they find an error.
// - You must manually add a call to all validation methods
// to the Validate() function.
// When creating a new ValidationError object, remember
// that the first parameter is the exact name of the field
// that has the bad value, and the error message should
// not contain the field name, but instead the <FieldName>
// tag, which will be replaced by the UI or consuming app.
// Val_Name
public bool Val_Name()
{
// Name required
if (this.Data.Name == DTOBase.String_NullValue)
{
this.ValidationErrors.Add(new ValidationError("Person.Name", "<FieldName> is required"));
return false;
}
else
{
return true;
}
}

// You get the idea. I’m leaving out the rest of the validation code
// so you don’t go blind reading the same lines over and over.
}



No persistence logic there, just data and validation logic.  So you’re probably thinking, if the persistence logic doesn’t go in my entity class, then where does it go?  The answer is, another class.  POCOs must be hydrated by some other class that encapsulates the persistence logic for that entity, like a repository or a data controller.  I typically use a repository.  For this example I used a PersonRepository class that encapsulates the logic for getting a new person object, getting a personDTO from the DAL, and then setting person.Data = personDTO. Same with the save.  My PersonRepository class has a SavePerson() method that takes a full person object then passes its person.Data value to the DAL to be persisted.  Code for getting and setting a person entity in my UI looks like this:



hydrate from db:


Person person = PersonRepository.GetPersonByEmail(email);


 


save to db:


PersonRepository.SavePerson(ref person, true);


Why Would I Ever Want to Do This?


The next question you might ask is What’s the point?  Why should I use these patterns instead of just using DataTables and putting all my persistence logic in my entity objects?  That answer is a little tougher.  I prefer a POCO / Repository / DTO architecture, but it’s not the one right way to design an application.  I think the benefits are that it is a very clean and easy to maintain architecture.  It provides separation of business logic and persistence logic, which is more in line with the Single Responsibility Principle.  Using POCOs with DTOs and a well designed DAL is just about the best performing architecture you can build. But, I think most .Net developers will be driven to use POCOs and repositories (but not DTOs) by ORMs.  Entity Framework, nHibernate, and a lot of the ORMs out there require or assume a POCO type architecture. In fact, Entity Framework has introduced an IPOCO interface which I’m having trouble finding documentation on but it sounds like something good. Also, if you want to get into Domain Driven Design, you’ve got to embrace the POCO.  In his excellent book Applying Domain-Driven Design and Patterns, Jimmy Nilsson even has a section titled “POCO as a Lifestyle”. 


So, in conclusion, learn to love the POCO, and make sure you don’t spread any misinformation about it being the same thing as a DTO.  DTOs are simple data containers used for moving data between the layers of an application.  POCOs are full fledged business objects with the one requirement that they are Persistence Ignorant (no get or save methods).  Lastly, if you haven’t checked out Jimmy Nilsson’s book yet, pick it up from your local university stacks.  It has examples in C# and it’s a great read.

What's the difference between Abstract classes and Interfaces?

A good way to distinguish between a case for the one or the other for me has always been the following:

  1. Are there many classes that can be "grouped together" and described by one noun? If so, have an abstract class by the name of this noun, and inherit the classes from it. (A key decider is that these classes share functionality, and you would never instantiate just an Animal... you would always instantiate a certain kind of Animal: an implementation of your Animal base class)
    Example: Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (I might make this method virtual so that I can override it for certain animals, like Fish, which does not breath the same as most animals).
  2. What kinds of verbs can be applied to my class, that might in general also be applied to others? Create an interface for each of these verbs.
    Example: All animals can be fed, so I will create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - I will not implement this on the base class, since this does not apply to Cat.
    As said by someone else's reply: the main difference is where you want your implementation. By creating an interface, you can move your implementation to any class that implements your interface.
    By creating an abstract class, you can share implementation for all derived classes in one central place, and avoid lots of bad things like code duplication.

An abstract class is a class that can not be instantiated but that can contain code.
An interface only contains method definitions but does not contain any code. With an interface, you need to implement all the methods defined in the interface.

If you have logic that will be the same for all the derived classes, it is best to go for a abstract class in stead of an interface.

For more detail this is another link http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface

Code First From Database' Template not showing in Visual Studio Entity Data Model Wizard

According to Microsft in this article is should see an option 'Code First From Database' when adding a new item to the project under 'ADO.NET Entity Data Model' in step 3.

entity-framework-before

Where is it the component for Code First like following picture?

entity-framework-code-first

For installing in Visual Studio 2012 or 2013 this functions you can download the install for this link http://www.microsoft.com/en-us/download/details.aspx?id=40762

Extract detail from barcode on bollettini prefilled (Italy)

 

bollettino

namespace PSC
{
public class Bollettini
{
public bool getCode(string strCode)
{
bool rtn = true;

if (strCode.Length != 50)
{
return false;
}

int first = Convert.ToInt16(strCode.Substring(0, 2));
Bollettino = strCode.Substring(2, first);

int second = Convert.ToInt16(strCode.Substring(first + 2, 2));
Contocorrente = strCode.Substring(first + 4, second);

int third = Convert.ToInt16(strCode.Substring(first + second + 4, 2));
string tmp = strCode.Substring(first + second + 6, third);
Importo = Convert.ToDecimal(tmp) / 100;

int fouth = Convert.ToInt16(strCode.Substring(first + second + third + 6, 1));
Codice = strCode.Substring(first + second + third + 7, fouth);

if (Codice != "896")
{
rtn = false;
}

return rtn;
}
}
}

ASP.NET MVC 4 and Entity Framework Database Migrations

ASP.NET MVC 4 was released in beta by the Microsoft ASP.NET MVC Developer Team and it comes with a number of really cool features: Bundling and Minification Support of CSS and JavaScript, Database Migrations using Entity Framework 4.3, Web APIs, Mobile Web with support for jQuery Mobile, Real Time Communication via SignalR, and Asynchronous Support. The Database Migrations using Entity Framework Code-First is really cool and is very much like Rails where you can change your code and then via Package Manager add migrations and update your database as your code evolves. Because the EF Migration Files and Configuration get added to your Visual Studio Solution, all the database migration changes get added to source code.

ASP.NET MVC 4 and Entity Framework Code-First

ASP.NET MVC support for EF Code-First has been there since ASP.NET MVC 3. To jump start playing with Database Migrations start an empty ASP.NET MVC 4 Project and use Package Manager to install or update Entity Framework to the latest version that includes Database Migrations.

Install-Package EntityFramework

Add a simple Product Class that represents a product in your E-Commerce Website. Let's intially make Product simple by just providing an Id and Title to it.

public class Product {
    public int Id { get; set; }
    publis string Title { get; set; }
}

Run the Add Controller Recipe in ASP.NET MVC 4 to add a Products Controller that uses Entity Framework to read/write to the Database of your E-Commerce Website.


aspnet-mvc-4-entity-framework-scaffolding


Once the Add Controller Recipe is finished you will have a working ASP.NET MVC 4 Website that reads and writes products to the Database using Entity Framework. The ProductsController was created along with all actions and views that display, create, update, and delete products.


Enable Database Migrations to ASP.NET MVC 4 Website


Now we want to enable database migrations to ASP.NET MVC 4 by using the Package Manager Console.

Enable-Migrations

Enabling database migrations creates a new Migrations Folder in your Visual Studio Solution as well as an InitialCreate Target Migration that has both an Up and Down Migration. The Up Migration creates the Products Table while the Down Migration drops the Products Table.

public partial class InitialCreate : DbMigration {
    public override void Up() {
        CreateTable(
            "Products",
                 c => new
                 {
                      Id = c.Int(nullable: false, identity: true),
                      Title = c.String(),
                  })
                  .PrimaryKey(t => t.Id);
);
     }


     public override void Down() {
          DropTable("Products");
     }
}

Add New Database Migration to ASP.NET MVC 4 Website


Now let's say we want to add more properties to the Product Class as well as make Title a Required Property and a length of 255 characters.

public class Product {
    public int Id { get; set; }

    [Required,MaxLength(255)]
    public string Title { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }
}

One can now add a data migration as well as update the database via the Package Manager Console.

Add-Migration AddDescriptionPriceToProduct
Update-Database

The Add-Migration command creates another file in the Migrations Folder of our ASP.NET MVC 4 Project and the Update-Database command updates the database with the new Description and Price Columns as well as modifies the Title Column to be only 255 characters and not nullable.


entity-framework-database-migrations-visual-studio


If you look at the ASP.NET MVC 4 Database before and after issuing this Database Migration you will notice the effect.


entity-framework-aspnet-mvc-4-migrate-database


And, of course, the new Database Migration File has the approprite Up and Down Methods.

public partial class AddDescriptionPriceToProduct : DbMigration {
    public override void Up() {
        AddColumn("Products", "Description", c => c.String());
        AddColumn("Products", "Price",
c => c.Decimal(nullable: false, precision: 18, scale: 2));
        AlterColumn("Products", "Title",
c => c.String(nullable: false, maxLength: 255));
    }

    public override void Down() {
        AlterColumn("Products", "Title", c => c.String());
        DropColumn("Products", "Price");
        DropColumn("Products", "Description");
    }
}

Using IsolateStorageSettings

The IsolatedStorageSettings is a place to store Key/Value pairs of data.

So let's say that my application used the Microsoft Ad control, but I wanted to be nice and give the user the ability to turn the ads on and off.

On my Settings screen, I would have a checkbox for allowing the ads. In code, I would save the value by doing this...

var settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("AllowAds"))
settings["AllowAds"] = AdsCheckbox.IsChecked.Value;
else
settings.Add("AllowAds", AdsCheckbox.IsChecked.Value);

settings.Save();


If you will notice, the ApplicationSettings object does have a method that allows you to check to see if the key already exists in the Settings. An exception will be thrown if you try to add a key that already exists, so it's necessary to do this check before assigning a value.

Also, as you can see, it's very easy to get the value out of the settings...

// when the form opens, I want to set the Checkbox to being checked
// or unchecked depending on the setting
var settings = IsolatedStorageSettings.ApplicationSettings;

if (settings.Contains("AllowAds"))
AdsCheckbox.IsChecked = bool.Parse(settings["AllowAds"].ToString());



However, the IsolatedStorageSettings class isn't only for simply datatypes. It can also store your custom class objects.

Employee class
public class Employee
{
public string FullName { get; set; }
public decimal Salary { get; set; }
}


How to programmatically hide the keyboard

I have a textbox with a button inside. When the user presses the Action, a progress bas is displayed, the screen goes dark, and some magic happens.

My problem is that since the action doesn't result in the textbox losing focus, the on-screen keyboard is not hidden, and keeps covering half the screen.

Just set focus to the main page:
this.Focus();
this will focus a control that doesn't use the keyboard and thus hide the keyboard. Unfortunately there is no API to the keyboard to hide it.

Blogger C# API

using System;
using System.Text;
using Google.GData.Client;
using System.Net;
using System.Xml;
using System.Text.RegularExpressions;

namespace BloggerDevSample
{
class ConsoleSample
{
/** Lists the user's blogs. */
static void ListUserBlogs(Service service)
{
Console.WriteLine("\nRetrieving a list of blogs");
FeedQuery query = new FeedQuery();
// Retrieving a list of blogs
query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
AtomFeed feed = null;
feed = service.Query(query);
foreach (AtomEntry entry in feed.Entries)
{
Console.WriteLine(" Blog title: " + entry.Title.Text);
}
}

/** Lists the user's blogs and returns the URI for posting new entries
* to the blog which the user selected.
*/
static Uri SelectUserBlog(Service service)
{
Console.WriteLine("\nPlease select a blog on which to post.");
FeedQuery query = new FeedQuery();
// Retrieving a list of blogs
query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
AtomFeed feed = service.Query(query);

// Publishing a blog post
Uri blogPostUri = null;
if (feed != null)
{
foreach (AtomEntry entry in feed.Entries)
{
// Print out the title of the Blog
Console.WriteLine(" Blog name: " + entry.Title.Text);
Console.Write(" Post to this blog? (y/n): ");
if (Console.ReadLine().Equals("y"))
{
// find the href in the link with a rel pointing to the blog's feed
for (int i = 0; i < entry.Links.Count; i++)
{
if (entry.Links[i].Rel.Equals("http://schemas.google.com/g/2005#post"))
{
blogPostUri = new Uri(entry.Links[i].HRef.ToString());
Console.WriteLine(" Your new posts will be sent to " + blogPostUri.AbsoluteUri.ToString());
}
}
return blogPostUri;
}
}
}
return blogPostUri;
}

/** Creates a new blog entry and sends it to the specified Uri */
static AtomEntry PostNewEntry(Service service, Uri blogPostUri)
{
Console.WriteLine("\nPublishing a blog post");
AtomEntry createdEntry = null;
if (blogPostUri != null)
{
// construct the new entry
AtomEntry newPost = new AtomEntry();
newPost.Title.Text = "Marriage!";
newPost.Content = new AtomContent();
newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" +
"<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
"<p>He is the last man on earth I would ever desire to marry.</p>" +
"<p>Whatever shall I do?</p>" +
"</div>";
newPost.Content.Type = "xhtml";
newPost.Authors.Add(new AtomPerson());
newPost.Authors[0].Name = "Elizabeth Bennet";
newPost.Authors[0].Email = "liz@gmail.com";

createdEntry = service.Insert(blogPostUri, newPost);
if (createdEntry != null)
{
Console.WriteLine(" New blog post created with title: " + createdEntry.Title.Text);
}
}
return createdEntry;
}

/** Creates a new blog entry and sends it to the specified Uri */
static void PostAndDeleteNewDraftEntry(Service service, Uri blogPostUri)
{
Console.WriteLine("\nCreating a draft blog post");
AtomEntry draftEntry = null;
if (blogPostUri != null)
{
// construct the new entry
AtomEntry newPost = new AtomEntry();
newPost.Title.Text = "Marriage! (Draft)";
newPost.Content = new AtomContent();
newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" +
"<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" +
"<p>He is the last man on earth I would ever desire to marry.</p>" +
"<p>Whatever shall I do?</p>" +
"</div>";
newPost.Content.Type = "xhtml";
newPost.Authors.Add(new AtomPerson());
newPost.Authors[0].Name = "Elizabeth Bennet";
newPost.Authors[0].Email = "liz@gmail.com";
newPost.IsDraft = true;

draftEntry = service.Insert(blogPostUri, newPost);
if (draftEntry != null)
{
Console.WriteLine(" New draft post created with title: " + draftEntry.Title.Text);
// Delete the newly created draft entry
Console.WriteLine(" Press enter to delete the draft blog post");
Console.ReadLine();
draftEntry.Delete();
}
}
}

/** Display the titles for all entries in the previously selected blog. */
static void ListBlogEntries(Service service, Uri blogUri)
{
if (blogUri != null)
{
Console.WriteLine("\nRetrieving all blog posts");
// Retrieve all posts in a blog
FeedQuery query = new FeedQuery();
Console.WriteLine(" Query URI: " + blogUri.ToString());
query.Uri = blogUri;
AtomFeed feed = service.Query(query);
foreach (AtomEntry entry in feed.Entries)
{
Console.WriteLine(" Entry Title: " + entry.Title.Text);
}
}
}

/** Display title for entries in the blog in the hard coded date range. */
static void ListBlogEntriesInDateRange(Service service, Uri blogUri)
{
Console.WriteLine("\nRetrieving posts using query parameters");
// Retrieve all posts in a blog between Jan 1, 2006 and Apr 12, 2007
FeedQuery query = new FeedQuery();
query.Uri = blogUri;
query.MinPublication = new DateTime(2006, 1, 1);
query.MaxPublication = new DateTime(2007, 4, 12);
AtomFeed feed = service.Query(query);
foreach (AtomEntry entry in feed.Entries)
{
Console.WriteLine(" Entry Title: " + entry.Title.Text);
}
}

/** Change the contents of the newly created blog entry. */
static AtomEntry EditEntry(AtomEntry toEdit)
{
Console.WriteLine("\nUpdating post");
// Edit the new entry
if (toEdit != null)
{
toEdit.Title.Text = "Marriage Woes!";
Console.WriteLine(" Press enter to update");
Console.ReadLine();
toEdit = toEdit.Update();
}
return toEdit;
}

/** Delete the specified blog entry. */
static void DeleteEntry(AtomEntry toDelete)
{
Console.WriteLine("\nDeleting post");
// Delete the edited entry
if (toDelete != null)
{
Console.WriteLine(" Press enter to delete the new blog post");
Console.ReadLine();
toDelete.Delete();
}
}

/** Get the comments feed URI for the desired blog entry. */
static Uri SelectBlogEntry(Service service, Uri blogPostUri)
{
Console.WriteLine("\nPlease select a blog entry on which to comment.");
FeedQuery query = new FeedQuery();
query.Uri = blogPostUri;
AtomFeed feed = service.Query(query);
Uri commentPostUri = null;

if (feed != null)
{
foreach (AtomEntry entry in feed.Entries)
{
// Print out the title of the Blog
Console.WriteLine(" Blog entry title: " + entry.Title.Text);
Console.Write(" Post a comment on this entry? (y/n): ");

if (Console.ReadLine().Equals("y"))
{
// Create the Post URL for adding a comment by finding this entry's id number.

// Find the href in the link with a rel pointing to the blog's feed.
for (int i = 0; i < entry.Links.Count; i++)
{

if (entry.Links[i].Rel == "edit")
{
string commentUriStart = Regex.Replace(blogPostUri.ToString(), "/posts/default", "");
string selfLink = entry.Links[i].HRef.ToString();
string entryId = Regex.Replace(selfLink, blogPostUri.ToString() + "/", "");
// Build the comment URI from the blog id in and the entry id.
commentPostUri = new Uri(commentUriStart + "/" + entryId + "/comments/default");
Console.WriteLine(" Your new comments will be sent to " + commentPostUri.ToString());
return commentPostUri;
}
}
}
}
}

return commentPostUri;
}

static AtomEntry PostNewComment(Service service, Uri commentPostUri)
{
Console.WriteLine("\nCommenting on a blog post");
AtomEntry postedComment = null;
if (commentPostUri != null)
{
// Add a comment.
AtomEntry comment;
comment = new AtomEntry();
comment.Title.Text = "This is my first comment";
comment.Content.Content = "This is my first comment";
comment.Authors.Add(new AtomPerson());
comment.Authors[0].Name = "Blog Author Name";
postedComment = service.Insert(commentPostUri, comment);
Console.WriteLine(" Result's title: " + postedComment.Title.Text);
}
return postedComment;
}

static void ListEntryComments(Service service, Uri commentUri)
{
if (commentUri != null)
{
Console.WriteLine("\nRetrieving all blog post comments");
// Retrieve all comments on a blog entry
FeedQuery query = new FeedQuery();
Console.WriteLine(" Query URI: " + commentUri.ToString());
query.Uri = commentUri;
AtomFeed feed = service.Query(query);
foreach (AtomEntry entry in feed.Entries)
{
Console.WriteLine(" Comment Title: " + entry.Title.Text);
}
}
}

static void DeleteComment(AtomEntry commentEntry)
{
Console.WriteLine("\nDeleting the comment");
if (commentEntry != null)
{
// Delete the comment.
Console.WriteLine(" Press enter to delete the new comment post");
Console.ReadLine();
commentEntry.Delete();
}
}

static void Main(string[] args)
{
Service service = new Service("blogger", "blogger-example");

// ClientLogin using username/password authentication
string username;
string password;
if (args.Length != 2)
{
Console.WriteLine("Usage: BloggerDevSample.exe <username> <password>");
return;
}
else
{
username = args[0];
password = args[1];
}

service.Credentials = new GDataCredentials(username, password);

ListUserBlogs(service);
Uri blogPostUri = SelectUserBlog(service);
AtomEntry createdEntry = PostNewEntry(service, blogPostUri);
PostAndDeleteNewDraftEntry(service, blogPostUri);
ListBlogEntries(service, blogPostUri);
ListBlogEntriesInDateRange(service, blogPostUri);
AtomEntry editedEntry = EditEntry(createdEntry);
DeleteEntry(editedEntry);
Uri commentPostUri = SelectBlogEntry(service, blogPostUri);
AtomEntry commentEntry = PostNewComment(service, commentPostUri);
ListEntryComments(service, commentPostUri);
DeleteComment(commentEntry);

Console.WriteLine("Press enter to quit");
Console.ReadLine();
}
}
}

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:
  • <program name>
  • <username>
  • <password>
  • <uri>
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.

Transparent Live Tile For Windows Phone 8.1

Windows Phone 8.1 Dev Preview

Windows Phone 8.1 developer preview is totally awesome. So what is one of the most important things app devs can do right away, without much fuss, to make their apps look great with Windows Phone 8.1? Revisit your app’s Live Tile images. Why? In 8.1, Start screen is mesmerizing with the parallax effect and Live Tile with background overlay. Dev preview users are going crazy with new Start experience, and I am sure, with public release, end users are going to love to have background image as well. Take a look at this awesome Nokia Lumia 925 Start screen:

wp_ss_20140416_00151

When users have a background image, they might not like to have solid Live Tiles block their beautiful background. So, revisit your app’s Live Tile images – all of them! Check if they are transparent or not? If they are like Cortana, Avirall Time Suite, etc. in the image above, you are all set. You can safely ignore this article and find some other awesome way to improve your app for WP8.1 (think Cortana). If they are not, I suggest to update ‘em ASAP. And it’s easy, too. Let’s see how you can create transparent Live Tile images with Open Source Inkscape. You could choose to use Paint.NET (not MS Paint), Photoshop, GIMP, or any other tool which allows you to export image with transparency. Though I prefer GIMP for image editing but I chose Inkscape for this demo. Let’s go.

Step 1: Setup the page

inkscape01

  1. Open Inkscape and create a new document and Open Document Properties from file menu.
  2. In most cases app icons are solid white, if yours is one too, change the background color of the page, temporarily, to light yellow. This is while working only so that you can see white color. Before exporting we will reset this to transparent (this is very important).
  3. This example is for 336 X 336 medium tile. So set the custom size to 336 X 336.
  4. Make sure Units is “px”.

Step 2: Setup the drawing

inkscape02

Windows Phone 8 Asset Template Guide suggests a 336 X 336 tile to have 110px margin on all sides. Create 110px margin guides on all the sides. To create margin guides click and drag from the horizontal ruler on the top and from the vertical ruler on the left.

Step 3: Create Live Tile image of your app

inkscape03

The center part between the margins is the space where your tile image will go. Create your image here. For this example I simply dragged the box from tool box and made a hole in it :D

Step 4: Set background to transparent

inkscape03a

To create a transparent Live Tile image we would like to have a transparent background. Go back in document properties and set Background to transparent by resetting “A” to 0. If your image is solid white, you might not see anything after making the background transparent. Don’t worry, your image is there (maybe somebody can tell how working space (not document background) in Inkscape can be made a different color than white).

Step 5: Export

inkscape04

  1. Open Export dialog from File > Export Bitmap…
  2. Set X0, X1, Y0, Y1 as shown in the image above.
  3. Browse for the image location, and make sure you give “PNG” as the extension of the image, NOT JPG or BMP.
  4. Export. (Alternatively, as suggested by Austin Andrews, you could export as SVG, and use his awesome service!)

Step 6: Check Final Image

windowsphotoviewer05

Notice that your final image does not have a white background. Windows Photo Viewers’s light blue background is your image’s background.

You are done. You would want to change all Live Tile images of your app in the same way. A transparent Live Tile image will encourage users to have your app pinned to Start screen without obstructing their beautiful background images.

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  November 2017  >>
MonTueWedThuFriSatSun
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Month List