Posts
39
Comments
89
Trackbacks
0
Saturday, April 06, 2013
Entity Framework Code First: One to One Relationships

Setting up one to one relationships is not as straightforward as one would hope with Entity Framework using Code First. The EF documentation states that to set up a one to one documentation the foreign key must be the primary key of the child table. This is not entirely true. EF doesn't actually check the table to make sure this is the case, so simply marking it as the public key will work. The below code is an example of a of a one to one relationship where each User has exactly one UserProfile

//Parent table
[Table("User")]
public class User
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserID { get; set; }
public string UserName { get; set; }
[ForeignKey("UserProfile")]
[Key]
public int UserProfileId { get; set; }
public virtual UserProfile UserProfile { get; set; }
}

//Child table

[Table("UserProfile")]
public class UserProfile
{
[Key]
public int UserProfileId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Account User { get; set; }
}

posted @ Saturday, April 06, 2013 5:56 PM | Feedback (1)
Friday, March 29, 2013
Angular OnBlur

For whatever reason, Angular does not have a built-in directive for onBlur. So here is a custom directive that executes when the onBlur event is raised.

var modulesDirective = angular.module('myApp.directives', []).
  directive('appVersion', ['version', function (version) {       return function (scope, elm, attrs) {           elm.text(version);       };   }]);
modulesDirective.     directive('ngOnBlur', function($parse){         return function(scope, elm, attrs){                       var onBlurFunction = $parse(attrs['ngOnBlur']);                 elm.bind("blur", function(event) {                     scope.$apply(function() {                         onBlurFunction(scope, { $event: event });                     })});         };     });

 

And here is an example of the markup to call this directive.
<input type="text" ng-On-Blur="alert('onBlur event raised');" />
posted @ Friday, March 29, 2013 1:03 PM | Feedback (2)
Monday, February 04, 2013
Windows Azure ACS

Here is a video interview I did with David Giard on the topic of Azure ACS. We cover why one should use ACS, along with how it works and common use scenarios.

posted @ Monday, February 04, 2013 8:56 PM | Feedback (2)
Sunday, January 20, 2013
ASP.NET SQL Membership Provider in SQL Azure

Attempting to set up the asp.net sql membership provider in Windows Azure SQL Database via conventional methods, either running aspnet_regsql.exe or scripting out the data from an on-premise database, will not work. You will encounter errors because the scripts attempt to use features not available in Windows Azure SQL Database. Example: “An error occurred during the execution of the SQL file 'InstallCommon.sql'. The SQL error number is 40508 and the SqlException message is: USE statement is not supported to switch between databases. Use a new connection to connect to a different Database.”

Instead, to set up the membership database in Windows Azure SQL Database you will have to execute a group of scripts found here.

posted @ Sunday, January 20, 2013 4:13 PM | Feedback (0)
Thursday, October 04, 2012
What's New in Windows Azure
I'll be speaking at the Central Ohio Cloud Computing User Group Monday (10/15) on the new features recently released in Windows Azure. Details can be found here.
posted @ Thursday, October 04, 2012 11:06 AM | Feedback (3)
Wednesday, August 29, 2012
Azure Access Control Service Slides
Here are the slides on the Azure Access Control Service talk I did at the CloudDevelop conference. The abstract can be found here.
posted @ Wednesday, August 29, 2012 10:03 AM | Feedback (41)
Tuesday, August 28, 2012
The Architecture of Open Source Applications
I recently came across "The Architecture of Open Source Applications", an amazing book on application architecture. I am shocked and somewhat embarrassed I am just now finding out about it. For an overview, check out this presentation by the co-editor, Greg Wilson. And best of all, it is freely available here.  
posted @ Tuesday, August 28, 2012 11:13 AM | Feedback (2)
Sunday, January 29, 2012
MVC4 slides and demo
Here are the slides and demo from the MVC 4 presentation given at the Central Ohio .NET Developers Group on 01/26/12. Thanks for everyone who came out!
posted @ Sunday, January 29, 2012 10:01 PM | Feedback (2)
Thursday, January 26, 2012
Speaking at CONDG

