Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Mixing C# source code with PowerShell script code to speed your development

I had some C# code ready but needed to use it inside a PowerShell script.

At StackOverflow I found some code that put me in the right path. So here's a practical example when mixing codes inside a PowerShell script file:

. ".\Invoke-Parallel.ps1" # Importing another script into this PowerShell script file

$csharpSource = @"

using System;
using System.Collections.Generic;
using System.Linq;

public class DateExtensions
{
     public static List<Tuple<DateTime, DateTime>> GetWeeksBetweenDates(DateTime startDate, DateTime endDate)
     {
        var weeks = new List<Tuple<DateTime, DateTime>>();
        
    
         for (DateTime date = startDate; date <= endDate; date = date.AddDays(8))
         {
            var weekEnd = date.AddDays(7);
                            
            weeks.Add(new Tuple<DateTime, DateTime>(date, weekEnd <= endDate ? weekEnd : endDate));
         }

        return weeks;
    }
}
"@

Add-Type -TypeDefinition $csharpSource # Includes the C# code defined above to be called through the PowerShell script

$appPath = "C:\SomeFolder"
$startDate = [datetime]'6/1/2017'
$endDate = [datetime]'5/5/2018'

$weeks = [DateExtensions]::GetWeeksBetweenDates($startDate, $endDate)

#Calls MyApp in batches, that is, for each week...
$weeks | Invoke-Parallel -ImportVariables -ScriptBlock {   
    Set-Location -Path $appPath
           
    $date = [string]::Format("{0:yyyyMMdd},{1:yyyyMMdd}", $_.Item1, $_.Item2)

    #Write-Host $date

    dotnet MyApp.dll budat=$date cpudt=$date # Calls .NET Core "executable" DLL for each week
}

pause #Keeps PowerShell window open to see the results

As we see in the code above, the variable $csharpSource holds the C# source code that later will called in the PowerShell script.

We then add\mix the C# code to\with PowerShell with the command Add-Type passing to it the $csharpSource variable that holds the source code. Simple as that.

Inside PowerShell script code we call the method defined in C# code with:

$weeks = [DateExtensions]::GetWeeksBetweenDates($startDate, $endDate)

This is pretty useful because we don't need to convert our C# code to PowerShell idiom.

Hope it helps.

Reference:
How to convert C# code to a PowerShell Script?

Just got the C# gold badge at StackOverflow

This is a “marketing” post… Open-mouthed smile Just kidding.

This is just to inform that I got the C# #Csharp gold badge at #StackOverflow @StackExchange after 5 years and 6 months and 342 answers posted on the C# tag! What a milestone towards a so awesome programming language.

C# gold badge earned at StackOverflow

Once when I was starting back in 2003 a somewhat experienced coworker told me: this thing [ coding ] is not for you.

I proved him wrong!

The lesson to be learnt here is: never trust others when they say you are not capable even more when you are just starting something. Instead use that as a trampoline. Not easy but you must not give up. Keep pushing always.

People that motivate us are a rare kind. So use this post as a motivation and BEFORE that remember: put God first in everything you start in your life. I remember at that time in my life I talked to God and told him that I really liked this profession|area and asked for his help so that he could guide me and provide me wisdom. Here I’m today being able to write this post. How grateful I’m.

To top that, last week a cousin (13 years old) approached me and told me he’d like to follow the same path I followed and asked what I did to get where I’m today. I answered: you have to have a passion for what you do, strive for excellence and be prepared to spend some good amount of time trying and trying... as I wrote above: don’t give up. There’ll be for sure many rocks on the road… The Long and Winding Road as sung by The Beatles is a truth but if you persist in what you really believe then success is a matter of time.

Somehow sometime somewhere God will move things in your favor.

And we know that all things work together for good to them that love God, to them who are called according to his purpose. Romans 8:28 https://www.bible.com/bible/1/rom.8.28

A snapshot of my StackOverflow profile on the day I got the C# gold badge

http://stackoverflow.com/users/114029/leniel-macaferi

Windsor dependency injection in ASP.NET MVC filter attributes

I learn so much each day that I don’t have time to post about every interesting thing I discover.

Generally I get to these discoveries/solutions to overcome a wall that somehow appears while developing a given functionality.

