Category Archives: .NET

Referencing JSON.NET in Windows Phone 8

Sometimes we just want to knock our heads against the wall until the wall cracks or we loose our senses…

That’s how I feel now, after loosing more than 30 minutes figuring out how reference JSON.NET in a Windows Phone 8 Project.

So, I took the Silverlight assembly, and added it to the project and this is what I got:  a nice “A reference to a higher version or incompatible assembly cannot be added to the project.” error message..

cannot-import-assembly
Continue reading “Referencing JSON.NET in Windows Phone 8” »

[Windows 8] [Workaround] – Javascript runtime Error: Object doesn’t support property or method ‘itemFromDescription’

Lately I’ve been playing with the Windows 8 developer tools, being focused on the HTML5 + Javascript version.

Although the paradigm changes a bit (being a pure OOP developer) I must say I’m well impressed with it.

The labs are a great place to start, and will provide a general knowledge of the main features of the windows store apps.

One of these features is the semantic zoom. While I was trying to use it on a experience project of my own, I got the nice exception “Javascript runtime Error: Object doesn’t support property or method ‘itemFromDescription'” when zooming out.

When zooming out, the position of each item will be retrieved. The action happens on the ui.js file:


                if (typeof key === "string" && this._dataSource.itemFromKey) {
                    itemPromise = this._dataSource.itemFromKey(key, (this._isZoomedOut ? {
                        groupMemberKey: item.key,
                        groupMemberIndex: item.index
                    } : null));
                } else {
                    var description = (this._isZoomedOut ? item.groupDescription : item.firstItemDescription);

                    if (WinJS.validation) {
                        if (description === undefined) {
                            throw new WinJS.ErrorFromName("WinJS.UI.ListView.InvalidItem", strings.listViewInvalidItem);
                        }
                    }

                    itemPromise = this._dataSource.itemFromDescription(description);
                }

If you look closely, you’ll see that if the type of the key used for the group is not a string, the fallback will be the “item.groupDescription” (zoomed out) which obviously can be undefined (depending on the group object structure).

The workaround is to convert the group key to string:

var groupedItems = list.createGrouped(
    function groupKeySelector(item) {
         return item.departmentId.toString();
    },
    ....
);

And that’s it. It doesn’t solve the problem, but it goes around it.
Cheers

[c#] Extending Enums on .NET

One of these days I had the need to create and extensible enum. Extensible in a way that allows people to add items to it, but outside the assembly where the enum is declared.

The short answer to this is that enums are not extensible Triste

It become clear that I would need to find a workaround. Since we had some legacy code already working, it was necessary to keep the normal usage of the enum (i.e. switch – case).

The following solution may not be the best one, but it’s working good, allowing the extension of the enum and still preserve their traditional usage on the switch-case blocks.

Note: the following code is used to “replace” enums deriving from INT. Deriving from other datatype involves changing the operators.


Continue reading “ Extending Enums on .NET” »

[Sharepoint] Hide QuickLauch on feature activation

Sometimes, when applying branding to Sharepoint sites, it’s necessary to hide the quicklaunch bar.

Some people do that by overriding the css styles, and basically making it invisible. This is a good approach for when, on certain pages, we need to display the quicklaunch, while on the others we need to hide it.

Please note that the quicklaunch it’s always there, with this approach. It’s simply not visible.

For a situation where we’ll never want to display the quicklaunch, we can simply deactivate it, with a feature.

Let’s say we create a feature called “HideQuickLaunch”, scoped for a site (Web). On the event receiver we can override the following methods:


//disable quicklaunch on feature activation
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using (SPWeb currentWeb = (SPWeb)properties.Feature.Parent)
    {
        currentWeb.AllowUnsafeUpdates = true;
        currentWeb.QuickLaunchEnabled = false;
        currentWeb.Update();
        currentWeb.AllowUnsafeUpdates = false;
    }
} 

//enable quicklaunch on feature deactivation
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    using (SPWeb currentWeb = (SPWeb)properties.Feature.Parent)
    {
        currentWeb.AllowUnsafeUpdates = true;
        currentWeb.QuickLaunchEnabled = false;
        currentWeb.Update();
        currentWeb.AllowUnsafeUpdates = false;
    }
} 


Hope it helps ;)

[SQL Server] – Generate Random Datetime within a range

One of these days I had the need to obtain a random datetime inside a specified range, on SQL Server 2008.

After a few minutes I came up with this script:



DECLARE @DateFrom DATETime = '2012-01-01'
DECLARE @DateTo DATeTime = '2012-06-30'
DECLARE @DaysRandom Int= 0
DECLARE @MillisRandom Int=0

--get random number of days

select @DaysRandom= DATEDIFF(day,@DateFrom,@DateTo)
SELECT @DaysRandom = ROUND(((@DaysRandom -1) * RAND()), 0)

--get random millis
SELECT @MillisRandom = ROUND(((99999999) * RAND()), 0)

SELECT @DateTo = DATEADD(day, @DaysRandom, @DateTo)
SELECT @DateTo = DATEADD(MILLISECOND, @MillisRandom, @DateTo)
SELECT @DateTo

Hope it’s useful.

[Sharepoint] – DataContext with custom URL

Hello,

One of these days I had to do some bugfixing on a Sharepoint project which used the Microsoft.SharePoint.Linq.DataContext class.

While trying to access a SPList belonging to Site Collection another Site Collection I always had an “Invalid Url Exception” right from the contructor, and other times I had exceptions when accessing the objects.

var context  = new DataContext(otherSiteColUrl);
 


The problem is that inside, the constructor, the URL is only taken into account if we have no HttpContext. If we do have one, the context URL (which means, the current site url) the custom url passed on the constructor is ignored.
Continue reading “[Sharepoint] – DataContext with custom URL” »

[TIP – Sharepoint] – CAML Query – Filtering Boolean fields

A few days ago I needed to build a CAML query that return all the items which have changed since the last execution. I have a Yes/No (boolean) field called “HasChanged” that when the item is changed turns to “True”.

The query would be something like this:

<query>
   <where>
       <eq>
         <fieldref Name="HasChanged"></fieldref>
         <value Type="Boolean">true</value>
      </eq>
   </where>
</query>


The truth is that this query will not work as you might think. For Sharepoint, Yes/No fields are represented by 1 and 0. As so, the query has to be like:
Continue reading “[TIP – Sharepoint] – CAML Query – Filtering Boolean fields” »

[.NET] Access Embedded Resource File

Sometimes it’s necessary to embed a resource file in the assembly in order to make the distribution easier, or to protect the resource file.

In order to set the resource as embedded, it’s necessary to change the “Build Action” to Embedded Resource:



Continue reading “[.NET] Access Embedded Resource File” »

Using an enum on a FluentNHibernate mapping [C#]

One of these days I needed to map a C# class to a database table using FluentNHibernate. So far so good….
But then I got stuck as one the class properties was an enum.

As it turns out, there is no automatic mapping to enums.

The solution is to use a Custom Type and let FluentNHibernate know that that specific property has a custom type.
How can that be achieved?

Continue reading “Using an enum on a FluentNHibernate mapping [C#]” »