Social Icons

twitter google plus linkedin rss feed

Pages

25.2.12

CrossDomain SecurityException accessing my Azure WCF Service from Silverlight

Just uploaded a WCF Service Web Role to Azure with the intention of accessing it from a Silverlight web part, but I got the dreaded and almost expected:
System.ServiceModel.CommunicationException: An error occurred while trying to make a request to URI 'http://localhost:81/MyService.svc'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details. ---> System.Security.SecurityException ---> System.Security.SecurityException: Security error.
Yes, cool, but how do I add my crossdomain.xml or my clientaccesspolicy.xml files to an “Azure Web Role” which I just heard exists?

To my surprise it’s very easy you just have to add the XMLs to the project:

adding crossdomain.xml and clientaccesspolicy.xml to azure web role

Then you’ll be able to debug and, after you “Upgrade” the package in Azure Hosted service, you’ll be able to access it from Silverlight.

By the way, I don’t like "Upgrade" here, I find it misleading. I would have used Update.

No comments:

Post a Comment

20.2.12

MessageBox, DialogBox and Popup windows in Silverlight with the ChildWindow control

I know this has been around since Silverlight 3, but I didn’t know about it! Really? I can't believe it!

So for me is new and it looks great. In the past I have created user controls for this, but this ChildWindow has even animations…

To create it is as simple as adding a new item of this class to the project:

Create a new Silverlight Child Window
And then, tweak a bit the XAML to make it look the way you need and that’s all.

To use it you just have to create it and show it like this:
MessageWindow window = new MessageWindow("Info!", string.Format("This is a ChildWindow example."), true);
window.Show();

As always, there’s a catch. Unlike the MessageBox it won’t stop the thread waiting for your reply (this is also good in some cases, I have found lately that the MessageBox dialogs are quite resource cosuming) so if you want to use the response the user has selected in your ChildWindow you should subscribe to the Close event, something like this:
MessageWindow window = new MessageWindow("Info!", string.Format("This is a ChildWindow example."), true);
window.Show();

window.Closed += (sndr, args) =>
{
    if (window.DialogResult == true)
    {
        StratexWS.GetFBAUsersAsync();
        LoadingWindow.Show();
    }
};

I have tweaked a bit the OOTB code. Mine looks like this:

ChildWindow example
By the way, there’s at least another catch, it won’t work in the constructor… it only works after the control has been loaded (http://vanderbiest.org/blog/2010/08/03/silverlight-4-childwindow-is-not-visible/)

No comments:

Post a Comment

14.2.12

Extension Methods for Null Objects

Is it possible to use an extension method on something that is null?

How beautiful would it be to do something like:
if (!MyString.IsNull()) return MyString.ToString();
I read somewhere a couple of years ago that would be impossible because if the object was null you’d not be allowed to call the method or something like that… But in my head it makes perfect sense.

So I have been refraining myself of doing this for a long time but today I felt brave enough.

The Method Extensions:
public static bool IsNull(this string str)
{
    return str == null;
}

public static string ToStringSafe(this object obj)
{
    return (obj ?? string.Empty).ToString();
}
The main method obviously every good test program should be a console application:
static void Main(string[] args)
{
    string str = null;

    if (str.IsNull())
        Console.WriteLine("It was null...");
    else
        Console.WriteLine("It wasn't null...");

    Console.WriteLine(str.ToStringSafe());

    Console.ReadKey();
}
And it works! This just opens a new dimension to my spaghetti recipes.

The first useful example that comes to my mind apart from the ToStringSafe and ToInt, ToDateTime... Look at me, I can't stop! is:

/// 
/// Disposes the object if it's not null.
/// 
public static void DisposeSafe(this IDisposable DisposableObject)
{
    if (DisposableObject != null)
        DisposableObject.Dispose();
}
With this method I won’t have to worry if the object is null or not. Everything is disposed properly!

It frightens me sometimes to get so excited about this things…

No comments:

Post a Comment

8.2.12

Shrink All the Databases

I wouldn’t recommend to do this in a production environment it doesn’t sounds to me too best practicy,  but if your development is running out of hard drive space I think this is a good alternative to shrinking the databases one by one…

The SQL script I use is this:

declare @db varchar(255)declare c cursor for
select name from sys.databases where is_read_only=0 and state=0
  and name not in ('master','model','tempdb','msdb')
open c
fetch c into @db
while @@fetch_status=0
begin
  exec SP_dboption @db,'trunc. log on chkpt.','true'
  DBCC shrinkdatabase (@db)
  fetch next from c into @db
end
close c
deallocate c
Shrink All The Databases

(I got it from here but mine is properly formatted :P)

No comments:

Post a Comment

2.2.12

Extending, Overriding and Base Classes

A couple of days ago my cousin asked me about the meaning of the word override. I tried to explain it with a couple of stupid examples and both sounded dull… Well this is a real life example.

We want to create Silverlight web parts and all of them share the same basic properties and the same render method. So extending Microsoft.SharePoint.WebPartPages.WebPart we will create a BaseSilverlightWebPart with this features (overriding the render method of the WebPart class) and then we will use it to create the other web parts easily.

The base class is like this:
    public abstract class BaseSilverlightWebpart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        #region Web Part Properties
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Stratex")]
        [WebDisplayName("XAP List URL")]
        [Description("Select the URL of the XAP list.")]
        public string XAPListUrl { get; set; }
        #endregion

        #region Private Properties
        Dictionary<string, string> InitParams;
        #endregion

        #region Abstract
        /// <summary>
        /// Setup here the of the XAP you will use
        /// </summary>
        public abstract string XAPName { get; }

        /// <summary>
        /// Setup here the initial parameters you will use in your Silverlight Web Part
        /// </summary>
        public abstract void SetUpParameters();
        #endregion

        #region Methods
        public void AddParameter(string Name, string Value)
        {
            if (InitParams == null)
                InitParams = new Dictionary<string, string>();

            if (InitParams.ContainsKey(Name))
                InitParams[Name] = Value;
            else
                InitParams.Add(Name, Value);
        }
        #endregion

        #region Overrides
        protected override void CreateChildControls()
        {
            SetUpParameters();

            if (string.IsNullOrEmpty(XAPListUrl))
                XAPListUrl = string.Format("{0}/Lists/XAPLibrary/", SPContext.Current.Web.ServerRelativeUrl);

            //Sometimes when you create the web part it's 0px by 0px... ¬ ¬
            if (string.IsNullOrEmpty(Height)) Height = "150px";
            if (string.IsNullOrEmpty(Width)) Width = "150px";

            LiteralControl obj = new LiteralControl();
            obj.Text = "<object id='silverlightHost' height='" + Height + "' width='" + Width +
                @"' data='data:application/x-silverlight-2,' type='application/x-silverlight-2' style='display:block' class='ms-dlgDisable'>
                            <param name='Source' value='" + XAPListUrl + XAPName + @"' />
                            <param name='MinRuntimeVersion' value='3.0.40624.0' />
                            <param name='Background' value='#00FFFFFF' />
                            <param name='windowless' value='true' />
                            <param name='autoUpgrade' value='true' />
                            ";

            if (InitParams.Count > 0)
            {
                obj.Text +="<param name='initParams' value='";

                int i = 0;
                foreach (var param in InitParams)
                {
                    if (i++ == 0)
                        obj.Text += string.Format("{0}={1}", param.Key, param.Value);
                    else
                        obj.Text += string.Format(", {0}={1}", param.Key, param.Value);
                }

                obj.Text += @"' />
                ";
            }
            obj.Text += @"<a href='http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0' style='text-decoration: none;'>
                <img src='http://go.microsoft.com/fwlink/?LinkId=108181' alt='Click here to install Silverlight' style='border-style: none'/>
                </a>
                </object>";

            this.Controls.Add(obj);
        }
        #endregion
    }
