Showing posts with label hacking. Show all posts
Showing posts with label hacking. Show all posts

Thursday, November 10, 2011

Those Darn Gray Box's

(if you just need the hack er I mean 'solution' skip to the end)

ok so I was talking or rather tweeting with @ColinEberhardt about this issue with the gray box in IE on #wp7 (see his post at: https://github.com/phonegap/phonegap-wp7/issues/26). I've been working on my own HTMLApplicationHost Framework for doing HTML based WP7 apps and post this on codeplex: http://htmlappwp7.codeplex.com/ since what march I think. I've gotten 3 such apps in the Windows Phone 7 market place and one in Android that are HTML based. Here are a few links to some of those.

SMART Spending Habits: Windows Phone 7 (Deeplink, Paid version): http://windowsphone.com/s?appid=b44a9f3a-3480-4923-aa35-df26f6eb3c9e

SMART Spending Habits: Android 2.2 Version: https://market.android.com/details?id=com.SMART.SpendingHabits

I'm not sure I'm an expert at HTML phone apps yet but I do strongly believe that just about anything is possible and that there must be a solution to this gray box issue on phone 7 (wp7). So I took on the task of seeing what I could do. I started with creating a new phone 7 app that used my HTML Application Host framework etc (blah blah blah setting up stuff etc) so I got to the point of having my index.html page and started my tests in #wp7.

So the first test looked like this:

function test1() {
test1Location.innerHTML = "test 1 complete";
}

<div id="test1Location"><a onclick="test1();" href="http://www.blogger.com/post-create.g?blogID=887975141009593463#">test1</a></div>

running this clearly made the gray box... so I tried this:

<div id="test2Location"><a href="javascript:test2();">test 2

function test2() {
test2Location.innerHTML = "test 2 complete";
}

and as expected this made a nice gray box as well. So I tried this hoping it would work better:

function test3() {
test3Location.innerHTML = "test 3 complete";
}


<div onclick="test3();" id="test3Location"><u>test 3</u></div>

but alas this made a nice gray box too... *grr* so at this point I went back to Colin's post and watched the video and read a few other related posts then knowing that I didn't have a solution I had to try this:

function test4() {
test4Location.innerHTML = "test 4 complete";
}

<div id="test4Location"><a onclick="test4();" href="http://www.blogger.com/post-create.g?blogID=887975141009593463">test4 (will break)</a></div>

and yes this created a gray box AND blew up when the control tried to navigate to no where... and finally I thought I would try something else... yes this time a bit of a hack and messy, not very clean as such but lets take a look:

function test5() {
test5Location.innerHTML = "test 5 complete";
}

<div id="test5Location"><img onclick="test5();" src="http://www.blogger.com/test.jpg" width="99" height="99" /></div>

Amazingly enough, no gray box in the emulator on my machine. Now this is kind of a hack isn't real as it only works sometimes in the emulator under certain conditions but really its still there just it can't be seen due to the speed of the hardware. If you lucky enough to not see it you still will on the phone hardware. Until the windows phone team can manage a real fix for this annoying bug... but wait I'm not willing to give up yet.

so how do we make it go away in the mean time? the real hack is to just not let the events fire. This means really thinking abit out of hte box and doing some native C# stuff to fix the problem well sort of. The solution I'm not going to give you all the code (its a bit messy and a bit much and very custom) now but I'll explain how it works.

So how about we put a native but invisable touch panel over the top of the web browser control that hosts our app. This means that all events show up on that panel then you expose on your web browser control some interface and you process the events in C# to determine what is going on. then you pipe those events into the javascript context of the webbrowser control. This also means you have to have some javascript events to handle all the events you want to call or do something with. This is very specific to phone 7 and very customized around each action or event but it does in fact work. :) problem solved albiet an extremely painful hack until they fix this bug maybe in tango or apollo...

Thursday, January 13, 2011

'Extending' Your Phone 7...

