20 September, 2014

Could not establish secure channel for SSL/TLS with authority

There is a WCF service in a test machine and it uses https. It has a self signed certificate for the machine dns.

Every time I called the web service it returned an error
Could not establish trust relationship for SSL/TLS secure channel

The binding and endpoint configuration in the client and the server were OK and i could even make the service call successfully through soapUI (a free tool to test web services).

In the end, since the certificate was self signed, and not on my machine, I had to install the certificate in my machine for the call to work.

Install certificate using Windows:
  1. - open Internet explorer
  2. - open the service site
  3. - click on the red "Certificate error" box right next to the address bar
  4. - choose view certificates
  5. - install certificate
  6. - next, select "Place all certificates in the following store"
  7. - Select Trusted Root Certification Authorities
  8. - accept everything and you're done.

12 September, 2014

Sharing a local photo to Facebook on Android using Facebook SDK

Most of the steps depicted here can be found on Facebook Developers page but sharing a photo while showing the share dialog isn't fully documented.

Download SDK

Download the Facebook SDK and extract it.

Setup Workspace

Add the Facebook SDK project to your workspace and link the library to your project.

Register App on Facebook

Follow these steps to create a Facebook app and get the Application Id.

Android Manifest

Add these elements to your app Manifest file inside the application element and replace the 123456789456789 of the provider with the application id you got from the facebook page.
<activity android:name="com.facebook.LoginActivity" android:label="@string/app_name" android:theme="@android:style/Theme.Translucent.NoTitleBar" />

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

<provider android:authorities="com.facebook.app.NativeAppCallContentProvider123456789456789" android:name="com.facebook.NativeAppCallContentProvider" android:exported="true" />
The provider was what I was missing from my solution resulting on the photo being published without showing any dialog to the user.
Don't forget to add the facebook_app_id string in your string.xml file.

Initialization

I ended up using Android Simple Facebook library to login the user if necessary since it's really easy to use. 
private Permission[] permissions = new Permission[] { Permission.PUBLISH_ACTION };

public initialization(String appId, String appNamespace, Bundle savedInstanceState) {
 // Facebook SDK initialization
 uiHelper = new UiLifecycleHelper(this, null /*statusCallback*/);
 uiHelper.onCreate(savedInstanceState);

 // Simple Facebook Library initialization
 SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder().setAppId(appId).setNamespace(appNamespace).setPermissions(permissions).build();
 SimpleFacebook.setConfiguration(configuration);
}
Use the status callback to get Facebook session status
It is also needed to attach some lifecycle events to these libraries.
@Override
protected void onSaveInstanceState(Bundle outState) {
 super.onSaveInstanceState(outState);
 uiHelper.onSaveInstanceState(outState);
}

@Override
protected void onResume() {
 super.onResume();
 uiHelper.onResume();
 mSimpleFacebook = SimpleFacebook.getInstance(activity);
}

@Override
protected void onPause() {
 super.onPause();
 uiHelper.onPause();
}

@Override
protected void onDestroy() {
 uiHelper.onDestroy();
 super.onDestroy();
}

Login user

Before actually posting the user is requested to be logged in and authorize the app. Since we're using the Facebook SDK it requires the Facebook App to be installed on the device. Since the user will already be logged in the Facebook App this post will not request the user to login again. The first post will, however, request permission for your app to post in the user timeline.
As stated above, I've used Simple Facebook library for login.
public void checkFacebookLogin(final File photo) {
 if (facebook.isLoggedIn()) {
  postPhoto(photo);
 } else {
  facebook.logIn(new OnLoginListener() {

   @Override
   public void onFail(String result) {}

   @Override
   public void onException(Throwable exception) {}

   @Override
   public void onThinking() {}

   @Override
   public void onNotAcceptingPermissions(Type type) {}

   @Override
   public void onLogin() {
    postPhoto(photo);
   }
  });
 }
}
On production code you should actually handle the other events.

Post Photo

