Locating your MediaElement Video Source File in a Silverlight 3 Control

In this Demo I will show 3 ways to have your web page locate your MediaElement’s video file.

I have created a Silverlight 3 application and let it automatically create a web site to host the control.

clip_image002

 

Drag a <MediaElement> onto the UserControl and set its source file attribute.

clip_image004

 

Drag the video file using window explorer and drop it in the root of my Silverlight’s UserControl project.

clip_image006

 

Note the size of this file is about 25mb.

clip_image008

 

I will demo 3 different methods for setting the location so that the web page can find it.

 

Method 1

Highlight the video and set its “Build Action” to “Content”

Your properties will look like below:

clip_image010

 

Change the source attribute to have a forward slash before the video name.

clip_image012

 

Build the solution.

Test using the test aspx page (TestMediaTestPage.aspx) in your web project and the video should work fine.

Check the size of your xap in the ClientBin folder. Notice that it includes the video file.

clip_image014

 

Method 2

Again from a fresh Silverlight solution containing the 2 projects, drag the video to the root of the Silverlight project.

Highlight the video and set its “Build Action” to “Resource”.

 

Add a <MediaElement> onto the UserControl and set its source file attribute.

In this case a slash is not used in front of the file name in the MediaElement

clip_image016

 

Build the solution.

Once again check the size of your xap in the ClientBin folder. Notice that it includes the video file.

Test using the test aspx page (TestMediaTestPage.aspx) in your web project and the video should work fine.

 

Method 3

Again from a fresh Silverlight solution containing the 2 projects, drag the video to the root of the Silverlight project.

 

Highlight the video and verify its “Build Action” is set to “None”.

 

Add a <MediaElement> onto the UserControl and set its source file attribute.

It does not matter if a slash is in front of the file name or not in the MediaElement

 

Build the solution and using windows explorer check the size of the xap file in the ClientBin.

Notice that it does not include the video file.

 

clip_image018

 

Using windows explorer, drag the video file into the ClientBin folder.

clip_image020

 

Test using the test aspx page (TestMediaTestPage.aspx) in your web project and the video should work fine.

Here is a video recap.

Hiding Secrets in a Web.Config Section

Sometimes while developing websites on your dev machine you may want to encrypt sections of your web.config to hide user ids, passwords or other secret type stuff.

To do this by using a particular directory path, as in a file system hosted website, you can use the ASPNET_REGIIS utility with the –pef switch. If you are using IIS to host your site rather than a website, you can use the ASPNET_REGIIS utility with the –pe switch and a –app switch to point to the virtual directory. Either of these two techniques can be used to encrypt using the RSAProtectedConfigurationProvider and the machine key.

In this example I have a website hosted in the file system and will use the –pef switch. My website has an <appSettings> section that contains secrets.

clip_image002

To encrypt this section first open a .Net command prompt.

Execute the ASPNET_REGIIS command using the –pef switch followed by the section name (case sensitive) and the directory path as shown below.

clip_image004

After you hit enter and you will receive a success message:

clip_image006

Returning to the IDE, if you left your web.config displayed, you will be prompted to reload the file.

clip_image008

Click “Yes” to view the web.config again.

Notice that the <appSettings> has changed.

clip_image010

You will see some squiggles concerning invalid child elements. To clear them modify the configuration element by adding a namespace.

xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0

Below is an example.

clip_image012

The retrieval of the encrypted values is done automatically. In the button click handler shown below, I retrieve the unencrypted value no different than when unencrypted.

clip_image014

clip_image016

To decrypt the web.config file, use the ASPNET_REGIIS command again from a .Net command prompt. The difference is you replace the –pef switch with –pdf switch to decrypt the section.

clip_image018

This command will return your web.config section to its unencrypted format.

Again, if you are not using a website but IIS, you may want to use the ASPNET_REGIIS utility with the –pe switch.

Also the machine key may need permissions granted depending under which identity the site is running. It should be located at \Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys.

(BTW Ssuper was either a typo or stands for Super, super. Take your pick)

Technorati Tags: ,,

Binding an ASP.NET GridView to a typed dataset

Often we have typed datasets coming back from component methods that we want to bind to a GridView at runtime. There are multiple ways to do this. The first technique is without using an ObjectDataSource, the second one is with an ObjectDataSource. Although with either technique its not to difficult to do the bind, formatting the gridview can be a challenge.