So I can't condon hacking phone 7 outside of the context that MS has provided in any case... however it can be done easily enough.

I've found that it is straight forward enough to hack. One thing that has bothered me with the phone was the default accent colors on the phone are lame. for the most part I don't really like any of them. One way to fix it is this app you have to side load, called advanced config. Currently it only works for HTC but does let you test registry hacks on phone 7.

You can get the app (xap) from here http://www.touchxperience.com/

In this case there are a number of cool phone 7 hack apps. but for me having a nice steel gray just makes the phone more zen.

Again I'm not responsible for you mucking up your phone... don't do any of this...

Friday, December 3, 2010

Windows Phone 7 Socket Support...

or not...

if you have a dev account and or otherwise unlock your phone you can run unmanaged code... again Jeremiah does a wonderful hack with source using sockets on phone 7... don't worry this is another hack that won't get through the phone 7 market place vetting process but its fun to play with. check out Jeremiah's project here with source code:


http://groups.google.com/group/wpf-disciples/browse_thread/thread/e8f14483a41e6b0d

Tuesday, November 16, 2010

Native Code On Phone 7

So a friend of mine showed me this article and he tried it and it worked (http://www.futile.com/). In any case he tried it and it works but I'm pretty sure this won't get by the app store... :) In any case here is the article on how this guy got some native code going on phone 7:

Windows Phone 7 & “native” apps, the missing link!

Tuesday, August 24, 2010

Getting the Root Visual in Phone7

ok, so this should have been easy for me but for some reason it took a half hour to figure it out so I figure it must be something that some one else might struggle just in case. That being the case if you are in some nested set of user controls and need to get a reference to the top level of your phone 7 UI here is the code:

PhoneApplicationFrame Temp = Application.Current.RootVisual as PhoneApplicationFrame;
MainPage TheUI = Temp.Content as MainPage;

now main page is the loaded PhoneApplicationPage is this could change pending your code and further 'TheUI' is something I made up but all things the same the reference to TheUI would then allow you to call any instances of the root visual. and the best part is this is admittedly a bit hacky... :)

Wednesday, June 9, 2010

Updates to Silverlight Code Browser

A couple of bits of news. I did a number of updates to the HackingSilverlightCodeBrowser here:

http://www.hackingsilverlight.net/HackingSilverlightCodeBrowser.html

including things like MEF and IsolatedStorage. As to the community edition of the book, I'm still trying to get some contributors to finish. I've been slammed with 60 hour weeks so chapter 2 and 4 and appendix a still need edits. maybe a weeks worth of work pending time which tends to be limited in my life. :)

Wednesday, May 5, 2010

HackingSilverlight Code Browser

So sometime ago I had been working on a sample browser for all the different samples I had used for hackingsilverlight and for blog posts. After awhile with all the jumping around between projects, and my failing memory I found I needed a quick easy way to remember all the code clips I used often. For me I needed something like a rola-deck for code so after taking my toys and leaving the sandbox as it were regarding the book HackingSilverlight between projects for the 5 minutes here or there I've been working on a tool that I'm using in place of the older sample browser. And so the HackingSilverlight Code Browser was born. Its still a work in progress and really its all about me and my workflow but on the off chance it might help some one here it is:

http://www.hackingsilverlight.net/HackingSilverlightCodeBrowser.html

of course if you go to just hackingsilveright.net there is a click here to install button that will install the oob version but from this link you can also just right click and select install. Remember this tool is not designed to teach anything or example things to anyone, its purpose is to quick recall code that I know how to use already and make it easier to remember. So remember this isn't silverlight 101 , its more like silverlight 400 :) In any case when you first load the app there is a number of key elements. First on the left is a tag cloud where the tags related to blocks of code that have been 'tagged'. in the center is everything matching the search result and then in the far right is the search box. there is no search button as it updates dynamically as you type. I did put a reset and help link below this but really just start typing.

