ASP.NET MVC 3 Preview 1 : New Features Part 1

by Rod 29. July 2010 00:05

This is isn't an introduction post on MVC so if you’re looking through to understand what MVC is I suggest you binging/googling it!

ASP.NET MVC 3 Preview 1 was released yesterday, this post is the first among other posts I’m going to write that will walkthrough some of the new features.

You can get the bits here.

Phil Haack wrote an article with a detailed summary of what’s new (or even better read the release notes ;)).
In short here are the new features:
* Razor Syntax View Engine.
* Dynamic View and ViewModel propeties.
* Service Location and Dependency Injection Support.
* Global Filters.
* Support for .NET Framework 4 Metadata Attributes.

Now let’s get into the practical:
After having installed the bits, Open up a new project and choose “ASP.NET MVC 3 Web Application (Razor)”
You might of noticed 2 Templates are available one with Razor View engine and the other ASPX, this will be regrouped later on in one template, and you’ll make your choice later on in the project creation (probably the same time you choose whether or not you want to create a Unit test project)

After creating the project scroll down to Views/Shared, you’ll notice the _Layout.cshtml page which is the equivalent of the Master Page in ASPX.
Like in Master Pages, you can define different sections in your “_Layout.cshtml” file.

We’re going to define add some custom content in header (we’re going to add a slogan) and a footer.
In order to do that we’ll use @RenderSection and end up with something like this:

 

layout

 

This release doesn’t support syntax highlighting or intellisense, so you’ll understand why the screenshots might look plain!

Now what we want to do is define what’s going to be rendered in these sections through our Index.cshtml (home view); we’ll add the content to the sections with “@section nameofthesection ”

home

 

Everything outside @section is rendered as normal body content.

So with this we’ll end up with something like this :

homeresult

Now let’s get into something the Razor View Engine made easier and faster for us:

Usually when you’d want to write c# code and iterate through a list in the VIEW you’d do something like this :

mvc2iteration

 

As you might of noticed we’re really bound to this <$= %> syntax!

In MVC 3 the mixing is a lot smoother (This is proper Razor syntax):

 

mvc3iteration

 

 

You might of noticed in the home view, there’s something weird and new View.Message”, although there’s a property called “View” in the home controller, so where did this come from?

As you’ve already guessed @View.Message is a proper cleaner way to write “ViewData["Message"]”.
Now let’s get to the controller you can see :

ViewModel.Message = "Welcome to ASP.NET MVC!";
//This also is the equivalent to :
ViewData["Message"] = "Welcome to ASP.NET MVC!";

So why not call it View here on the controller? Because View is already a method; the Microsoft team found it shorter and cleaner than ViewModel on the View but they’re still open for suggestions for a smoother short name.

So this concludes this post; There are more new interesting features, but will leave them for future posts!

 

 

 

Tags: , ,

asp.net

WP7 development vs BlackBerry development

by Rod 28. July 2010 00:28

As you might already know I developed a BlackBerry application called Mobholicavailable on appworld
I wasn’t a pro in Java when I did that, but had the basics and knew c# very well.
The development experience was literally hell; well for one reason I’ve been used to something a lot better!

Here are a few points I think BlackBerry should improve:

* The BlackBerry Plug-in freezes a lot upon launch time (at least once every 3 times) and during normal development.
* Work on their views implementation; even if it’s Java they should work on something similar to Android in order to really separate the view and make it easier / more professional to develop on.
* Documentation is poor its been there for years now whereas in a matter of months the Android documentation ousted it in quality and quantity.
* Appworld should do more testing on the applications; I’ve seen applications on the featured list completely freeze or never worked once on my mobile.
* Appworld’s minimum application fee should be less than 2.49 euros!!! (this is beneficial for everyone!)

Now to be less negative, I’ve been working on Windows Phone 7 applications, the development experience is just 100 times better than the BlackBerry experience I had.
Richer tools are available for us (you can get them for free here) like VS 2010 Express and Expression Blend for Windows Phone 7 Beta