I use Castle Windsor as my Inversion of Control [ IoC ] container. Recently I’ve been implementing some features that depend heavily on ASP.NET MVC action filter attributes and at some point I needed to get a reference to a service that hits the database for some data checking rules. Unfortunately one cannot ask a Windsor container to give back a dependency when inside an attribute because as Krzysztof Koźmic (the developer of Windsor) says in his answer for the question: Injecting dependency into CustomAttribute using Castle Windsor at StackOverflow:

You can't. Attributes are metadata. Putting behavior into them is wrong. Putting dependencies is even worse.

Although I understand the point I Googled a little bit more and found this great post by Dino Esposito called ASP.NET MVC: Resolve or Inject? That’s the Issue…. In this post Dino shows how to use ASP.NET MVC extension point called DependencyResolver that sits here System.Web.Mvc.DependencyResolver. It simplifies service location and dependency resolution…

With this I was able to do the following in a custom WindsorDependencyResolver.cs class:

public class WindsorDependencyResolver : IDependencyResolver
{
    private readonly IWindsorContainer _container;

    public WindsorDependencyResolver(IWindsorContainer container)
    {
        _container = container;
    }

    public Object GetService(Type serviceType)
    {
        return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.Kernel.HasComponent(serviceType) ? _container.ResolveAll(serviceType).Cast<object>() : new object[] { };
    }
}

The above code I took from this great question at StackOverflow: Castle Windsor Dependency Resolver for MVC 3. There’s an extensive list of useful info there.

In the container bootstrap code inside Global.asax file we put this class into use:

private static void BootstrapContainer()
{
    _container = new WindsorContainer().Install(FromAssembly.This());

    var controllerFactory = new WindsorControllerFactory(_container.Kernel);

    ControllerBuilder.Current.SetControllerFactory(controllerFactory);

    // Create and register the resolver
    var resolver = new WindsorDependencyResolver(_container);
    DependencyResolver.SetResolver(resolver);
}

See how we’re passing Windsor’s app container to the Dependency Resolver. This way when we ask the DependencyResolver for a service/repository/whatever it’ll get it from the container and we’ll take advantage of the container’s powerful capabilities. You can read about such awesome capabilities in this series of posts called Windsor tutorial - ASP.NET MVC 3 application (To be Seen) written by Windsor’s developer (Krzysztof Koźmic).

Now it’s just a matter of using the Dependency Resolver for our benefit:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Make sure the user is authenticated.
        if (httpContext.User.Identity.IsAuthenticated == false)
            return false;

        // If User has the "SuperUser" role he can surf all the app...
        if (httpContext.User.IsInRole(AccountController.SuperUser))
            return true;

        var permissionService = DependencyResolver.Current.GetService(typeof(PermissionService)) as PermissionService;

        return permissionService.UserHasPermission(httpContext);
    }
}

The real good thing about the Dependency Resolver is that once you set the resolver you can call it throughout your ASP.NET MVC…

OK. It diverges from Krzysztof’s main point that one should not put behavior in attributes, but it does the job and is working as expected in my case.

This has helped me to continue my development and I hope it’ll also help you.

User Password Expired filter attribute in ASP.NET MVC

A recent set of requirements I’ve been playing with deals with passwords. This one specifically handles password expiration.

Given that I’m working with ASP.NET MVC I know I can rest assured that there’s some great (read awesome) way of implementing a given requirement. This is exactly what happened and I want to show you how to have a clean and beautiful solution to this problem.

So my client’s requirement is the following:

Passwords should expire in 45 days.

I’m currently using the default ASP.NET membership provider. It gives you a database schema ready to manage users and roles. You just have to use ASP.NET Configuration Tool to create Roles and Users, decorate your Controllers/Actions with the Authorize attribute and you’re good to go most of the time. The default membership provider allows a fast project start – no doubt – but as always there’s something that must be done according to the infinitude of possible requirements that change project by project. One of these not contemplated things is a setting in the default provider for handling user’s password expiration. We have to roll our own code to manage this.

My friend Google told me that some folks have already done some work related to this and as always I borrow some of their code and adapt it to my specific case/technology.

First I created a PasswordExpiredAttribute that derives from/extends the AuthorizeAttribute. Here’s its code:

