Solving development problems  |  About this blog

Archive for the ‘microsoft’ tag

Silverlight: Equidistant items in a stack panel

This post describes how to align items in a container so the two neighbour items are always aligned with equal distance. Solution should be flexible, meaning that when items are changed or when container is resized items should keep equal distance in between. Reader should have some basic knowledge about C# and XAML for Silverlight.

Ideas

  • using Canvas and positioning items with absolute coordinates – items are always fixed, coordinates need to be calculated, so it is the least flexible approach, no
  • using StackPanel with items that have margin – margins need to be recalculated when an item is added or removed or when container is resized, maybe
  • using Grid with predefined rows and columns – notice predefined, means less flexibility, but offers equal size rows/columns, maybe
  • using a custom control – making Grid more dynamic but extending number of rows/columns when items are added, yes

Custom Control: EqualDistanceStackPanel

As written before, custom control should extend Grid to become more flexible

public class EqualDistanceStackPanel : Grid
{
}

 

EqualDistanceStackPanel should implement ItemsSource and ItemTemplate just like ItemsControl

#region ItemsSource
public IEnumerable ItemsSource
{
  get { return (IEnumerable)GetValue(ItemsSourceProperty); }
  set { SetValue(ItemsSourceProperty, value); }
}

public static readonly DependencyProperty ItemsSourceProperty =
  DependencyProperty.Register("ItemsSource", typeof(IEnumerable),
  typeof(EqualDistanceStackPanel), new PropertyMetadata(ItemsSourceChanged));

private static void ItemsSourceChanged(DependencyObject d,
  DependencyPropertyChangedEventArgs e)
{
  var panel = d as EqualDistanceStackPanel;
  if (panel != null)
  {
    if (e.OldValue != null)
    {
      panel.ClearItems();
    }
    if (e.NewValue != null)
    {
      panel.BindItems(e.NewValue as IEnumerable);
    }
  }
}
#endregion

public DataTemplate ItemTemplate
{
  get;
  set;
}

 

ClearItems method deletes all previous elements from the panel and BindItems attaches fresh controls from item template.

protected void ClearItems()
{
  this.Children.Clear();
}

protected void BindItems(IEnumerable items)
{
  if (this.ItemTemplate == null)
  {
    return;
  }

  //Create and attach children
  foreach (var item in items)
  {
    var element = this.ItemTemplate.LoadContent() as FrameworkElement;
    element.DataContext = item;
    this.Children.Add(element);
  }

  //Realign in container
  Refresh();
}

 

How should the custom control look in XAML? EqualDistanceStackPanel gets a collection of items, e.g. of UIElement type.

<Grid xmlns:c="clr-namespace:Avivo.Controls">
  <c:EqualDistanceStackPanel ItemsSource="{Binding Items}" Orientation="Vertical">
    <c:EqualDistanceStackPanel.ItemTemplate>
      <DataTemplate>
        <ContentPresenter Content="{Binding}" />
      </DataTemplate>
    </c:EqualDistanceStackPanel.ItemTemplate>
  </c:EqualDistanceStackPanel>
</Grid>

 

Example

Ruler has been made to demonstrate the usage of EqualDistanceStackPanel. Numbers are bound to the control and ticks are bound to another control using the same binding collection. Left image represents container height 300px and right when resized to 460px – elements are automatically aligned with equal distance.

Try demo, resize browser to see the effect. This control has been originally developed for custom chart axes in QR Code Statistics application. EqualDistanceStackPanel control is lightweight, works for the statistics application and should be improved for general usage.

Source code

  • Source code, Visual Studio sample Silverlight and web project

References

Written by developer

March 29th, 2011 at 2:00 pm

How to show compiler errors in ASP.NET MVC Views?

Just open your csproj project file in notepad and find MvcBuildViews and set value to True.

<MvcBuildViews>true</MvcBuildViews>

Written by Avivo

February 7th, 2011 at 4:21 pm

How to create custom error 404 in ASP.NET MVC

Introduction

So, whenever an error occurs, you would like to show a custom 404 error page in ASP.NET MVC? This blog post describes how to techically handle and display error page effectively. Reader should have some basic knowledge of setting IIS and ASP .NET MVC project.

Error page is displayed when something goes wrong. Page should inform user about what happened and what he or she should do next. Page should also inform bots, crawlers, spiders not to search any relevent content in there, e.g. Google won’t display error page as search result. This is handled with HTTP status code known as 404. There are also other HTTP status codes for specific problems, e.g. for maintenance, for restricted access…

Create action and view

First, create a friendly page for user and set indicator for bots not to handle this page as obvious page. In this case “Main” controller with “Error” action. Note for IE 5,6: error page should have content larger than 512 bytes otherwise IE will display its own content.

public class MainController
{
  public ActionResult Error()
  {
    //404 - Tell search engine not to display this page on search results
    Response.StatusCode = 404;
    Response.StatusDescription = "Not Found";
    return View();
  }
}