Training kit available for both gamers and normal application developers (XNA and Silverlight) available here.

I wrote a simple none technical article for the company I work for demonstrating a Proof of Concept of the first application I developed on WP7 for Renault. (the application has more functionalities and has changed a bit since)

If you’re an Android / BlackBerry developer I really invite you to check out the technical posts I wrote on developing on Windows Phone 7 available through this blog(specially the one with MVVM – since this is the hype,hot topic right now in .net development).

WP7 development still has a few missing things comparing to BlackBerry.
With BlackBerry I was able to access the phone’s calendar/ tasks etc..directly from the application; and I still can’t from a WP7 application.
Here’s the list of things you can do though: http://msdn.microsoft.com/en-us/library/ff428753(v=VS.92).aspx

Tags: ,

general development | WP7

Mobholic : New update released.

by Rod 20. July 2010 01:00

I’ve re-launched today Mobholic!
Mobholic is a BlackBerry application that ranks you both locally and internationally on your phone usage!
The application comes with new exiting features:
* New website with 3D charts.
* Charts accessible also from the mobile app
* Ranking per  Email Sending/ Receiving / Deleting
* Ranking per words typed in your Email.
* Ranking per distance traveled with your BlackBerry (if mobile phone supports GPS)
* Top Movers in the last 24 hours ranking.

Hurry and check out the website now : http://mobholic.com
And get the application from BlackBerry App World 

I’m working for a company right now where Surface and Windows Phone 7 Development is something we do everyday!
I’m pretty exited and will be doing something for Mobholic on WP7, if not a brand new idea.

Tags:

Personal

Productivity

by Rod 13. June 2010 21:52

Here it is, it’s been a while since I’ve written anything none technology related but I feel this subject really relates to what I and other people around me deal with on a daily basis.

I’ve started my new internship for this summer whereas my university year hasn’t really ended yet. So have to manage my time and study at night/ in the week-ends for the upcoming exams.

So you might have guessed, time isn’t really something you can just waste and not feel guilty about.

A lot might think this is a bad idea, you’ re forcing yourself a lot, and you’ll just penalize your studies.

Au contraire my friends; I’ve studied this week-end like no other week-end this year, you see when you have less time, you intend to make that time worthwhile; you become more productive and therefore you manage more efficiently your tasks and maybe even discover new limits.

Tags: ,

Personal

Creating your first MVVM silverlight application on windows phone 7.

by Rod 5. June 2010 15:13

The goal of this tutorial is to create an MVVM driven twitter mini client application for windows phone 7. We’ll do the exact same twitter client Scott Guthrie did in the MIX 10 presentation except we’ll follow the MVVM pattern. 
So here’s how we’d want it to look like.

The source code for this tutorial is also available.

1) Why MVVM ?

MVVM is a design patter, better for testing and for big enterprise projects since there wouldn’t be any code behind in your view, everything would be exposed and controlled by your ViewModel – so easier to test.
(Here’s a more detailed guide about the MVVM pattern).

Here’s a schema summarizing the pattern:

MVVM_pattern_diagram_thumb

2) In order to develop for Windows Phone 7, you need to get the free SDK here, the current version is the April CTP refresh. (Visual Studio 2010 Express comes with the tools you can download, so developing for windows phone 7 can be absolutely free).

Let’s Start coding!

Open Visual Studio and create a new project using the “Silverlight for Windows Phone” Tab and choosing the “Windows Phone Application” template.

Let’s start of by creating a new class called: ViewModelBase and make it implement the INotifyPropertyInterface.

This is going to be the class we’re going to derive from all of our ViewModels.

Now let’s add some properties in this Base class in order to get save some lines of code and not repeat ourselves in the other ViewModel classes we’re going to write.

protected void OnNotifyPropertyChanged(string p)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(p));
    }
}       
public event PropertyChangedEventHandler PropertyChanged;