Actually post the photo.
public void postPhoto(File photo) {
 if (FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.PHOTOS)) {
  FacebookDialog shareDialog = new FacebookDialog.PhotoShareDialogBuilder(this).addPhotoFiles(Arrays.asList(photos)).build();
  uiHelper.trackPendingDialogCall(shareDialog.present());
 }
}
Since the WebDialog provided by the Facebook SDK doesn't post photos it looks like we're stuck with this method.

27 December, 2013

Java REST API HTTP Helper

To ease up on HTTP calls I've build a helper that takes care of their inner workings.

package com.milagaia.helper;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

public class HttpHelper {

 protected static final String UTF8 = "UTF-8";
 protected static final String CONTENT_TYPE = "application/json; charset=utf-8";
 
 public InputStream Post(String url, String content, int timeoutMillis) 
   throws ConnectTimeoutException, UnsupportedEncodingException, ClientProtocolException, IOException {

  InputStream result = null;

  DefaultHttpClient httpClient = buildHttpClient(timeoutMillis);
  HttpUriRequest req = buildPost(url, content);

  HttpResponse httpResponse = httpClient.execute(req);

  HttpEntity httpEntity = httpResponse.getEntity();
  result = httpEntity.getContent();

  return result;
 }

 public boolean Put(String url, String content, int timeoutMillis) 
   throws ConnectTimeoutException, UnsupportedEncodingException, ClientProtocolException, IOException {

  DefaultHttpClient httpClient = buildHttpClient(timeoutMillis);
  HttpUriRequest req = buildPut(url, content);

  HttpResponse httpResponse = httpClient.execute(req);

  int statusCode = httpResponse.getStatusLine().getStatusCode();

  return statusCode == HttpStatus.SC_OK;
 }

 public InputStream Get(String url, int timeoutMillis) 
   throws ConnectTimeoutException, UnsupportedEncodingException, ClientProtocolException, IOException {

  InputStream result = null;

  DefaultHttpClient httpClient = buildHttpClient(timeoutMillis);
  HttpUriRequest req = buildGet(url);

  HttpResponse httpResponse = httpClient.execute(req);

  HttpEntity httpEntity = httpResponse.getEntity();
  result = httpEntity.getContent();

  return result;
 }

 public InputStream Delete(String url, int timeoutMillis) 
   throws ConnectTimeoutException, UnsupportedEncodingException, ClientProtocolException, IOException {

  InputStream result = null;

  DefaultHttpClient httpClient = buildHttpClient(timeoutMillis);
  HttpUriRequest req = buildDelete(url);

  HttpResponse httpResponse = httpClient.execute(req);

  int statusCode = httpResponse.getStatusLine().getStatusCode();

  if (statusCode == HttpStatus.SC_OK) {

   HttpEntity httpEntity = httpResponse.getEntity();
   result = httpEntity.getContent();
  }

  return result;
 }

 private DefaultHttpClient buildHttpClient(int timeoutMillis) {

  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpParams httpParameters = httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutMillis);
  HttpConnectionParams.setSoTimeout(httpParameters, timeoutMillis);

  return httpClient;
 }

 private HttpPost buildPost(String url, String content) 
   throws UnsupportedEncodingException {

  HttpPost httpPost = new HttpPost(url);
  ByteArrayEntity baEntity = new ByteArrayEntity(content.getBytes(UTF8));
  baEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE));
  httpPost.setEntity(baEntity);

  return httpPost;
 }

 private HttpGet buildGet(String url) 
   throws UnsupportedEncodingException {

  HttpGet httpGet = new HttpGet(url);

  return httpGet;
 }

 private HttpPut buildPut(String url, String content) 
   throws UnsupportedEncodingException {

  HttpPut httpPut = new HttpPut(url);
  ByteArrayEntity baEntity = new ByteArrayEntity(content.getBytes(UTF8));
  baEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE));
  httpPut.setEntity(baEntity);

  return httpPut;
 }

 private HttpDelete buildDelete(String url) 
   throws UnsupportedEncodingException {

  HttpDelete httpDelete = new HttpDelete(url);

  return httpDelete;
 }
}
And when i need more advanced features such as authentication I either extend or make the necessary changes. 
Hope this helps someone else.

05 December, 2013

Stock Me Up! by Coding Buffalo

