While a was at Teched2009 and watching Tim Heuer presenting Silverlight 3 I noticed a new cool feature named Local Messaging!

When I saw this new feature, a crazy idea crossed my mind. Could this be used in order to allow the user to open my website in only one browser window?

The answer is yes! But not the way I first thought. Here is how (code in MainPage.xaml.cs):

string _localName = "SL App";
bool _Close = false;

public MainPage()
{
InitializeComponent();

Loaded += new RoutedEventHandler(MainPage_Loaded);
try
{
LocalMessageReceiver incomingMessage = new LocalMessageReceiver(_localName);
//Start listening
incomingMessage.Listen();
}
catch (ListenFailedException)
{
_Close = true;
}
}

protected void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (_Close)
{
HtmlPage.Window.SetProperty("location", "/InfoMessage.aspx");
}
else
{
LocalMessageSender msgSender = new LocalMessageSender(_localName);
msgSender.SendAsync("New instance loaded");
}
}

Loading Default.aspx

image

Clicking on the first link
image

 

Then on the second link

image

 

Those are the files in the solution

image

 

 

That’s an exception driven solution but works for me! :)

This works also across different browsers but if you want you can changed to allow one instance per browser.

Here are the solution files.

 

Enjoy!

kick it on DotNetKicks.com

Recently I was in a situation where a user was required to change the password upon first login.

But MembershipUser’s ChangePassword requires 2 arguments. Old and new password. In my case the password was hashed and I couldn’t retrieve it unless the user enter it.

changepass

So I wanted to change the password without asking the old one. The solution was :

image

  1. Reset the password
  2. Keep the generated password in a var
  3. Call MembershipUser.ChangePassword using the generated password as the old one!

It does an extra query to the database but does the job! If the password was stored in Clear or Encrypted form it could be retrieved.

N2 CMS

First of all i have to say that N2 CMS i a great Content Management System and really extensible! I discovered it a while ago and i decided to re-develop projects that were built with DotNetNuke with N2.

What do i want?

I want to show a page or a content only to anonymous users. I am using the default ASP.NET Role Provider for Sql Server.

Implementation

So first of all i had to extend that provider. This is how :

public class MyCustomSqlRoleProvider : System.Web.Security.SqlRoleProvider
{
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        if (roleNames.Any(x => x == "Anonymous"))
            throw new InvalidOperationException("Cannot add \"Anonymous\" role
 to user(s). Role is automaticaly assigned.");
        base.AddUsersToRoles(usernames, roleNames);
    }
 
    public override string[] GetAllRoles()
    {
        List<string> roles = base.GetAllRoles().ToList();
        roles.Add("Anonymous");
        return roles.ToArray();
    }
    public override bool IsUserInRole(string username, string roleName)
    {
        if (HttpContext.Current != null && 
                   !HttpContext.Current.User.Identity.IsAuthenticated && 
                   HttpContext.Current.User.Identity.Name == username)
        {
            return roleName == "Anonymous";
        }
        else
            return base.IsUserInRole(username, roleName);
    }
}
 

Nothing fancy here. Just adding the Anonymous Role and checking if user is not logged in and the role being checked is “Anoynoumous” to return true. Also i try to ensure that no one will try to add the '”Anonoymous” role to a registered user.

Next i had to implement an ISecurityManager to do the Authorization. This is how :

public class MyCustomSecurityManager : N2.Security.SecurityManager
{
    public MyCustomSecurityManager(IWebContext webContext) : base(webContext) { }
 

public MyCustomSecurityManager(IWebContext webContext,

N2.Configuration.EditSection config) : base(webContext, config) { }

 
    public override bool IsAuthorized(ContentItem item, IPrincipal principal)
    {
        bool isAuthorized = base.IsAuthorized(item, principal);
        if (!isAuthorized && !principal.Identity.IsAuthenticated && 
                      item.AuthorizedRoles.Count > 0)
        {
            isAuthorized = item.AuthorizedRoles.Any(x => x.Role == "Anonymous");
        }
        return isAuthorized;
    }
}

Inheriting from N2.Security.SecurityManager i had to override only the IsAuthorized method to work the way i intended to.

And last but not least i had to add to the web.config the following

<n2>
 <engine>
  <components> 
   <add service="N2.Security.ISecurityManager, N2"
     implementation="MyCustomSecurityManager, AssemblyName" />
  </components> 
 </engine>
</n2>

Conclusion

I hope to find this post useful. If you have any suggestions or questions please let me know. And i case you haven’t checked N2 CMS just take a quick look.

kick it on DotNetKicks.com

I always had the question if I could add a LiteralControl via Markup code. Let's say something like that :

<div class="header">
    <asp:LiteralControl runat="server" ID="ltrHeader"></asp:LiteralControl>
</div>
<div class="sub-header">
    <asp:LiteralControl runat="server" ID="ltrSubHeader" Text="Some Text" ></asp:LiteralControl>
</div>