in the bottom corner you'll notice a version number, a contributor link and a add to library link so if I run across a bit of code that I think is important I can send email to my self to remind me. Also back on the left at the top is a cover shot that links back to the site and if you are running an outdated version you will get a warning along the left side.

If you happen to select one of the results from the middle you get a code box viewer that does some simple formating of the code and lets you select the contents. also all the tags associated with that block are shown and they are clickable. Clicking tags will close the code viewer and do a search on that tag. There are two arrow buttons if you get board and want to scroll through blocks quickly plus there are the help and contributor dialogs.

The help dialog is much like this post just giving a basic discriptions of functionality and then the contributor dialog is is a list of everyone that has helped, inspired or contributed in some way.

And thats pretty much it. oh and one more thing. only constructive feedback is of any use or more importantly if you have cool snippets to add... please feel free to contact me about it. And the code base I'll use to replace the existing HSL codeplex project...

Friday, March 12, 2010

Dirty Dirty Silverlight Hack... - Silverlight 4 Hack: Use Native/Desktop CLR Without COM Registration

Here is a hack of the month. Jeremiah is probably my favoriate Silverlight Prodagy and he has done it again with this wonderful hack, 'Use Native/Desktop CLR Without COM Registration' I like the first line, "WARNING: Information and code here can easily be abused. Please do not use it as a crutch in application planning, but more for utter despair or experimentation. Thus I wrote this blog post from that perspective."

Certainly Jeremiah's code can be abused but what is really interesting to me is how this is one more way to push the limits of what Silverlight can do. 'Hacking' doesn't have to be evil but can be just that pushing the limits and making things better. With that commentary here is the first paragraph and sample code from his article and for the rest you will have to go read his post:

Silverlight 4 + OOB + Elevated Trust gives us the ability to use COM. That would be extremely useful (vs. really useful), except we cannot use just any COM class. It has to support IDispatch (COM automation). It also has to have a ProgID associated to it. That leaves you still with quite a few built-in COM objects to work with, as Justin document's quite well here. What about running our own native or .NET code? One would have to register a COM object first, which requires administrator rights. That’s no fun for an end user! Optimally, it would be nice to be able to add your desktop CLR objects as resources to your XAP, and from Silverlight code, be able to instantiate and use your Desktop .NET classes. This is a hack to do just that.

Huh? What does the hack do?
Let me explain it in code.

/* Create our Desktop .NET helper */
dynamic fullDotNetProxy = fullDotNetProxy = ComAutomationFactory.CreateObject("ClrProxy");

/* Have our .NET helper load up our .NET assembly we extracted from our SL app resources */
dynamic assembly = fullDotNetProxy.GetAssembly(m_assembliesPath + "\\Inject.Test.dll");

/* Get our .NET Type */
dynamic testClassType = fullDotNetProxy.GetDotNetType(assembly, " Inject.Test.TestClass");

/* Create an object instance of our .NET type */
m_testClass = fullDotNetProxy.CreateInstance(testClassType);

/* Run our RunMe method on our .NET object */
m_testClass.RunMe();


Read the rest at:

http://jmorrill.hjtcentral.com/Home/tabid/428/EntryId/442/Silverlight-4-Hack-Use-Native-Desktop-CLR-Without-COM-Registration.aspx

Wednesday, February 10, 2010

Silverlight 4 - 3D (ish)

One of the great new features in Silverlight 3 was the ability todo psuedo 3d via what alot of us joke about as 2.5D. things like prespective transforms and the like.

One of my fellow MVP's Einar Ingebrigtsen got a bit zellous (must have been bored) and make this awesome tool kit for 3d (ish) in Silverlight 4. Granted its not native into the platform but honestly I'm not sure I want it built in. To much over head... But using a toolkit likeEinar's Balder really makes it reasonable.

Here is the Sample Browser:
http://www.ingebrigtsen.info/silverlight/Balder/20100208/TestPage.html