These last couple of months I've been working with a friend on a new app for managing stock portfolios which we're publishing today in beta form.

The app is called Stock Me Up! and it just reached a point where it's stable and feature rich enough for everyone to use. The beta release is aimed at getting feedback from users to improve the app until it's everything it can be.
Here are some screenshots of the app as it is in version 1.0:




For this project my friend +Daniel Cachapa  and I formed a team called +Coding Buffalo aimed and getting solutions such as this app to the market. I'll keep you posted on new projects.
Anyway, if you're interested in financial stuff or are simply curious to see the app, you can download it here: https://play.google.com/store/apps/details?id=com.codingbuffalo.stockmeup.
The app itself is free with advertising. If you really hate ads there's a plugin to disable them. Please let us know what you think.

For more information visit: http://stockmeup.codingbuffalo.com


22 September, 2013

Serviço Educativo

In the past two and a half months I've been in charge of a new solution called Serviço Educativo. It's main goal is to organize and make readily available information regarding education activities hosted by museums, theaters, gardens, companies, and any other entity providing these kinds of services, in Portugal.

On the 1st of September, the solution went live. We made a backoffice for those entities to add their own information and events, an android app and a windows phone app to browse the available data. In development are still the iOS app and the web page which will be ready before year-end. The solution is free in all app stores, and entities must only contact us to get their credentials, again, for free. More information can be found at http://servicoeducativo.pt. I would like to state again, that this solution is, for now, just available in Portugal.

This project has been a wonderful experience and I would like to thank all those involved. I would like to thank +Filipa Lopes with whom the idea for this project was created, +Eduardo Vieitas , IT People Consulting CEO that made the bet and is funding the whole project and +Nuno Silva who has been in charge of all project communication. I would also like to thank my father, +Alvaro Milagaia, and again +Filipa Lopes and +Nuno Silva who all have been adding the first batch of entities into the system. We're closing in on 200 entities in Continental Portugal, Azores and Madeira. Thank you all very much.

We're now in production and I couldn't be happier. We've had very good feedback in this first month and have great hopes for the future. If you're in Portugal and want to check out which education activities are available near you, go to the app store of your device, search for "Serviço Educativo" and check it out. Oh, and don't forget to leave feedback.

19 June, 2013

Custom fonts in Android (Part 3 of 3) - Memory leaks and FontsHelper

As reported here in issue 9904 there is a memory leak if we call Typeface.createFromAsset() multiple times as the fonts are kept open.
To avoid this problem and to keep from accessing assstes multiple times we'll create FontsHelper, a class that will contain all typefaces needed by the app.

public class FontsHelper {

 public static final String ROBOTO_LIGHT = "fonts/Roboto-Light.ttf";
 public static final String ROBOTO_BOLD = "fonts/Roboto-Bold.ttf";
 public static final String ROBOTO_CONDENSED = "fonts/Roboto-Condensed.ttf";
 
 private static Map fonts = new HashMap();
 
 public static Typeface getTypeFace(Context context, String fontPath) {
  
  if (!fonts.containsKey(fontPath)) {
   
   Typeface font = Typeface.createFromAsset(context.getAssets(), fontPath);
   fonts.put(fontPath, font);
  }
  
  return fonts.get(fontPath);
 }
 
 public static void setFont(View view, Typeface font) {
 
        if (view instanceof ViewGroup) 
  {
            for (int i = 0; i < ((ViewGroup)view).getChildCount(); i++) {
   
                setFont(((ViewGroup)view).getChildAt(i), font);
            }
        } else if (view instanceof TextView) {
  
            ((TextView) view).setTypeface(font);
        }
    }
 
 public static void setFont(Context ctx, TextView view, AttributeSet attrs) {

  TypedArray styleAttrs = context.obtainStyledAttributes(attrs, R.styleable.CustomFontView);
  String customFont = styleAttrs.getString(R.styleable.CustomFontView_customFont);
  setFont(context, view, customFont);
  styleAttrs.recycle();
 }

