Pages

Wednesday, April 24, 2013

Detect the screen resolution for Windows Phone OS 7.1 applications

    As you probably know Windows Phone 7.1 applications run perfectly on Windows Phone 8 devices. This means that your application/s could run on multiple display resolutions (which are the resolutions supported by Windows Phone 8 devices). If you want to take advantage of the new resolutions (for example downloading higher quality images for higher resolutions devices, fix some minor UI anomalies on higher resolutions) you will need to know the ScaleFactor of the device. The property is only available in the Windows Phone 8.0 SDK, but the good news is that you can access it using reflection.

Solution:
We retrieve the Get method of the ScaleFactor property and invoke it only if the application is running on an Windows Phone 8 device.

Here is the source code:
  public static Size DisplayResolution  
{
get
{
if (Environment.OSVersion.Version.Major<8)
return new Size(480,800);
int scaleFactor=(int) GetProperty(Application.Current.Host.Content, "ScaleFactor");
switch (scaleFactor)
{
case 100:
return new Size(480, 800);
case 150:
return new Size(720, 1280);
case 160:
return new Size(768, 1280);
}
return new Size(480, 800);
}
}
private static object GetProperty(object instance, string name)
{
var getMethod= instance.GetType().GetProperty(name).GetGetMethod();
return getMethod.Invoke(instance, null);
}

I am also attaching a small sample Windows Phone OS 7.1 test project.


SOURCE CODE

P.S. I think Telerik could use this method to fix this RadToolTip visual anomaly (the 1 pixel width lines that I have filled with blue for contrast) :


NAMASTE

Tuesday, April 16, 2013

3 ways to force the WebBrowser control to logout from Facebook

     Decided to write this post because it took me some time to find the answer. Maybe you already know that if you use OAuth Facebook connect inside your Windows Phone application there is one step where you use the WebBrowser control to let the user authenticate on the Facebook server and authorize your app. The "problem" presents itself when you want to link another user because the WebBrowser control has already memorized the old credentials and will automatically use them. What needs to be done is to logout the old user from the WebBrowser without actually telling the user to go on the web page and click logout. I have found 3 easy ways to do that: the first two will work on both Windows Phone 7.x and Windows Phone 8 and are Facebook specific and the third one will only work on Windows Phone 8 (generic method for OAuth providers). The 3 methods can use the WebBrowser control headless (you don't actually have to show the WebBrowser control to the user and don't even have to have the webbrowser attached to a Page):  

Method 1: described by Rene Schulte in this blog post  
The method constructs the logout Uri using your AppId and a SessionKey that is obtained from the AccessToken you got when the user authenticated.

Get the SessionKey:
  private static string ExtractSessionKeyFromAccessToken(string accessToken)  
{
if (!String.IsNullOrEmpty(accessToken))
{
var parts = accessToken.Split('|');
if (parts.Length > 2)
{
return parts[1];
}
}
return String.Empty;
}

Obtain the logout Uri:
  public Uri GetLogoutUri(FacebookCredentials credentials)  
{
var sessionkey = ExtractSessionKeyFromAccessToken(credentials.AccessToken);
var url = String.Format("http://facebook.com/logout.php?app_key={0}&session_key={1}&next={2}", EndpointData.FacebookAppId, sessionkey, EndpointData.FacebookLogoutCallbackUrl);
return new Uri(url);
}

Make the WebBrowser navigate to the logout Uri:
 Browser.Navigate(FacebookService.GetLogoutUri(EndpointData.Settings.Facebook));  

Method 2:
If for some reason you don't have the Facebook AppId available (my case) you can use the WebBrowser to navigate to the Logout page https://www.facebook.com/logout.php and after the page gets loaded you just execute the script document.forms['logout_form']:
 wb.LoadCompleted += wb_LoadCompleted;  
wb.Navigate(new Uri("https://www.facebook.com/logout.php"));
Once the page gets loaded:
 void wb_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)  
{
wb.LoadCompleted -= wb_LoadCompleted;
if (wb.SaveToString().Contains("logout_form"))
wb.InvokeScript("eval", "document.forms['logout_form'].submit();");
}

Method 3:
This is the easiest one, but will only work on Windows Phone 8: call the new WebBrowser async method ClearCookiesAsync(). This method works for every OAuth provider (Dropbox, Box, Skydrive, Picasa, Flickr, Google Drive... infinite list).

NAMASTE

Thursday, April 11, 2013

SharePoint 2013 : the Big Five

Trends impacting collaborative tools and platforms

I have been working for quite some years now consulting companies mostly on the technical side of building and designing collaborative environments but when preparing for a presentation about why people should upgrade their current environment to the latest (and off course greatest) version I tried to summarize some trends which significantly impact the way that we should think about these environments.
  • It’s a multi-device & mobile world.  90% of people use multiple screens sequentially to accomplish their goals with search being the most common ways consumers continue from one device to another (Source Google: The New multi-screen world study )
  • Social collaboration is the new norm. 82% of the world’s online population engages in social networks. The usage of social tools has changed the mindset of people and is blurring the division between private and work life. People are expecting to same ease of connecting with co-workers and keeping up to date  within the enterprise as they are used to connect and follow their social network outside  outside of it. The fact that a new digital generation ( a.k.a Generation Y) is entering the workforce will put even more pressure on companies to embrace social tools.
  • Businesses are faced with an increased pace of change. Most people seem to think that the accelerating change is typical for technology but this accelerated pace of change also applies to business in general. According to research the average lifespan of a S&P 500 company is 18 years today (compared with 68 years in 1950). At this rate 75% of the S&P 500 will be replaced by 2027 (Source Innosight.com, 2012: Creative destruction whips through corporate America). Extrapolating from past patterns by the end of the year 2020, the average lifespan will have been shortened to about 10 years (See Survival and performance in the era of discontinuity). The only corporate survivors will be those that can increase the rate of creative destruction without losing control of present operations.
  • No man is an island – collaboration is required for value creation. 66% of CIOs from top-performing organizations see collaboration as key to innovation. (Source: IBM CIO study, 2001). Most tasks performed by knowledge workers have become so complex that they require people with diverse skill sets and from multiple disciplines to collaborate. Unfortunately organization are still quite hierarchical organized which impedes efficient collaboration. Definitely read – Enterprise Social Networks what has changed and the changing role of middle management
  • Renewed focus on people as the core asset in the battle for companies survival.  Although the next quote was made by Andrew Carnegie at the end of the 19th century it holds more true then ever.
  • The only irreplaceable capital an organization possesses is the knowledge and ability of its people. The productivity of that capital depends on how effectively people share their competence with those who can use it.
    If you look at information workers (the typically users of your platform) you will notice a shift in structure based work (Processes, routines,controls,…) to more knowledge based work (research, problem-solving, relationship driven,…) But knowledge workers are more likely to excel when they are engaged. Gallup estimates that engaged employees are 18% more productive and that attrition decreases with 51%. At the same time employees are expecting more from their employers. They don’t just go to work to get paid, they want to be motivated, challenged and have a clear purpose( definitely check out the video What motivates us?)
    Related posts:
  • Enterprise 2.0 and organizational culture
  • Knowledge and talent in a people ready business
  • Knowledge is power! So why share your knowledge?
  • The value in social networks
  • Colleagues, Social Distance & Relevance in People Search, and other Social Networking tools in SharePoint
  •  

Thursday, April 4, 2013

Value cannot be null.Parameter name: parentContext in Windows Phone 7


Today morning I am just open Visual Studio 2010 and create a new Windows phone project and came across an issue with windows phone xaml page with the following error in design view.

Value cannot be null.Parameter
name: parentContext in Windows Phone 7

To rectify this issue I did two worked around and both are worked.
1) Build your project and close the page windows and then open.
2) Close the Visual Studio IDE and re-launch it.

Hope it helps.

SharePoint Saturday Belgium 2013 – Building the “Hot or Not” app on SharePoint 2013 … or how not to sell social to your client or boss

I’m presenting a SharePoint development session on social at SharePoint Saturday Belgium 2013  end of April. I’m still in the brainstorming phase but below is the abstract – so if you have something specific you want to see in the session – leave a comment;

Session abstract: ​Enterprise social networks allow you share best practices within organizations, identify co-workers with particular expertise, exchange knowledge and work more efficiently together on projects , but they can also be a lot of fun. Microsoft has made some significant investments in social capabilities with SharePoint Server 2013. In this session we will explore the different social capabilities in SharePoint 2013 and show how to build a SharePoint app which leverages social and search features to build your own "Hot or Not" app. Technologies covered in this session include the new Social and Search REST APIs in SharePoint 2013, the SharePoint app framework, Azure , Windows 8 and Windows Phone 8 ... but it is mostly about having some fun to build a social app. Warning: session is heavy on code ... and pretty girls.

Wednesday, April 3, 2013

Presenting at Be the Change Hero for better information collaboration in your organization

 

I’m presenting the keynote next week at “Be the Change Hero for better information collaboration in your organisation” in Brussels – if you are interested check out Be the Change Hero roadshow event site.  Focus of the sessions is on getting more value out of yor SharePoint investement. For those of you who can not attend – I will share the slidedeck afterwards.

Technorati Tags: ,

Tuesday, April 2, 2013

Smooth scrolling content on Windows Phone

     Gotta say that I am not 100% satisfied about the title of this blog post, but since I haven't found a better one I will use this one (don't get it wrong windows phone has smooth scrolling implemented). This post is focusing on how to smooth scroll the content of a ScrollViewer. If you are using the ScrollViewer you know that it already has the method ScrollToVerticalOffset that can be used to manually scroll the content but this method doesn't have any animation implemented so you will see only a fast redraw of the new content without getting the "feeling" that the content scrolled to the new position. The easiest way to achieve this task would be using a StoryBoard with an Animation on the property VerticalOffset of the ScrollViewer, but VerticalOffset is a read-only property so it cannot be set and therefore cannot be used for animation.
     The solution I found was to build a custom control and add a custom property that can be used as a target for a DoubleAnimation. The attached sample (see the link at the end of the post) is using a ListBox as the content of my Custom Control but you can use anything else inside the control (a better approach for the ListBox would be to create a custom control derived directly from ListBox and use the built-in ScrollViewer). 
      Let's start from the XAML part of the User Control:

  <ScrollViewer x:Name="scroller">  
<ContentPresenter Content="{Binding ContentArea, ElementName=userControl}"/>
</ScrollViewer>

    So we have a ScrollViewer which inside has a ContentPreseter that has its content binded to the control's property ContentArea. Now let us have a look at the .cs code.

 public static readonly DependencyProperty VerticalOffsetProperty = DependencyProperty.Register("VerticalOffset",  
typeof(double), typeof(SmoothScroller), new PropertyMetadata(VerticalOffsetPropertyChanged));
public double VerticalOffset
{
get { return (double)this.GetValue(VerticalOffsetProperty); }
set { this.SetValue(VerticalOffsetProperty, value); }
}
private static void VerticalOffsetPropertyChanged(object sender, DependencyPropertyChangedEventArgs args)
{
SmoothScroller cThis = sender as SmoothScroller;
cThis.scroller.ScrollToVerticalOffset((double)args.NewValue);
}
public static readonly DependencyProperty ContentAreaProperty = DependencyProperty.Register("ContentArea", typeof(object), typeof(SmoothScroller), null);
public object ContentArea
{
get { return (object)GetValue(ContentAreaProperty); }
set { SetValue(ContentAreaProperty, value); }
}

     The property that we will use for animation is the VerticalOffset that uses the method VerticalOffsetPropertyChanged to scroll to a vertical offset inside the control's scroller. The property VerticalOffset can be animated and we will use it to smooth scroll the ListBox content.
     Here is the content of the MainPage.xaml

  <uc:SmoothScroller x:Name="smoothScroller">  
<uc:SmoothScroller.ContentArea>
<ListBox x:Name="lstItems" ItemsSource="{Binding Items}" ScrollViewer.VerticalScrollBarVisibility="Disabled" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemTemplate="{StaticResource DataTemplate}" >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</uc:SmoothScroller.ContentArea>
</uc:SmoothScroller>

     So we have the SmoothScroller control which inside its ContentArea has a ListBox (the ListBox has it's scrollviewer disabled). What the sample does is it is changing the selected item every second (incrementing the selectedindex) and scrolls the content so that the newly SelectedItem is centered in the ScrollViewer. Here is the code used for scrolling:

  void dt_Tick(object sender, EventArgs e)  
{
((ListBox)smoothScroller.ContentArea).SelectedIndex = idx;
var container = ((ListBox)smoothScroller.ContentArea).ItemContainerGenerator.ContainerFromIndex(idx) as FrameworkElement;
var transform = container.TransformToVisual(smoothScroller.scroller);
var elementLocation = transform.Transform(new Point(0, 0));
double newVerticalOffset = elementLocation.Y + smoothScroller.scroller.VerticalOffset - smoothScroller.scroller.ActualHeight / 2 ;
//Animate transition
DoubleAnimation verticalAnimation = new DoubleAnimation();
verticalAnimation.From = smoothScroller.scroller.VerticalOffset;
verticalAnimation.To = newVerticalOffset;
verticalAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));
var sb = new Storyboard();
sb.Children.Add(verticalAnimation);
Storyboard.SetTarget(verticalAnimation, smoothScroller);
Storyboard.SetTargetProperty(verticalAnimation, new PropertyPath(SmoothScroller.VerticalOffsetProperty));
sb.Begin();
idx++;
if (idx >= 56)
dt.Stop();
}

     Pretty basic: select the new index in the ListBox, calculate the new VerticalOffset so that the newly selected item is centered in our scrollviewer and create and start a 500ms animation for the SmoothScroller.VerticalOffsetProperty. Anyway I am sure that you will better understand how it works when you will try the sample code.
     The sample is far from perfect (before starting a new animation I should check if the old one finished, should not automatically scroll when the user is manipulating the list,...).
     Here is a screenshot from the sample:

As usual let me know if you need help. The code works on both Windows Phone 7.1 and Windows Phone 8 SDK.

SOURCE CODE


Monday, April 1, 2013

Building a Windows 8 app for SharePoint 2013 Part 1: using Javascript and CSOM

I followed two sessions about building a Windows 8 app for SharePoint 2013 during the SharePoint conference in Vegas. The two sessions used a different approach for building such an app. In the next couple of blog posts I will outline the different approaches and provide some feedback around it. Let’s start with the CSOM approach.

The SharePoint CSOM and Javascript approach to build Windows 8 apps
During the session Fun with SharePoint Social, CSOM and Windows 8 delivered by Mark Rackley and Eric Harlan (Slideshare for a local BIWUG redelivery available here) at SharePoint Conference Las Vegas a solution depicted by the image below was built. For a complete walkthrough check out Creating your First Windows 8 Application using the Client Object Model (CSOM) and JavaScript
from Mark.

For those of you unfamiliar with CSOM – this is an abbreviation of the  SharePoint Client Side Object Model. So the basic setup was actually a Visual Studio solution which combines a JavaScript WinRT project and a Windows Runtime compontent.  Listed below is  a download link with a  very simple example to get you started.  This is how the code of the Windows Runtime Component looks like – it is basic CSOM code.  Some things you should think about:
  • Add a reference to the required Microsoft SharePoint Client Runtime components
  • Make sure that you pass in the required credentials – the code below assumes that the Windows 8 machine is in the same domain as your SharePoint Server and that you can log in with integrated security
  • The SocialFollowingManager is the most important class – for background info on follows in SharePoint 2013 – check out Common programming tasks for following content in SharePoint 2013
  • You will need to use a separate object to pass the information from the SocialFollowingManager back to the Javascript Windows Store App. By default the SocialFollowingManager returns a ClientResult of type SocialActor which is not a valid Windows Runtime Parameter type and which can’t be returned in a public method
  • You can’t use nested classes – that’s whyFollowedContent is a separate class.
  • If you receive “Unable to connect to the remote server” when connecting to SharePoint you probably still need to make sure that your application has the correct capabilities enabled.  Open up your Application Manifest and make sure that you have “Enterprise Authentication” and  “Private Networks (Client and Server) checked



  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Threading.Tasks;
  6: using System.Net;
  7: using Microsoft.SharePoint.Client;
  8: using Microsoft.SharePoint.Client.Social;
  9: 
 10: namespace CSOM
 11: {
 12:     public sealed class FollowedContent
 13:     {
 14:         public string ID { get; set; }
 15:         public string Type { get; set; }
 16:         public string Name { get; set; }
 17:         public string Uri { get; set; }
 18:     }
 19:     
 20:     public sealed class Social
 21:     {
 22: 
 23:         public static FollowedContent[] GetFollowedContent()
 24:         {
 25:             
 26:             ClientContext ctx = new ClientContext("http://sp2013");
 27:             ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
 28:             
 29:             SocialFollowingManager sfmgr = new SocialFollowingManager(ctx);
 30:             ClientResult<SocialActor[]> actors = sfmgr.GetFollowed(SocialActorTypes.All);
 31: 
 32:             sfmgr.Context.ExecuteQuery();
 33: 
 34:             FollowedContent[] followedContent = new FollowedContent[actors.Value.Length];
 35: 
 36:             int index = 0;
 37: 
 38:             foreach (SocialActor actor in actors.Value)
 39:             {
 40:                 FollowedContent content = new FollowedContent();
 41:                 content.ID = actor.Id;
 42:                 content.Type = actor.ActorType.ToString();
 43:                 content.Name = actor.Name;
 44:                 content.Uri = actor.Uri;
 45:                 followedContent[index++] = content;
 46: 
 47:             }
 48: 
 49:             return followedContent;
 50:         }
 51:     }
 52: }
 53: 


I like this approach of building Windows 8 apps since it allows for a clean separation of the SharePoint codebase from the UI part. At the same time SharePoint developers can leverage the SharePoint object model using CSOM.  It is possible to leverage numerous Javascript libraries (such as JQuery UI) to build a compelling user experience.


Code samples – download BIWUGApp1.rar