Well It IS possible and simple to be honest. Just Register the control at the top of the page like that :

<%@ Register Assembly="System.Web" Namespace="System.Web.UI" TagPrefix="asp" %>

You might have a warning that "Element 'LiteralControl' is not a known element." but it will compile just fine and you can set the Text programmatically!

Hope that helps anyone who wants to use a LiteralControl over Literal!

Enjoy!

How about a sneak peek  into the .NET Framework 4.0?

At Steven Martin's blog you can see about  WCF και WF improvements, Dublin etc...

More to come of course at PDC..

Yeaaaaah...!

Finally a solution!!!!!!!! How can we stream a shoutcast radio via a Silverlight application?

Well in 6 steps...

1. Open Expression Blend

2. Create a Project

3. Add a media element

4. Add the code below at the cs (or vb) file

public Page()
{
// Required to initialize variables
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}

void Page_Loaded(object sender, RoutedEventArgs e)
{
try
{

myElem.Source = new Uri("http://mystation:port/;");
myElem.Play();
}
catch (Exception ex)
{

}
}

5. We put mms instead of http and at the end "/;" without the quotes

6. We hit F5 and listen our radio!!!

Enjoy!

Edit : it works with http really good but i never tried until now... So no need for mms at the beginning of the URL.

Many times I needed to set a default value for a property.

For example at the property below

public string Property1 {get; set;}

I wanted a default value "Value1". The only way was to create a private field or to set it in code like Property1 = "Value1" somewhere.

What if I wanted to do this for all my properties ?

For this case i decided to create a custom attribute which does that thing. Takes a value and if the value of the current property is null sets it to the given value.

 

To be more specific let's begin with the custom attribute class:

 [global::System.AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
sealed class DefaultValueAttribute : Attribute
{
readonly object defaultValue;
readonly Type valueType;

public DefaultValueAttribute(object defaultValue, Type valueType)
{
this.valueType = valueType;
this.defaultValue = Convert.ChangeType(defaultValue, valueType);
}
public Type ValueType { get { return valueType; } }
public object DefaultValue
{
get { return defaultValue; }
}
}

Then we have a helper class with an extension method :

public static class DefaultValueAttributeHelper
{
public static void SetDefaultValues(this object obj)
{
Type t = obj.GetType();
foreach (var item in t.GetProperties())
{
foreach (var attr in item.GetCustomAttributes(typeof(DefaultValueAttribute), true))
{
DefaultValueAttribute val = ((DefaultValueAttribute)attr);
if (item.GetValue(obj, null) == null ||
((item.GetValue(obj, null).ToString() == "0") &&
(val.ValueType != typeof(string))))
item.SetValue(obj, val.DefaultValue, null);
}
}

}
}

And finally how this can be used  for example at an ASP.NET Page:

 

public partial class UserDetails : System.Web.UI.Page
{
public UserDetails()
{
this.SetDefaultValues();
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(StringProp + "<br>" + IntProp + "<br>" + (DoubleProp + 1));
}

[DefaultValueAttribute("6.11354", typeof(double))]
public double DoubleProp { get; set; }

[DefaultValueAttribute("6", typeof(int))]
public int IntProp { get; set; }

[DefaultValueAttribute("String1", typeof(string))]
public string StringProp { get; set; }


}

Well that's all ... This is really simple. Next step is to create an interface so the above attirbute can be used with custom objects.

If anyone has any improvements please let me know!

kick it on DotNetKicks.com

Today I ran into an excellent post of Bill Beckelman about a server side asp.net message box.

More info you can find on this post. And I thought what if I wanted to use it via the client ? So I decided to extended a little further and to add a client-side behavior.

 

How can be used via the client?

To use the MessageBox via client you should call the
ShowMessageBox(type,Header,Text,Width,Height) function.

The first argument is the type. At the moment possible values are info,error,success and warning.
The second is the the header of the messagebox and the third is the text. You can also use html...!
The other two are width and height of the message box.

Example : ShowMessageBox('info','A Simple Header','Just some text',400,125);

So simple :)

You can view a demo or you can download the updated version.

Again credits to Bill Beckelman!

Screenshots

image.axd

image1.axd

image2.axd 

kick it on DotNetKicks.com

Just a few hours ago the 1.2 version of the ultimate web development tool, Firebug , has been released. Several improvements and bug fixes come with this release. You can find more at John's post.

Update NOW!!!!

When I want to add a user control to a page I use the @Register directive at the top of the page. and the I add the control to the markup. But what if I want to add a user control programmatically but I have no reference of it via the markup? That is where the @Reference directive comes to action.

What's the story?

We have a user control with the name myUserControl.aspx

1

We add at the top of the page the control we want to programmatically add like this...

2

And finally the controls is being added to the page like this...

3

In general, when we declare a control in the page layout we use @Register and when we create the control programmatically we use @Reference.

That's it ...

kick it on DotNetKicks.com

More Posts Next page »