Archive for the ‘.NET’ Category.

Handling a leftover Principal Identity with WebOrb for .NET

In order to authorize calls to a service, WebOrb for .NET stores a principal object created by the authentication handler. The IPrincipal interface has the IsInRole(roleName) method which is responsible for checking if the user represented by the principal’s identity belongs to a role. System administrators can secure individual methods, classes or namespaces using the WebORB configuration file or the management console. Upon authenticating a user, WebOrb stores the Principal Identity in a session variable and subsequent calls make use of the rolebased authorization.

The Problem
The following scenario demonstrates the problem I was having:

  • First, a user successfully authenticates and logs into the application
  • The user then closes the application browser tab without logging out.
  • The browser had multiple tabs open
  • A user reopens the application in a new tab and attempts to log in
  • The user supplies invalid credentials
  • A WebORBAuthenticationException is thrown, preventing WebOrb from creating a new Principal Identity

Everything should be fine since a new Principal Identity wasn’t created right? Wrong.

The previous principal is still stored in the session and is used for authorizing other service calls. Since the user had previously authenticated, that user’s roles will be used for authorization.

The Solution
At the beginning of my CheckCredential method in my AuthenticationHandler, I simply call:

HttpContext.Current.Session.Clear();

Everything works as expected. Since I don’t have any other session information, the Clear() method fulfills my need. If you have other session information, you may need to loop through the session looking for variables of type System.Security.Principal.GenericIdentity and Weborb.Security.Credentials. Remove both of those variables.

Note: I did have some issues using System.Web.HttpContext.Current in my service library. It was unrecognized. I simply had to add a reference to System.Web and all was ok.

Using WebOrb Role-Based Security with the Flex Mate Framework

While implementing a flex-based login solution that used WebOrb & .NET role-based security, I ran into problems attempting to utilize Mate’s RemoteObjectInvoker.

The History

In order to implement .NET’s role based security, we need to Authenticate and Authorize our users. Per WebOrb’s Documentation:

“Authentication is the process of verifying user credentials and establishing user identity. Authentication’s goal is to verify that the user is who they say they are. A result of a successful authentication in .NET is typically an instance of the System.Security.Principal.IPrincipal interface. A .NET principal carries the identity of the authenticated user. Additionally, it can check if a user belongs to a particular role. When a principal is associated with a thread, .NET automatically performs code-access security checks for the methods invoked by the thread and thus enforces role-based security.”

Flex provides an API for sending the authentication credentials in a RemoteObject. SetCredentials tells Flex to send the credentials with the next service call to authenticate and create an identity. Once an identity is established, its used for all other service calls that use the same ChannelSet until the logout() function is used.

public function setCredentials( userid:String, password:String ) : void
public function logout() : void

In order to handle authentication, WebOrb registers a custom handler for all setCredentials() calls. Excellent information can be found in the WebOrb documentation on how to set the AuthenticationHandler.

The Problem

Implementing the Mate Framework, I use RemoteObjectInvoker to make calls to my .NET services exposed by WebOrb. Mate provides properties (username and password) on the ServiceInvoker class which the RemoteObjectInvoker extends. So, I attempted the following:

<services:Services id="services"/>
<RemoteObjectInvoker instance="{services.loginService}" 
    method="getUserData"
    username="{event.username}"
    password="{event.password}"/>

Note: Services contains a list of my RemoteObjects per Mate’s Suggested Best Practices.

In the event the user was successfully authenticated, this worked great. If the user is not authenticated, a fault is returned. The problem is that when new credentials are entered, they are not sent to the server. Instead, the original credentials are sent.

Another problem I ran into is logging out the user. I couldn’t find a means to logout a user anywhere in the RemoteObjectInvoker.

The Solution - InlineInvoker