and the code here:
http://balder.codeplex.com
and
http://github.com/einari/Balder

from a ux standpoint I think the kind of visualization work for business is just awesome. Balder should be in everyones tool kit.

Monday, January 4, 2010

Asynchronous Image Loading in Silverlight

So one task that was bugging me today was doing image loading asynchronously so as to not drag the app down. Now there are some 'xaml' ways of doing this in wpf and supposedly in SL but alas I have not seem it work well. I'm working on a larger class that does this better but here is the basics of how I got it to work in C# code... to start with lets take a look at the following code:


WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);

if (ImagePath.IndexOf("http") < 0)
{
string URL = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
ImagePath = URL.Substring(0, URL.LastIndexOf('/')) + "/" + ImagePath;
}

client.OpenReadAsync(new Uri(ImagePath, UriKind.RelativeOrAbsolute), ImagePath);

this code lived in the constructor of the class I made. Basically its a user control that replaces the image tag so I can use it in Xaml or programatically etc. in this case I needed to use it programmatically to generate this image 'effect' that I was working on so I passed it into the constructor. the key to the code above is it creates a web client, then checks the url and finally calls the async method that loads the image.

the next bit of code is the event handler:

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
BitmapImage ImageToLoad = new BitmapImage();
ImageToLoad.SetSource(e.Result as Stream);
TargetImage.Source = ImageToLoad;
}
catch (Exception)
{ }
}

this code is simple enough. Basically the BitmapImage is created and we load the result as a stream into it and then use that to set the source on an image. At least for me this seemed to work well. I'll probably add a few other features namely some reference counting so when I load 1000 of these it doesn't try to grab them all at once...

Wednesday, December 30, 2009

Silverlight Hosting in WPF

Ok so we know this has been done. Yawn, and it can be done any number of ways from hacking it in a browser control but actually doing it in WPF without the browser control can be a huge pain. Here is a little trick that helps you do just that without all the jumping around.

Jeremiah, (this programmer extraordinaire with apparently WAY to much time on his hands) wrote this little codeplex project that is a 'WPF Panel' that hosts Silverlight. http://silverlightviewport.codeplex.com/

pretty slick, if you dive into the code it is kind of complicated but to use it is straight forward enough. If you download the project and run it you can see it in his test application running a xap in Window1.xaml.

&lt;slvp:SilverlightViewportElement BaseUrl="http://silverlight.net/"
Source="http://silverlight.net/clientBin/showcasenav/ShowcaseNav.xap"
ViewportSize="550,550"
RenderFps="40"
x:Name="slViewport">
&lt;slvp:SilverlightViewportElement.Effect>
&lt;DropShadowEffect BlurRadius="50" />
&lt;/slvp:SilverlightViewportElement.Effect>
&lt;slvp:SilverlightViewportElement.LayoutTransform>
&lt;RotateTransform Angle="10" />
&lt;/slvp:SilverlightViewportElement.LayoutTransform>
&lt;/slvp:SilverlightViewportElement>

you'll notice this is all the standard WPF fare but lets look at the properties on the main panel itself. First is our base url that tells the control the domain in which the xap or silverlight application lives. Next we have the 'Source' which points to our xap file. We then set a view port size as 'ViewportSize' and then the last one we will mention is 'RenderFps' which is the 'speed' that the Silverlight is 'rendered' into your panel. In effect your app now runs in the WPF app. Nice and clean as long as you don't look at the source for the panel which is more a work of art... :)

Self Editing XML File

This particular post is a rehash of one I didn't some years back. Basically it is a little technique I developed some 7 or 8 years ago to solve a simple database issue once but I wanted only one file to exist in this case the exe or sorts that was also the xml file. As this applies to Silverlight in the since that I can use this application technique to also be used as a shell for a Silverlight application without all the silly security barriers... > : )