This basically says whenever my property is changed the event PropertyChanged is launched.

Let’s create our View now.

Open up the MainPage.xaml.

I’m going to add a TextBox, a button and a listbox unto the design view (you can manipulate the controls and dimension them to whatever you want from the designer view etc ..)

So here’s how my view looks like right now:

view

Now let’s modify our listbox in order to contain an image and the status update. (many ways you can do this, you can ofcourse do it from Blend), but this isn’t the purpose of this tutorial. So we’ll keep it simple.

Add a Image then a textbox for the message and another for the username inside the listbox template while editing the xaml.

So our Xaml for the listbox can look like this:

  <ListBox Height="500" HorizontalAlignment="Left" 
                     Margin="20,115,0,0" 
                     Name="listBox1" VerticalAlignment="Top" Width="440">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Height="100" Width="100" 
                                   VerticalAlignment="Top" Margin="0,10,8,0"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock />
                                <TextBlock   />
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

 

Now let’s add our ViewModel for this specific View.

Create a new folder called “ViewModels” and then a new class in that folder named: “MainViewModel”

Make that class derive from our “ViewModelBase” class.

So let’s think about what we want exactly:

* When the button Look up is pressed we want the above page title to change to “Whatever we put in the textbox” ‘s Feed”.

* When the button Look up is pressed, we get the status updates for the specific user entered in the textbox.

Okay let’s jump into that, remember there shouldn’t be any code behind on my view that’s event driven specific etc..

First let’s start off by linking our View to the ViewModel we just created.

There are two ways of doing this, one from the View XAML directly, the other in the code behind while calling the constructor of the View.

The most common method is the second so we’ll do that.

Open the code behind of the MainPage View.

Add the namespace of the ViewModels, create a new variable of type “MainViewModel”.
Set the DataContext of the View as the MainViewModel variable we just created.

private MainViewModel _mainViewModel = new MainViewModel();

        public MainPage()
        {
            InitializeComponent();
            DataContext = _mainViewModel;
        }

Here’s the inside of our MainPage class now.

Let’s create now our TwitterItem class:

Create a new class called TwitterItem and add the following properties (there’s nothing different here from ScottGu’s post) : Username , Message, ImageSource.

Then add a static method that we’ll help us parse the xml returned and return a list of TwitterItems.

So overall our class looks like this now:

public class TwitterItem
{
    public string Username { get; set; }
    public string Message { get; set; }
    public string ImageSource { get; set; }

    public static List<TwitterItem> GetTweetsFromResponse(String Response)
    {
        List<TwitterItem> lsttweets = new List<TwitterItem>();

        XElement xmlTweets = XElement.Parse(Response);
        lsttweets = (from tweet in xmlTweets.Descendants("status")
                    select new TwitterItem
                    {
                        ImageSource = tweet.Element("user").Element("profile_image_url").Value,
                        Message = tweet.Element("text").Value,
                        Username = tweet.Element("user").Element("screen_name").Value
                    }).ToList();

        return lsttweets;
    }
}


Now let’s go back to our MainViewModel class.

I’m going to need a property for the textbox text (which will be the username for the feeds we want to get), another one for the title, and finally a RelayCommand for the Button.

What? RelayCommand? what’s that? it’s a helper from the MVVM light toolkit developed by Laurent Bugnion
(He also presented the Toolkit in MIX 10)

The toolkit works on WPF, Silverlight and WP7.

Now why would we need this?It’s simply a really big time saver + commands don’t exist on WP7 because WP7 use Silverlight 3.

RelayCommands helps us link commands on methods, you’ll understand this in a minute.

So first let’s add the dlls from the toolkit you can get them here.

references

Now that’s done we can add our RelayCommand.

So this how class looks like now:

public class MainViewModel : ViewModelBase
    {
        public string strUsername { get; set; }
        public RelayCommand GetTweetsCommand { get; private set; }
    }

 