public class PasswordExpiredAttribute : AuthorizeAttribute
{
    private static readonly int PasswordExpiresInDays =
int.Parse(ConfigurationManager.AppSettings["PasswordExpiresInDays"]);

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;
           
        if(user != null && user.Identity.IsAuthenticated)
        {
            MembershipUser membershipUser = Membership.GetUser();

            TimeSpan ts = DateTime.Today - membershipUser.LastPasswordChangedDate;

            // If true, that means the user's password expired
            // Let's force him to change his password before using the application
if (ts.TotalDays > PasswordExpiresInDays) { filterContext.HttpContext.Response.Redirect( string.Format("~/{0}/{1}?{2}", MVC.Account.Name, MVC.Account.ActionNames.ChangePassword, "reason=expired")); } } base.OnAuthorization(filterContext); } }

As you see, the code goes inside the OnAuthorization overridable method. I get the PasswordExpiresInDays setting from the Web.config <appSettings> section. This gives an easy way to change the requirement in the future without the need of recompiling the whole app.

<appSettings>
    <add key="PasswordExpiresInDays" value="45" />
</appSettings>

The code explains itself but let’s go through it:

1 - If the User is authenticated, let’s get his membership data;
2 - A TimeSpan is useful for getting the difference in days between Today and the last time the user changed his password ( LastPasswordChangedDate )
3 - Check if the TimeSpan.TotalDays is greater than the PasswordExpiresInDays setting we got from the Web.config file. If true the user must change his password and we redirect him to the ChangePassword view.

Note 1: I’m using T4MVC to retrieve the Controller and Action names in the code above. You should take a look at it! Really…

Note 2: See that "reason=expired" in the response redirect URL? I’m using this querystring as a route parameter inside the ChangePassword action method to display a message to the user informing him that he’s being asked to change the password because it has expired.

/// <summary>
/// This allows the logged on user to change his password.
/// </summary>
public virtual ActionResult ChangePassword(string reason)
{
    var viewModel = new ChangePasswordViewModel();

    if (reason != null)
    {
ShowMessage(Infrastructure.Notification.MessageType.Warning, Localization.PasswordExpired, true); } return View(viewModel); }

By the way: I use MvcNotification infrastructure by Martijn Boland to display beautiful messages to the user.

OK, getting back to the main point… now it’s just a matter of applying the PasswordExpiredAttribute filter to every controller of the app but the AccountController. With ASP.NET MVC 3 it’s easy to apply a filter to every controller and action using GlobalFilters. Instead of going controller by controller to add this attribute we can just register it as a global filter in the Global.asax file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
filters.Add(new PasswordExpiredAttribute()); }

Doing so the PasswordExpiredAttribute will be executed for every controller and action but there’s a problem with the above approach. Since it’s a global filter, it’ll be executed even for the AccountController. Remember: we don’t want it to be executed for the AccontController… How can we exclude a global filter from a single controller or action? To achieve this, there’s an awesome thing we can do: create a ExcludeFilterAttribute and a ExcludeFilterProvider. WOW, ASP.NET MVC has a Filter Provider that gives us even more power when working with filters. Look here for the complete story: Exclude a Filter by Ori Calvo. I’ve uploaded the source code files here: ExcludeFilterAttribute.cs and ExcludeFilterProvider.cs

Now it’s just a matter of decorating the AccountController with the ExcludeFilter attribute like this:

[ExcludeFilter(typeof(PasswordExpiredAttribute))]
public partial class AccountController : BaseController
{
...
}

The ExcludeFilter attribute explicitly tells the ASP.NET MVC runtime to ignore the PasswordExpiredAttribute for the AccountController.

With this in place, once the logged in user tries to access any part of the site and his password is expired, he'll be redirected to the ChangePassword view and won't be allowed access to anywhere else in the site until he changes the password. This is great and the requirement is implemented.

Of course in software there are multiple ways of doing the same thing. If you know of any better option, please share you knowledge in the comments.

Hope it helps.

Bonus
While working on this requirement I posted a question at StackOverflow regarding the use of Web.config settings as magic strings. I’ve found a nice way to let the code a little bit cleaner. So, if you want a nice way to access your Web.config app settings as properties with compile time checking and nice error handling, you can do as described here: T4MVC for Web.config <appSettings>

This is a much better/cleaner code IMO (see the AppSettings class that was automatically generated with the T4 template):