 public static boolean setFont(Context ctx, TextView view, String fontPath) {

  boolean successful = true;
 
  try {
  
   Typeface tf = AssetsHelper.getTypeFace(ctx, fontPath);
   view.setTypeface(tf);
  } catch (Exception e) {
   
   Log.e(TAG, "Error to get typeface: " + e.getMessage());
   successful = false;
  }

  return successful;
 }
This way we avoid the memory leaks and can further simplify the CustomFontTextView class from the previous post.

public class CustomFontTextView extends TextView {

 public CustomFontTextView(Context context, AttributeSet attrs) {

  super(context, attrs);
  FontsHelper.setFont(context, this, attrs);
 }

 public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {

  super(context, attrs, defStyle);
  FontsHelper.setFont(context, this, attrs);
 }
 
 public CustomFontTextView(Context context, String fontPath) {
  
  super(context);
  FontsHelper.setFont(context, this, fontPath);
 }
}
With the custom font static variables in FontsHelper and the constructor with a fontPath argument in CustomFontTextView we can also apply the font by code in an easier way.

Custom fonts in Android (Part 2 of 3) - Setting font in xml

The objective is to have the following xml:

<?xml version="1.0" encoding="utf-8"?>
<com.demo.LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:control="http://schemas.android.com/apk/res/com.demo"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.demo.CustomFontTextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        control:customFont="fonts/Roboto-Light.ttf" />

</com.demo.LinearLayout>

To enable this we need to declare a custom attribute in values\attrs.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    
    <declare-styleable name="CustomFontView">
        <attr name="customFont" format="string" />
    </declare-styleable>

</resources>
Now we can add the control namespace as seen in the first snippet in line 4.
To read the customFont value and actually apply it to the TextView we're going to extend it and read the new attribute. The CustomFontTextView could be something like this:

public class CustomFontTextView extends TextView {

 public CustomFontTextView(Context context, AttributeSet attrs) {

  super(context, attrs);
  setCustomFont(context, this, attrs);
 }
 