<?xml version="1.0" encoding="utf-8"?>
<EventMap xmlns:mx="http://www.adobe.com/2006/mxml" 
		xmlns="http://mate.asfusion.com/" 
		xmlns:services="services.*">
	<mx:Script>
		<![CDATA[
			import events.LoginEvent;
 
			public function setCredentials(username:String, password:String):void
			{
				services.userService.setCredentials(username, password);
			}
			public function logout():void
			{
				services.userService.logout();
			}
		]]>
	</mx:Script>
 
	<services:Services id="services"/>
 
	<EventHandlers type="{LoginEvent.LOGIN}" debug="true">
 
		<InlineInvoker method="setCredentials" arguments="{[event.hcoid, event.password]}"/>
		<RemoteObjectInvoker instance="{services.userService}" method="getUserData" arguments="{[event.username]}">
			<resultHandlers>
			...
			</resultHandlers>
		</RemoteObjectInvoker>
	</EventHandlers>
 
	<EventHandlers type="{LoginEvent.LOGOUT}" debug="true">
		<InlineInvoker method="logout"/>
	</EventHandlers>
</EventMap>

The solution is pretty simple and should probably be implemented into a Mate Extension (I’m thinking something like a CredentialInvoker or maybe an extension to the RemoteObjectInvoker). There might very well be a better way to do this or it could already be built in. Regardless, the solution wasn’t’ instantly clear for me, so hopefully this will help someone else.

Flex for .NET Developers on Flex.org…Sweet!

On the newly redesigned Flex.org site, there is now a link for “Flex for .NET Developers”. After clicking the link, you’ll quickly see some information on WebOrb & Fluorine and a couple links to some quick little tutorials I had written a while ago to getting up and going with Flex + .NET. I’m happy to see Adobe making an effort with those of us that combine Flex and .NET technologies.

I think it’s important to remember that these technologies can and do play nice and I’m excited to see this sub-group of the community continue to grow! Thanks!

Fluorine (.NET Remoting) updated to Alpha release v16; Adds support Flex’s RemoteObject

Fluorine has been updated to Alpha release v16. Big news in this release is that it adds support for Flex’s RemoteObject! A special thanks to TheSilentGroup for a great release! Possibly my favorite part of the new release and using RemoteObject is that ServiceCapture now parses my AMF3 correctly! Yippee!

In order to update my projects (As created from my this post), I’ve followed the following steps and everything seems to work great.

1) Create a services-config.xml in the root of your Flex application. It should look like this:

[xml]



class="flex.messaging.services.RemotingService"
messageTypes="flex.messaging.messages.RemotingMessage">



*







[/xml]

2) In your Flex Project Properties -> Flex Compiler -> Additional Compiler Arguments add the following
[xml]
-services “services-config.xml”
[/xml]

3) Create your RemoteObject services as follows:

[xml]
destination="fluorine"
endpoint="{gateway}"
source="com.yourdomain.service.yourServiceName"
showBusyCursor="true"/>
[/xml]

4) Copy the new “com.TheSilentGroup.Fluorine.dll” file from the new Fluorine release into your .NET Application’s bin directory.

Good luck and enjoy….and again, thanks SilentGroup for the fantastic product, Fluorine!

Does Flex need to assume AMF3 Date’s are UTC?

Background Information:
I’ve inherited an application that stores many Dates and Times. The software is used by people all over the world who manually enter Dates & Times from worksheets into the software. The information is stored in a SQL Database and all dates and times are stored without any Timezone information and represent all different timezones. Dates from different timezones aren’t compared or mixed, so when a report is generated form the database, its assumed the report and its dates and times are relevant to the client.

Many different applications hook into this system and I don’t have the luxury of changing anything other than my Flex application to make it match the rest of the system.

My Goal:
My Flex application should allow a user to enter a Date and Time, which I store into a Date Type. For example:
“11/16/2006 03:00:00 PM” would be entered by a user in Eastern Standard Time (GMT-5).
“11/16/2006 03:00:00 PM” would be entered by a user in Pacific Standard Time (GMT-8).
“11/16/2006 03:00:00 PM” would be entered by a user in Moscow (GMT+3).

Each of those Dates would be saved in my database as: “11/16/2006 03:00:00 ”

My Problem:
AMF3 no longer supports a Timezone Offset. See “AMF3 Specification” at OSFlash.org. I currently can take a Date & Time from my Database -> Backend (.NET in this case) > Gateway (Fluorine in this case) -> AMF3 and in reverse from AMF3 -> Gateway -> Backend -> Database without the Date or Time being modified in any way and without any Timezone information.