I have a small app for a library that keeps track of a library’s membership, books checked out, etc. I have  a business component that has a method which returns information about a member and another method that returns the books currently checked out by a member. This is returned in a typed dataset

My sample form looks like this.

image

 

Technique 1: Without an ObjectDataSource

The user of the page can enter a member number in the textbox and click the button. In the button click event handler the binding and formatting takes place.

protected void Button1_Click(object sender, EventArgs e)
    {
        //get a instance of business layer class
        JL.LibraryBusiness.BusinessLayer bl = new JL.LibraryBusiness.BusinessLayer();
        //get page data (non grid) by calling method
        JL.LibraryEntities.Member mymember= bl.GetMember(short.Parse(TextBox1.Text));
        TextBox2.Text = mymember.LastName;
        //get grid data by calling method and returning typed dataset
        JL.LibraryEntities.ItemsDataSet myitems= bl.GetMemberItemsOnLoan(short.Parse(TextBox1.Text));
        GridView1.Columns.Clear();
        // set the datsource of the grid
        GridView1.DataSource = myitems;
        // sets some props of the grid
        GridView1.Attributes.Add("style", "table-layout:fixed");
        //we will add columns for more control - so dont generate them 
        GridView1.AutoGenerateColumns = false;
        // add a select button
        GridView1.AutoGenerateSelectButton=true;
        //ISBNColumn
        BoundField isbn = new BoundField();
        isbn.DataField = myitems.Items.ISBNColumn.ColumnName;
        isbn.HeaderText = "ISBN";
        isbn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        GridView1.Columns.Add(isbn);
        //CopyNumberColumn
        BoundField copyno = new BoundField();
        copyno.DataField = myitems.Items.CopyNumberColumn.ColumnName;
        copyno.HeaderText = "Copy Number";
        copyno.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
        GridView1.Columns.Add(copyno);
        //TitleColumn
        BoundField title = new BoundField();
        title.DataField = myitems.Items.TitleColumn.ColumnName;
        title.HeaderText = "Title";
        GridView1.Columns.Add(title);
        //CheckoutDateColumn
        BoundField outdate = new BoundField();
        outdate.DataField = myitems.Items.CheckoutDateColumn.ColumnName;
        outdate.HeaderText = "Out Date";
        outdate.DataFormatString = "{0:MMM-dd-yyyy}"; 
        GridView1.Columns.Add(outdate);
        //DueDateColumn
        BoundField duedate = new BoundField();
        duedate.DataField = myitems.Items.DueDateColumn.ColumnName;
        duedate.HeaderText = "due date";
        duedate.DataFormatString = "{0:MMM-dd-yyyy}"; 
        GridView1.Columns.Add(duedate);
        // Bind the Grid   
        GridView1.DataBind();        
    }

 The above code adds a select button to the grid. To capture row info when the select button is clicked you can use the SelectedIndexChanged event handler.

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    //to get the row that was selected in the grid
    //cell 0 is the button
    Label1.Text = "You have selected isbn " + GridView1.SelectedRow.Cells[1].Text +
        " and copy number " + GridView1.SelectedRow.Cells[2].Text;
}

 Some formatting is best done while the grid is being populated with data, especially if the formatting depends on the data. The code below highlights the due date column red if the book is overdue. This uses the RowDataBound event handler. The width of cells can also be changed here.

 
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //change the width of a column
        e.Row.Cells[3].Width = 250;
 
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((DateTime.Parse(e.Row.Cells[5].Text)).Date < DateTime.Now.Date)
            {
                //change the backcolor of a cell if overdue
                e.Row.Cells[5].BackColor = System.Drawing.Color.Red;
            }
        }
        
    }

 

Technique 2: With an ObjectDatasource

 Drag an ObjectDataSource onto the page

image

Use the ObjectDataSource’s smart tag to configure.

image

 A wizard will start. Choose your business layer component.

image

 

Choose the same business component method that you called from the button click in technique 1.

image

 

Choose the field on the form to pass into that method. In this example it is Textbox1.

image 

Click Finish. The default formatted grid is displayed.

image

 The next step is to format each column as you want. Click the GridView’s smart tag and choose Edit Columns.

image

Remove columns you don't want by highlighting them in the selected fields box and click the red X.

image

 Change column properties like header text and alignment.

image

Format dates using format strings.

image

 Set column widths by using ItemStyle

image

 

Add a Select Button

image

 