DISCLAMIER: I AM NOT RESPONSIBLE FOR THE USE OF THIS TECHNOLOGY IN FACT YOU SHOULD STOP READING NOW BEFORE YOU HURT YOUR SELF OR OTHERS...

But lets not focus on that... lets focus on the mechanics of what we are talking about. A long time ago in a galaxy far far away there was a company called Microsoft that as the center of the universe they released this cool little DHTML technology back before they changed the name to AJAX and it was still cool called an HTA or Hyper Text Application or 'HTml Application' which basically is an HTML file with the file extension of '.hta' instead of '.html' and when you have one of these locally and you click on it, it then renders without all that silly browser chrome/buttons etc. oh and with the rights of a win32 app installed locally...

Basically with a little markup you can control and manipulate the browser chrome and any com object on the system with a script friendly API you can talk to.

Now this 'hta' thing works if the page is hosted on a web page too... albeit you get ONE security dialog that doesn’t really explain what is going on and if the user clicks ok the hta runs as a locally installed app w/o silly security sandbox stuff going on... and yes that basically means it can for all intents and purposes fdisk your hard drive...

DISCLAMER 2: STOP READING HERE AND DON'T DO THIS STUFF.

Like anything though this can be used for good and evil.

Ok back to how to-do it. if you Google HTA on Bing (or Google) you can get the reference material for hta's but basically it is an html file that runs in a version of IE w/o the sandbox. so basically any html that works there works in the hta too with the added addition of this tag:

<HTA:APPLICATION id="oVDProcess"
applicationName="Virtual Desktop - Lite"
singleinstance="yes"
caption="no"
contextmenu="no"
innerborder="no"
scroll="no"
showintaskbar="no"
version="1.0.032"
SELECTION="no"
windowState="normal"
icon="img\im_gray.ico"
/ >

Now as mentioned you can also access any of your com objects the XML Document object or the 'File System' object... here is some sample code from my magic self editing file:

var oDOM = null;
var giHeight = 360;
var giWidth = 800;

function initFrm() {
try {
self.resizeTo( giWidth, giHeight );
self.moveTo( ( window.screen.availWidth - giWidth ) / 2, ( window.screen.availHeight - giHeight ) / 2 );

oDOM = new ActiveXObject("Microsoft.XMLDOM");
oDOM.async = false;
oDOM.loadXML( oXMLDATA.innerHTML );
instantReport();
} catch(e) {
alert( "Your OS is missing components or they are disabled for processing XML data!\nDESC: " + e.description );
}
}

Notice in this case the code creates the xml document object and loads part of the 'HTML' in...

And here is another sample:


function saveSelf() {
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
var oTempFile = oFSO.OpenTextFile( "xLinks.XML.hta", 1 );
var sSelfSource = String( oTempFile.ReadAll() );

var oPAGEARRAY = sSelfSource.split( '<meta' + ' val="2345"/>' );

var sNewSource = oPAGEARRAY[0] + '<meta' + ' val="2345"/> <xml id="oXMLDATA"> ' + oDOM.xml + ';</xml><meta' + ' val="2345"/> ' + oPAGEARRAY[2]

var oSDOM = new ActiveXObject("Microsoft.XMLDOM");
oSDOM.async = false;
oSDOM.loadXML( sNewSource );

if( oSDOM.xml != "" ) {
var oNewFile = oFSO.CreateTextFile( "xLinks.XML.hta", 1 );
oNewFile.WriteLine( oSDOM.xml );
oNewFile.close();
oNewFile = null;
alert( "Save Success!" );
window.close();
} else {
alert( "Save Operation Failed!" );
}
}

This function creates a File System Object. The trick here is basically the file runs as an HTA i.e. executable but then loads itself as a xml file or custom xml data base and updates 'records' in itself and overwrites itself. Now the trick here is that your HTML must be XML complaint. Really if you don't know what this means maybe you should start somewhere else before reading about how to hurt yourself with this stuff... :)