The problem is, Flex assumes the AMF3 information is in UTC(GMT). So as soon AMF3 is deserialzed into Flex, the Flex Date is modified to the client’s local timezone offset.

What I want is all three of the dates above to show up in Flex, regardless of the client timezone, as “11/16/2006 03:00:00 PM” and I don’t want to have to manually display the UTC Date all over my Flex application in order to do this. This would include if the Date is a member in a ValueObject.

My Solution (Work in Progress):
Everytime a Date is brought into Flex, I call a function:
[as]
public static function getUTCDate(myDate:Date):Date
{
return new Date(myDate.fullYearUTC, myDate.monthUTC, myDate.dateUTC, myDate.hoursUTC, myDate.minutesUTC, myDate.secondsUTC, myDate.millisecondsUTC);
}
[/as]
which is called as
[as]
flexDate = DateUtil.getUTCDate(flexDate);
[/as]

Everytime a Date is sent from Flex, I call a function:
[as]
public static function sendUTCDate(myDate:Date):Date
{
var sDate:Date = new Date(Date.UTC(myDate.fullYear, myDate.month, myDate.date, myDate.hours, myDate.minutes, myDate.seconds, myDate.milliseconds));
return sDate;
}
[/as]
which is called as
[as]
flexDate = DateUtil.sendUTCDate(flexDate);
[/as]

My Wish
Something that would make this automatic for me. Either a way to tell the AMF3 Date Deserialization to be saved as a Local Date, or some way to not make me call manually call these functions every time a Date is deserialized or serialized.

Many Thanks to Anyone with Any Ideas!

Storing Dates as Strings in Flex while using Date Components and Date Sorting

Due to an existing implementation of the application I’m working on and problems transferring Dates from Fluorine (.NET Remoting Gateway) to Flex, I decided to store and pass all my Dates as Strings. At first, this seemed like a reasonable and easy to implement change. As time has gone on, more and more problems seem to arise. I’m sure the best thing to do would be to find a way to use Date-typed Dates, but I’ve figured out and thought I’d share some workarounds/hacks in case anyone else is trying to/forced to use Strings as Dates.

1) Binding my dates to a DataGrid column:
In order to have my dates display in the form mm/dd/yyyy, I do the following:
Call a labelFunction named “dateLabel” which then calls a static function from my Util package “formatDateDisplay”
[xml]

[/xml]
[as]
private function dateLabel(item:Object, column:DataGridColumn):String
{
return Utils.formatDateDisplay(item[column.dataField]);
}
[/as]
[as]
//This is found in my Utils Package
public static function formatDateDisplay(date:String):String
{
// This removes any time data that is appened onto my Date String
return date.substr(0, date.search(’ ‘));
}
[/as]

2) My DataGrid Columns should be able to be sorted by Date rather than by String Comparison
Call a sortCompareFunction named “dateMyDatePropertyCompare” which then calls a static function from my Utils package “dateFromStringSortCompare”
[xml]

[/xml]
[as]
private function dateMyDatePropertyCompare(obj1:Object, obj2:Object):int
{
return Utils.dateFromStringSortCompare(obj1.myDateProperty, obj2.myDateProperty);
}
[/as]
[as]
public static function dateFromStringSortCompare(obj1:String, obj2:String):int
{
var date1:Date = (obj1 == ” || obj1 == null) ? null : new Date(obj1);
var date2:Date = (obj2 == ” || obj2 == null) ? null : new Date(obj2);

if (date1 < date2)
return -1;
else if (date1 > date2)
return 1;
else
return 0;
}
[/as]

3) Binding my String-Date to a DateField
You can not bind a String to a DateField selectedDate property, so it must be cast into a Date Type. The only way I’ve found to make this Bind is to do the following:
[xml]
selectedDate=”{(model.myDateProperty == null || model.myDateProperty == ”) ? null : new Date(model.myDateProperty)}”
[/xml]
and to save the DateField value to a String:
[as]
obj.myDateProperty= myDateField.selectedDate.toDateString();
[/as]

My hope is that one of the following happens from this post:

- Someone can save some time and use something I’ve written here
- I’ll learn a much cleaner way to do this and I’ll follow this up with a “I can’t believe i was doing that, now I’m doing this…post”