Move the Select button to the first position using the up arrow.

image

 

Click OK, now the grid is formatted as desired.

image

 

Change the Button Click to use the Select method of the ObjectDataSource. Notice there is a lot less code.

protected void Button1_Click(object sender, EventArgs e)
{
    //get a instance of business layer class
    JL.LibraryBusiness.BusinessLayer bl = new JL.LibraryBusiness.BusinessLayer();
    //get page data (non grid) by calling method
    JL.LibraryEntities.Member mymember = bl.GetMember(short.Parse(TextBox1.Text));
    TextBox2.Text = mymember.LastName;
    // fill the grid
    ObjectDataSource1.Select();
}

 

The SelectedIndexChanged event handler is the same as technique 1.

The column sizing can be removed from RowDatabound, otherwise it is also the same.

 In both techniques the page displays with proper formatting.

image

  

That is it. Good luck with your formatting!

Technorati Tags: ,,

Adding your WPF control to the toolbox

We all reuse our windows controls out of the toolbox so why not our WPF user controls? The process is really the same. To show the steps involved let’s first write a simple WPF user control.

 image

After renaming the control and adding a WPF application project to my solution(to test with), my solution looks like this

image

Since the functionality of the control is not important in this article, I just pasted in some animation code from msdn into my MyDemoControl.xaml file. 

<UserControl x:Class="MyDemoControl.MyDemoControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="156" Width="267">
    <!-- This example :
    from http://msdn.microsoft.com/en-us/library/system.windows.media.animation.pointanimation.aspx
    shows how to use PointAnimation to animate the
    position of an ellipse by animating the Center property of an 
    EllipseGeometry. PointAnimation is used because the Center property
    takes a Point value. -->
        <Canvas>
            <Path Fill="Blue" Margin="15,15,15,15">
                <Path.Data>
                    <!-- Describes an ellipse. -->
                    <EllipseGeometry x:Name="MyAnimatedEllipseGeometry"
                    Center="0,0" RadiusX="15" RadiusY="15" />
                </Path.Data>
                <Path.Triggers>
                    <EventTrigger RoutedEvent="Path.Loaded">
                        <BeginStoryboard Name="MyBeginStoryboard">
                            <Storyboard>
 
                                <!-- Animate the Center property so that the ellipse animates from 
                                one point on the screen to another. -->
                                <PointAnimation
                                Storyboard.TargetProperty="Center"
                                Storyboard.TargetName="MyAnimatedEllipseGeometry"
                                Duration="0:0:2" From="0,0" To="156,267" RepeatBehavior="Forever" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Path.Triggers>
            </Path>
        </Canvas>
</UserControl>

Now let’s add the control to the toolbox!

Step 1:

 Add a using statement to the top of you control's .cs file. This is needed for the ToolboxBitmap we will be using.

using System.Drawing;

Step 2:

Add a image resource to the project for an icon. (right click the project in solution explorer, choose properties, choose Resources tab)

image

You can use an existing or create a new icon. I created a new one.

First select Images from the left dropdown

image

Then click the add resource button

image

Enter the image name in the dialog that pops up.

The name you use is extremely important.

image

Note it should be the class name followed by a period then the word “icon”.

image

I tried to draw a “W” for my icon.

In the properties window change the Build Action property for the BMP to Embedded Resource.

image

Note the full name of the file is the class + “icon” + the extension

Step 3:

Add an ToolboxBitmap attribute to your control class.

[ToolboxBitmap(typeof(MyDemoControl))]
public partial class MyDemoControl : UserControl
{
    public MyDemoControl()
    {
        InitializeComponent();

Notice only the type is needed because of our naming convention used on our bitmap.

Build the control project.

Step 4:

Now to add it to the toolbox,

Right click in the toolbox (where you want the control to be located) and select Choose Items.

 image

You may need to wait a bit for the Choose Toolbox Items dialog to appear. When it does,

Choose the WPF Components tab. This is important! The .Net tab will not work for WPF controls.

Click the browse button and navigate out to your DLL, choose it, click Open.

 image

Once you have selected your DLL you should see the icon that will be used for your control on the dialog 

image

 

Click OK. You should now see the control in your toolbox with proper icon.

image 

Step 5:

Switch back to the WPF Application project in the solution.

Drag your new control out of the toolbox and position it in the Window element.

Set the WPF Application project to be startup.

Run to test the behavior.

«November»
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345