public class PasswordExpiredAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;

        if (user != null && user.Identity.IsAuthenticated)
        {
            MembershipUser membershipUser = Membership.GetUser();

            TimeSpan ts = DateTime.Today - membershipUser.LastPasswordChangedDate;

            // If true, that means the user's password expired
            // Let's force him to change his password before using the system
            if (ts.TotalDays > int.Parse(AppSettings.PasswordExpiresInDays))
            {
                filterContext.HttpContext.Response.Redirect(
                    string.Format("~/{0}/{1}?{2}", MVC.SGAccount.Name, MVC.SGAccount.ActionNames.ChangePassword,
                    "reason=expired"));

            }
        }

        base.OnAuthorization(filterContext);
    }
}

References:
ASP.NET MVC Authentication - Global Authentication and Allow Anonymous by Jon Galloway

ASP.NET MVC Authentication - Customizing Authentication and Authorization The Right Way by Jon Galloway

Exclude a Filter by Ori Calvo

Introducing System.Web.Providers - ASP.NET Universal Providers for Session, Membership, Roles and User Profile on SQL Compact and SQL Azure by Scott Hanselman

Conditional Filters in ASP.NET MVC 3 by Phil Haack

T4MVC by David Ebbo

Resize image on the fly with ASP.NET MVC

I built a piece of code sometime ago and today I decided to optimize it.

My use case is this: a user can upload some photos of his house for example. Image dimensions (height x width) are not restricted. The user can upload any photo as long as its size is less than or equal to 750 KB.

Then, I have a listing page (Index.cshtml) that has a WebGrid. The grid shows realties available for sell, rent, etc. In this grid I want to display just a thumbnail of a given photo (the first one I grab as per code bellow) for each realty. I placed a constraint such that the thumbnail dimensions must be 100x100 pixels. Of course one shouldn’t load the full size version of a photo just to show it on the grid. The grid has 10 rows per page and if the images are on the range of 500 KB, the load put on the user connection to transmit all those photos from the server to the client would be high: 10 x 500 KB ≃ 5 MB. This would be an unresponsive page! No doubt…

Googling a little bit I stumbled upon something I didn’t know yet. It’s called WebImage and comes in System.Web.Helpers just as the WebGrid I discussed earlier. With this little kid on the block, one can have a controller “action” that does something like this:

public void GetPhotoThumbnail(int realtyId)
{
// Loading photos’ info from database for specific Realty...
var photos = DocumentSession.Query<File>().Where(f => f.RealtyId == realtyId); if (photos.Any()) { var photo = photos.First(); new WebImage(photo.Path) .Resize(101, 101, false, true) // Resizing the image to 100x100 px on the fly... .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage) .Write(); } // Loading a default photo for realties that don't have a Photo new WebImage(HostingEnvironment.MapPath(@"~/Content/images/no-photo100x100.png")).Write(); }
Calling the .Write() method does the magic. As you can see, I’m not saving the thumbnail in the disk, that is, a new image is generated on the fly/dynamically and sent to the user’s browser. Amazing…
In a view using the Razor syntax one would have something like this to display the photo:
<img src="@Url.Action("GetPhotoThumbnail", new { realtyId = item.Id })" width="100" height="100"/>
Another useful variation/overload of the above action method is this one (even more dynamic):
public void GetPhotoThumbnail(int realtyId, int width, int height)
{
    // Loading photos’ info from database for specific Realty...
    var photos = DocumentSession.Query<File>().Where(f => f.RealtyId == realtyId);

    if (photos.Any())
    {
        var photo = photos.First();

        new WebImage(photo.Path)
            .Resize(width, height, false, true) // Resizing the image to 100x100 px on the fly...
            .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage)
            .Write();
    }

    // Loading a default photo for realties that don't have a Photo
        new WebImage(HostingEnvironment.MapPath(@"~/Content/images/no-photo100x100.png")).Write();
}
Then, in the view one would call the action passing the width and height variables as per requirement:
<img src="@Url.Action("GetPhotoThumbnail", new { realtyId = item.Id, width = 100, height = 100 })" />
There are a handful of available functions in a WebImage. You should really check them out.

You can find more insightful info about the WebImage class reading this post by Gunnar Peipman: ASP.NET MVC 3 Beta: Simple image manipulations using WebImage helper

Note: there really are better ways of handling this kind of situation (adding image caching, etc – see ImageResizer) but for the site I’m working on, the solution I show in this post is sufficient and pretty responsive right now.

Hope it helps.

Hide table column and colorize rows based on value with jQuery

This is a handy piece of code that I used last year in one of my projects. I had scheduled to post it but it was just after I saw this question at StackOverflow that I decided to write about it. So here it is…

Let’s say you want a nice UI experience and to achieve that you wanna colorize/highlight a table row according to a given value present in a column of this row.
This is a simple task when we use jQuery.

I use the WebGrid that comes with ASP.NET MVC to display data on a web page using an HTML <table> element. It’s available in the namespace System.Web.Helpers. The approach described in this post is useful not only with the WebGrid but with any framework/language you use to output HTML code since the manipulation is done on the client side with jQuery.

Take this screen as an example:

HTML table with last column Active to be hidden displaying values Yes and NoFigure 1 - HTML table with last column Active to be hidden displaying values Yes and No

We want hide the last column “Active” and color the row which has a value Yes in this same column.

The above statement can be accomplished with the following code:

(function ($)
{ hideColumnColorRow = function (column)
{ $(
'td:nth-child(' + column + '),th:nth-child( ' + column + ')').hide(); $('tr').find('td:nth-child(' + column + '):contains(Yes)').parent().css('backgroundColor', 'LightGreen'); // Could be an hexadecimal value as #EE3B3B };
})(jQuery);

The hideColumnColorRow function* takes the column number as a parameter. It hides the column <td> and its header <th> using jQuery’s supper useful nth-child selector. Then for each table row <tr> it traverses the row’s columns and looks at the value of each column using :contains selector. If it finds a value = ‘Yes’ it’ll assign a background color to the column’s parent, that in this case is the <tr> (the row) using its CSS backgroundColor property.

So, taking Figure 1 as an example, the above code can be used in an ASP.NET MVC view this way:

<script type="text/javascript">

    $(document).ready(function ()
{
hideColumnColorRow(5); // Hiding the 5th column and colorizing the row for which this column has a value = Yes
});
</script>

* I’ve placed the jQuery/JavaScript function inside a file named custom.js. It resides inside the Scripts folder of the sample app available here. There’s no need to reference this script file in the view page because with the introduction of ASP.NET 4.5 we now have an all new Bundling and Minification Support for CSS and JavaScript files.

When the the app is run, this is the result:

HTML table with column Active hidden and highlighted rows based on its valueFigure 2 - HTML table with column Active hidden and highlighted rows based on its value

This is a really interesting requirement that one can implement in no time thanks to the power of jQuery. jQuery is one of the most fascinating things when we talk about software development. Its creator “John Resig” should be awarded a Computer Science Nobel Prize if that existed. Well it could be the Turing Award.

Anyone should take a look at jQuery and start using it as early as possible. It’s a must have today. I simply love it! Coração vermelho

Source code
I’ve put together a sample ASP.NET MVC 4 (uses NET Framework 4.5) so that you can try this out. You can run the app using the recently launched Visual Studio 11 Beta. You can download the free Visual Studio 11 Express Beta for Web here and the app code here.

Hope it helps.

ResourceManager with External Localization Assembly

As a software developer I like to work with everything that is related to software Localization known as L10n. Besides being a developer working defining the architecture that will be adopted in a given project and doing the hard “FUN” work writing the code, I’m also a translator if you don’t know it yet.

One thing I've been trying to do recently is to be able to use localized strings that are present in an external assembly [ DLL ] using the ResourceManager object.
I have localized strings in resource [ .resx ] files that are specific for each locale I support. I place these .resx files in a separate class library project to maintain things organized.

So, suppose the namespace of this class library is MyProject.L10n and the .resx file name is Localization.resx. This gives me access to a class named Localization within the code. I also have Localization.pt.resx. I support English and Portuguese locales in my project for now. This naming pattern allows me to have in the future a file called Localization.es-ES.resx for Castilian Spanish (as written and spoken in Spain) and another one called Localization.es-AR.resx for Argentine Spanish. During runtime the .NET framework will select the correct .resx file to extract the localized string from based on the current culture the user has set while browsing my website.

After adding a reference to this class library, I'm able to use this code in my ASP.NET MVC project in a Razor view:

MyProject.L10n.Localization.LocalizedString;

This works as expected, but it's not what I need, though. As you see the localized string key [ LocalizedString ] is hard coded. I want to be able to use the method GetString from the ResourceManager object so that I can write code like this:

ResourceManager.GetString(item.DynamicLocalizedStringValue);

The problem and the catchy here is that in order to use the resource manager the way I want, I have to point it to the external assembly this way:

grid.Column(
columnName: "Type",
header: Localization.Type,format: (item) => new ResourceManager("MyProject.L10n.Localization", typeof(Localization).Assembly).GetString(item.Type.ToString()))

This part does the tricky: typeof(Localization).Assembly

In the code block above I’m using WebGrid that is a new helper that comes with ASP.NET MVC 3. It simplifies the task of rendering tabular data. When I do item.Type.ToString() I’m actually getting different values for each row of my grid and I pass this dynamic value to ResourceManager that in return gives me the translated/localized version of a give string key.

Going even further I’ve implemented a Razor’s Helper method in a file called Helpers.cshtml and placed such file inside the App_Code folder. This is the helper’s code:

@using System.Resources
@using MyProject.L10n

@helper GetLocalizedString(string stringValue)
{
    ResourceManager rm = new ResourceManager("MyProject.L10n.Localization", typeof (Localization).Assembly);

    @rm.GetString(stringValue);
}

Now it’s just a matter of calling the helper this way in whatever place/view I need it:

grid.Column(
columnName: "Type",
header: Localization.Type,
format: (item) => @Helpers.GetLocalizedString(item.Type.ToString()))

The above code is way more clear than the one I showed your before…

Hope this post helps shed some light in this subject since the only thing that should be done is to get a reference to the assembly that holds the Localization class and pass it to the ResourceManger’s constructor.

Blogger Posts Searcher using Google Data .NET/Java Client APIs

It just happened today that I wanted to know if I had already published a post with a given title in one of the blogs I publish: http://jes4us.blogspot.com. During translation (I translate the posts from English to Portuguese) I had a feeling that I had  already worked on a similar text… well, it turns out I was mistaken!

Instead of going through the extensive list of posts looking one by one I thought why not leverage the power of Google Data API? You may say: why not do a simple Google search instead? Good point. As I like to play with code I couldn’t resist.

So here it is. A simple and faster way of knowing if I have a post with a given title. Bellow you’ll find the codez to both the .NET client API and the Java one.

Blogger Data API for .NET
1 - Download the client library here: http://code.google.com/p/google-gdata/downloads/list

2 - Install the .msi package Google_Data_API_Setup_1.9.0.0.msi.

3 - Create a new Console project and reference the DLL Google.GData.Client that’s in this folder: C:\Google Data API SDK\Redist

using System;
using System.Linq;
using Google.GData.Client;

namespace BlogPostsSearcher
{
    class Program
    {
        static void Main(string[] args)
        {
            Service bloggeService = AcquireService();

            AtomFeed feed = AcquireAndSetupFeed(bloggeService);

            // Search posts that contain the word "StringToSearchFor" in their titles
            var query = feed.Entries.Where(p => p.Title.Text.Contains("StringToSearchFor");

            // Writes the Blog's Title
            Console.WriteLine(feed.Title.Text);

            // Prints each post found...
            foreach (AtomEntry entry in query)
            {
                Console.WriteLine(string.Format("Post Title: {0} - Date Published: {1}", entry.Title.Text, entry.Published.ToShortDateString()));
            }

        }

        private static AtomFeed AcquireAndSetupFeed(Service service)
        {
            FeedQuery blogFeedUri = new FeedQuery("http://www.blogger.com/feeds/" + YourBlogID + "/posts/default");

            // Setting the number of posts to retrieve
            blogFeedUri.NumberToRetrieve = 1000;

            AtomFeed feed = service.Query(blogFeedUri);
            
            return feed;
        }

        private static Service AcquireService()
        {
            Service service = new Service("blogger", "YourCompanyName-BloggerPostsSearcher");

            service.Credentials = new GDataCredentials("YourEmailAddress@gmail.com", "YourPassword");

            GDataGAuthRequestFactory factory = (GDataGAuthRequestFactory)service.RequestFactory;
            
            return service;
        }
    }
}

Blogger Data API for Java
1 - Download the client library here: http://code.google.com/p/gdata-java-client/downloads/list

2 - Unzip the file http://code.google.com/p/gdata-java-client/downloads/detail?name=gdata-src.java-1.46.0.zip

3 - Create a new Java Project and add references to:
- gdata-client-1.0.jar that’s in this path: gdata/java/lib/
- google-collect-1.0-rc1
that’s in this path: gdata/java/deps/

import java.io.IOException;
import java.net.URL;
import java.util.List;

import com.google.gdata.client.GoogleService;
import com.google.gdata.data.Entry;
import com.google.gdata.data.Feed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

/**
 * @author Leniel Macaferi
 * @date 11-21-2011
 */
public class BloggerClient
{ public static void main(String[] args) throws IOException, ServiceException { try { GoogleService bloggerService = new GoogleService("blogger", "YourCompanyName-BloggerPostsSearcher"); bloggerService.setUserCredentials("YourEmailAddress@gmail.com", "YourPassword"); searchPosts(bloggerService, "YourBlogID", "StringToSearchFor"); } catch (AuthenticationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void searchPosts(GoogleService myService, String blogId, String search) throws ServiceException, IOException { // Request the feed URL feedUrl = new URL("http://www.blogger.com/feeds/" + blogId + "/posts/default"); Feed resultFeed = myService.getFeed(feedUrl, Feed.class); // Setting the number of posts to retrieve... resultFeed.setTotalResults(1000); List<Entry> posts = resultFeed.getEntries(); // Print the results System.out.println(resultFeed.getTitle().getPlainText()); for (Entry post : posts) { if(post.getTitle().getPlainText().contains(search)) { System.out.println("\t" + post.getTitle().getPlainText()); } } System.out.println(); } }

In the code above you need to replace accordingly the following parts:

- YourEmailAddress
- YourPassword
- YourBlogID

References
Blogger Client Libraries and Sample Code

Blogger Developer's Guide: .NET

Blogger Developer's Guide: Java

Tree Graph Ordered Traversal Level by Level in C#

Recently as part of a job interview process, I was asked to solve some programming problems. This post shows the solution for one of such problems.

Problem
The problem ( or could we call it an algorithm exercise? ) is this:

Consider a tree of integers. Knowing that its root node is 0, and given its adjacency list as a two dimensional array of integers, write a function that prints out the elements/nodes in order/level by level starting from the root. That is, the root is printed in the first line, elements that can be reached from the root by a path of distance 1 in the second line, elements reached by a path of distance 2 in the third line, and so forth. For example, given the following adjacency list (draw the tree for a better view):

0 => 1, 2, 3
1 => 0, 4
2 => 0
3 => 0, 5
4 => 1, 6
5 => 3
6 => 4

The program should print:

0
1 2 3
4 5
6

Little bit of theory
If you read about Tree in Graph theory, you’ll see that we can represent a tree using a graph because a tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree.

The tree in this problem isn’t a binary tree, it’s a n-ary tree.

Solution
With theory in mind, here goes my proposed solution…

I’m reusing some code from past posts. In special, the Graph, AdjacencyList, Node, NodeList and EdgeToNeighbor classes.

I use this method to fill a Graph with the Tree structure:

/// <summary>
/// Fills a graph with a given tree structure.
/// </summary>
/// <param name="graph"></param>
private static void FillGraphWithTreeStructure(Graph graph)
{
    // Vertexes
    graph.AddNode("0", null);
    graph.AddNode("1", null);
    graph.AddNode("2", null);
    graph.AddNode("3", null);
    graph.AddNode("4", null);
    graph.AddNode("5", null);
    graph.AddNode("6", null);

    // Edges
    graph.AddDirectedEdge("0", "1");
    graph.AddDirectedEdge("0", "2");
    graph.AddDirectedEdge("0", "3");

    graph.AddDirectedEdge("1", "4");

    graph.AddDirectedEdge("4", "6");

    graph.AddDirectedEdge("3", "5");

    /* This is the tree:
               
            0
          / | \
         1  2  3
        /       \
       4         5
      /
     6
             
        This is the expected output:
             
        Level 1 = 0
        Level 2 = 1 2 3
        Level 3 = 4 5
        Level 4 = 6

    */
}

This is the method that does the hard work:

/// <summary>
/// Performs an ordered level-by-level traversal in a n-ary tree from top-to-bottom and left-to-right.
/// Each tree level is written in a new line.
/// </summary> 
/// <param name="root">Tree's root node</param>
public static void LevelByLevelTraversal(Node root)
{
    // At any given time each queue will only have nodes that
    // belong to a level
    Queue<Node> queue1 = new Queue<Node>();
    Queue<Node> queue2 = new Queue<Node>();

    queue1.Enqueue(root);

    while (queue1.Count != 0 || queue2.Count != 0)
    {
        while (queue1.Count != 0)
        {
            Node u = queue1.Dequeue();

            Console.Write(u.Key);

            // Expanding u's neighbors in the queue
            foreach (EdgeToNeighbor edge in u.Neighbors)
            {
                queue2.Enqueue(edge.Neighbor);
            }
        }

        Console.WriteLine();

        while (queue2.Count != 0)
        {
            Node v = queue2.Dequeue();

            Console.Write(v.Key);

            // Expanding v's neighbors in the queue
            foreach (EdgeToNeighbor edge in v.Neighbors)
            {
                queue1.Enqueue(edge.Neighbor);
            }
        }

        Console.WriteLine();
    }
}

To spice things up I have implemented a Parallel version of the above method using a ConcurrentQueue:

/// <summary>
/// Performs an ordered level-by-level traversal in a n-ary tree from top-to-bottom and left-to-right in Parallel using a ConcurrentQueue.
/// Each tree level is written in a new line.
/// </summary> 
/// <param name="root">Tree's root node</param>
public static void LevelByLevelTraversalInParallel(Node root)
{
    // At any given time each queue will only have nodes that
    // belong to a level
    ConcurrentQueue<Node> queue1 = new ConcurrentQueue<Node>();
    ConcurrentQueue<Node> queue2 = new ConcurrentQueue<Node>();

    queue1.Enqueue(root);

    while (queue1.Count != 0 || queue2.Count != 0)
    {
        while (queue1.Count != 0)
        {
            Node u;
                    
            queue1.TryDequeue(out u);

            Console.Write(u.Key);

            // Expanding u's neighbors in the queue
            foreach (EdgeToNeighbor edge in u.Neighbors)
            {
                queue2.Enqueue(edge.Neighbor);
            }
        }

        Console.WriteLine();

        while (queue2.Count != 0)
        {
            Node v;
                    
            queue2.TryDequeue(out v);

            Console.Write(v.Key);

            // Expanding v's neighbors in the queue
            foreach (EdgeToNeighbor edge in v.Neighbors)
            {
                queue1.Enqueue(edge.Neighbor);
            }
        }

        Console.WriteLine();
    }
}

Now it’s time to measure the execution time using a StopWatch:

private static void Main(string[] args)
{
    Graph graph = new Graph();

    FillGraphWithTreeStructure(graph);

    Stopwatch stopWatch = new Stopwatch();

    stopWatch.Start();

    LevelByLevelTraversal(graph.Nodes["0"]);

    stopWatch.Stop();

    // Write time elapsed
    Console.WriteLine("Time elapsed: {0}", stopWatch.Elapsed);

    //Resetting the watch...
    stopWatch.Reset();

    stopWatch.Start();

    LevelByLevelTraversalInParallel(graph.Nodes["0"]);

    stopWatch.Stop();

    // Write time elapsed
    Console.WriteLine("Time elapsed: {0}", stopWatch.Elapsed);

    Console.ReadKey();
}

Now the results:

Sequential
0
1 2 3
4 5
6
Time elapsed: 00:00:00.0040340

Parallel
0
1 2 3
4 5
6
Time elapsed: 00:00:00.0020186

As you see, time is cut by a factor of 2. I currently have a Core 2 Duo processor in my Mac mini.

Hope you enjoy it and feel free to add your 2 cents to improve this code! Of course there are other ways of solving this very problem and I would like to see those other ways. Do you have any other better idea?

Download
You can get the Microsoft Visual Studio Console Application Project at:

https://sites.google.com/site/leniel/blog/TreeLevelTraversal.rar

To try out the code you can use the free Microsoft Visual C# 2010 Express Edition that you can get at: http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-csharp-express