Comments are welcome and hoped for as always….

Adobe Flex 2.0 + Cairngorm + Fluorine + ASP.NET Sample Application / Tutorial

After my last tutorial/post about using WebOrb, I began using Fluorine. Recently a request was made for a tutorial, so here goes…

Using Service Capture , an ABSOLUTELY fantastic tool and Fluorine with AMF3, still seems to be a problem. Also, I wanted to try and use the RemoteObject tag with my solution to make using .NET a little less coupled. Well, it turns out; Fluorine still seems to work great with AMF0, the remoting format from Flash 8. This led me to Renaun’s RemoteObjectAMF0 which easily plugs into a Cairngorm ServiceLocator. So there’s the pieces, now to put together the puzzle.

Renauns’s RemoteObject also works with AMF3. The reason I’ve been using AMF0 is that AMF3 + Fluorine doesn’t seem to display correctly in Service Capture. Possibly after I’m done developing my current project, I’ll switch this to AMF3 and see if any problems occur. You simply need to change the the line in RemotingConnection.as:

objectEncoding = ObjectEncoding.AMF0;
to:
objectEncoding = ObjectEncoding.AMF3;

First you will need the following for this tutorial: Visual Studio 2005, Adobe Flex Builder 2.0, Renaun’s RemoteObjectAMF0 (link), and Cairngorm (link), and Fluorine.

Open Visual Studio and Create a New Web Service: File -> New -> Website -> Empty Web Site.
Create a new C# Class: File -> New -> File -> Class -> Name the class EmployeeService.cs. You may be prompted about placing the cs file in the App_Code Folder, choose Yes.

A file EmployeeService.cs will be created in the App_Code Folder. Open EmployeeService.cs. Enter the following code.

[csharp]
using System;
using System.Web;

using net.shrefler.vo;

namespace net.shrefler.service
{
public class EmployeeService
{
public EmployeeService()
{
}

public EmployeeVO[] getEmployees()
{
EmployeeVO[] emps = new EmployeeVO[2];
EmployeeVO emp = new EmployeeVO();

emp.firstName = “Sam”;
emp.lastName = “Shrefler”;
emps[0] = emp;
emp = new EmployeeVO();
emp.firstName = “Your”;
emp.lastName = “Name”;
emps[1] = emp;

return emps;
}
}
}
[/csharp]

Create a new C# Class: File -> New -> File -> Class -> Name the class EmployeeVO.cs. You may be prompted about placing the cs file in the App_Code Folder, choose Yes.

A file EmployeeVO.cs will be created in the App_Code Folder. Open EmployeeVO.cs. Enter the following code.

[csharp]
using System;
using System.Web;

namespace net.shrefler.vo
{
public class EmployeeVO
{
public string firstName;
public string lastName;

public EmployeeVO()
{
}
}
}
[/csharp]

Next we’ll need to add Fluorine to our application. Add a “Bin” Folder to your Web Site. Right-Click on Bin and go to “Add Existing Item.” Browse to where you downloaded Fluorine and add “com.TheSilentGroup.Fluorine.dll”. Right click the root folder of your website and go “Add Reference”. Click the Browse tab, and add the “com.TheSilentGroup.Fluorine.dll” in your Bin folder.

Open web.config and add the following code.

[xml]




net.shrefler.vo.EmployeeVO
net.shrefler.vo.EmployeeVO






[/xml]

Next, create an empty Gateway.aspx file in the root of your website.

Finally, Rather than describing all the flex code: I decided to just use the Source View. So here is the flex code: (link)

I hope this helps everyone as much as I hope it will help me. As always, comments are appreciated. Good Luck!

Attention .NET + Flex Developers…Be Heard!

Following Graeme’s lead (I suggest reading his post), I also wanted to write a quick note to Adobe about the importance of .NET Developers…

A long time Coldfusion Developer, due to new employement, I find myself becoming an ASP.NET Developer. While not yet totally sold on the .NET Framework and often finding myself missing the convenience of Coldfusion, that is neither here nor there. The fact of the matter is, my company has too much investment (again, I’m not here to argue for or against this) in .NET to convince a move to Coldfusion. There is however, a void in the presentation of our application. Enter Flex.