Extending it we can create a Silverlight Web Part as easy as:
    public class DynamicStrategyMap : BaseSilverlightWebpart
    {
        #region Overrides
        public override string XAPName
        {
            get { return "StratexPointStrategyMap.xap"; }
        }

        public override void SetUpParameters()
        {
            AddParameter("site", HttpUtility.UrlEncode(SPContext.Current.Web.ServerRelativeUrl));
        }
        #endregion
    }
Note that wou dont have to override nothing if you don't need to. The render method is exactly the same as in the base class so we don't have to name it. The class will use its base class method automatically. Look how we are saving code not writing again all the properties or the big render method from the base class here, we just change what we really need to change.
We can also add new properties if we want as in:
    public class StratexHeartBeat : BaseSilverlightWebpart
    {
        #region WebPartProperties
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Stratex")]
        [WebDisplayName("NumberOfEvents")]
        public string NumberOfEvents { get; set; }

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Stratex")]
        [WebDisplayName("TimerLapse")]
        public string TimerLapse { get; set; }

        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Stratex")]
        [WebDisplayName("Indicator Summary Url")]
        public string IndicatorSummaryUrl { get; set; }
        #endregion

        #region Overrides

        public override string XAPName
        {
            get { return "StratexHeartBeat.xap"; }
        }

        public override void SetUpParameters()
        {
            AddParameter("site", HttpUtility.UrlEncode(SPContext.Current.Web.Url));

            if (string.IsNullOrEmpty(IndicatorSummaryUrl))
                IndicatorSummaryUrl = string.Format("{0}/Lists/WebPartPages/IndicatorSummary.aspx", SPContext.Current.Web.ServerRelativeUrl);

            AddParameter("indicatorsummaryurl", IndicatorSummaryUrl);

            if (Common.ConvertToInt(NumberOfEvents) < 1) NumberOfEvents = "1";

            AddParameter("numberofnews", NumberOfEvents);

            if (Common.ConvertToInt(TimerLapse) < 1) TimerLapse = "1";

            AddParameter("timerlapse", TimerLapse);
        }
        #endregion
    }
Or we can ever add more code to the render overriding the overrided render method.
    public class Commentary : BaseSilverlightWebpart
    {
        #region Overrides
        public override string XAPName
        {
            get { return "Commentary.xap"; }
        }

        public override void SetUpParameters()
        {
            AddParameter("site", HttpUtility.UrlEncode(SPContext.Current.Web.ServerRelativeUrl));
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            //We are using this code to be able to close the explorer window from Silverlight
            LiteralControl JavaScript = new LiteralControl();

            JavaScript.Text = @"<script type='text/javascript'>
                                function doCloseLocal() 
                                {
                                    var version = parseFloat(navigator.appVersion.split('MSIE')[1]);

                                    if (version >= 7) {window.open('', '_parent', ''); }

                                    else { window.opener = self;  }

                                    window.close();
                                }
                                </script>";
            this.Controls.Add(JavaScript);
        }

        #endregion
    }
Note that before adding the new control we call the base.Render so the web part is rendered in the page.
So this is how overriding looks like in real life. Now it make sense… or does it?

No comments:

Post a Comment