Now we need an ObservableCollection for the tweets, and this collection will be the item source of our listbox.

private ObservableCollection<TwitterItem> _lstTweets;
public ObservableCollection<TwitterItem> LstTweets
{
    get
    {
        return _lstTweets;
    }
    set
    {
        if (_lstTweets != value)
        {
            _lstTweets = value;
            OnNotifyPropertyChanged("LstTweets");
        }
    }
}

Finally our last property needed, is the Title one since it’s going to be binded to the title in order to set the Title to “screen name” ‘s feed.

private string _title;
public string Title
{
    get
    {
        return _title;
    }
    set
    {
        if (_title != value)
        {
            _title = value;
            OnNotifyPropertyChanged("Title");
        }
    }
}


Now let’s write the methods to get the tweets from the twitter api (one will be used for the async call,
and the other for the response):

private void GetTweetsCall(string screenName)
  {
      WebClient client = new WebClient();
      client.DownloadStringCompleted += 
          new DownloadStringCompletedEventHandler(twitter_Response);
      client.DownloadStringAsync(
          new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name="
              + screenName));
  }

  private void twitter_Response(object sender, DownloadStringCompletedEventArgs e)
  {
     if (e.Error == null)
      {
          LstTweets = TwitterItem.GetTweetsFromResponse(e.Result);
      }
  }

 

Finally we have to add the constructor and in that constructor we’re going to link our relay command to the method that calls the twitter api, and set the “Title” property with the txtUsername property + “’s feed”:

public MainViewModel()
 {
         GetTweetsCommand = new RelayCommand(() =>
             {
                 Title = txtUsername + "'s Feeds";
                 GetTweetsCall(txtUsername);
             }
         );
 }


All this is nice, but that’s not enough, we need to bind everything on the View.

So for the title TextBlock, we bind the text to the Title:

<TextBlock Text="{Binding Title, Mode=OneWay}" 
                       Style="{StaticResource PhoneTextPageTitle2Style}"/>

 

Repeat the same thing for the TextBox but instead of setting the Mode OneWay you have to set it TwoWay because we’re using the Text written in the TextBox by the user in our ViewModel.

<TextBox Height="72" HorizontalAlignment="Left" Margin="31,37,0,0" 
                     Text="{Binding txtUsername,Mode=TwoWay}" 
                     VerticalAlignment="Top" Width="275" />

Now we have to bind the listbox Item source to our ObservableCollection.

  <ListBox Height="500" HorizontalAlignment="Left" 
                     Margin="20,115,0,0" 
                     VerticalAlignment="Top" 
                     Width="440" ItemsSource="{Binding LstTweets, Mode=OneWay}">

So what’s left? Binding the image and 2 textblocks inside our listbox.

   <Image Height="100" Width="100"  Source="{Binding ImageSource , Mode=OneWay}"
                                   VerticalAlignment="Top" Margin="0,10,8,0"/>
                            <StackPanel Orientation="Vertical">
                                <TextBlock  Text="{Binding Username , Mode=OneWay}"  />
                                <TextBlock  Text="{Binding Message , Mode=OneWay}"  
                                           />
                            </StackPanel>


Now how do we set the Command on our button in wp7 based on Silverlight 3 where commands weren't supported ?  With the MVVM light toolkit!

It’s easier to do this with Blend by just drag and dropping , but not the purpose of this tutorial ;) ..

So just copy/paste this in your button XAML:

  <Button Content="Look up" Height="70" 
                    HorizontalAlignment="Left" Margin="300,37,0,0" 
                    VerticalAlignment="Top" Width="160">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <GalaSoft_MvvmLight_Command:EventToCommand 
                            Command="{Binding GetTweetsCommand, Mode=OneWay}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>

Add the necessary namespace imports :

 xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
 xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7" 
  

As you noticed the Command Binding in the eventTrigger is set to the RelayCommand we created in our ViewModel.

Then a little bit of styling on our View in order to make it look good.

Run your application now!