From my previous work with Coldfusion and Flash, and having been led/heavily pushed toward Flex by Darron Schall, I’m now so grateful, I’ve been aware of Flex for quite some time. I waited and waited for Flex Builder 2 to be released. I jumped at the first opprotunity to incorporate it into my current .NET project.

I was met with reistance from co-workers due to them having NO knowledge of Flex.

No problem: I’ll just woo them with Examples of Flex being used with .NET.

Problem: I couldn’t find any.

Now, luckily, Flex examples, especially anything using the charting components, with a promise that I could utilize our .NET base was enough for me to get a chance, unfortunately, for some, I would guess they’ll have to pass on Flex. Also, I started to question, was I tricking myself…was it worth it…am I going to actually be able to do this based on what a couple of blogs say?

The resounding answer is YES! So far, utilizing Flex is wonderful and my company is over joyed seeing some of the things Flex can do. I love working with Flex.

So to answer Matt Chotin’s Question: The following is a little wish list, complete with a disclaimer of “Thank you Adobe for all you do. I love being a part of your developer community and I think the work you are currently doing is Fantastic!”

Adobe needs to help us .NET developers. We need to know we are cared for and loved. How about adding some .NET + Flex articles to the Adobe Developer Center. It would be an privaledge to help with something like that, the question is, are you interested Adobe, is there anything like this in the works?

Please educate me on Adobe’s stance on Fluorine (a tool that I highly recommend and that I’m using in all my projects). An article endorsing its use would make me feel great moving forward as a “Flex.NET” developer.

All of these things would combine to increasing the number of and the awareness of Flex.NET developers. As a current developer, it would motivate me to continue this amazing ride knowing that as the community grows, so will my demand as a Flex.NET developer rather than worrying about being left behind.

Again, Thank you Adobe for the Fantastic Work!

Flex + Cairngorm + WebOrb 2.0 Standard (Free) + .NET Sample Application / Tutorial

After my last tutorial/post about using JSON, Mark Piller from TheMidnightCoders commented that my requested functionality (Easily pass back client classes back and forth) could be completed using his product, WebOrb.NET. Thanks Mark!

After further investigation, I was still a little confused as how to accomplish this using a non-beta, standard (free) version of WebOrb.NET. Well, it turns out; WebOrb v2.0 works great with AMF0, the remoting format from Flash 8. This led me to Renaun’s RemoteObjectAMF0 which easily plugs into a Cairngorm ServiceLocator. So there’s the pieces, now to put together the puzzle.

First you will need the following for this tutorial: Visual Studio 2005, Adobe Flex Builder 2.0, Renaun’s RemoteObjectAMF0 (link), and Cairngorm (link).

Install WebOrb 2.0. Following all the system defaults should work just fine.

Open Visual Studio and Create a New Web Service: File -> New -> Website -> Empty Web Site.
Create a new C# Class: File -> New -> File -> Class -> Name the class EmployeeService.cs. You may be prompted about placing the cs file in the App_Code Folder, choose Yes.

A file EmployeeService.cs will be created in the App_Code Folder. Open EmployeeService.cs. Enter the following code.

[csharp]
using System;
using System.Web;
using Weborb.Util;
using net.shrefler.vo;

namespace net.shrefler.service
{
public class EmployeeService
{
public EmployeeService()
{
}

public EmployeeVO[] getEmployees()
{
EmployeeVO[] emps = new EmployeeVO[2];
EmployeeVO emp = new EmployeeVO();

emp.firstName = “Sam”;
emp.lastName = “Shrefler”;
emps[0] = emp;
emp = new EmployeeVO();
emp.firstName = “Your”;
emp.lastName = “Name”;
emps[1] = emp;

return emps;
}
}
}
[/csharp]

Create a new C# Class: File -> New -> File -> Class -> Name the class EmployeeVO.cs. You may be prompted about placing the cs file in the App_Code Folder, choose Yes.

A file EmployeeVO.cs will be created in the App_Code Folder. Open EmployeeVO.cs. Enter the following code.

[csharp]
using System;
using System.Web;