Monday, December 7, 2009

Hacking the Silverlight Xap file

Every now and then I find I need to pull resources out of a Xap file. One of the issues with this is knowing what’s in the XAP. There have been a number of solutions I’ve used over the years (ok that is like 2.5 ish years) like having an index file either a Csv or Xml etc. A few weeks ago I ran across this little class that some guys were talking about on the Silverlight Insiders/MVP thread called un-zipper found here:

http://www.sharpgis.net/post/2009/04/21/REALLY-small-unzip-utility-for-Silverlight.aspx

What is cool about this class is it makes getting the assets out of a zap even if you don’t know what is in the xap up front easy and straight forward. From a using standpoint you basically need to create a webclient and a call and use the Unzipper to run through the contents. The Unzipper class deals with mucking up what is in the xap so all you need to-do is run through the collection and pull out what you need… Let us take a look at what you need to-do:
Assuming you have the Unzipper class (download here) you need the following libraries:

using System.Collections.ObjectModel;
using System.Net;
using System.Windows.Controls;

From here we need to create a web client

WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("HackingXaps.xap", UriKind.RelativeOrAbsolute));


In this code we create the WebClient, add a handler and run the call pointed at our xap we want to load.

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
UnZipper unzip = new UnZipper(e.Result);

foreach (string filename in unzip.GetFileNamesInZip())
{
//do something with the file name…?
}
}
}

From here you can pretty much do whatever you want. Look to see this in the up coming version of the HackingSilverlight library.

Tuesday, November 24, 2009

Silverlight and Dual Screen Monitors...

So I'm working on this dual screen kiosk thing and want to use Silverlight as for some reason I can't use WPF / .net4 etc. long story and not the point. What do I do now?

Well along time ago in a galaxy mostly still down the street I used do alot of 'dhtml' or ajax kinds of things or whatever we are calling it now days and there was this little thing called an hta you could do to get around all that silly security stuff in the browser that keeps you from nuking the hard drive, and file system access etc.

So the trick I found is to have the hta host the Silverlight app and have it resize its self to take up all the monitors. with a third monitor hidden in the kiosk... poof, Silverlight dual screen full screen black magic.

for those interested in hta's:

http://msdn.microsoft.com/en-us/library/ms536495(VS.85).aspx

basically you want the following properties set on the hta tag in the html header:

caption=no
contextmenu=no
indderborder=no
border=none
windowstate=normal
scroll=no
showintaskbar=no

and then on load on the body tag execute the following:

window.moveTo(0,0);
window.resizeTo(x,y);

which could be a function of
window.screen.availWidth and or window.screen.availHeight

see black ecma magic saves the day.

Friday, May 1, 2009

Converting Silverlight Apps to WPF

Using Ariel's Simon design I built this game called Silverlight Simon. Jobi suggested making it a WPF app and then a surface version. I got it working and will do a post on it later but strictly speaking here this is how I overcame some of the issues going from a Silverlight user control to WPF.

The first thing I found out when I moved my code into Xaml was a number of things that WPF doesn't do that you can do in Silverlight.

1. there is NO VSM... at all.
2. there is no autoplay on media element.
3. no 2.5D (ie, all the plane projection stuff)
4. and all my animation calls to story boards didn't work.

When I first ported the code over I knew the VSM and 2.5d was not going to work so I started with ripping that out. the first thing that then poped up was all my animations calls. For example say I have a click event and I'm doing something like [animationname].Begin();

well that doesn't work as all my animations are 'resources' I played with this for a while and with some Dr. WPF medicine I found that I basically had to change all my animation issues to something like this:


Storyboard foobar = TopSimonGrid.FindResource("PrefsBtnPressedKey") as Storyboard;
foobar.Begin();

from their I got my animations working. I then removed my auto play on the media element and it would compile. but as soon as an event tried to fire a sound I got another error. I ended up having to add
LoadedBehavior="Manual"