I will be speaking tonight at CONDG on the topic of mobile capabilities in the new release of ASP.NET MVC 4.  Leading EDJE is sponsoring the event and will be providing dinner.

posted @ Thursday, January 26, 2012 11:12 AM | Feedback (2)
Saturday, April 16, 2011
SharePoint 2010: Enable Developer Dashboard

The following stsadm command will enable the developer dashboard in SharePoint 2010

stsadm -o setproperty -pn developer-dashboard -pv on

To enable it only for OnDemand (recommended) use this

stsadm -o setproperty -pn developer-dashboard -pv ondemand

When set for OnDemand an icon will appear in the upper right hand corner of the SharePoint site.  Clicking it will toggle the dashboard on and off for a specific page and user.  The performance is significantly better than doing a blanket trace for all pages and users.  Also, only site collection administrators will see the toggle icon.

posted @ Saturday, April 16, 2011 7:49 PM | Feedback (2)
Sunday, March 20, 2011
WCF 4.0 Presentation Slides

Here are the slides from the March MOCSDUG presentation on WCF 4.0. The code samples I used were modified versions of Microsoft's WCF and WF Samples for .NET Framework 4.0

posted @ Sunday, March 20, 2011 10:47 PM | Feedback (8)
Wednesday, March 02, 2011
Speaking about WCF 4.0 at MOCSDUG

I will be speaking about the new features in WCF 4.0 at the the Mid-Ohio Connected Systems Developer User Group (MOCSDUG) tomorrow, 03/03/11.  Here are more details 

posted @ Wednesday, March 02, 2011 6:23 PM | Feedback (1)
Monday, April 19, 2010
AutoMapper

Well-architected SOA applications tend to have at least two representations of a domain object, a message contract used as an external interface and an entity used internally by the application.  The reason for having two different data structures is to enable loose coupling between internal application logic and the consuming clients.  For the developer, this means a line of code like the one below repeated for every property of a message contract

Entities.Customer.FirstName = DataContracst.Customer.FirstName

With AutoMapper the same can be achieved with two lines of code.  First the types must be associated.  For a web application putting the code in the Application_Start event of the global.asax will work.

Mapper.CreateMap<DataContracts.Customer, Entities.Customer>();

Once the types have been associated the following code will map an object of type DataContracts.Customer to Entities.Customer.

Mapper.Map(customerDataContract, customerEntity);

posted @ Monday, April 19, 2010 5:42 PM | Feedback (0)
Monday, November 09, 2009
Hornget

Now that open source tools are becoming more popular within the Microsoft development community, finding the latest releases and and dependencies can be a lot of work.  Hornget simplifies this search process.  It is a central repository of all the latest open source releases.  Currently the site has packages in the following categories: frameworks, ioc, loggers, mappers, mocks, orm, and web.

posted @ Monday, November 09, 2009 8:41 PM | Feedback (0)
Wednesday, September 30, 2009
Speaking at MOCSDUG
I will be speaking at the Mid-Ohio Connected Systems Developers User Group tomorrow.  Details can be found here
posted @ Wednesday, September 30, 2009 5:20 PM | Feedback (0)
Saturday, August 22, 2009
Execute Client Commands From ASP.NET
There are times when it is necessary to execute client code from an asp.net page.   A number of ways exist to go about this, but the following is the easiest way I have found since  it does not require installation of a browser plugin.  Instead it streams a .bat file response to the user for execution.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string file = @"echo you are running a bat file
pause";

        Response.Clear();
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.AddHeader("Content-Disposition", "attachment; filename=test.bat");
        Response.ContentType = "application/octet-stream";
        Response.Write(file);
       
    }
}
posted @ Saturday, August 22, 2009 6:16 PM | Feedback (0)
Wednesday, July 08, 2009
Finding Broken Links
Broken links have always been an issue with websites and intranets, and with the pervasiveness of user-driven content the problem has only increased.   Xenu's Link Sleuth is a utility to remedy this.  It will crawl an entire site and create a report of all working and broken links.  It has the ability to verify "'links, images, frames, plug-ins, backgrounds, local image maps, style sheets, scripts and java applets".  The download page can be found here.
posted @ Wednesday, July 08, 2009 3:10 PM | Feedback (0)
Wednesday, June 17, 2009
Speaking at COSPUG
I will be speaking at the Central Ohio SharePoint User Group tomorrow from 5:30-7:00 PM.  The topic will be SharePoint Security.  Stop by if you are in the area and interested.
posted @ Wednesday, June 17, 2009 8:31 PM | Feedback (0)
Tuesday, May 19, 2009
SharePoint: Embed Web Parts Within Web Parts
This might seem obvious, but web parts can easily be embedded within other web parts.  The abstract web part class inherits from the System.Web.UI.WebControls.WebControl (Actually it inherits from System.Web.UI.WebControls.WebParts.Part which inherits from System.Web.UI.WebControls.Panel which inherits from System.Web.UI.WebControls.WebControl).  This allows web parts to be added to the control tree the way any other control is added.

this.Controls.Add(new YourCustomWebPartClass());
posted @ Tuesday, May 19, 2009 5:27 PM | Feedback (0)
Thursday, January 29, 2009
Populate Drop Down List With All SharePoint Sites

I recently wrote a SharePoint web part where a requirement was to populate a drop down list with all sites (SPWebs) of a site collection.  This is probably a very common scenario but the API didn’t support it easily.  Initially it looked very straightforward.  The site collection property exposes an AllWebs property which is an SPWebCollection of every site within the site collection.  Unfortunately, this will cause an Access Denied exception when accessed by any user not in the site collection administrators group, even if that user has access to every site in the collection.

Another approach was to use the GetSubWebsForCurrentUser method on the top level site object.  Unfortunately, this method does not retrieve the entire site tree, but only the child sites directly underneath the parent site.  The below function will recursively call the GetSubWebsForcurrentUser method for each sub site and bind the results to a drop down list.

private void RecursivelyPopulateDDLSites(DropDownList DDLSites, SPWebCollection Webs)
        {
            foreach (SPWeb web in Webs)
            {
                
               DDLSites.Items.Add(new ListItem(web.Title, web.ID.ToString()));
               if (web.GetSubwebsForCurrentUser().Count > 0)
               {
               RecursivelyPopulateDDLSites(DDLSites, web.GetSubwebsForCurrentUser());
               }

            }
            
        }
posted @ Thursday, January 29, 2009 6:12 PM | Feedback (1)
Wednesday, January 28, 2009
C# Encryption

The .net framework contains useful classes for encryption found in the System.Security.Cryptography namespace. Even though these classes shield the developer from the complexity of the encryption algorithms, there is still a significant amount of implementation detail to handle.  Under most scenarios, a developer simply wants a function that takes a clear text string as a parameter and returns an encrypted string.  The C# code for this function is below

public string EncryptString(string ClearText)
        {

            byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

            System.Security.Cryptography.SymmetricAlgorithm rijn =  SymmetricAlgorithm.Create();

            MemoryStream ms = new MemoryStream();
            byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); 
            byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo"); 
            CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), 
	   CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);

            cs.Close();

            return Convert.ToBase64String(ms.ToArray());
        }

The function to go from an encrypted string to clear text will do everything in the function above but in the opposite order. 

private string DecryptString(string EncryptedText)
        {
            byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


            byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj"); 
            byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo"); 

            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), 
            CryptoStreamMode.Write);

            cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

            cs.Close();

            return Encoding.UTF8.GetString(ms.ToArray());

        }

Be sure to replace the encryption keys I provided above with your own unique values.  This site is an easy way to generate random letters of a given length.  Also, note that the encryption type used above is symmetric t.  If you need an asymmetric or hash algorithm use the appropriate class within the Cryptography namespace.

posted @ Wednesday, January 28, 2009 8:15 PM | Feedback (14)
Tuesday, December 16, 2008
LINQ Error: Could not find an implementation of the query pattern for source type
If you receive an error like the following for a LINQ expression "Could not find an implementation of the query pattern for source type 'Microsoft.SharePoint.SPWebCollection'.  'Where' not found.  Consider explicitly specifying the type of the range variable" the reason is either that the object does not implement IEnumerable or that the compiler needs to be explicity told what to enumerate.  In the above case Microsoft.SharePoint.SPWebCollection is enumerable for type SPWeb so to fix the error the code needs to be modified from this

IEnumerable<SPWeb> webs = from web in SPContext.Current.Site.AllWebs where web.Permissions.DoesUserHavePermissions(SPRights.ViewListItems) select web;

To this

IEnumerable<SPWeb> webs = from SPWeb web in SPContext.Current.Site.AllWebs where web.Permissions.DoesUserHavePermissions(SPRights.ViewListItems) select web;
posted @ Tuesday, December 16, 2008 3:13 PM | Feedback (0)
Connect to Oracle with SSIS

Before connecting to an Oracle database from SSIS, there are two prerequisites that must be completed.  First, the client drivers must be installed on the server running the SSIS package.  Secondly, the tnsnames.ora configuration file must be set up with the appropriate connection information.


There are many client drivers that correspond to different versions of the Oracle database server and the client OS.  They can be downloaded here from the Oracle website (registration required).  Once the drivers have been downloaded and extracted, installation can begin by running setup.exe.  On the select installation type, the Runtime or Administrator option should be selected.  After selecting a file location the drivers will install on the system.  Assuming setup completes successfully, the tnsnames.ora file is ready to be modified.
The TNSNAMES.ora file instructs the oracle driver where and how to connect to an Oracle Database.  Under the default installation file path, a sample TNSNAMES.ora file can be found C:\oracle\product\[database version]\client_1\network\ADMIN\SAMPLE.  However, the actual TNSNAMES.ora should be place one directory up in the ADMIN folder.  For more information on TNSNAMES refer to the Oracle documentation


With the above steps completed the connection can now be established from within SSIS.  Because the OLE DB Source and Destination shapes rely on OLE DB Connections, the connection must first be created.  To complete this, right click on the Connection Manager pane and Select New OLE DB Connection.   In the provider drop down list select Oracle Provider for OLE DB.  In the Server or file name textbox enter the connection name defined in your tnsnames.ora file.  Finally, enter your username and password and click Test Connection.


If the connection is not successful the TNSPing utility can be used to troubleshoot any issues.  It can be found default file location is C:\oracle\product\[database version\client_1\bin.

posted @ Tuesday, December 16, 2008 1:14 AM | Feedback (1)
Friday, November 28, 2008
Visual Studio 2008 Default Keyboard Shortcuts

Knowing the IDE keyboard shortcuts is one of the easiest ways to increase coding productivity.  Think about how much of a bottleneck the mouse can be.  It uses 4 commands:  horizontal movement, vertical movement, left click, and right click.  Communicating with a complex editor with these four commands is like trying to chop down a tree with just one hand.  Here is a reference of the most commonly used keybindings for Visual Studio 2008.  However, these are only the defaults.  You can customize your environment from the Tools > Options > Envrionment > Keyboard screen.

posted @ Friday, November 28, 2008 10:38 PM | Feedback (0)
Wednesday, October 01, 2008
SharePoint: Edit Page missing from Dispform.aspx

You may notice the Edit Page option missing from the Site Actions menu on pages that use the list item templates (by default they are AllItems.aspx, EditForm.aspx, NewForm.aspx, DispForm.aspx).  First, make sure you have a web part zone on the page.  The site actions won't display Edit Page option if the page doesn't contain a single zone.

<WebPartPages:WebPartZone runat="server" Frametype="TitleBarOnly" id="Zone1" Title="loc:Right"><ZomeTemplate></ZomeTemplate></WebPartPages:WebPartZone>

However, even with the zone, the Edit Page option doesn't always appear.  This is a bug with SharePoint.  A workaround is to make sure the page contains at least one web part.  You can do this in SharePoint Designer by clicking on the "Click to insert a Web Part" link inside the webpart zone and then dragging a web part from the Web Part List menu.

posted @ Wednesday, October 01, 2008 3:22 PM | Feedback (1)