namespace net.shrefler.vo
{
public class EmployeeVO
{
public string firstName;
public string lastName;

public EmployeeVO()
{
}
}
}
[/csharp]

Next we’ll need to add WebOrb to our application. In your webroot folder should be a weborb directory. Copy “weborb.dll” from its bin directory into a bin directory in your new website. Then copy “weborb.config” and “web.config” from the weborb root directory to the root of your local website.

Open weborb.config and add the following code inside the tag.

[xml]

net.shrefler.EmployeeVO
net.shrefler.EmployeeVO

[/xml]

Rather than describing all the flex code: I decided to just use the Source View. So here is the flex code: (link)

I hope this helps everyone as much as I hope it will help me. As always, comments are appreciated. Good Luck!

Flex + JSON + .Net Sample Application / Tutorial

Don’t have enough time to wait for Adobe to release .NET Remoting for Flex?  Not quite ready to dive into Flourine?  Not able to purchase or install webOrb.NET on your server?  Dreading working with XML and WebServices?  Me Too, Me Too, Me Too, Me Too.  Luckily, I’ve found something that seems to have made my life a little easier for the time being.  JSON - as originally explained by Mike Chambers here. JSON for Actionscript 3.0, a jewel written by Darron Schall for Adobe, in the corelib released by Adobe and JSON.net for .NET.

JSON - pronounced Jason - allows you to serialize and deserialize data. 

Broken down:  You can send a bunch of different data types from .NET <-> Flex including Arrays and Objects and Arrays of Objects.  Where I see room for improvement would be after getting a generic object, being able to automatically convert that to a ValueObject (TransferObject) on both the client and server side.  Until that happens, I’ll just take care of it manually - unless someone has a better recommendation. 

On With The Show:

First you will need the following to follow this tutorial:  Visual Studio 2005, Adobe Flex Builder 2.0, JSON.net

Open Visual Studio and Create a New Web Service: File -> New -> Website -> ASP.NET Web Service.

 A file Service.asmx will be created and in the folder “App_Code” Sective.cs will be created.  Open Service.cs.  Enter the following code.

[csharp]
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using Newtonsoft.Json;

public class Employee
{
public int id = 0;
public string firstName = “”;
public string lastName = “”;
}

public class Service : System.Web.Services.WebService
{
public Service () {
}

[WebMethod]
public string GetEmployee() {
Employee e = new Employee();
e.id = 12345;
e.firstName = “Sam”;
e.lastName = “Shrefler”;

string output = JavaScriptConvert.SerializeObject(e);

return output;
}
}
[/csharp]

Next, you’ll need to copy “Newtonsoft.Json.dll” and “Newtonsoft.Json.XML” into your App_Code directory.  Next, right-click the Project and go to “Add Reference”.  Select Browse then Find “Newtonsoft.Json.dll” and hit OK.  A Bin directory should be created containing the “Newtonsoft.Json.dll” and “Newtonsoft.Json.XML” in your project.  Right click on Service.asmx and go to “View in Browser”.   A Service Description should come up.  Click “GetEmployee” then click “Invoke”.  If all is working properly, you should see the following output:

[xml]

{”id”:12345,”firstName”:”Sam”,”lastName”:”Shrefler”}
[/xml]

Great!  Your Webservice is ready to go.  Next we’ll move to the client-side: Flex!

Create a new Project. In the main mxml file, add the following code:

[as]



import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;
import com.adobe.serialization.json.JSON;

private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);

//De-serialize the object
var employee:Object = JSON.decode(rawData);

//Add the Object to an Array
var arr:Array = new Array();
arr.push(employee);

//create a new ArrayCollection passing the de-serialized Object Array
//ArrayCollections work better as DataProviders, as they can
//be watched for changes.
var dp:ArrayCollection = new ArrayCollection(arr);

//pass the ArrayCollection to the DataGrid as its dataProvider.
grid.dataProvider = dp;
}
]]>











[/as]

Compile and Build the application. You should see the data grid populated with one record straight from ASP.NET. Future enhancements I’d like to make to this application will be to clean the source, implement cairngorm in the flex code, and find a way to automatically transfer from generic objects to value objects in both Flex and .NET.

I hope this helps and any feedback is appreciated!
Â