Type in a screen name inside the textbox and click the “Look up” button and this is the result:

result

Hope you enjoyed this article, MVVM isn’t an easy concept, but a lot of helpers out there, I personally really like MVVM light toolkit. I'll do my best to write more articles on windows phone 7 and MVVM!

In the mean time you can get the source code here.

Tags: , ,

WP7

MobHolic update delayed due to App World issue.

by Rod 30. April 2010 22:54

I’m posting with kind of bad news, the update release date of MobHolic is going to be pushed for a simple reason:

App World has an issue regarding the updates: after posting an update, App world will notify you that there’s an update but it’ll re-install the old application.

They said they’re working on it and users will have to re-install App world.

Unfortunately they didn’t give me a timeframe for the update.

I’ll keep you posted.

Tags:

MobHolic : First Review from BlackBerry Cool

by Rod 13. April 2010 23:40

Dear Readers!

BlackBerry Coolwrote the first review for the MobHolic application!

Get the application hereand start getting ranked! ;).

I’m first at the moment, but I will reset my numbers because I started before everyone else!

Check out the stats on http://www.mobholic.com

Tags:

Personal

MobHolic : Get ranked on your BlackBerry addiction!

by Rod 12. April 2010 02:51

Dear readers,

I’ve launched my first mobile application !

MobHolic is a mobile application that permits users to get a day to day usage time of their phone. These numbers are then calculated and summed up to have a rank for their phone addiction both internationally and locally.

The application is available on the BlackBerry app world store.

For additional info : http://www.mobholic.com/

mobholic

Tags:

Personal

ASP.NET : MVC or WebForms ?

by Rod 21. March 2010 03:24

With Asp.net MVC 2’s launch, I’ve been more and more curious on MVC, problem is I’m a used Web forms developer.

So started doing more research on what’s best to be oriented in etc..

And found this really interesting article with SWOT analysis :

http://blog.gadodia.net/choosing-between-webforms-and-mvc/

Tags: ,

asp.net

WP7 - Blend : Twitter Client Design WP7 with Blend (Basic)

by Rod 21. March 2010 02:06

In the first post I did for WP7, I showed how to develop a simple, mini Twitter client with VS 2010 RC.

This post is going to be designer oriented (beginner level, as if you’ve never used Blend before!)

In order to be able to use Blend for WP7, check out this site : http://www.silverlightshow.net/news/Expression-Blend-4-for-Windows-Phone.aspx

Now let’s get to the fun part.

In the designer window, right-click the "Update Status” button > Edit Template > Create Empty.

Name the template whatever you want, I’m calling it :”HotButton”.

post

Change the layout container of the new template from “Grid” to “Border”.

post1

Now let’s start designing :

Set the BorderThickness and CornerRadius to whatever you want.

In order to find the Properties faster you can use the Search bar.

post3

post4

Apply a gradient background by selecting the Background property and then picking the Gradient brush option.

And pick the colors you want from the palette.(left : start point , right : end point ).

post5

Now let’s add the text for our button.

Go to the “Assets” tab then Controls > double click on TextBlock (while insuring the Border layout container is still selected)

post6

 

Now let’s align our text, because we have to admit it is ugly on the left, so let’s change both “VerticalAlignment” and “HorizontalAlignment” Properties.

post7

Now go to the Foreground property of the TextBlock and set a foreground color, in my case it’s going to be something close to black.

post8

Mmmm what’s missing now ?

We have to link the Text property to the actual content of the Button. So to do that, click on the tiny square next to the Text Property > Template Binding > Content.

post9

And here you go, now let’s run our application. (Note : Blend will ask you if you want to run the application on the emulator or a device, be sure emulator is selected)

post10

That’s of course not everything you can do, we can change the Textbox, add some animation etc..

I’ll cover the animation in another post, stay tuned!

Tags:

WP7

About the author

Rodrigue Hajjar

.NET Developer.

.Supinfo Student.

 

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar