воскресенье, 29 ноября 2009 г.

Many to many relationships in the entity data model

This tutorial will explain how many-to-many relationships appear in the Entity Data Model.

What is a Many-to-Many relationship?

A many-to-many relationship is one where two data tables or entities have multiple rows that are connected to one or more rows in the other table.

A typical example is the EmployeeAddress join table in the AdventureWorks sample database. One employee could have multiple addresses (home, vacation, etc.) and it's possible for one address to apply to multiple employees. In databases, a join table is generally used to create the relationships.

Note that there are additional properties in the join table to track the address type (a customization of the original table), when the joins were created/modified and a unique identifier for each row.


Another example of this is Students and Classes in a database for managing a school. One student can be in many classes and one class can have many students. m2m2

Many to Many Relationships in the Entity Data Model

The Entity Data Model Wizard handles these two sets of tables very differently when they are imported into an EDM.

The Employee/Addresses entities mirror the tables -- two entities with a join entity in between. There are navigation properties to traverse between the three entities, Employee.EmployeeAddresses gets you from the Employee to the join entity and from there you can use EmployeesAddresses.Addresses to get the addresses for the Employee you began with.


Using this data in code requires building join queries or queries that drill through multiple navigation properties (eg Employee.EmployeeAddress.Addresses), for example:

Private Sub employeeaddress()    Dim aw As New AdventureWorksTModel.AdventureWorksTEntities    Dim empaddQuery = From e In aw.Employees, ea In e.EmployeeAddresses _          Select e.EmployeeID, e.HireDate, ea.AddressType, ea.Addresses.City    For Each emp In empaddQuery.OrderBy(Function(e) e.EmployeeID)       Console.WriteLine(String.Format("ID {0}:: Hire Date: {1:d}, Address Type: {2}, City {3}", _       emp.EmployeeID, emp.HireDate, emp.AddressType, emp.City))    Next End Sub 

Which results with:

ID 1:: Hire Date: 7/31/1996, Address Type: Home , City Monroe
ID 1:: Hire Date: 7/31/1996, Address Type: Vacation , City Seattle
ID 2:: Hire Date: 2/26/1997, Address Type: Home , City Bellevue
ID 2:: Hire Date: 2/26/1997, Address Type: Weekend , City Everett

The student/class entities however, have no join table. Instead they have navigation properties to get to their related data. You can query class.students and you can query for student.classes.

This is a special benefit that the Entity Framework provides when join tables contain only the keys and no additional columns.

Because of this it is possible to traverse directly into the related data without the use of a join entity. Here's an example that uses a nested from clause to create an anoymous type based on the related data.

Private Sub studentclasses()   Dim school As New SchoolSampleModel.SchoolSampleEntities   Dim studclassQuery = From student In school.students From c In student.classes _                        Select student.firstname, student.lastname, c.classname     For Each student In studclassQuery.OrderBy(Function(s) s.lastname & s.firstname)       Console.WriteLine(String.Format("Student {0},{1}: {2}", _                                       student.lastname.TrimEnd, student.firstname.Trim, student.classname))     Next End Sub 

Which results with:

Student Doe,John: European History
Student Doe,John: Art History
Student Robin,Stacey: American History
Student Smith,Jane: American History
Student Smith,Jane: French
Student Williams,Bill: European History
Student Williams,Bill: French
Student Williams,Bill: Computers 101

среда, 25 ноября 2009 г.

Modal Popup Extender and show/hide

<cc1:modalpopupextender id="ModalPopupExtender1" runat="server" BehaviorID="MsgPopup" targetcontrolid="LinkButton1" BackgroundCssClass="modalBackground" PopupControlID="Panel2"></cc1:modalpopupextender>

instead id, use BehaviorId

$find('MsgPopup').show() // to show the ModalPopupExtender.

$find('MsgPopup').hide() // to hide the ModalPopupExtender.

понедельник, 23 ноября 2009 г.

Configuring IIS for Silverlight Applications


Microsoft® SilverlightTM is a cross-browser, cross-platform plug-in for delivering the next generation of .NET based media experiences and rich interactive applications for the Web. Silverlight offers a flexible programming model that supports AJAX, VB, C#, Python, and Ruby, and integrates with existing Web applications. Silverlight supports fast, cost-effective delivery of high-quality video to all major browsers running on the Mac OS or Windows.

In most cases, hosters do not need to perform particular deployments to support Silverlight. However, check for the following basic items that could prevent Silverlight from functioning correctly.

MIME Types

In Windows Server 2008 IIS 7.0

All MIME types needed to support Silverlight are implemented by default in Windows Server 2008 IIS 7.0 and Windows Vista SP1. Windows Vista RTM customers can add mime types by running "IIS Manager", clicking on "Mime Types", then clicking "add" and adding the following mime types:

  • .xap application/x-silverlight-app
  • .xaml application/xaml+xml
  • .xbap application/x-ms-xbap

Alternatively, you can add the following mime types to your %windir%\system32\inetsrv\config\applicationHost.config file in the section.

In Windows Server 2003 IIS 6.0

To enable IIS 6.0 in Windows Server 2003 or IIS7 in Windows Vista RTM with the appropriate MIME Types, add:

  • .xap application/x-silverlight-app
  • .xaml application/xaml+xml
  • .xbap application/x-ms-xbap

Here is a VBS script you could run to enable each of these types:

if WScript.Arguments.Count < 2 then
WScript.Echo "Usage: " + WScript.ScriptName + " extension mimetype"
end if
'Get the mimemap object.
Set MimeMapObj = GetObject("IIS://LocalHost/MimeMap")
'Get the mappings from the MimeMap property.
aMimeMap = MimeMapObj.GetEx("MimeMap")
' Add a new mapping.
i = UBound(aMimeMap) + 1
Redim Preserve aMimeMap(i)
Set aMimeMap(i) = CreateObject("MimeMap")
aMimeMap(i).Extension = WScript.Arguments(0)
aMimeMap(i).MimeType = WScript.Arguments(1)
MimeMapObj.PutEx ADS_PROPERTY_UPDATE, "MimeMap", aMimeMap
WScript.Echo "MimeMap successfully added: "
WScript.Echo " Extension: " + WScript.Arguments(0)
WScript.Echo " Type: " + WScript.Arguments(1)

If you copy and paste the code above into a VBS file and save it as ADDMIMETYPE.VBS the syntax to add each type would be:

ADDMIMETYPE.VBS .xap application/x-silverlight-app ADDMIMETYPE.VBS .xaml application/xaml+xmlADDMIMETYPE.VBS .xbap application/x-ms-xbap

Using the IIS Manager User Interface in Windows Server 2003 IIS 6.0

1. Go to Start\Administrative Tools and run IIS Manager, see figure below:

2. Right click on the server name and select "Properties", see figure below:

3. In the Properties Dialog, click on the "MIME Types" button, see figure below:

4. In the "MIME Types" Dialog, click the "New" button, see figure below:

5. In the "MIME Type" Dialog enter one MIME Type at the time:

  • .xap application/x-silverlight-app
  • .xaml application/xaml+xml
  • .xbap application/x-ms-xbap
  • see figure below:

    For detailed information on Silverlight, visit http://silverlight.net/.

    пятница, 20 ноября 2009 г.

    Semi transparent Silverlight on top of HTML

    My last post was about laying Silverlight on top of HTML, using CSS for positioning and ordering of the layers.

    However one thing that had me stumped for a bit was how to set the transparency on the Silverlight area. Surely it can't be that hard!?

    Lessons learned

    In my previous post I mentioned, possibly using the CSS opacity setting on the tag to achieve the goal. Having had a play around, I found that, yes you can do it that way, and it seems to work fine (keep in mind different browsers support it somewhat differently). However there is a much simpler and neater way of doing it.

    In the default test page that gets created the tag takes a parameter named background , this gave me the first clue.


    Next I saw Michael Kordahi's example of overlaying SL on top of HTML and got some ideas from how he was doing things, the problem was that he was using the SL 1.0 way of calling up the silverlight using the createSilverlight() in a silverlight.js file etc. So I had to figure out how to translate that into what I was doing, it would seem pretty basic. Michael was passing in the following as part of his javascript call to create the Silverlight object. background:'transparent', isWindowless: 'true'. However passing in those as parameters to my HTML objet tag didn't work.

    To make what was a pretty long story short( the long version including me stumbling around trying to figure things out) , here is what I learned.

    A. There seems to be some issues with passing in parameters to HTML , I got caught out a few times making changes then refreshing the page and nothing happening (making me think I was doing it wrong), this went on until I found some resources confirming that I was in fact doing it the right way. Once I started closing and restarting the browser between changes, things worked a lot better.

    B. The background and windowless attributes seem to be SL2 specific ones. Looking at various resources (including both W3C and Microsoft) covering the HTML tag gave me no information, however eventually I came upon this blog post by Alex Golesh, that briefly talks about the difference in between SL2 and CreateSilverlight(), this post in itself didn't really tell me what I wanted to know but it pointed me onwards and evetually I found my way to the Microsoft SL2 documentation about Instantiating a Silverlight Plug-In. You can tell it's beta documentation but at least it's got some info, I guess this was a lesson learnt, start by looking at the MS documentation, then hit the web.

    So, on to the actual solution!

    As I said it seems like it should be pretty simple, and guess what, it is! There's two steps, first edit the hosting page, then make the necessary modifications to the XAML.

    Step 1

    If you're hosting your SL in a HTML page, set the background parameter to transparent and the windowless parameter to true. Also keep in mind the size, building a full SL app this is usually set to 100% width and height, however if we want to use it together with the HTML, we want to change it to match the actual size of your XAML/Silverlight element.

    If you're hosting it in a aspx page using the SL2 Silverlight control, you want to do the same adjustments as above, adjust the size, then add the parameters PluginBackground and Windowless.


    As per usual when working with server controls you can either change things in code as per above or use the properties window as below.

    Step 2

    Adjust the opacity/transparency of the XAML, this can be done in a few different ways and they have slightly different outcomes.

    Option 1

    Setting the opacity of the user control
    Or on the LayoutRoot element
    Gives the following result
    The thing to notice here is that the opacity setting is inherited by the children of the control it's set on.
    Hence both the canvas and the button are effected in both cases.

    Option 2

    A slightly different and most of the time a probably, a more appropriate way of setting the transparency/opacity, is to set the background of the LayoutRoot, to the hexadecimal representation of a colour and include the alpha transparency.
    Which gives us the following result, where the background is semi transparent but the button is not affected.

    Hope you find this useful, I've definitely found that resources in regards to this seems a bit sparse at the moment. And the ones that are out there can be a bit tricky to find.


    Blog post by Malky Wullur on overlaying Silverligth on top of Virtual Earth, very cool.

    Post by Alex Golesh on Instantiating a Silverlight Plug-In

    Using Silverlight.js

    Instantiating a Silverlight Plug-In (Silverlight 2)

    HTML Objects

    среда, 18 ноября 2009 г.

    Automatic Generation of Stored Procedure Return Types

    new feature of the Entity Framework in .NET 4.0 is the ability to return collections of complex type instances from stored procedures. In the next public release of the designer, we have enriched this functionality by adding the ability to automatically create these complex types by querying stored procedure metadata from the database server. To demonstrate this feature, we will use the Northwind database, and we will focus on a stored procedure called “CustOrdersDetail”. Looking at the designer’s model browser window after we reverse engineer Northwind, we see:


    Double-clicking “CustOrdersDetail” brings up the “Add Function Import” dialog:


    We click “Get Column Information” in order to see the metadata returned by the server about this stored procedure’s return columns. Then, we click on the “Create New Complex Type” button, and the designer automatically creates a new complex type that matches the shape of the data returned from the stored procedure:


    To make life more interesting (and realistic,) let’s rename some of the properties in the generated complex type: ProductName to Name, and UnitPrice to Price. To keep things running, we then need to fix the function import’s mappings to look like this:


    Finally, to simulate some real-world churn, we change the stored procedure’s return shape: We’ll rename “UnitPrice” to “UnitPricing”, add a new column called “Foo”, and delete “Quantity”:

    ALTER PROCEDURE CustOrdersDetail @OrderID int
    SELECT ProductName,
    UnitPricing=ROUND(Od.UnitPrice, 2),
    Discount=CONVERT(int, Discount * 100),
    Foo = '!',
    ExtendedPrice=ROUND(CONVERT(money, Quantity * (1 - Discount) * Od.UnitPrice), 2)
    FROM Products P, [Order Details] Od
    WHERE Od.ProductID = P.ProductID and Od.OrderID = @OrderID

    That done, we double click on the function import again, get column information, and this time, click on the “Update” button. The designer will now inspect the mappings, the existing complex type, and the new return shape, and produce these proposed changes to the complex type:


    As you can see, “Foo” will be added, and “Quantity” will be deleted. In addition, the mappings are used to map “Name” to “ProductName” meaning no action will be taken for it. Finally, since “UnitPricing” is seen as new, “Price” will be deleted and “UnitPricing” will be put in its stead. Since we do not want this, we will rename the column in the function import’s mapping to “UnitPricing” and rerun the above process. This time we get:


    Which is what we would want.

    In conclusion, the designer now exposes the Entity Framework’s new ability to return complex type instances from stored procedure. On top of this, it adds some features to make this capability easier to use and to iterate over. In future releases of Visual Studio, we will improve the iterative features and look into supporting batch imports of stored procedures, so that you will not need to import them one by one. We look forward to your feedback.

    Noam Ben-Ami
    Program Manager, Entity Designer

    четверг, 12 ноября 2009 г.

    Motherboard Serial Number


    I'm trying to get the serial number of the motherboard with the following code:


    string SerialNumber = "";

    ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_BaseBoard");

    foreach (ManagementObject mo in mbs.Get())
    SerialNumber = mo["SerialNumber"].ToString().Trim();

    return SerialNumber;

    It appears to work, however the number returned does not match the manufacture serial number.

    Does anyone know of a better method, or a way to getting the actual manufacture serial number.

    Работа с реестром в C#

    1. Запись в реестр

    using Microsoft.Win32;

    RegistryKey saveKey = Registry.LocalMachine.CreateSubKey("software\\.....");
    saveKey.SetValue("имя ключа","данные которые хочешь записать");

    2. Чтение из реестра

    using Microsoft.Win32;

    RegistryKey readKey = Registry.LocalMachine.OpenSubKey("software\\.....");
    string loadString = (string)readKey.GetValue("имя ключа");

    Задача "Шифрование произвольных данных", реализации на C#

    Как известно, принцип "мы с Томарой ходим парой" весьма распространён в различных API, нужно не просто знать какие методы вызывать, но и в какой последовательности. В MSDN много примеров как закриптовать целый файл. Но, к сожалению, нет ничего о том как закриптовать просто строку или массив байт. Следующий класс позволяет восполнить данный пробел. http://rsdn.ru/forum/src/85033.1.aspx

    среда, 11 ноября 2009 г.

    ASP.NET Multiple Selection DropDownList with AJAX HoverMenuExtender

    Recently, I was looking for a multiple selection dropdownlist control for my new project. After spending some time researching for it, I decided to put together all my finding in one web user control. This web user control consists of an ASP.NET AJAX HoverMenuExtender, JavaScript, StyleSheet and CheckBoxListExCtrl . The final product will work with or without a MasterPage and you can drag and drop more than one instances of the control on to the page. This is not a perfect control, feel free to modify it to tailor your requirement and share your thoughts. Below is a step by step tutorial on how I have accomplished this. Hope this tutorial will give someone an idea on how to use ASP.NET AJAX HoverMenuExtender and create multiple selection dropdownlist. http://blog.ysatech.com/post/2009/09/09/ASP-NET-Multiple-Selection-DropDownList-with-AJAX-HoverMenuExtender.aspx

    понедельник, 9 ноября 2009 г.

    Learn Expression Blend

    Training Videos | Starter Kits | Tutorials | White Papers

    Project Rosetta: Tutorials for Designers and UI Developers

    Project Rosetta is a site for designers and UI developers where they can learn how to take their existing skills and apply them to a different technology. http://visitmix.com/labs/rosetta/

    New Options for Visual Studio 2010 Beta2 WPF and Silverlight Projects


    To get to this Options dialog, use the Tools menu, selected Options, select Text Editors, select XAML, select Miscellaneous.

    MarkupExtension IntelliSense and Editing

    The most requested feature for the WPF & Silverlight XAML Editor was MarkupExtension IntelliSense. This feature has been added to Visual Studio 2010 Beta2.

    In addition to IntelliSense you also get some entry helpers.

    1. When you type a { (left curly brace) Visual Studio will automatically insert the } (right curly brace) for you.

    You can disable this feature by un-checking the above option, “Closing braces for MarkupExtensions.”

    2. When you press the SPACEBAR inside {} (curly braces) Visual Studio will automatically insert a comma for you to the left of the space added by pressing the SPACEBAR.

    You can disable this feature by un-checking the above option, “Commas to separate MarkupExtension parameters.”

    Toolbox Auto-Population

    Visual Studio 2010 Beta2 now adds all Custom Controls and UserControls in the Solution to the Toolbox when you build the solution. Control’s are added to a separate Toolbox tab for each project.

    You can disable this feature by un-checking the above option, “Automatically populate toolbox items.”

    How Auto-Population Works

    When you build a project, its corresponding tab in the Toolbox is cleared and then all types that derive from FrameworkElement are added to the Toolbox tab for that project. (see Fine Print below for more details)

    When you build the solution, all projects Toolbox tabs are updated as explained above.

    If you want to prevent an item from appearing in the Toolbox during the Auto-Population processing decorate the class with the System.ComponentModel.DesignTimeVisible attribute and pass False in the constructor.

    The following code snippet shows the DesignTimeVisible attribute decorating the CustomView UserControl. The CustomView UserControl will not appear in the Toolbox.

    Imports System.ComponentModel  <DesignTimeVisible(False)> Public Class CustomerView     Inherits UserControl  End Class

    Fine Print

    To appear in the Auto-Population Toolbox process a type must derive from FrameworkElement and:

    1. Are public and have a default public or internal constructor or are internal and have either a default public or internal constructor

    3. Types deriving from Window or Page are ignored

    4. FrameworkElements in other .exe projects are ignore

    5. Internal classes will only be displayed when the active designer is for an item in the same project

    6. Friend Assemblies are not taken into account for Toolbox Auto-Population

    The Channel 9 Learning Center

    The Channel 9 Learning Center is the destination for free technical training on emerging Microsoft products and technologies. The Learning Center consists of a set of courses with each course including a set of videos, hands-on labs, and source code samples to get you up-to-speed quickly. http://channel9.msdn.com/learn/

    How to consume an XML feed in ASP.NET - RSS

    XML is the standard for distributing content on the internet, however it can prove a challenge when trying to consume and handle the data retrieved from an XML document. This is the first in a two part series on consuming and displaying XML content on your own website. We will be using XPathDocument and XPathNavigator to select the information we want from the XML document and a simple repeater to display the information within our own website. I will also show a ridiculously easy technique that can be used to cache the consumed content so that every request to your site does not require a round trip to the XML document. Part one will use an RSS feed as the XML document, part two will use the same techniques to consume a Twitter feed. http://www.wduffy.co.uk/blog/how-to-consume-an-xml-feed-in-aspnet-rss/

    Animating a Web Form using ASP.NET AJAX

    Recently I deployed an ASP.NET 2.0 AJAX application that interfaced with a real-time mailing engine to retrieve content, decode it, and then email the altered content via the same mailing engine. As a result, users of this application had to put up with longer than usual wait times after the submit button was clicked based on how busy the email engine was at certain times of the day.

    The problem was solved using the UpdateProgress control and some AJAX code wired to the submit button on the ASPX page to cover up the delay. The solution has been implemented and is working well. Nevertheless, this triggered my search for a solution to animate the entire form instead. Here, I will demonstrate my very first attempt on how I went about doing this. http://dotnetslackers.com/articles/ajax/Animating-a-Web-Form-using-ASP-NET-AJAX.aspx

    Building an Efficient Search Page Using QueryExtender control in ASP.Net 4.0

    Building a search page is one of the very common and repeated tasks we do in any data driven websites. To do this, we will build a select query with where clause based on the search parameter supplied through the input controls on the page. With the introduction of .Netframework 2.0, the data access is made easier with the help of new set of data access controls called DataSource controls. But, building complex filtering conditions that is required to build a search page is still complex with the help of existing datasource controls. Understanding this need, Microsoft has introduced a new extender control called QueryExtender control with ASP.Net 4.0(Currently in beta 1) release that works with LINQ. http://www.codedigest.com/Articles/ASPNET/289_Building_Efficient_Search_Page_Using_QueryExtender_control_in_ASPNet_40.aspx