Register route that eats anything

Open Global.asax(.cs) in the MVC project and register error page route. Rule should be designed to capture all requests that do not fit in previous route rules. Simple solution: {*anything} rule captures any path including slashes, e.g. /shop/mushrooms-123.

//Somewhere in Global.asax
public static void RegisterRoutes(RouteCollection routes)
{
  //Registered routes
  //...

  //Error route should be registered last
  routes.MapRoute
  (
    "ErrorPage",
    "{*anything}",
    new { controller = "Main", action = "Error" }
  );
}

Advantage: no redirects, requested URL string should be kept in browser’s location bar. For example, when
user requests /shop/mushrooms-123 in browser the error page content will be display but the URL will remain original.
The opposite of redirecting and displaying /error in location bar.

How to handle other errors?

Other errors in ASP .NET can be handled in Application_Error method in Global.asax.

//Somewhere in Global.asax
protected void Application_Error()
{
  //Useful for debugging to get error details
  Exception ex = Server.GetLastError();

  //Redirect to error page
  //Can be "/Main/Error" or "/error" or other route as "ErrorPage" rule eats all
  Response.Redirect(Request.ApplicationPath + "/error/500");
}

Configuration in IIS 7.5

1. Open IIS Manager. Shortcut: click Start in Windows, type “inetmgr” in search box then press Enter.
2. Click on a website on the left side.
3. Select Error Pages on the right side.
4. Configure scenarios for specific status codes, as displayed on screenshots.

Troubleshooting

Q: Browser displays system error page when I expect custom error page.
A: Configure Error Pages for the website in IIS. Error Pages may differ between websites.

Q: Error handling is defined in web.config but does not work in Windows Server 2008.
A: Try to edit Error Pages directly in IIS (IIS Manager -> Sites -> (website name) -> Error Pages)

Q: Status code 200 OK displays a custom error page but 404 Not Found displays generic IIS error page (yellow box with techical message)
A: Configure Error Pages (see above). “customErrors” in web.config may not work as expected.

Q: Can I keep status 200 OK to display error page?
A: It will do the job for users who visually see and understand the content, but may not work for bots (i.e. displaying error page in search result)


String or binary data would be truncated. The statement has been terminated.

If this is not a problem for you that some long string will be truncated and you don’t want SQL to send you this error just use at the beginning of your StoreProcedure this statement:

SET ANSI_WARNINGS OFF

The dark side of Android phone development – part 2

About this blog post
Unlike the Official Google articles that are mostly praising Android as Mobile platform, this article covers practical development experiences with Android platform.

Authors of this article have prior practical experiences in web and desktop enterprise software development and have recently developed few Java applications for Android 2.1-update1. Content has been written in Autumn 2010, statements in the article are referenced to that time and to the testing on Samsung Galaxy S i9000 phone.

Android Development

As we pointed out in this blog title, we just wanted to make an awesome Android phone application and we wanted to find out how much effort does Android OS really take for a development. Users don’t care about this and web press don’t care much as long Apps are great and working and all the hard work by developers isn’t mentioned a lot, except at dev blogs.

How Android is working
Android market is the main source from which users download mobile Apps to their phones. First thing that we noticed is that Google, the grandmaster of web search engines, doesn’t even have search feature on Android Market website so you can not find mobile App that you are looking for. By statistics there is only a small amount of payable Apps and their price is around a dollar ($1) and most of the applications on the Market are free.

Web view of Android market v iPhone App store

Google definitely plays whole different game on mobile space. Knock-outing all other players with free OS for all handset Vendors it gained mass and popularity and is trying to secure future dominance over mobile search and advertisement, Apps. This isn’t such a bad strategy after all if you think that predictions for Mobile market are $17.5 billion $ by 2012.

Developers are the most collateral damage inside Android value system. They are trying to make good Apps and it is a shame that Google don’t care to promote developers properly with better Market and it looks like Google is the only one who gains profit out of this relationship. Is it also true that Google has been lucky, or to say it better, just on time with Android launch and become the only real competitor to iPhone, which is sold by only one vendor – Apple.

On the contrary, Android, that has open approach, allowed many different vendor carriers to get into smart phone market (HTC, SAMSUNG, …). Taking advantage of growing Apps market and advertising Android platform Google is collecting large statistic numbers for variety of marketing use. At the same time public relationship (mostly fans) has done a great job hiding the background of so called always beta Android platform.


Why Android is not very friendly for developers and can improve a lot in the future?

  1. No earnings for developers Developers have less chances to earn money on the market since the users expect to download FREE applications - good for users, bad for developers. In the long term is also bad for users because they will get lower quality products. Here are not counted enterprise solutions for real clients.
  2. Market is not organized Market is huge, tens of thousands of Apps, lots of daily uploads with no quality control... Lots of free Apps are very poor and not very good and this means that is harder to find a quality product on Android market. Consider how can normal user find your application?
  3. Bad API consistency Java in theory is a good idea, you should learn language, coded once and then run the code on different platforms and Android runs Java applications. Android platform have different features, like file structure, graphical interface, accessing hardware features, etc. So programmers make APIs and libraries to simplify development, to avoid writing code for same functionality over and over again. Android API has like every other API issues with backward compatibility, extensibility, maintainability... and backward compatibility is poor, applications written for 2.1 are not guaranteed to work on newer phones (2.2). Code does not necessarily compile for latest version because Google has renamed a method or a constant (e.g. frequently used FILL_PARENT renamed to MATCH_PARENT).
  4. API bugs API documentation is sometimes inaccurate and outdated, for example saying "this method will always return a list with at least one element" but what it does is exactly the opposite - returning null. As Android has many documentation issues phone manufacturers interpret documentation in their own way, not following the documentation strictly (e.g. random phone resolutions). Manufacturers improvize to gain some hardware features, like accessing the secondary camera or secondary SD card (e.g. originally /sdcard is for external storage but on Samsung Galaxy S /sdcard is used for internal, /sdcard/sd for external). Developers always have to look for work-arounds, trying to write some logic code at first that it does not work, trying the other way and it does not work either, trying for the third way when it finally works. Dealing with that kind of work-arounds takes time and nerves. In long-term this issues may result in non-consistent APIs, different for each phone model, as it was back in J2ME days.

  5. Other Android disadvantages we experienced:
    • Not so easy customizable (you can change colour of a button but cannot change the transition animation between activities)
    • Emulator is slow, no camera support
    • Sometimes during development testing Phone Galaxy S freezed and the only way to wake up the phone was to take battery out.
    • Not as friendly to use as iPhone, e.g. you have to deal with USB drivers. Not as fast as iPhone.

Conclusion: Android solutions are short-terms for developer, patch it and "works now" and API design is really a large downside for a mass consumer product as it is Android.

Why Android is also not perfect for final users?

  1. Bound to Google Android phone user needs GMail account to download an application from the market. Once a user logs in with GMail account and downloads at least one application it can no longer remove the account from the phone without resetting the phone to the factory defaults. With default settings open Google has chance to always track an account for controlling downloads and tracking IP and GPS location of the phone (default settings on Samsung Galaxy S phone).
  2. Hacks, viruses, security, privacy issue on Android phones can be exploited easily with numerous hacks to unlock the phone (e.g. by uploading custom firmware ROM) or bypass security restrictions (root access hacks). Even with the brand new phone you can type *#*#...# sort of secret codes to access the hidden or debugging features on Android phone. For access to for hidden GPS settings type: *#*#1472365#*#* on Samsung Galaxy S phone).
    Pre-installed system applications can enable Wi-Fi, Bluetooth, camera, browse contacts without user ever knowing or agreeing. In our case we get unwanted silent imports of GMail messages and contacts just by logging with GMail account on the Android market.
  3. Beta quality products for users Nowadays Mobile phone market is already huge and touch screens are very popular and competitors are fighting for every percent on the market. To be a step before or to catch the competitors Google needs to provide Android products fast. Quick releases mean less testing and buggy features, resulting in fair-quality beta products. Samsung Galaxy S is at the time of writing the hottest Android phone on the market and many are comparing as Android iPhone, but guess what: GPS does not even work correctly with the initial firmware. Sometimes touch screen freezes and you cannot turn off or reset the phone because "turn off" is triggered with a touch (there is always a way to take battery out and insert it again).
    To emphasize this test with Galaxy S: Android software is currently the main problem, not hardware. Software could be a whole lot better, hardware is at it's optimum.


What are the conclusion sorted by the facts:

  1. Users expect free apps resulting less $ for developers
  2. Fairly compatible platform versions
  3. Android market is big with lot of toy apps and few very useful everyday applications
  4. Privacy issues: Google holds you and you can not escape
  5. Questionable security, easily exploited platform (hacks)
  6. Constant searching for work-arounds during development
  7. Phone manufacturers use API in its own interpretation
  8. Fair quality software, is it a bug or feature?

Final words

In the terms of software and UX we have to admit that iPhone is currently much better then Android, who is trying to catch up, resulting in quick decisions, bugs, and lower quality product. Android is improving and we can soon expect it will be a stable platform (1 year) and because is »open« platform compare to »closed« iPhone system has lot of potential to overcome iPhone. There is large amount of phone manufacturers that produce Android phones with free Android OS opposite to iPhone which is under Apple control. Very important fact is that number of Android developers are growing more rapidly than developers for iPhone and also on the market Android phones are selling faster then iPhone (USA example). Android is definitely a step forward compared to J2ME but now it looks that it is going to the same problematic direction (resolutions, different hardware, compatibility).

What do you think? Share your thoughts in the comments.