that way my sound method started working. At this point you could play the game if you could get past the fact that all the styles that used the VSM looked like crap. I know there was this codeplex project called WPF Toolkit ( http://www.codeplex.com/wpf ) which included a prototype VSM (Visual State Manager). I pulled it down and tried it out. The only hard part was figuring out the right name space to get my vsm: working. as it turns out it is where you would expect if it was part of WPF kind of:

xmlns:vsm="clr-namespace:System.Windows;assembly=WPFToolkit"

With this mojo going on everything worked but my flip fx control. I couldn't find that any one get industrous enough to build the 2.5d stuff for WPF so I took the old animations from the SL2 fx control but put them in the vsm flip animations generic xaml so that it would use that instead of the 2.5d. I then had to change the content presentor to have the transforms needed and then poof like magic Silverlight simon worked like a champ.

For something extra I ripped out the WPF window chrome so Simon sits on the desktop and I found that my drop shadow on Simon was know on my desktop.

for those that are interested ripping out the chrome which is way easier then it used to be I had to add this to the window tag:

WindowStyle="None" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent"

from there you can pretty much do what you want.

ok ok ok, here is a little update. for Simon the above works fine... but for my uber tile project a few more issues came up... starting with dependency property registration sanity check....

So it is not so much a difference other then that the code that shouldn't work does in Silverlight 3 but blows up properly in WPF. take a look at this code:

public readonly DependencyProperty BackLink2TitleProperty = DependencyProperty.Register("BackLink2Title", typeof(string), typeof(MediaPlayer), new PropertyMetadata(new PropertyChangedCallback(OnBackLink2TitlePropertyChanged)));

in the named registration value you can't have two of these with the same value. Silverlight will currently over look that little indiscretion. WPF... not so much :)

Tuesday, April 28, 2009

Silverlight Eval Function

So this is a huge hack and the only purpose really for me is to be able to say I can do it and YOU can too albeit don't do this... I know I would have a huge melt down if some one on one of my projects did this. But alas here it is. So I'm working on my new Silverlight 3 'Tools' class and I thought I would go ahead and add this little static member called 'eval' where you pass in some code and it gets executed. So as mentioned I have not been able to come up with a good reason todo this yet but anyway back to the topic. So the code looks like this:

Tools.eval([some code]);

So the 'some code' is any ECMA complaint code that can execute in the context of hte hosting page. and the source looks like this:


private static string ClientSideEvalName = string.Empty;
private static ScriptObject ClientSideEvalFunction = null;

public static ScriptObject eval(string ECMACode)
{
if (string.IsNullOrEmpty(ClientSideEvalName))
{
ClientSideEvalName = "eval" + (Guid.NewGuid().ToString().Replace('-', 'x'));
InsertECMAScript("function " + ClientSideEvalName + "(InputValue) { return eval(InputValue); }");
ClientSideEvalFunction = (ScriptObject)HtmlPage.Window.GetProperty(ClientSideEvalName);
}
return (ScriptObject)(ClientSideEvalFunction.InvokeSelf(ECMACode));
}

We start with two private static members The first one holds a string reference and the other will hold a reference to the external component of eval that makes it work. the eval function then basically checks to see if there is a client side element already that is ready to be called. If not then it will be created. Once it is created then the eval function invokes the reference and passing the input ECMA Code to execute it and return any results.

clean, no. dirty, yes, very. :)

Tuesday, April 21, 2009

Custom Text Runs, Data Binding and cheating...

Faisel sent posted a question:

'Hi,
I have a requirement of showing additional text in a TextBlock. I have a Class in my silverlight application. I want to bind two of the properties in a TextBlock in my main page and show text something like this : "You make me feel - BONFIRE ".
The first part of the text here is a song name and the second part here is artist name. I need to show artist name based on the song name. For example if song is by another artist. It will show song name - "Still loving you - SCORPIONS" .
I tried to bind the Text property of the run to bind the Artist property to show the additional text in the TextBlock. There's some example of WPF which binds the Text property of Run by creating a BindableRun Class which derives from Run. But the problem in Silverlight is Run Class is Sealed in Silverlight.
Is there anyone who can help me to get the desired result. Someone please help me.'

I did the following response that I thought was interesting :) if it might make a few cringe... lol

one easy method would be to loose the binding. I know alot of people would be freaked out and this totally feeds into Dr. WPF's MVpoo design pattern but you could do something like this, so lets say we have this xaml that looks like this:

<stackpanel name="MyPanel" orientation="Vertical">
<button type="submit" content="add" click="Button_Click">
</stackpanel>

so the button doesn't need to be there and we could use a scroll panel or custom control but any element with a children collection would work. but in this case lets say we have this method button_click which contains this code:

TextBlock ThisBlock = new TextBlock();
//ThisBlock.Style = [whatever]...
ThisBlock.Text = Guid.NewGuid().ToString();
Run NewRun = new Run();
//Run.FontStyleProperty = ...
NewRun.Text = " ABC ";

ThisBlock.Inlines.Add(NewRun);
MyPanel.Children.Add(ThisBlock);

so each time you click the button you gets some text with a 'Run' at the end. to translate to the real solution when you load the page or get this data you need to parse it on your own in a loop and depending on some condition change the run context but you could also bind events and do other things at that time. of course you loose the whole data binding but really what it comes down to is does your code do the job?

the thread can be found at:

'http://dotnetslackers.com/Community/forums/showing-additional-text-in-a-textblock/t/3169.aspx '

anyway I know its a hacky way of doing things but hey, that is what 'hackingsilverlight' is all about :)

Wednesday, September 3, 2008

Desklighter Live

Hmm... more on Silvelright on the desktop. One of the guys at IM did this wonderful little tool that turns xaps into desktop applications... very very cool hack this tool makes it so you don't ahve to use the hack I posted a while back for every single xap as this does all the work for you.

http://blendables.com/labs/Desklighter/Default.aspx

Friday, August 15, 2008

Dev Teach 2008 Toronto Canada

I'm doing at least 3 sessions at DevTeach Dec 1-5th in Toronto Canada so far the 3 sessions I'm doing are:

Building Silverlight Controls
David J Kelley - SLV467
Designed primarily for Developers. This technical presentation walks through a number of senerios for building Silverlight Controls including user controls and custom panels. The usage of properties, dependency properties, events, reusability, and encapsulated control architecture is reviewed in detail. In the presentation we will build a custom chart control based on a user control and built custom panels and review dispatch timer and multi threading in the context of controls.

Hacking Silverlight 2 - For Designers and Developers
David J Kelley - SLV469
Designed for Designers and Developers. This engaging presentation gets the audience involved in bridging the gap between design teams and software development using Silverlight and the Silverlight toolablity story. The presentation is full of audience participation and skits that get audience members up out of their seats and excited about Silverlight. The basics of team work using Microsoft tools for design and development are used and the audience is shown some of the coolest Silverlight hacks that can make Silverlight applications really shine. With the “Coming out of the closet” skit the audience is shown sexy UI using Silverlight, learning about speed of development and why we care about Sexy engaging Web 2.0 experiences.

SilverLight 2.0 Achitectural Best Practices
David J Kelley - SLV421
Designed Developers and Architects or people wanting to understand Silverlight archtecture. This presentation startings with a detailed technical review of Silverlight control, application architecture and design patterns. Design patterns as applied to Silverlight application development and general best practices are reviewed in detail. The presentation includes learning from the trenchs of building Silverlight apps on a large scale including horror stories and ‘Anti-Patterns’ or things ‘not to do’ are reviewed.

check out http://www.devteach.com/Session.aspx for more information