 public void setCustomFont(Context context, TextView view, AttributeSet attrs) {

  TypedArray styleAttrs = context.obtainStyledAttributes(attrs, R.styleable.CustomFontView);
  String customFont = styleAttrs.getString(R.styleable.CustomFontView_customFont);
  setCustomFont(context, view, customFont);
  styleAttrs.recycle();
 }
}
Just like this CustomFontTextView, the same method can be applied to all views. To apply to multiple views inside a complex view check Arnaud's answer in http://stackoverflow.com/questions/9797872/use-roboto-font-for-earlier-deviceshttp://stackoverflow.com/questions/9797872/use-roboto-font-for-earlier-devices.

To avoid having the same path copied all over your xml files you may consider creating styles and put the path there.

<style name="RobotoTextView" parent="android:Widget.Holo.Light.TextView">
 <item name="customFont">fonts/Roboto-Bold.ttf</item>
</style>
And then applying that style in your custom controls:
    <com.demo.CustomFontTextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        style="@style/RobotoTextView" />
On the last part we will focus on a memory leak you may find and how to avoid it.

Custom fonts in Android (Part 1 of 3) - Adding to project and set by code

To use custom fonts in Android add the necessary font files to assets/fonts (you may need to create the assets folder).
To apply them by code use the following snippet:

Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
textView.setTypeface(font);
On the second part of this series we'll apply custom fonts in xml.
UPDATE: Oh, and please don't include unnecessary fonts in the asstes folder as seen above as it will bloat your apk. Thanks.

15 April, 2013

Parcitypate is a Finalist

Hey everyone, just wanted the share my joy in these news.
My team (+Rui Milagaia (me) , +Lara Rodrigues and +Vasco Avillez) passed to the second phase of the Lisbon BIG Apps contest with our project Parcitypate.
Our project was one of the 15 chosen between 206 submitted from 10 countries.
Now, the hard work starts.
Wish me luck

01 April, 2013

Code Writer Helper

When working with MDA developers have a to write a lot of Transformer code. There are two important steps to write good code generation.

First step: write and test the end code to minimize errors.
Step two: write the transformer that will generate that code based on models.

The second step usually takes a lot of time as the developer has to write a lot os boilerplate prefix, suffix code in the transformer. To make sure the generated code is readable he must also write indentation related code.

Enter Code Writer Helper. It's just a very simple tool that accepts the prefix, suffix, empty row, add tab and remove tab strings, and returns the code ready to be pasted in the transformer file.
Everything written in the Original Code box is transformed in real time to the transformed Code box.

You can also creating different configurations by clicking on the "+" on the top right corner.

This was written in WPF and it's available on CodePlex.

Happy transforming.

Let machines to machine work

DRY - Don't Repeat Yourself

Every developer knows this principle, and a lot actually apply it, yet most are confined in the code-related meaning of it.
 "Let no line of code be repeated."

When its time to do documentation of a system or start the implementation of a new one, etc most of us either start from scratch or do a lot of copy paste. In no time, the documentation is dated and incorrect and so are year old systems that don't follow the new company standards. And that's the good perspective, because some systems won't be outdated because the company stops learning and starts its slow descent to failure.

Why must we continue to limit ourselves to the code and spend most of our working time repeating meaningless tasks over and over again.

Take documentation of a web service. The interface changes and lets update the document, it changes again, and again and again and.... why doesn't the document. If it is actually needed let the document be generated from the interface.

Take system deployment. Hopefully most don't have to do it by hand nowadays but some still do.

Whenever a task repeats itself those who repeat it lose a chance to create something new. And those who can't create won't learn. Most tasks can be automated, let your mind wonder and find new ways to automate your work. Let your imagination run wild and you will find something for sure. People are slow and error prone but the potential for madness that we have gives us creativity. Everyone loves doing what they are best at and no one likes to lose, so why keep competing with machines in these meaningless tasks instead of winning at creating new ones.

The creative mind should create. A great company must have its employees do human work. Once a task is done automate it however you can so you won't have to do it again. The future then awaits with new and exciting tasks of learning and creating new things and simply letting machines to machine work



25 May, 2012

Silverlight + XNA Full size render with System Tray and ApplicationBar

While developing a XNA +  Silverlight App (a Libra port for Windows Phone 7) the XNA rendered page wasn't occupying the whole screen.
After some googling i arrived at Samuel Blanchard blog (its in french) with the answer.
Turns out the System tray and the Application bar rendering is done differently from the rest of the page. And the System tray acts like the Application bar when it's opacity isn't set to 1 (they don't resize the screen area).
So, by setting the opacity of the System tray and the ApplicationBar to 0.99 and then adding margins equal to their height to the LayoutRoot I've managed to get a full XNA rendered layout with System Tray and ApplicationBar.

Opacity settings
shell:SystemTray.Opacity="0.99"
shell:ApplicationBar IsVisible="True" Opacity="0.99"

LayoutRoot margins (SystemTray Height = 32; ApplicationBar Height = 72)
Grid x:Name="LayoutRoot" Margin="0,32,0,72"

10 April, 2012

ODP.NET Slow first connection

I was having a problem with the first time the Oracle provider connection was made. I enabled the oracle log and it only started after the big delay.

Using ProcessMonitor i was finally able to verify that the w3wp process was having trouble creating some directories in the oracle client directory. 

The necessary directory structure was:

C:\oracle_client\log\diag\clients

This saved 20 seconds from the first connection delay. 

Hope it helps someone.

04 April, 2012

Split Large Xml file in smaller valid Xml Files using LinqToXml

Splitting a large xml file using Linq to Xml.

The main performance hit is the initial load of the xml to memory (must find a solution to load each node as needed). There is certaintly room for improvement but for now, its gets the job done.

string path = @"c:\large.xml";
int nrParts = 220;

XElement root = XElement.Load(path);
XElement cleanedRoot = new XElement(root);
cleanedRoot.RemoveAll();
XNode[] children = root.Nodes().ToArray();
int childrenCount = children.Count();

int nodeCountPerPart = (int)Math.Ceiling(childrenCount / (double)nrParts);
int totalNodesToAdd = childrenCount;
int indexBase = 0;

for (int i = 0; i < nrParts; i++)
{
    XElement newRoot = new XElement(cleanedRoot);
    indexBase = i * nodeCountPerPart;
    for (int j = 0; j < Math.Min(nodeCountPerPart, totalNodesToAdd) ; j++)
    {
        newRoot.Add(children[indexBase + j]);
    }

    newRoot.Save(string.Format(@"c:\large_part{0}.xml", i+1));
    totalNodesToAdd -= nodeCountPerPart;
}


UPDATE: Using this method +Master Aucrun  has created a simple WinForms project to easily split an xml file. Thanks +Master Aucrun. You can get it here.

22 March, 2012

WP7 DatabaseSchemaUpdater multiple version update

While testing the Windows Phone 7 DatabaseSchemaUpdater I started getting the following error: "A column ID occurred more than once in the specification."

I searched the web for a while and got nowhere.

So, analizing my code for the 10th time i noticed something. On the second update (version 1 to version 2) I was adding a new table:

schemaUpdater.AddTable();

And on the third update (v2 to v3) I was adding a new column to that same table:

schemaUpdater.AddColumn< ClassName >("PropertyName");

If the user updates the app regularly everything goes smoothly, but if the user doesn't update for some time and then has to go through all the updates the app crashes.

The problem is that when the new table was added, since the user is already at the newest version, the table already has the column that the next update will try to add. At that point it will crash, and continue crashing at every update unless the DatabaseSchemaVersion is properly updated.

This can lead to a lot of frustration and data loss for the user and must be taken into account when updating.

Since I couldn't find a way to get the current schema to check for table columns before adding them I made a simple workaround.

When updating keep a list of added table names in that update and when adding columns only add them if the table where the column is being added doesn't have its name on the list.
Check the example below



private const int LatestDatabaseVersion = 2;

private List tablesAddedInThisUpdateSession = null;
public List TablesAddedInThisUpdateSession
{
get
{
if (tablesAddedInThisUpdateSession == null)
{
tablesAddedInThisUpdateSession = new List();
}

return tablesAddedInThisUpdateSession;
}
}

public void UpdateIfNeeded()
{
// create an instance of DatabaseSchemaUpdater
DatabaseSchemaUpdater schemaUpdater = this.CreateDatabaseSchemaUpdater();

int version = schemaUpdater.DatabaseSchemaVersion;

// if current version of database schema is old
while (version < LatestDatabaseVersion)
{
switch (version)
{
case 0:
version = UpdateFromVersion0ToVersion1();
break;
case 1:
version = UpdateFromVersion1ToVersion2();
break;
default:
break;
}
}
}

private int UpdateFromVersion0ToVersion1()
{
DatabaseSchemaUpdater schemaUpdater = this.CreateDatabaseSchemaUpdater();

schemaUpdater.AddTable<Contact>();
TablesAddedInThisUpdateSession.Add("Contact");

// IMPORTANT: update database schema version before calling Execute
schemaUpdater.DatabaseSchemaVersion = 1;
schemaUpdater.Execute();

return schemaUpdater.DatabaseSchemaVersion;
}

private int UpdateFromVersion1ToVersion2()
{
DatabaseSchemaUpdater schemaUpdater = this.CreateDatabaseSchemaUpdater();

if (!TablesAddedInThisUpdateSession.Contains("Contact"))
{
schemaUpdater.AddColumn<Contact>("Phone");
}

schemaUpdater.DatabaseSchemaVersion = 2;
schemaUpdater.Execute();

return schemaUpdater.DatabaseSchemaVersion;
}

06 March, 2012

Asp.NET Concurrent AJAX Calls

In Asp.NET "if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished." (ASP.NET Session State Overview)

The keywords here are "same session".

When an Ajax call to an ASP.NET Web method is made:

[WebMethod(true)] // EnableSession = true
public static void MethodName()
{
}

If the "EnableSession" is set to true there can be only one ajax call at a time. Further calls will wait in pending state until the call is finished. Once it's finished the order of previous calls is not guaranteed.

If EnableSession is set to false you can make concurrent calls but will not have access to the Session. The number of calls that can be made depends on each browser.

However, if you're user ASP.NET MVC 3 and above there is an attribute named SessionState that enables you to make concurrent calls and still access your session (in read-only mode)

Concurrent calls :
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

Sequencial calls:
[SessionState(System.Web.SessionState.SessionStateBehavior.Required)]

21 February, 2012

WCF IEnumerable DataContracts bug

Kept getting an error while using SoapUI to create valid requests for a WCF web service hosted in IIS.
While debugging the operation executed without any problems, but the client always got a connection error (java.net.SocketException: Connection reset).
Turns out there is a bug in WCF when serializing a DataContract with an IEnumerable<T> member. Changed to List<T> and the problem was gone.

19 February, 2012

Solution file (.sln) comments (#)

When to adding comments to Solution files start the comment line with the # char.

Example:

# Comment

17 February, 2012

WCF service contract changes supported by old proxy

Needed to know which changes to a WCF Service Contract could an old proxy support. The tests were made with BasicHttpBinding and WsHttpBinding and a client with a proxy generated by visual studio. All DataContract attributes were strings.

My results were:

Add an Operation - OK
Remove an Operation - OK unless the client calls it.


Added Attribute to response object - OK
Added Attribute to request object - OK

Removed Attribute from response object - OK (the client interprets it as null)
Removed Attribute from request object - OK (the client interprets it as null)

Change the type of an Attribute of the response object -depends whether the new type can be parsed to the old type from the message string.
Change the type of an Attribute of the request object -depends whether the new type can be parsed to the old type from the message string.

Change the Attribute name in the response object - OK (the client gets null since the old attribute was removed)
Change the Attribute name in the request object - OK (the client gets null since the old attribute was removed)

All OK results indicate that no Exception is thrown.
The client will not be aware of new properties or new operations but will also not crash (at least for nullable properties, haven't tested types other than strings).

The results were the same for both bindings.

Other bindings, especially ones that have binary serialization will probably present different behaviors.

10 July, 2010

Comparing collections with LINQ

Once in a while i have to call the Distinct LINQ method and, more often than not, i don't want to compare the objects reference. To this effect Microsoft provides the interface IEqualityComparer<T>.
The IEqualityComparer<T> interface implements two methods: bool Equals(T x, T y) and int GetHashCode(T obj). These methods are both used by LINQ to compare objects in collections.
Since i need to compare most of the business objects in my solutions, and don't want to go through the hassle of implementing tens of new classes (one per object) I wanted a generic solution.
Simple enough, I built myself the GenericComparer<T>.

public class GenericComparer<T> : IEqualityComparer<T>
{
public GenericComparer(Func<T, T, bool> equals, Func<T, int> getHashCode)
{
this.equals = equals;
this.getHashCode = getHashCode;
}

readonly Func<T, T, bool> equals;
public bool Equals(T x, T y)
{
return equals(x, y);
}

readonly Func<T, int> getHashCode;
public int GetHashCode(T obj)
{
return getHashCode(obj);
}
}

This worked fine. I could finally just set my comparer directly in my LINQ command. All i had to give was the expression to be used in the Equals and GetHashCode methods.



IEnumerable<mytype> result = collection.Distinct(new GenericComparer<mytype>(((mt1, mt2) => mt1.id == mt2.id), (mt => mt.id.GetHashCode())));

Still, it was more code than I would like to see. Since all I want is to receive all unique elements based on a single expression then that's all i should have to write. A simple tweak to the GenericComparer class and I got a simpler comparer SimpleGenericComparer<T>.

public class SimpleGenericComparer<T> : IEqualityComparer<T>
{
public SimpleGenericComparer(Func<T, int> getHashCode)
{
this.getHashCode = getHashCode;
}

public bool Equals(T x, T y)
{
return getHashCode(x) == getHashCode(y);
}

readonly Func<T, int> getHashCode;
public int GetHashCode(T obj)
{
return getHashCode(obj);
}
}
Having the Equals method simply compare both objects with the GetHashCode expression i could finaly just give the expression with which the comparison will be made.

IEnumerable<mytype> result = collection.Distinct(new SimpleGenericComparer<mytype>(mt => mt.id.GetHashCode());