Search Results

Search found 262 results on 11 pages for 'brilliant'.

Page 11/11 | < Previous Page | 7 8 9 10 11 

  • CodePlex Daily Summary for Tuesday, December 21, 2010

    CodePlex Daily Summary for Tuesday, December 21, 2010Popular ReleasesSQL Monitor - tracking sql server activities: SQL Monitor 3.0 alpha 7: 1. added script save/load in user query window 2. fixed problem with connection dialog when choosing windows auth but still ask for user name 3. auto open user table when double click one table node 4. improved alert message, added log only methodOpen NFe: Open NFe 2.0 (Beta): Última versão antes da versão final a ser lançada nos próximos dias.EnhSim: EnhSim 2.2.6 ALPHA: 2.2.6 ALPHAThis release supports WoW patch 4.03a at level 85 To use this release, you must have the Microsoft Visual C++ 2010 Redistributable Package installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=A7B7A05E-6DE6-4D3A-A423-37BF0912DB84 To use the GUI you must have the .NET 4.0 Framework installed. This can be downloaded from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992 - Fixing up some r...LINQ to Twitter: LINQ to Twitter Beta v2.0.18: Silverlight, OAuth, 100% Twitter API coverage, streaming, extensibility via Raw Queries, and added documentation. Bug fixes.ASP.NET MVC Project Awesome (jQuery Ajax helpers): 1.4.3: Helpers (controls) that you can use to build highly responsive and interactive Ajax-enabled Web applications. These helpers include Autocomplete, AjaxDropdown, Lookup, Confirm Dialog, Popup Form, Popup and Pager new stuff: Improvements for confirm, popup, popup form RenderView controller extension the user experience for crud in live demo has been substantially improved + added search all the features are shown in the live demoGanttPlanner: GanttPlanner V1.0: GanttPlanner V1.0 include GanttPlanner.dll and also a Demo application.N2 CMS: 2.1 release candidate 3: * Web platform installer support available N2 is a lightweight CMS framework for ASP.NET. It helps you build great web sites that anyone can update. Major Changes Support for auto-implemented properties ({get;set;}, based on contribution by And Poulsen) A bunch of bugs were fixed File manager improvements (multiple file upload, resize images to fit) New image gallery Infinite scroll paging on news Content templates First time with N2? Try the demo site Download one of the templ...TweetSharp: TweetSharp v2.0.0.0 - Preview 6: Documentation for this release may be found at http://tweetsharp.codeplex.com/wikipage?title=UserGuide&referringTitle=Documentation. Note: This code is currently preview quality. Preview 6 ChangesMaintenance release with user reported fixes Preview 5 ChangesMaintenance release with user reported fixes Preview 4 ChangesReintroduced fluent interface support via satellite assembly Added entities support, entity segmentation, and ITweetable/ITweeter interfaces for client development Numer...Team Foundation Server Administration Tool: 2.1: TFS Administration Tool 2.1, is the first version of the TFS Administration Tool which is built on top of the Team Foundation Server 2010 object model. TFS Administration Tool 2.1 can be installed on machines that are running either Team Explorer 2010, or Team Foundation Server 2010.Hacker Passwords: HackerPasswords.zip: Source code, executable and documentationSubtitleTools: SubtitleTools 1.3: - Added .srt FileAssociation & Win7 ShowRecentCategory feature. - Applied UnifiedYeKe to fix Persian search problems. - Reduced file size of Persian subtitles for uploading @OSDB.Facebook C# SDK: 4.1.0: - Lots of bug fixes - Removed Dynamic Runtime Language dependencies from non-dynamic platforms. - Samples included in release for ASP.NET, MVC, Silverlight, Windows Phone 7, WPF, WinForms, and one Visual Basic Sample - Changed internal serialization to use Json.net - BREAKING CHANGE: Canvas Session is no longer support. Use Signed Request instead. Canvas Session has been deprecated by Facebook. - BREAKING CHANGE: Some renames and changes with Authorizer, CanvasAuthorizer, and Authorization ac...NuGet (formerly NuPack): NuGet 1.0 build 11217.102: Note: this release is slightly newer than RC1, and fixes a couple issues relating to updating packages to newer versions. NuGet is a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development. This release is a Visual Studio 2010 extension and contains the the Package Manager Console and the Add Package Dialog. This new build targets the newer feed (h...WCF Community Site: WCF Web APIs 10.12.17: Welcome to the second release of WCF Web APIs on codeplex Here is what is new in this release. WCF Support for jQuery - create WCF web services that are easy to consume from JavaScript clients, in particular jQuery. Better support for using JsonValue as dynamic Support for JsonValue change notification events for databinding and other purposes Support for going between JsonValue and CLR types WCF HTTP - create HTTP / REST based web services. This is a minor release which contains fixe...LiveChat Starter Kit: LCSK v1.0: This is a working version of the LCSK for Visual Studio 2010, ASP.NET MVC 3 (using Razor View Engine). this is still provider based (with 1 provider Sql) and this is still using WebService and Windows Forms operator console. The solution is cleaner, with an installer to create tables etc. You can also install it via nuget (Install-Package lcsk) Let me know your feedbackOrchard Project: Orchard 0.9: Orchard Release Notes Build: 0.9.253 Published: 12/16/2010 How to Install OrchardTo install the Orchard tech preview using Web PI, follow these instructions: http://www.orchardproject.net/docs/Installing-Orchard-Using-Web-PI.ashx Web PI will detect your hardware environment and install the application. --OR-- Alternatively, to install the release manually, download the Orchard.Web.0.9.253.zip file. The zip contents are pre-built and ready-to-run. Simply extract the contents of the Orch...DotSpatial: DotSpatial 12-15-2010: This release contains a few minor bug fixes and hopefully the GDAL libraries for the 3.5 x86 build actually built to the correct directory this time.DotNetNuke® Community Edition: 05.06.01 Beta: This is the initial Beta of DotNetNuke 5.6.1. See the DotNetNuke Roadmap a full list of changes in this release.MSBuild Extension Pack: December 2010: Release Blog Post The MSBuild Extension Pack December 2010 release provides a collection of over 380 MSBuild tasks. A high level summary of what the tasks currently cover includes the following: System Items: Active Directory, Certificates, COM+, Console, Date and Time, Drives, Environment Variables, Event Logs, Files and Folders, FTP, GAC, Network, Performance Counters, Registry, Services, Sound Code: Assemblies, AsyncExec, CAB Files, Code Signing, DynamicExecute, File Detokenisation, GU...Silverlight Contrib: Silverlight Contrib 2010.1.0: 2010.1.0 New FeaturesCompatibility Release for Silverlight 4 and Visual Studio 2010New Projectsaqq2: aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2aqq2Cameleon CMS: Caméléon, le CMS open-source le plus simple d'utilisation sur le marché.Dail Emulator: Dail Emulator is a software that emulates the server software of Aeonsofts game FlyFF. Specifically made for the now defunct version 6 of the game.Dmitry Lyalin's WP7 Sample Application: A project where im putting all my public samples in a single WP7 client test applicationElixir: DotNetNuke module test framework. Use this DLL to write concise, to-the-point tests for your modules that can target multiple DNN platforms and multiple browsers.FlightTableEditor: This edits the Flight and Healing Tables of Pokémon Fire Red and Pokémon Leaf Green.Genetico UNLaM: Algoritmo Genetico UNLaMHelpCentral HelpDesk Ticket Application: An open-ended framework and client for a helpdesk ticket application and bug tracker. Built to be as extensible and available as possible, the central system is a WCF webservice which can be accessed by any client application.Import Media for Umbraco: This package allows you to import multiple or large files that have been uploaded to the server via FTP or other means. A new media item is created in the media tree and the media is moved from the upload location to the new directory for the media item.LargeCMS full sample (How to call CryptMsg API in streaming mode): LargeCms implements SignedLargeCMS and EnvelopedLargeCMS classes, my own version of .NET SignedCms and EnvelopedCMS to work with large data. It shows a way to call CryptMsg API in streaming mode to overcome the limitations of current .NET classesLinq.Autocompiler: Adds runtime, on demand compilation of Linq queries (in Linq to SQL), which creates CompiledQuery instances and stores them in a cache. Mathetris: it's a game.MonoWiimote: Managed c# library for using Wii Remote device under Mono/Linux enviroment. It requires libcwiimote-0.4 (sudo apt-get install libcwiimote-0.4).Movie Captor: Concorrendo no Desafio .NETNSpotifyLib: A .NET library contains wrapper classes for the Spotify Metadata API. http://developer.spotify.com/en/metadata-api/overview/ This library supports searching for artists, albums and tracks by using the Spotify Metadata API. In the future I'll add support for Lookups as well.Silverhawk: It's developed in C# programming language.SimpleSpy: Detecting object handle on cursor move and get its information. Basically this is a bare bone program for detecting object handle at cursor and add your own logic to detect for further information. SunburnJitter: JitterSunburn contains helper classes and methods to use the jitter physics engine easier in your sunburn projects. Simple component based shapes will provide easy editing in editor. It's developed in C#.Sunrod: Sunrod is a .NET wrapper for the Obsidian Portal API.TouchStack - A MonoTouch ServiceStack.NET client: TouchStack makes it easier for MonoTouch developers to consume Web services created and exposed by the brilliant ServiceStack.NET webservice framework. TouchStack is written in C# and uses the MonoTouch library.VNTViewer: Viewer for notes/memos (VNT files)VpNet: Official .NET Wrapper for Virtual Paradise.xlGUI: Streamlet GUI Framework

    Read the article

  • Adopting Technologies for the Sake of Technologies

    - by shiju
    Unlike other engineering industries, the software engineering industry is really lacking maturity. The lack of maturity can see in different aspects of entire software development life cycle. I think other engineering industries are well organised and structured with common, proven engineering practices. The software engineering industry is greatly a diverse industry with different operating systems, and variety of development platforms, programming languages, frameworks and tools. Now these days, people are going behind the hypes and intellectual thoughts without understanding their core business problems and adopting technologies and practices for the sake of technologies and practices and simply becoming a “poster child” of technologies and practices. Understanding the core business problem and providing best, solid solution with a platform neutral approach, will give you more business values and ROI, instead of blindly adopting technologies and tailor-made your applications for the sake of technologies and practices. People have been simply migrating their solutions in favour of new technologies and different versions of frameworks without any business need. The “Pepsi Challenge” in the Software Development  Pepsi Challenge marketing campaign of the 1980s was a popular and very interesting marketing promotion in which people taste one cup of Pepsi and another cup with Coca Cola. In the taste test, more than 50% of people were preferred Pepsi  over Coca Cola. The success story behind the Pepsi was more sweetness contains in the Pepsi cola. They have simply added more sugar and more people preferred more sweet flavour. You can’t simply identify the better one after sipping one cup of cola based on the sweetness which contains. These things have been happening in the software industry for choosing development frameworks and technologies. People have been simply choosing frameworks based on the initial sugary feeling without understanding its core strengths and weakness. The sugary framework might be more harmful when you develop real-world systems. There is not any silver bullet for solving all kind of problems and frameworks and tools do have strengths and weakness. So it would be better to understand their strength and weakness. And please keep in mind that you have to develop real apps to understand the real capabilities and weakness of a framework. Evaluating a technology based on few blog posts will harm your projects and these bloggers might be lacking real-world experience with the framework. The Problem with Align a Development Practice with Tools Recently I have observed a discussion in a group where one guy asked suggestions for practicing Continuous Delivery (CD) as part of the agile based application engineering. Then the discussion quickly went to using and choosing a Continuous Integration (CI) tool and different people suggested different Continuous Integration (CI) tools for simply practicing Continuous Delivery. If you have worked with core agile engineering practices, you could clearly know that the real essence of agile is neither choosing a tool nor choosing a process. By simply choosing CI tool from a particular vendor will not ensure that you are delivering an evolving software based on customer feedback. You have to understand the real essence of a engineering practice and choose a right tool for practicing it instead of simply focus on a particular tool for a practicing an development practice. If you want to adopt a practice, you need a solid understanding on it with its real essence where tools are just helping us for better automation. Adopting New Technologies for the Sake of Technologies The another problem is that developers have been a tendency to adopt new technologies and simply migrating their existing apps to new technologies. It is okay if your existing system is having problem  with a technology stack or or maintainability challenge with existing solution, and moving to new technology for solving the current problems. We have been adopting new technologies for solving new challenges like solving the scalability challenges when the application or user bases is growing unpredictably. Please keep in mind that all new technologies will become old after working with it for few years. The below Facebook status update of Janakiraman, expresses the attitude of a typical customer. For an example, Node.js is becoming a hottest buzzword in the software industry and many developers are trying to adopt Node.js for their apps. The important thing is that Node.js is a minimalist framework that does some great things for some problems, but it’s not a silver bullet. I have been also working with Node.js which is good for some problems, but really bad for choosing it for all kind of problems. By adopting new technologies for new projects is good if we could get real business values from it because newer framework would solve some existing well known problems and provide better solutions where it can incorporate good solutions for the latest challenges . But adopting a new technology for the sake of new technology is really bad idea. Another example is JavaScript is getting lot of attention so that lot of developers are developing heavy JavaScript centric web apps. First, they will adopt a client-side JavaScript MV* framework from AngularJS, Ember, Backbone etc, and develop a Single Page App(SPA) where they are repeating the mistakes we did in the past with server-side. The mistakes we did in the server-side is transforming to client-side. The problem is that people are just adopting new technologies, but not improving their solutions. I predict that many Single Page App will suck in the future. We need a hybrid approach where we should be able to leverage both server-side and client-side for developing next-generation web apps. The another problem is that if you like a particular framework, use it for all kind of apps. In the past, I know some Silverlight passionate guys were tried to use that framework for all kind of apps including larger line of business apps. And these days developers are migrating their existing Silverlight apps in favour of HTML5 buzzword. So the real question is, what is the business values we are getting from these apps when we are developing it for the sake of a particular technology instead of business need. The another problem is that our solutions consultants are trying to provide unnecessary solutions for the sake of a particular technology or for a hype. For an example, Big Data solutions are great for solving the problem of three Vs : volume, velocity and variety. But trying to put this for every application will make problems. Let’s say, there is a small web site running with limited budget and saying that we need a recommendation engine for the web site with a Hadoop based solution with a 16 node cluster, would be really horrible. If we really need a Hadoop based solution, got for it, but trying to put this for all application would be a big disaster. It would be great if could understand the core business problems first, and later choose a right framework for providing solutions for the actual business problem, instead of trying to provide so many solutions. The Problem with Tied Up to a Platform Vendor Some organizations and teams are tied up with a particular platform vendor where they don’t want to use any product other than their preferred or existing platform vendor. They will accept any product provided by the vendor regardless of its capability. This will lets you some benefits regards with integration and collaboration of different products provided by the same vendor, but it will loose your opportunity to provide better solution for your business problems. For a real world sample scenario, lot of companies have been using SAP for their ERP solutions. When they are thinking about mobility or thinking about developing hybrid mobile apps, they can easily find out a framework from SAP. SAP provides a framework for HTML 5 based UI development named SAPUI5. If you are simply adopting that framework only based for the preference of existing platform vendor, you might be loose different opportunities for providing better solution. Initially you might enjoy the sugary feeling provided by the platform vendor, but you have to think about developing apps which should be capable for solving future challenges. I am not saying that any framework is not good and I believe that all frameworks are good over another one for solving at least one problem. My point is that we should not tied up with any specific platform vendor unless your organization is having resource availability problems. Being Polyglot for Providing Right Solutions The modern software engineering industry is greatly diverse with different tools and platforms. Lot of open source frameworks and new programming languages have been releasing to the developer community, where choosing the right platform without any biased opinion, is really a difficult task. But it would really great if we could develop an attitude with platform neutral mindset and being a polyglot developer for providing better solutions based on the actual business problems. IMHO, we should learn a new programming language and a new framework every year. This will improve the quality of our developer capabilities and also improve the quality of our primary programming language skills. Being polyglot for individual developers and organizational teams will give you greater opportunity to your developer experience and also for your applications. Organizations can analyse their business problem without tied with any technology and later they can provide solutions by choosing different platform and tools. Summary    In this blog post, what I was trying to say that we should not tied up or biased with any development platform, technology, vendor or programming language and we should not adopt technologies and practices for the sake of technologies. If we are adopting a technology or a practice for the sake of it, we are simply becoming a “poster child” of the technology and practice. We should not become a poster child of other people’s intellectual thoughts and theories, instead of it we should become solutions developers and solutions consultants where we should be able to provide better solutions for the business problems. Being a polyglot developer is a good idea for improving your developer skills which lets you provide better solutions for the business problems. The most important thing is that we should become platform neutral developers where our passion should be for providing brilliant solutions. It would be great if we could provide minimalist, pragmatic business solutions. You can follow me on Twitter @shijucv

    Read the article

  • Use IIS Application Initialization for keeping ASP.NET Apps alive

    - by Rick Strahl
    I've been working quite a bit with Windows Services in the recent months, and well, it turns out that Windows Services are quite a bear to debug, deploy, update and maintain. The process of getting services set up,  debugged and updated is a major chore that has to be extensively documented and or automated specifically. On most projects when a service is built, people end up scrambling for the right 'process' to use for administration. Web app deployment and maintenance on the other hand are common and well understood today, as we are constantly dealing with Web apps. There's plenty of infrastructure and tooling built into Web Tools like Visual Studio to facilitate the process. By comparison Windows Services or anything self-hosted for that matter seems convoluted.In fact, in a recent blog post I mentioned that on a recent project I'd been using self-hosting for SignalR inside of a Windows service, because the application is in fact a 'service' that also needs to send out lots of messages via SignalR. But the reality is that it could just as well be an IIS application with a service component that runs in the background. Either way you look at it, it's either a Windows Service with a built in Web Server, or an IIS application running a Service application, neither of which follows the standard Service or Web App template.Personally I much prefer Web applications. Running inside of IIS I get all the benefits of the IIS platform including service lifetime management (crash and restart), controlled shutdowns, the whole security infrastructure including easy certificate support, hot-swapping of code and the the ability to publish directly to IIS from within Visual Studio with ease.Because of these benefits we set out to move from the self hosted service into an ASP.NET Web app instead.The Missing Link for ASP.NET as a Service: Auto-LoadingI've had moments in the past where I wanted to run a 'service like' application in ASP.NET because when you think about it, it's so much easier to control a Web application remotely. Services are locked into start/stop operations, but if you host inside of a Web app you can write your own ticket and control it from anywhere. In fact nearly 10 years ago I built a background scheduling application that ran inside of ASP.NET and it worked great and it's still running doing its job today.The tricky part for running an app as a service inside of IIS then and now, is how to get IIS and ASP.NET launched so your 'service' stays alive even after an Application Pool reset. 7 years ago I faked it by using a web monitor (my own West Wind Web Monitor app) I was running anyway to monitor my various web sites for uptime, and having the monitor ping my 'service' every 20 seconds to effectively keep ASP.NET alive or fire it back up after a reload. I used a simple scheduler class that also includes some logic for 'self-reloading'. Hacky for sure, but it worked reliably.Luckily today it's much easier and more integrated to get IIS to launch ASP.NET as soon as an Application Pool is started by using the Application Initialization Module. The Application Initialization Module basically allows you to turn on Preloading on the Application Pool and the Site/IIS App, which essentially fires a request through the IIS pipeline as soon as the Application Pool has been launched. This means that effectively your ASP.NET app becomes active immediately, Application_Start is fired making sure your app stays up and running at all times. All the other features like Application Pool recycling and auto-shutdown after idle time still work, but IIS will then always immediately re-launch the application.Getting started with Application InitializationAs of IIS 8 Application Initialization is part of the IIS feature set. For IIS 7 and 7.5 there's a separate download available via Web Platform Installer. Using IIS 8 Application Initialization is an optional install component in Windows or the Windows Server Role Manager: This is an optional component so make sure you explicitly select it.IIS Configuration for Application InitializationInitialization needs to be applied on the Application Pool as well as the IIS Application level. As of IIS 8 these settings can be made through the IIS Administration console.Start with the Application Pool:Here you need to set both the Start Automatically which is always set, and the StartMode which should be set to AlwaysRunning. Both have to be set - the Start Automatically flag is set true by default and controls the starting of the application pool itself while Always Running flag is required in order to launch the application. Without the latter flag set the site settings have no effect.Now on the Site/Application level you can specify whether the site should pre load: Set the Preload Enabled flag to true.At this point ASP.NET apps should auto-load. This is all that's needed to pre-load the site if all you want is to get your site launched automatically.If you want a little more control over the load process you can add a few more settings to your web.config file that allow you to show a static page while the App is starting up. This can be useful if startup is really slow, so rather than displaying blank screen while the user is fiddling their thumbs you can display a static HTML page instead: <system.webServer> <applicationInitialization remapManagedRequestsTo="Startup.htm" skipManagedModules="true"> <add initializationPage="ping.ashx" /> </applicationInitialization> </system.webServer>This allows you to specify a page to execute in a dry run. IIS basically fakes request and pushes it directly into the IIS pipeline without hitting the network. You specify a page and IIS will fake a request to that page in this case ping.ashx which just returns a simple OK string - ie. a fast pipeline request. This request is run immediately after Application Pool restart, and while this request is running and your app is warming up, IIS can display an alternate static page - Startup.htm above. So instead of showing users an empty loading page when clicking a link on your site you can optionally show some sort of static status page that says, "we'll be right back".  I'm not sure if that's such a brilliant idea since this can be pretty disruptive in some cases. Personally I think I prefer letting people wait, but at least get the response they were supposed to get back rather than a random page. But it's there if you need it.Note that the web.config stuff is optional. If you don't provide it IIS hits the default site link (/) and even if there's no matching request at the end of that request it'll still fire the request through the IIS pipeline. Ideally though you want to make sure that an ASP.NET endpoint is hit either with your default page, or by specify the initializationPage to ensure ASP.NET actually gets hit since it's possible for IIS fire unmanaged requests only for static pages (depending how your pipeline is configured).What about AppDomain Restarts?In addition to full Worker Process recycles at the IIS level, ASP.NET also has to deal with AppDomain shutdowns which can occur for a variety of reasons:Files are updated in the BIN folderWeb Deploy to your siteweb.config is changedHard application crashThese operations don't cause the worker process to restart, but they do cause ASP.NET to unload the current AppDomain and start up a new one. Because the features above only apply to Application Pool restarts, AppDomain restarts could also cause your 'ASP.NET service' to stop processing in the background.In order to keep the app running on AppDomain recycles, you can resort to a simple ping in the Application_End event:protected void Application_End() { var client = new WebClient(); var url = App.AdminConfiguration.MonitorHostUrl + "ping.aspx"; client.DownloadString(url); Trace.WriteLine("Application Shut Down Ping: " + url); }which fires any ASP.NET url to the current site at the very end of the pipeline shutdown which in turn ensures that the site immediately starts back up.Manual Configuration in ApplicationHost.configThe above UI corresponds to the following ApplicationHost.config settings. If you're using IIS 7, there's no UI for these flags so you'll have to manually edit them.When you install the Application Initialization component into IIS it should auto-configure the module into ApplicationHost.config. Unfortunately for me, with Mr. Murphy in his best form for me, the module registration did not occur and I had to manually add it.<globalModules> <add name="ApplicationInitializationModule" image="%windir%\System32\inetsrv\warmup.dll" /> </globalModules>Most likely you won't need ever need to add this, but if things are not working it's worth to check if the module is actually registered.Next you need to configure the ApplicationPool and the Web site. The following are the two relevant entries in ApplicationHost.config.<system.applicationHost> <applicationPools> <add name="West Wind West Wind Web Connection" autoStart="true" startMode="AlwaysRunning" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated"> <processModel identityType="LocalSystem" setProfileEnvironment="true" /> </add> </applicationPools> <sites> <site name="Default Web Site" id="1"> <application path="/MPress.Workflow.WebQueueMessageManager" applicationPool="West Wind West Wind Web Connection" preloadEnabled="true"> <virtualDirectory path="/" physicalPath="C:\Clients\…" /> </application> </site> </sites> </system.applicationHost>On the Application Pool make sure to set the autoStart and startMode flags to true and AlwaysRunning respectively. On the site make sure to set the preloadEnabled flag to true.And that's all you should need. You can still set the web.config settings described above as well.ASP.NET as a Service?In the particular application I'm working on currently, we have a queue manager that runs as standalone service that polls a database queue and picks out jobs and processes them on several threads. The service can spin up any number of threads and keep these threads alive in the background while IIS is running doing its own thing. These threads are newly created threads, so they sit completely outside of the IIS thread pool. In order for this service to work all it needs is a long running reference that keeps it alive for the life time of the application.In this particular app there are two components that run in the background on their own threads: A scheduler that runs various scheduled tasks and handles things like picking up emails to send out outside of IIS's scope and the QueueManager. Here's what this looks like in global.asax:public class Global : System.Web.HttpApplication { private static ApplicationScheduler scheduler; private static ServiceLauncher launcher; protected void Application_Start(object sender, EventArgs e) { // Pings the service and ensures it stays alive scheduler = new ApplicationScheduler() { CheckFrequency = 600000 }; scheduler.Start(); launcher = new ServiceLauncher(); launcher.Start(); // register so shutdown is controlled HostingEnvironment.RegisterObject(launcher); }}By keeping these objects around as static instances that are set only once on startup, they survive the lifetime of the application. The code in these classes is essentially unchanged from the Windows Service code except that I could remove the various overrides required for the Windows Service interface (OnStart,OnStop,OnResume etc.). Otherwise the behavior and operation is very similar.In this application ASP.NET serves two purposes: It acts as the host for SignalR and provides the administration interface which allows remote management of the 'service'. I can start and stop the service remotely by shutting down the ApplicationScheduler very easily. I can also very easily feed stats from the queue out directly via a couple of Web requests or (as we do now) through the SignalR service.Registering a Background Object with ASP.NETNotice also the use of the HostingEnvironment.RegisterObject(). This function registers an object with ASP.NET to let it know that it's a background task that should be notified if the AppDomain shuts down. RegisterObject() requires an interface with a Stop() method that's fired and allows your code to respond to a shutdown request. Here's what the IRegisteredObject::Stop() method looks like on the launcher:public void Stop(bool immediate = false) { LogManager.Current.LogInfo("QueueManager Controller Stopped."); Controller.StopProcessing(); Controller.Dispose(); Thread.Sleep(1500); // give background threads some time HostingEnvironment.UnregisterObject(this); }Implementing IRegisterObject should help with reliability on AppDomain shutdowns. Thanks to Justin Van Patten for pointing this out to me on Twitter.RegisterObject() is not required but I would highly recommend implementing it on whatever object controls your background processing to all clean shutdowns when the AppDomain shuts down.Testing it outI'm still in the testing phase with this particular service to see if there are any side effects. But so far it doesn't look like it. With about 50 lines of code I was able to replace the Windows service startup to Web start up - everything else just worked as is. An honorable mention goes to SignalR 2.0's oWin hosting, because with the new oWin based hosting no code changes at all were required, merely a couple of configuration file settings and an assembly directive needed, to point at the SignalR startup class. Sweet!It also seems like SignalR is noticeably faster running inside of IIS compared to self-host. Startup feels faster because of the preload.Starting and Stopping the 'Service'Because the application is running as a Web Server, it's easy to have a Web interface for starting and stopping the services running inside of the service. For our queue manager the SignalR service and front monitoring app has a play and stop button for toggling the queue.If you want more administrative control and have it work more like a Windows Service you can also stop the application pool explicitly from the command line which would be equivalent to stopping and restarting a service.To start and stop from the command line you can use the IIS appCmd tool. To stop:> %windir%\system32\inetsrv\appcmd stop apppool /apppool.name:"Weblog"and to start> %windir%\system32\inetsrv\appcmd start apppool /apppool.name:"Weblog"Note that when you explicitly force the AppPool to stop running either in the UI (on the ApplicationPools page use Start/Stop) or via command line tools, the application pool will not auto-restart immediately. You have to manually start it back up.What's not to like?There are certainly a lot of benefits to running a background service in IIS, but… ASP.NET applications do have more overhead in terms of memory footprint and startup time is a little slower, but generally for server applications this is not a big deal. If the application is stable the service should fire up and stay running indefinitely. A lot of times this kind of service interface can simply be attached to an existing Web application, or if scalability requires be offloaded to its own Web server.Easier to work withBut the ultimate benefit here is that it's much easier to work with a Web app as opposed to a service. While developing I can simply turn off the auto-launch features and launch the service on demand through IIS simply by hitting a page on the site. If I want to shut down an IISRESET -stop will shut down the service easily enough. I can then attach a debugger anywhere I want and this works like any other ASP.NET application. Yes you end up on a background thread for debugging but Visual Studio handles that just fine and if you stay on a single thread this is no different than debugging any other code.SummaryUsing ASP.NET to run background service operations is probably not a super common scenario, but it probably should be something that is considered carefully when building services. Many applications have service like features and with the auto-start functionality of the Application Initialization module, it's easy to build this functionality into ASP.NET. Especially when combined with the notification features of SignalR it becomes very, very easy to create rich services that can also communicate their status easily to the outside world.Whether it's existing applications that need some background processing for scheduling related tasks, or whether you just create a separate site altogether just to host your service it's easy to do and you can leverage the same tool chain you're already using for other Web projects. If you have lots of service projects it's worth considering… give it some thought…© Rick Strahl, West Wind Technologies, 2005-2013Posted in ASP.NET  SignalR  IIS   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • SQLAuthority News – SQLPASS Nov 8-11, 2010-Seattle – An Alternative Look at Experience

    - by pinaldave
    I recently attended most prestigious SQL Server event SQLPASS between Nov 8-11, 2010 at Seattle. I have only one expression for the event - Best Summit Ever This year the summit was at its best. Instead of writing about my usual routine or the event, I am going to write about the interesting things I did and how I felt about it! Best Summit Ever Trip to Seattle! This was my second trip to Seattle this year and the journey is always long. Here is the travel stats on how long it takes to get to Seattle: 24 hours official air time 36 hours total travel time (connection waits and airport commute) Every time I travel to USA I gain a day and when I travel back to home, I lose a day. However, the total traveling time is around 3 days. The journey is long and very exhausting. However, it is all worth it when you’re attending an event like SQLPASS. Here are few things I carry when I travel for a long journey: Dry Snack packs – I like to have some good Indian Dry Snacks along with me in my backpack so I can have my own snack when I want Amazon Kindle – Loaded with 80+ books A physical book – This is usually a very easy to read book I do not watch movies on the plane and usually spend my time reading something quick and easy. If I can go to sleep, I go for it. I prefer to not to spend time in conversation with the guy sitting next to me because usually I end up listening to their biography, which I cannot blog about. Sheraton Seattle SQLPASS In any case, I love to go to Seattle as the city is great and has everything a brilliant metropolis has to offer. The new Light Train is extremely convenient, and I can take it directly from the airport to the city center. My hotel, the Sheraton, was only few meters (in the USA people count in blocks – 3 blocks) away from the train station. This time I saved USD 40 each round trip due to the Light Train. Sessions I attended! Well, I really wanted to attend most of the sessions but there was great dilemma of which ones to choose. There were many, many sessions to be attended and at any given time there was more than one good session being presented. I had decided to attend sessions in area performance tuning and I attended quite a few sessions this year, compared to what I was able to do last year. Here are few names of the speakers whose sessions I attended (please note, following great speakers are not listed in any order. I loved them and I enjoyed their sessions): Conor Cunningham Rushabh Mehta Buck Woody Brent Ozar Jonathan Kehayias Chris Leonard Bob Ward Grant Fritchey I had great fun attending their sessions. The sessions were meaningful and enlightening. It is hard to rate any session but I have found that the insights learned in Conor Cunningham’s sessions are the highlight of the PASS Summit. Rushabh Mehta at Keynote SQLPASS   Bucky Woody and Brent Ozar I always like the sessions where the speaker is much closer to the audience and has real world experience. I think speakers who have worked in the real world deliver the best content and most useful information. Sessions I did not like! Indeed there were few sessions I did not like it and I am not going to name them here. However, there were strong reasons I did not like their sessions, and here is why: Sessions were all theory and had no real world connections. All technical questions ended with confusing answers (lots of “I will get back to you on it,” “it depends,” “let us take this offline” and many more…) “I am God” kind of attitude in the speakers For example, I attended a session of one very well known speaker who is a specialist for one particular area. I was bit late for the session and was surprised to see that in a room that could hold 350 people there were only 30 attendees. After sitting there for 15 minutes, I realized why lots of people left. Very soon I found I preferred to stare out the window instead of listening to that particular speaker. One on One Talk! Many times people ask me what I really like about PASS. I always say the experience of meeting SQL legends and spending time with them one on one and LEARNING! Here is the quick list of the people I met during this event and spent more than 30 minutes with each of them talking about various subjects: Pinal Dave and Brad Shulz Pinal Dave and Rushabh Mehta Michael Coles and Pinal Dave Rushabh Mehta – It is always pleasure to meet with him. He is a man with lots of energy and a passion for community. He recently told me that he really wanted to turn PASS into resource for learning for every SQL Server Developer and Administrator in the world. I had great in-depth discussion regarding how a single person can contribute to a community. Michael Coles – I consider him my best friend. It is always fun to meet him. He is funny and very knowledgeable. I think there are very few people who are as expert as he is in encryption and spatial databases. Worth meeting him every single time. Glenn Berry – A real friend of everybody. He is very a simple person and very true to his heart. I think there is not a single person in whole community who does not like him. He is a friends of all and everybody likes him very much. I once again had time to sit with him and learn so much from him. As he is known as Dr. DMV, I can be his nurse in the area of DMV. Brad Schulz – I always wanted to meet him but never got chance until today. I had great time meeting him in person and we have spent considerable amount of time together discussing various T-SQL tricks and tips. I do not know where he comes up with all the different ideas but I enjoy reading his blog and sharing his wisdom with me. Jonathan Kehayias – He is drill sergeant in US army. If you get the impression that he is a giant with very strong personality – you are wrong. He is very kind and soft spoken DBA with strong performance tuning skills. I asked him how he has kept his two jobs separate and I got very good answer – just work hard and have passion for what you do. I attended his sessions and his presentation style is very unique.  I feel like he is speaking in a language I understand. Louis Davidson – I had never had a chance to sit with him and talk about technology before. He has so much wisdom and he is very kind. During the dinner, I had talked with him for long time and without hesitation he started to draw a schema for me on the menu. It was a wonderful experience to learn from a master at the dinner table. He explained to me the real and practical differences between third normal form and forth normal form. Honestly I did not know earlier, but now I do. Erland Sommarskog – This man needs no introduction, he is very well known and very clear in conveying his ideas. I learned a lot from him during the course of year. Every time I meet him, I learn something new and this time was no exception. Joe Webb – Joey is all about community and people, we had interesting conversation about community, MVP and how one can be helpful to community without losing passion for long time. It is always pleasant to talk to him and of course, I had fun time. Ross Mistry – I call him my brother many times because he indeed looks like my cousin. He provided me lots of insight of how one can write book and how he keeps his books simple to appeal to all the readers. A wonderful person and great friend. Ola Hallgren - I did not know he was coming to the summit. I had great time meeting him and had a wonderful conversation with him regarding his scripts and future community activities. Blythe Morrow – She used to be integrated part of SQL Server Community and PASS HQ. It was wonderful to meet her again and re-connect. She is wonderful person and I had a great time talking to her. Solid Quality Mentors – It is difficult to decide who to mention here. Instead of writing all the names, I am going to include a photo of our meeting. I had great fun meeting various members of our global branches. This year I was sitting with my Spanish speaking friends and had great fun as Javier Loria from Solid Quality translated lots of things for me. Party, Party and Parties Every evening there were various parties. I did attend almost all of them. Every party had different theme but the goal of all the parties the same – networking. Here are the few parties where I had lots of fun: Dell Reception Party Exhibitor Party Solid Quality Fun Party Red Gate Friends Party MVP Dinner Microsoft Party MVP Dinner Quest Party Gameworks PASS Party Volunteer Party at Garage Solid Quality Mentors (10 Members out of 120) They were all great networking opportunities and lots of fun. I really had great time meeting people at the various parties. There were few people everywhere – well, I will say I am among them – who hopped parties. NDA – Not Decided Agenda During the event there were few meetings marked “NDA.” Someone asked me “why are these things NDA?”  My response was simple: because they are not sure themselves. NDA stands for Not Decided Agenda. Toys, Giveaways and Luggage I admit, I was like child in Gameworks and was playing to win soft toys. I was doing it for my daughter. I must thank all of the people who gave me their cards to try my luck. I won 4 soft-toys for my daughter and it was fun. Also, thanks to Angel who did a final toy swap with me to get the desired toy for my daughter. I also collected ducks from Idera, as my daughter really loves them. Solid Quality Booth Each of the exhibitors was giving away something and I got so much stuff that my luggage got quite a bit bigger when I returned. Best Exhibitor Idera had SQLDoctor (a real magician and fun guy) to promote their new tool SQLDoctor. I really had a great time participating in the magic myself. At one point, the magician made my watch disappear.  I have seen better magic before, but this time it caught me unexpectedly and I was taken by surprise. I won many ducks again. The Common Question I heard the following common questions: I have seen you somewhere – who are you? – I am Pinal Dave. I did not know that Pinal is your first name and Dave is your last name, how do you pronounce your last name again? – Da-way How old are you? – I am as old as I can be. Are you an Indian because you look like one? – I did not answer this one. Where are you from? This question was usually asked after looking at my badge which says India. So did you really fly from India? – Yes, because I have seasickness so I do not prefer the sea journey. How long was the journey? – 24/36/12 (air travel time/total travel time/time zone difference) Why do you write on SQLAuthority.com? – Because I want to. I remember your daughter looks like you. – Is this even a question? Of course, she is daddy’s little girl. There were so many other questions, I will have to write another blog post about it. SQLPASS Again, Best Summit Ever! Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: About Me, Pinal Dave, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, SQLAuthority Author Visit, T SQL, Technology Tagged: SQLPASS

    Read the article

  • LLBLGen Pro feature highlights: automatic element name construction

    - by FransBouma
    (This post is part of a series of posts about features of the LLBLGen Pro system) One of the things one might take for granted but which has a huge impact on the time spent in an entity modeling environment is the way the system creates names for elements out of the information provided, in short: automatic element name construction. Element names are created in both directions of modeling: database first and model first and the more names the system can create for you without you having to rename them, the better. LLBLGen Pro has a rich, fine grained system for creating element names out of the meta-data available, which I'll describe more in detail below. First the model element related element naming features are highlighted, in the section Automatic model element naming features and after that I'll go more into detail about the relational model element naming features LLBLGen Pro has to offer in the section Automatic relational model element naming features. Automatic model element naming features When working database first, the element names in the model, e.g. entity names, entity field names and so on, are in general determined from the relational model element (e.g. table, table field) they're mapped on, as the model elements are reverse engineered from these relational model elements. It doesn't take rocket science to automatically name an entity Customer if the entity was created after reverse engineering a table named Customer. It gets a little trickier when the entity which was created by reverse engineering a table called TBL_ORDER_LINES has to be named 'OrderLine' automatically. Automatic model element naming also takes into effect with model first development, where some settings are used to provide you with a default name, e.g. in the case of navigator name creation when you create a new relationship. The features below are available to you in the Project Settings. Open Project Settings on a loaded project and navigate to Conventions -> Element Name Construction. Strippers! The above example 'TBL_ORDER_LINES' shows that some parts of the table name might not be needed for name creation, in this case the 'TBL_' prefix. Some 'brilliant' DBAs even add suffixes to table names, fragments you might not want to appear in the entity names. LLBLGen Pro offers you to define both prefix and suffix fragments to strip off of table, view, stored procedure, parameter, table field and view field names. In the example above, the fragment 'TBL_' is a good candidate for such a strip pattern. You can specify more than one pattern for e.g. the table prefix strip pattern, so even a really messy schema can still be used to produce clean names. Underscores Be Gone Another thing you might get rid of are underscores. After all, most naming schemes for entities and their classes use PasCal casing rules and don't allow for underscores to appear. LLBLGen Pro can automatically strip out underscores for you. It's an optional feature, so if you like the underscores, you're not forced to see them go: LLBLGen Pro will leave them alone when ordered to to so. PasCal everywhere... or not, your call LLBLGen Pro can automatically PasCal case names on word breaks. It determines word breaks in a couple of ways: a space marks a word break, an underscore marks a word break and a case difference marks a word break. It will remove spaces in all cases, and based on the underscore removal setting, keep or remove the underscores, and upper-case the first character of a word break fragment, and lower case the rest. Say, we keep the defaults, which is remove underscores and PasCal case always and strip the TBL_ fragment, we get with our example TBL_ORDER_LINES, after stripping TBL_ from the table name two word fragments: ORDER and LINES. The underscores are removed, the first character of each fragment is upper-cased, the rest lower-cased, so this results in OrderLines. Almost there! Pluralization and Singularization In general entity names are singular, like Customer or OrderLine so LLBLGen Pro offers a way to singularize the names. This will convert OrderLines, the result we got after the PasCal casing functionality, into OrderLine, exactly what we're after. Show me the patterns! There are other situations in which you want more flexibility. Say, you have an entity Customer and an entity Order and there's a foreign key constraint defined from the target of Order and the target of Customer. This foreign key constraint results in a 1:n relationship between the entities Customer and Order. A relationship has navigators mapped onto the relationship in both entities the relationship is between. For this particular relationship we'd like to have Customer as navigator in Order and Orders as navigator in Customer, so the relationship becomes Customer.Orders 1:n Order.Customer. To control the naming of these navigators for the various relationship types, LLBLGen Pro defines a set of patterns which allow you, using macros, to define how the auto-created navigator names will look like. For example, if you rather have Customer.OrderCollection, you can do so, by changing the pattern from {$EndEntityName$P} to {$EndEntityName}Collection. The $P directive makes sure the name is pluralized, which is not what you want if you're going for <EntityName>Collection, hence it's removed. When working model first, it's a given you'll create foreign key fields along the way when you define relationships. For example, you've defined two entities: Customer and Order, and they have their fields setup properly. Now you want to define a relationship between them. This will automatically create a foreign key field in the Order entity, which reflects the value of the PK field in Customer. (No worries if you hate the foreign key fields in your classes, on NHibernate and EF these can be hidden in the generated code if you want to). A specific pattern is available for you to direct LLBLGen Pro how to name this foreign key field. For example, if all your entities have Id as PK field, you might want to have a different name than Id as foreign key field. In our Customer - Order example, you might want to have CustomerId instead as foreign key name in Order. The pattern for foreign key fields gives you that freedom. Abbreviations... make sense of OrdNr and friends I already described word breaks in the PasCal casing paragraph, how they're used for the PasCal casing in the constructed name. Word breaks are used for another neat feature LLBLGen Pro has to offer: abbreviation support. Burt, your friendly DBA in the dungeons below the office has a hate-hate relationship with his keyboard: he can't stand it: typing is something he avoids like the plague. This has resulted in tables and fields which have names which are very short, but also very unreadable. Example: our TBL_ORDER_LINES example has a lovely field called ORD_NR. What you would like to see in your fancy new OrderLine entity mapped onto this table is a field called OrderNumber, not a field called OrdNr. What you also like is to not have to rename that field manually. There are better things to do with your time, after all. LLBLGen Pro has you covered. All it takes is to define some abbreviation - full word pairs and during reverse engineering model elements from tables/views, LLBLGen Pro will take care of the rest. For the ORD_NR field, you need two values: ORD as abbreviation and Order as full word, and NR as abbreviation and Number as full word. LLBLGen Pro will now convert every word fragment found with the word breaks which matches an abbreviation to the given full word. They're case sensitive and can be found in the Project Settings: Navigate to Conventions -> Element Name Construction -> Abbreviations. Automatic relational model element naming features Not everyone works database first: it may very well be the case you start from scratch, or have to add additional tables to an existing database. For these situations, it's key you have the flexibility that you can control the created table names and table fields without any work: let the designer create these names based on the entity model you defined and a set of rules. LLBLGen Pro offers several features in this area, which are described in more detail below. These features are found in Project Settings: navigate to Conventions -> Model First Development. Underscores, welcome back! Not every database is case insensitive, and not every organization requires PasCal cased table/field names, some demand all lower or all uppercase names with underscores at word breaks. Say you create an entity model with an entity called OrderLine. You work with Oracle and your organization requires underscores at word breaks: a table created from OrderLine should be called ORDER_LINE. LLBLGen Pro allows you to do that: with a simple checkbox you can order LLBLGen Pro to insert an underscore at each word break for the type of database you're working with: case sensitive or case insensitive. Checking the checkbox Insert underscore at word break case insensitive dbs will let LLBLGen Pro create a table from the entity called Order_Line. Half-way there, as there are still lower case characters there and you need all caps. No worries, see below Casing directives so everyone can sleep well at night For case sensitive databases and case insensitive databases there is one setting for each of them which controls the casing of the name created from a model element (e.g. a table created from an entity definition using the auto-mapping feature). The settings can have the following values: AsProjectElement, AllUpperCase or AllLowerCase. AsProjectElement is the default, and it keeps the casing as-is. In our example, we need to get all upper case characters, so we select AllUpperCase for the setting for case sensitive databases. This will produce the name ORDER_LINE. Sequence naming after a pattern Some databases support sequences, and using model-first development it's key to have sequences, when needed, to be created automatically and if possible using a name which shows where they're used. Say you have an entity Order and you want to have the PK values be created by the database using a sequence. The database you're using supports sequences (e.g. Oracle) and as you want all numeric PK fields to be sequenced, you have enabled this by the setting Auto assign sequences to integer pks. When you're using LLBLGen Pro's auto-map feature, to create new tables and constraints from the model, it will create a new table, ORDER, based on your settings I previously discussed above, with a PK field ID and it also creates a sequence, SEQ_ORDER, which is auto-assigns to the ID field mapping. The name of the sequence is created by using a pattern, defined in the Model First Development setting Sequence pattern, which uses plain text and macros like with the other patterns previously discussed. Grouping and schemas When you start from scratch, and you're working model first, the tables created by LLBLGen Pro will be in a catalog and / or schema created by LLBLGen Pro as well. If you use LLBLGen Pro's grouping feature, which allows you to group entities and other model elements into groups in the project (described in a future blog post), you might want to have that group name reflected in the schema name the targets of the model elements are in. Say you have a model with a group CRM and a group HRM, both with entities unique for these groups, e.g. Employee in HRM, Customer in CRM. When auto-mapping this model to create tables, you might want to have the table created for Employee in the HRM schema but the table created for Customer in the CRM schema. LLBLGen Pro will do just that when you check the setting Set schema name after group name to true (default). This gives you total control over where what is placed in the database from your model. But I want plural table names... and TBL_ prefixes! For now we follow best practices which suggest singular table names and no prefixes/suffixes for names. Of course that won't keep everyone happy, so we're looking into making it possible to have that in a future version. Conclusion LLBLGen Pro offers a variety of options to let the modeling system do as much work for you as possible. Hopefully you enjoyed this little highlight post and that it has given you new insights in the smaller features available to you in LLBLGen Pro, ones you might not have thought off in the first place. Enjoy!

    Read the article

  • Pain Comes Instantly

    - by user701213
    When I look back at recent blog entries – many of which are not all that current (more on where my available writing time is going later) – I am struck by how many of them focus on public policy or legislative issues instead of, say, the latest nefarious cyberattack or exploit (or everyone’s favorite new pastime: coining terms for the Coming Cyberpocalypse: “digital Pearl Harbor” is so 1941). Speaking of which, I personally hope evil hackers from Malefactoria will someday hack into my bathroom scale – which in a future time will be connected to the Internet because, gosh, wouldn’t it be great to have absolutely everything in your life Internet-enabled? – and recalibrate it so I’m 10 pounds thinner. The horror. In part, my focus on public policy is due to an admitted limitation of my skill set. I enjoy reading technical articles about exploits and cybersecurity trends, but writing a blog entry on those topics would take more research than I have time for and, quite honestly, doesn’t play to my strengths. The first rule of writing is “write what you know.” The bigger contributing factor to my recent paucity of blog entries is that more and more of my waking hours are spent engaging in “thrust and parry” activity involving emerging regulations of some sort or other. I’ve opined in earlier blogs about what constitutes good and reasonable public policy so nobody can accuse me of being reflexively anti-regulation. That said, you have so many cycles in the day, and most of us would rather spend it slaying actual dragons than participating in focus groups on whether dragons are really a problem, whether lassoing them (with organic, sustainable and recyclable lassos) is preferable to slaying them – after all, dragons are people, too - and whether we need lasso compliance auditors to make sure lassos are being used correctly and humanely. (A point that seems to evade many rule makers: slaying dragons actually accomplishes something, whereas talking about “approved dragon slaying procedures and requirements” wastes the time of those who are competent to dispatch actual dragons and who were doing so very well without the input of “dragon-slaying theorists.”) Unfortunately for so many of us who would just get on with doing our day jobs, cybersecurity is rapidly devolving into the “focus groups on dragon dispatching” realm, which actual dragons slayers have little choice but to participate in. The general trend in cybersecurity is that powers-that-be – which encompasses groups other than just legislators – are often increasingly concerned and therefore feel they need to Do Something About Cybersecurity. Many seem to believe that if only we had the right amount of regulation and oversight, there would be no data breaches: a breach simply must mean Someone Is At Fault and Needs Supervision. (Leaving aside the fact that we have lots of home invasions despite a) guard dogs b) liberal carry permits c) alarm systems d) etc.) Also note that many well-managed and security-aware organizations, like the US Department of Defense, still get hacked. More specifically, many powers-that-be feel they must direct industry in a multiplicity of ways, up to and including how we actually build and deploy information technology systems. The more prescriptive the requirement, the more regulators or overseers a) can be seen to be doing something b) feel as if they are doing something regardless of whether they are actually doing something useful or cost effective. Note: an unfortunate concomitant of Doing Something is that often the cure is worse than the ailment. That is, doing what overseers want creates unfortunate byproducts that they either didn’t foresee or worse, don’t care about. After all, the logic goes, we Did Something. Prescriptive practice in the IT industry is problematic for a number of reasons. For a start, prescriptive guidance is really only appropriate if: • It is cost effective• It is “current” (meaning, the guidance doesn’t require the use of the technical equivalent of buggy whips long after horse-drawn transportation has become passé)*• It is practical (that is, pragmatic, proven and effective in the real world, not theoretical and unproven)• It solves the right problem With the above in mind, heading up the list of “you must be joking” regulations are recent disturbing developments in the Payment Card Industry (PCI) world. I’d like to give PCI kahunas the benefit of the doubt about their intentions, except that efforts by Oracle among others to make them aware of “unfortunate side effects of your requirements” – which is as tactful I can be for reasons that I believe will become obvious below - have gone, to-date, unanswered and more importantly, unchanged. A little background on PCI before I get too wound up. In 2008, the Payment Card Industry (PCI) Security Standards Council (SSC) introduced the Payment Application Data Security Standard (PA-DSS). That standard requires vendors of payment applications to ensure that their products implement specific requirements and undergo security assessment procedures. In order to have an application listed as a Validated Payment Application (VPA) and available for use by merchants, software vendors are required to execute the PCI Payment Application Vendor Release Agreement (VRA). (Are you still with me through all the acronyms?) Beginning in August 2010, the VRA imposed new obligations on vendors that are extraordinary and extraordinarily bad, short-sighted and unworkable. Specifically, PCI requires vendors to disclose (dare we say “tell all?”) to PCI any known security vulnerabilities and associated security breaches involving VPAs. ASAP. Think about the impact of that. PCI is asking a vendor to disclose to them: • Specific details of security vulnerabilities • Including exploit information or technical details of the vulnerability • Whether or not there is any mitigation available (as in a patch) PCI, in turn, has the right to blab about any and all of the above – specifically, to distribute all the gory details of what is disclosed - to the PCI SSC, qualified security assessors (QSAs), and any affiliate or agent or adviser of those entities, who are in turn permitted to share it with their respective affiliates, agents, employees, contractors, merchants, processors, service providers and other business partners. This assorted crew can’t be more than, oh, hundreds of thousands of entities. Does anybody believe that several hundred thousand people can keep a secret? Or that several hundred thousand people are all equally trustworthy? Or that not one of the people getting all that information would blab vulnerability details to a bad guy, even by accident? Or be a bad guy who uses the information to break into systems? (Wait, was that the Easter Bunny that just hopped by? Bringing world peace, no doubt.) Sarcasm aside, common sense tells us that telling lots of people a secret is guaranteed to “unsecret” the secret. Notably, being provided details of a vulnerability (without a patch) is of little or no use to companies running the affected application. Few users have the technological sophistication to create a workaround, and even if they do, most workarounds break some other functionality in the application or surrounding environment. Also, given the differences among corporate implementations of any application, it is highly unlikely that a single workaround is going to work for all corporate users. So until a patch is developed by the vendor, users remain at risk of exploit: even more so if the details of vulnerability have been widely shared. Sharing that information widely before a patch is available therefore does not help users, and instead helps only those wanting to exploit known security bugs. There’s a shocker for you. Furthermore, we already know that insider information about security vulnerabilities inevitably leaks, which is why most vendors closely hold such information and limit dissemination until a patch is available (and frequently limit dissemination of technical details even with the release of a patch). That’s the industry norm, not that PCI seems to realize or acknowledge that. Why would anybody release a bunch of highly technical exploit information to a cast of thousands, whose only “vetting” is that they are members of a PCI consortium? Oracle has had personal experience with this problem, which is one reason why information on security vulnerabilities at Oracle is “need to know” (we use our own row level access control to limit access to security bugs in our bug database, and thus less than 1% of development has access to this information), and we don’t provide some customers with more information than others or with vulnerability information and/or patches earlier than others. Failure to remember “insider information always leaks” creates problems in the general case, and has created problems for us specifically. A number of years ago, one of the UK intelligence agencies had information about a non-public security vulnerability in an Oracle product that they circulated among other UK and Commonwealth defense and intelligence entities. Nobody, it should be pointed out, bothered to report the problem to Oracle, even though only Oracle could produce a patch. The vulnerability was finally reported to Oracle by (drum roll) a US-based commercial company, to whom the information had leaked. (Note: every time I tell this story, the MI-whatever agency that created the problem gets a bit shirty with us. I know they meant well and have improved their vulnerability handling/sharing processes but, dudes, next time you find an Oracle vulnerability, try reporting it to us first before blabbing to lots of people who can’t actually fix the problem. Thank you!) Getting back to PCI: clearly, these new disclosure obligations increase the risk of exploitation of a vulnerability in a VPA and thus, of misappropriation of payment card data and customer information that a VPA processes, stores or transmits. It stands to reason that VRA’s current requirement for the widespread distribution of security vulnerability exploit details -- at any time, but particularly before a vendor can issue a patch or a workaround -- is very poor public policy. It effectively publicizes information of great value to potential attackers while not providing compensating benefits - actually, any benefits - to payment card merchants or consumers. In fact, it magnifies the risk to payment card merchants and consumers. The risk is most prominent in the time before a patch has been released, since customers often have little option but to continue using an application or system despite the risks. However, the risk is not limited to the time before a patch is issued: customers often need days, or weeks, to apply patches to systems, based upon the complexity of the issue and dependence on surrounding programs. Rather than decreasing the available window of exploit, this requirement increases the available window of exploit, both as to time available to exploit a vulnerability and the ease with which it can be exploited. Also, why would hackers focus on finding new vulnerabilities to exploit if they can get “EZHack” handed to them in such a manner: a) a vulnerability b) in a payment application c) with exploit code: the “Hacking Trifecta!“ It’s fair to say that this is probably the exact opposite of what PCI – or any of us – would want. Established industry practice concerning vulnerability handling avoids the risks created by the VRA’s vulnerability disclosure requirements. Specifically, the norm is not to release information about a security bug until the associated patch (or a pretty darn good workaround) has been issued. Once a patch is available, the notice to the user community is a high-level communication discussing the product at issue, the level of risk associated with the vulnerability, and how to apply the patch. The notices do not include either the specific customers affected by the vulnerability or forensic reports with maps of the exploit (both of which are required by the current VRA). In this way, customers have the tools they need to prioritize patching and to help prevent an attack, and the information released does not increase the risk of exploit. Furthermore, many vendors already use industry standards for vulnerability description: Common Vulnerability Enumeration (CVE) and Common Vulnerability Scoring System (CVSS). CVE helps ensure that customers know which particular issues a patch addresses and CVSS helps customers determine how severe a vulnerability is on a relative scale. Industry already provides the tools customers need to know what the patch contains and how bad the problem is that the patch remediates. So, what’s a poor vendor to do? Oracle is reaching out to other vendors subject to PCI and attempting to enlist then in a broad effort to engage PCI in rethinking (that is, eradicating) these requirements. I would therefore urge all who care about this issue, but especially those in the vendor community whose applications are subject to PCI and who may not have know they were being asked to tell-all to PCI and put their customers at risk, to do one of the following: • Contact PCI with your concerns• Contact Oracle (we are looking for vendors to sign our statement of concern)• And make sure you tell your customers that you have to rat them out to PCI if there is a breach involving the payment application I like to be charitable and say “PCI meant well” but in as important a public policy issue as what you disclose about vulnerabilities, to whom and when, meaning well isn’t enough. We need to do well. PCI, as regards this particular issue, has not done well, and has compounded the error by thus far being nonresponsive to those of us who have labored mightily to try to explain why they might want to rethink telling the entire planet about security problems with no solutions. By Way of Explanation… Non-related to PCI whatsoever, and the explanation for why I have not been blogging a lot recently, I have been working on Other Writing Venues with my sister Diane (who has also worked in the tech sector, inflicting upgrades on unsuspecting and largely ungrateful end users). I am pleased to note that we have recently (self-)published the first in the Miss Information Technology Murder Mystery series, Outsourcing Murder. The genre might best be described as “chick lit meets geek scene.” Our sisterly nom de plume is Maddi Davidson and (shameless plug follows): you can order the paper version of the book on Amazon, or the Kindle or Nook versions on www.amazon.com or www.bn.com, respectively. From our book jacket: Emma Jones, a 20-something IT consultant, is working on an outsourcing project at Tahiti Tacos, a restaurant chain offering Polynexican cuisine: refried poi, anyone? Emma despises her boss Padmanabh, a brilliant but arrogant partner in GD Consulting. When Emma discovers His-Royal-Padness’s body (verdict: death by cricket bat), she becomes a suspect.With her overprotective family and her best friend Stacey providing endless support and advice, Emma stumbles her way through an investigation of Padmanabh’s murder, bolstered by fusion food feeding frenzies, endless cups of frou-frou coffee and serious surfing sessions. While Stacey knows a PI who owes her a favor, landlady Magda urges Emma to tart up her underwear drawer before the next cute cop with a search warrant arrives. Emma’s mother offers to fix her up with a PhD student at Berkeley and showers her with self-defense gizmos while her old lover Keoni beckons from Hawai’i. And everyone, even Shaun the barista, knows a good lawyer. Book 2, Denial of Service, is coming out this summer. * Given the rate of change in technology, today’s “thou shalts” are easily next year’s “buggy whip guidance.”

    Read the article

  • The impossible inline Javascript delay/sleep

    - by trex005
    There is a JavaScript function, of which I have zero control of the code, which calls a function that I wrote. My function uses DOM to generate an iFrame, defines it's src and then appends it to another DOM element. However, before my function returns, and thus allows continued execution of the containing function, it is imperative that the iFrame be fully loaded. Here are the things that I have tried and why they do not work : 1. The SetTimeout option : 99.999% of the time, this is THE answer. As a matter of fact, in the past decade that I have been mentoring in JavaScript, I have always insisted that code could always be refactored to use this option, and never believed a scenario existed where that was not the case. Well, I finally found one! The problem is that because my function is being called inline, if the very next line is executed before my iFrame finishes loading, it totally neuters my script, and since the moment my script completes, the external script continues. A callback of sorts will not work 2. The "Do nothing" loop :This option you use while(//iFrame is not loaded){//do nothing}. In theory this would not return until the frame is loaded. The problem is that since this hogs all the resources, the iFrame never loads. This trick, although horribly unprofessional, dirty etc. will work when you just need an inline delay, but since I require an external thread to complete, it will not.In FF, after a few seconds, it pauses the script and an alert pops up stating that there is an unresponsive script. While that alert is up, the iFrame is able to load, and then my function is able to return, but having the browser frozen for 10 seconds, and then requiring the user to correctly dismiss an error is a no go. 3. The model dialogue : I was inspired by the fact that the FF popup allowed the iFrame to load while halting the execution of the function, and thinking about it, I realized that it is because the modal dialogue, is a way of halting execution yet allowing other threads to continue! Brilliant, so I decided to try other modal options. Things like alert() work beautifully! When it pops up, even if only up for 1/10th of a second, the iFrame is able to complete, and all works great. And just in case the 1/10 of a second is not sufficient, I can put the model dialogue in the while loop from solution 2, and it would ensure that the iFrame is loaded in time. Sweet right? Except for the fact that I now have to pop up a very unprofessional dialogue for the user to dismiss in order to run my script. I fought with myself about this cost/benefit of this action, but then I encountered a scenario where my code was called 10 times on a single page! Having to dismiss 10 alerts before acessing a page?! That reminds me of the late 90s script kiddie pages, and is NOT an option. 4. A gazillion other delay script out there:There are about 10 jQuery delay or sleep functions, some of them actually quite cleverly developed, but none worked. A few prototype options, and again, none I found could do it! A dozen or so other libraries and frameworks claimed they had what I needed, but alas they all conspired to give me false hope. I am convinced that since a built in model dialogue can halt execution, while allowing other threads to continue, there must be some code accessible way to do the same thing with out user input. The Code is literally thousands upon thousands of lines and is proprietary, so I wrote this little example of the problem for you to work with. It is important to note the ONLY code you are able to change is in the onlyThingYouCanChange function Test File : <html> <head> </head> </html> <body> <div id='iFrameHolder'></div> <script type='text/javascript'> function unChangeableFunction() { new_iFrame = onlyThingYouCanChange(document.getElementById('iFrameHolder')); new_iFrame_doc = (new_iFrame.contentWindow || new_iFrame.contentDocument); if(new_iFrame_doc.document)new_iFrame_doc=new_iFrame_doc.document; new_iFrame_body = new_iFrame_doc.body; if(new_iFrame_body.innerHTML != 'Loaded?') { //The world explodes!!! alert('you just blew up the world! Way to go!'); } else { alert('wow, you did it! Way to go!'); } } var iFrameLoaded = false; function onlyThingYouCanChange(objectToAppendIFrameTo) { iFrameLoaded = false; iframe=document.createElement('iframe'); iframe.onload = new Function('iFrameLoaded = true'); iframe.src = 'blank_frame.html'; //Must use an HTML doc on the server because there is a very specific DOM structure that must be maintained. objectToAppendIFrameTo.appendChild(iframe); var it = 0; while(!iFrameLoaded) //I put the limit on here so you don't { //If I was able to put some sort of delay here that paused the exicution of the script, but did not halt all other browser threads, and did not require user interaction we'd be golden! //alert('test'); //This would work if it did not require user interaction! } return iframe; } unChangeableFunction(); </script> </body> blank_frame.html : <html> <head> </head> <body style='margin:0px'>Loaded?</body> </html>

    Read the article

  • The broken Promise of the Mobile Web

    - by Rick Strahl
    High end mobile devices have been with us now for almost 7 years and they have utterly transformed the way we access information. Mobile phones and smartphones that have access to the Internet and host smart applications are in the hands of a large percentage of the population of the world. In many places even very remote, cell phones and even smart phones are a common sight. I’ll never forget when I was in India in 2011 I was up in the Southern Indian mountains riding an elephant out of a tiny local village, with an elephant herder in front riding atop of the elephant in front of us. He was dressed in traditional garb with the loin wrap and head cloth/turban as did quite a few of the locals in this small out of the way and not so touristy village. So we’re slowly trundling along in the forest and he’s lazily using his stick to guide the elephant and… 10 minutes in he pulls out his cell phone from his sash and starts texting. In the middle of texting a huge pig jumps out from the side of the trail and he takes a picture running across our path in the jungle! So yeah, mobile technology is very pervasive and it’s reached into even very buried and unexpected parts of this world. Apps are still King Apps currently rule the roost when it comes to mobile devices and the applications that run on them. If there’s something that you need on your mobile device your first step usually is to look for an app, not use your browser. But native app development remains a pain in the butt, with the requirement to have to support 2 or 3 completely separate platforms. There are solutions that try to bridge that gap. Xamarin is on a tear at the moment, providing their cross-device toolkit to build applications using C#. While Xamarin tools are impressive – and also *very* expensive – they only address part of the development madness that is app development. There are still specific device integration isssues, dealing with the different developer programs, security and certificate setups and all that other noise that surrounds app development. There’s also PhoneGap/Cordova which provides a hybrid solution that involves creating local HTML/CSS/JavaScript based applications, and then packaging them to run in a specialized App container that can run on most mobile device platforms using a WebView interface. This allows for using of HTML technology, but it also still requires all the set up, configuration of APIs, security keys and certification and submission and deployment process just like native applications – you actually lose many of the benefits that  Web based apps bring. The big selling point of Cordova is that you get to use HTML have the ability to build your UI once for all platforms and run across all of them – but the rest of the app process remains in place. Apps can be a big pain to create and manage especially when we are talking about specialized or vertical business applications that aren’t geared at the mainstream market and that don’t fit the ‘store’ model. If you’re building a small intra department application you don’t want to deal with multiple device platforms and certification etc. for various public or corporate app stores. That model is simply not a good fit both from the development and deployment perspective. Even for commercial, big ticket apps, HTML as a UI platform offers many advantages over native, from write-once run-anywhere, to remote maintenance, single point of management and failure to having full control over the application as opposed to have the app store overloads censor you. In a lot of ways Web based HTML/CSS/JavaScript applications have so much potential for building better solutions based on existing Web technologies for the very same reasons a lot of content years ago moved off the desktop to the Web. To me the Web as a mobile platform makes perfect sense, but the reality of today’s Mobile Web unfortunately looks a little different… Where’s the Love for the Mobile Web? Yet here we are in the middle of 2014, nearly 7 years after the first iPhone was released and brought the promise of rich interactive information at your fingertips, and yet we still don’t really have a solid mobile Web platform. I know what you’re thinking: “But we have lots of HTML/JavaScript/CSS features that allows us to build nice mobile interfaces”. I agree to a point – it’s actually quite possible to build nice looking, rich and capable Web UI today. We have media queries to deal with varied display sizes, CSS transforms for smooth animations and transitions, tons of CSS improvements in CSS 3 that facilitate rich layout, a host of APIs geared towards mobile device features and lately even a number of JavaScript framework choices that facilitate development of multi-screen apps in a consistent manner. Personally I’ve been working a lot with AngularJs and heavily modified Bootstrap themes to build mobile first UIs and that’s been working very well to provide highly usable and attractive UI for typical mobile business applications. From the pure UI perspective things actually look very good. Not just about the UI But it’s not just about the UI - it’s also about integration with the mobile device. When it comes to putting all those pieces together into what amounts to a consolidated platform to build mobile Web applications, I think we still have a ways to go… there are a lot of missing pieces to make it all work together and integrate with the device more smoothly, and more importantly to make it work uniformly across the majority of devices. I think there are a number of reasons for this. Slow Standards Adoption HTML standards implementations and ratification has been dreadfully slow, and browser vendors all seem to pick and choose different pieces of the technology they implement. The end result is that we have a capable UI platform that’s missing some of the infrastructure pieces to make it whole on mobile devices. There’s lots of potential but what is lacking that final 10% to build truly compelling mobile applications that can compete favorably with native applications. Some of it is the fragmentation of browsers and the slow evolution of the mobile specific HTML APIs. A host of mobile standards exist but many of the standards are in the early review stage and they have been there stuck for long periods of time and seem to move at a glacial pace. Browser vendors seem even slower to implement them, and for good reason – non-ratified standards mean that implementations may change and vendor implementations tend to be experimental and  likely have to be changed later. Neither Vendors or developers are not keen on changing standards. This is the typical chicken and egg scenario, but without some forward momentum from some party we end up stuck in the mud. It seems that either the standards bodies or the vendors need to carry the torch forward and that doesn’t seem to be happening quickly enough. Mobile Device Integration just isn’t good enough Current standards are not far reaching enough to address a number of the use case scenarios necessary for many mobile applications. While not every application needs to have access to all mobile device features, almost every mobile application could benefit from some integration with other parts of the mobile device platform. Integration with GPS, phone, media, messaging, notifications, linking and contacts system are benefits that are unique to mobile applications and could be widely used, but are mostly (with the exception of GPS) inaccessible for Web based applications today. Unfortunately trying to do most of this today only with a mobile Web browser is a losing battle. Aside from PhoneGap/Cordova’s app centric model with its own custom API accessing mobile device features and the token exception of the GeoLocation API, most device integration features are not widely supported by the current crop of mobile browsers. For example there’s no usable messaging API that allows access to SMS or contacts from HTML. Even obvious components like the Media Capture API are only implemented partially by mobile devices. There are alternatives and workarounds for some of these interfaces by using browser specific code, but that’s might ugly and something that I thought we were trying to leave behind with newer browser standards. But it’s not quite working out that way. It’s utterly perplexing to me that mobile standards like Media Capture and Streams, Media Gallery Access, Responsive Images, Messaging API, Contacts Manager API have only minimal or no traction at all today. Keep in mind we’ve had mobile browsers for nearly 7 years now, and yet we still have to think about how to get access to an image from the image gallery or the camera on some devices? Heck Windows Phone IE Mobile just gained the ability to upload images recently in the Windows 8.1 Update – that’s feature that HTML has had for 20 years! These are simple concepts and common problems that should have been solved a long time ago. It’s extremely frustrating to see build 90% of a mobile Web app with relative ease and then hit a brick wall for the remaining 10%, which often can be show stoppers. The remaining 10% have to do with platform integration, browser differences and working around the limitations that browsers and ‘pinned’ applications impose on HTML applications. The maddening part is that these limitations seem arbitrary as they could easily work on all mobile platforms. For example, SMS has a URL Moniker interface that sort of works on Android, works badly with iOS (only works if the address is already in the contact list) and not at all on Windows Phone. There’s no reason this shouldn’t work universally using the same interface – after all all phones have supported SMS since before the year 2000! But, it doesn’t have to be this way Change can happen very quickly. Take the GeoLocation API for example. Geolocation has taken off at the very beginning of the mobile device era and today it works well, provides the necessary security (a big concern for many mobile APIs), and is supported by just about all major mobile and even desktop browsers today. It handles security concerns via prompts to avoid unwanted access which is a model that would work for most other device APIs in a similar fashion. One time approval and occasional re-approval if code changes or caches expire. Simple and only slightly intrusive. It all works well, even though GeoLocation actually has some physical limitations, such as representing the current location when no GPS device is present. Yet this is a solved problem, where other APIs that are conceptually much simpler to implement have failed to gain any traction at all. Technically none of these APIs should be a problem to implement, but it appears that the momentum is just not there. Inadequate Web Application Linking and Activation Another important piece of the puzzle missing is the integration of HTML based Web applications. Today HTML based applications are not first class citizens on mobile operating systems. When talking about HTML based content there’s a big difference between content and applications. Content is great for search engine discovery and plain browser usage. Content is usually accessed intermittently and permanent linking is not so critical for this type of content.  But applications have different needs. Applications need to be started up quickly and must be easily switchable to support a multi-tasking user workflow. Therefore, it’s pretty crucial that mobile Web apps are integrated into the underlying mobile OS and work with the standard task management features. Unfortunately this integration is not as smooth as it should be. It starts with actually trying to find mobile Web applications, to ‘installing’ them onto a phone in an easily accessible manner in a prominent position. The experience of discovering a Mobile Web ‘App’ and making it sticky is by no means as easy or satisfying. Today the way you’d go about this is: Open the browser Search for a Web Site in the browser with your search engine of choice Hope that you find the right site Hope that you actually find a site that works for your mobile device Click on the link and run the app in a fully chrome’d browser instance (read tiny surface area) Pin the app to the home screen (with all the limitations outline above) Hope you pointed at the right URL when you pinned Even for you and me as developers, there are a few steps in there that are painful and annoying, but think about the average user. First figuring out how to search for a specific site or URL? And then pinning the app and hopefully from the right location? You’ve probably lost more than half of your audience at that point. This experience sucks. For developers too this process is painful since app developers can’t control the shortcut creation directly. This problem often gets solved by crazy coding schemes, with annoying pop-ups that try to get people to create shortcuts via fancy animations that are both annoying and add overhead to each and every application that implements this sort of thing differently. And that’s not the end of it - getting the link onto the home screen with an application icon varies quite a bit between browsers. Apple’s non-standard meta tags are prominent and they work with iOS and Android (only more recent versions), but not on Windows Phone. Windows Phone instead requires you to create an actual screen or rather a partial screen be captured for a shortcut in the tile manager. Who had that brilliant idea I wonder? Surprisingly Chrome on recent Android versions seems to actually get it right – icons use pngs, pinning is easy and pinned applications properly behave like standalone apps and retain the browser’s active page state and content. Each of the platforms has a different way to specify icons (WP doesn’t allow you to use an icon image at all), and the most widely used interface in use today is a bunch of Apple specific meta tags that other browsers choose to support. The question is: Why is there no standard implementation for installing shortcuts across mobile platforms using an official format rather than a proprietary one? Then there’s iOS and the crazy way it treats home screen linked URLs using a crazy hybrid format that is neither as capable as a Web app running in Safari nor a WebView hosted application. Moving off the Web ‘app’ link when switching to another app actually causes the browser and preview it to ‘blank out’ the Web application in the Task View (see screenshot on the right). Then, when the ‘app’ is reactivated it ends up completely restarting the browser with the original link. This is crazy behavior that you can’t easily work around. In some situations you might be able to store the application state and restore it using LocalStorage, but for many scenarios that involve complex data sources (like say Google Maps) that’s not a possibility. The only reason for this screwed up behavior I can think of is that it is deliberate to make Web apps a pain in the butt to use and forcing users trough the App Store/PhoneGap/Cordova route. App linking and management is a very basic problem – something that we essentially have solved in every desktop browser – yet on mobile devices where it arguably matters a lot more to have easy access to web content we have to jump through hoops to have even a remotely decent linking/activation experience across browsers. Where’s the Money? It’s not surprising that device home screen integration and Mobile Web support in general is in such dismal shape – the mobile OS vendors benefit financially from App store sales and have little to gain from Web based applications that bypass the App store and the cash cow that it presents. On top of that, platform specific vendor lock-in of both end users and developers who have invested in hardware, apps and consumables is something that mobile platform vendors actually aspire to. Web based interfaces that are cross-platform are the anti-thesis of that and so again it’s no surprise that the mobile Web is on a struggling path. But – that may be changing. More and more we’re seeing operations shifting to services that are subscription based or otherwise collect money for usage, and that may drive more progress into the Web direction in the end . Nothing like the almighty dollar to drive innovation forward. Do we need a Mobile Web App Store? As much as I dislike moderated experiences in today’s massive App Stores, they do at least provide one single place to look for apps for your device. I think we could really use some sort of registry, that could provide something akin to an app store for mobile Web apps, to make it easier to actually find mobile applications. This could take the form of a specialized search engine, or maybe a more formal store/registry like structure. Something like apt-get/chocolatey for Web apps. It could be curated and provide at least some feedback and reviews that might help with the integrity of applications. Coupled to that could be a native application on each platform that would allow searching and browsing of the registry and then also handle installation in the form of providing the home screen linking, plus maybe an initial security configuration that determines what features are allowed access to for the app. I’m not holding my breath. In order for this sort of thing to take off and gain widespread appeal, a lot of coordination would be required. And in order to get enough traction it would have to come from a well known entity – a mobile Web app store from a no name source is unlikely to gain high enough usage numbers to make a difference. In a way this would eliminate some of the freedom of the Web, but of course this would also be an optional search path in addition to the standard open Web search mechanisms to find and access content today. Security Security is a big deal, and one of the perceived reasons why so many IT professionals appear to be willing to go back to the walled garden of deployed apps is that Apps are perceived as safe due to the official review and curation of the App stores. Curated stores are supposed to protect you from malware, illegal and misleading content. It doesn’t always work out that way and all the major vendors have had issues with security and the review process at some time or another. Security is critical, but I also think that Web applications in general pose less of a security threat than native applications, by nature of the sandboxed browser and JavaScript environments. Web applications run externally completely and in the HTML and JavaScript sandboxes, with only a very few controlled APIs allowing access to device specific features. And as discussed earlier – security for any device interaction can be granted the same for mobile applications through a Web browser, as they can for native applications either via explicit policies loaded from the Web, or via prompting as GeoLocation does today. Security is important, but it’s certainly solvable problem for Web applications even those that need to access device hardware. Security shouldn’t be a reason for Web apps to be an equal player in mobile applications. Apps are winning, but haven’t we been here before? So now we’re finding ourselves back in an era of installed app, rather than Web based and managed apps. Only it’s even worse today than with Desktop applications, in that the apps are going through a gatekeeper that charges a toll and censors what you can and can’t do in your apps. Frankly it’s a mystery to me why anybody would buy into this model and why it’s lasted this long when we’ve already been through this process. It’s crazy… It’s really a shame that this regression is happening. We have the technology to make mobile Web apps much more prominent, but yet we’re basically held back by what seems little more than bureaucracy, partisan bickering and self interest of the major parties involved. Back in the day of the desktop it was Internet Explorer’s 98+%  market shareholding back the Web from improvements for many years – now it’s the combined mobile OS market in control of the mobile browsers. If mobile Web apps were allowed to be treated the same as native apps with simple ways to install and run them consistently and persistently, that would go a long way to making mobile applications much more usable and seriously viable alternatives to native apps. But as it is mobile apps have a severe disadvantage in placement and operation. There are a few bright spots in all of this. Mozilla’s FireFoxOs is embracing the Web for it’s mobile OS by essentially building every app out of HTML and JavaScript based content. It supports both packaged and certified package modes (that can be put into the app store), and Open Web apps that are loaded and run completely off the Web and can also cache locally for offline operation using a manifest. Open Web apps are treated as full class citizens in FireFoxOS and run using the same mechanism as installed apps. Unfortunately FireFoxOs is getting a slow start with minimal device support and specifically targeting the low end market. We can hope that this approach will change and catch on with other vendors, but that’s also an uphill battle given the conflict of interest with platform lock in that it represents. Recent versions of Android also seem to be working reasonably well with mobile application integration onto the desktop and activation out of the box. Although it still uses the Apple meta tags to find icons and behavior settings, everything at least works as you would expect – icons to the desktop on pinning, WebView based full screen activation, and reliable application persistence as the browser/app is treated like a real application. Hopefully iOS will at some point provide this same level of rudimentary Web app support. What’s also interesting to me is that Microsoft hasn’t picked up on the obvious need for a solid Web App platform. Being a distant third in the mobile OS war, Microsoft certainly has nothing to lose and everything to gain by using fresh ideas and expanding into areas that the other major vendors are neglecting. But instead Microsoft is trying to beat the market leaders at their own game, fighting on their adversary’s terms instead of taking a new tack. Providing a kick ass mobile Web platform that takes the lead on some of the proposed mobile APIs would be something positive that Microsoft could do to improve its miserable position in the mobile device market. Where are we at with Mobile Web? It sure sounds like I’m really down on the Mobile Web, right? I’ve built a number of mobile apps in the last year and while overall result and response has been very positive to what we were able to accomplish in terms of UI, getting that final 10% that required device integration dialed was an absolute nightmare on every single one of them. Big compromises had to be made and some features were left out or had to be modified for some devices. In two cases we opted to go the Cordova route in order to get the integration we needed, along with the extra pain involved in that process. Unless you’re not integrating with device features and you don’t care deeply about a smooth integration with the mobile desktop, mobile Web development is fraught with frustration. So, yes I’m frustrated! But it’s not for lack of wanting the mobile Web to succeed. I am still a firm believer that we will eventually arrive a much more functional mobile Web platform that allows access to the most common device features in a sensible way. It wouldn't be difficult for device platform vendors to make Web based applications first class citizens on mobile devices. But unfortunately it looks like it will still be some time before this happens. So, what’s your experience building mobile Web apps? Are you finding similar issues? Just giving up on raw Web applications and building PhoneGap apps instead? Completely skipping the Web and going native? Leave a comment for discussion. Resources Rick Strahl on DotNet Rocks talking about Mobile Web© Rick Strahl, West Wind Technologies, 2005-2014Posted in HTML5  Mobile   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • ANTS CLR and Memory Profiler In Depth Review (Part 1 of 2 &ndash; CLR Profiler)

    - by ToStringTheory
    One of the things that people might not know about me, is my obsession to make my code as efficient as possible.  Many people might not realize how much of a task or undertaking that this might be, but it is surely a task as monumental as climbing Mount Everest, except this time it is a challenge for the mind…  In trying to make code efficient, there are many different factors that play a part – size of project or solution, tiers, language used, experience and training of the programmer, technologies used, maintainability of the code – the list can go on for quite some time. I spend quite a bit of time when developing trying to determine what is the best way to implement a feature to accomplish the efficiency that I look to achieve.  One program that I have recently come to learn about – Red Gate ANTS Performance (CLR) and Memory profiler gives me tools to accomplish that job more efficiently as well.  In this review, I am going to cover some of the features of the ANTS profiler set by compiling some hideous example code to test against. Notice As a member of the Geeks With Blogs Influencers program, one of the perks is the ability to review products, in exchange for a free license to the program.  I have not let this affect my opinions of the product in any way, and Red Gate nor Geeks With Blogs has tried to influence my opinion regarding this product in any way. Introduction The ANTS Profiler pack provided by Red Gate was something that I had not heard of before receiving an email regarding an offer to review it for a license.  Since I look to make my code efficient, it was a no brainer for me to try it out!  One thing that I have to say took me by surprise is that upon downloading the program and installing it you fill out a form for your usual contact information.  Sure enough within 2 hours, I received an email from a sales representative at Red Gate asking if she could help me to achieve the most out of my trial time so it wouldn’t go to waste.  After replying to her and explaining that I was looking to review its feature set, she put me in contact with someone that setup a demo session to give me a quick rundown of its features via an online meeting.  After having dealt with a massive ordeal with one of my utility companies and their complete lack of customer service, Red Gates friendly and helpful representatives were a breath of fresh air, and something I was thankful for. ANTS CLR Profiler The ANTS CLR profiler is the thing I want to focus on the most in this post, so I am going to dive right in now. Install was simple and took no time at all.  It installed both the profiler for the CLR and Memory, but also visual studio extensions to facilitate the usage of the profilers (click any images for full size images): The Visual Studio menu options (under ANTS menu) Starting the CLR Performance Profiler from the start menu yields this window If you follow the instructions after launching the program from the start menu (Click File > New Profiling Session to start a new project), you are given a dialog with plenty of options for profiling: The New Session dialog.  Lots of options.  One thing I noticed is that the buttons in the lower right were half-covered by the panel of the application.  If I had to guess, I would imagine that this is caused by my DPI settings being set to 125%.  This is a problem I have seen in other applications as well that don’t scale well to different dpi scales. The profiler options give you the ability to profile: .NET Executable ASP.NET web application (hosted in IIS) ASP.NET web application (hosted in IIS express) ASP.NET web application (hosted in Cassini Web Development Server) SharePoint web application (hosted in IIS) Silverlight 4+ application Windows Service COM+ server XBAP (local XAML browser application) Attach to an already running .NET 4 process Choosing each option provides a varying set of other variables/options that one can set including options such as application arguments, operating path, record I/O performance performance counters to record (43 counters in all!), etc…  All in all, they give you the ability to profile many different .Net project types, and make it simple to do so.  In most cases of my using this application, I would be using the built in Visual Studio extensions, as they automatically start a new profiling project in ANTS with the options setup, and start your program, however RedGate has made it easy enough to profile outside of Visual Studio as well. On the flip side of this, as someone who lives most of their work life in Visual Studio, one thing I do wish is that instead of opening an entirely separate application/gui to perform profiling after launching, that instead they would provide a Visual Studio panel with the information, and integrate more of the profiling project information into Visual Studio.  So, now that we have an idea of what options that the profiler gives us, its time to test its abilities and features. Horrendous Example Code – Prime Number Generator One of my interests besides development, is Physics and Math – what I went to college for.  I have especially always been interested in prime numbers, as they are something of a mystery…  So, I decided that I would go ahead and to test the abilities of the profiler, I would write a small program, website, and library to generate prime numbers in the quantity that you ask for.  I am going to start off with some terrible code, and show how I would see the profiler being used as a development tool. First off, the IPrimes interface (all code is downloadable at the end of the post): interface IPrimes { IEnumerable<int> GetPrimes(int retrieve); } Simple enough, right?  Anything that implements the interface will (hopefully) provide an IEnumerable of int, with the quantity specified in the parameter argument.  Next, I am going to implement this interface in the most basic way: public class DumbPrimes : IPrimes { public IEnumerable<int> GetPrimes(int retrieve) { //store a list of primes already found var _foundPrimes = new List<int>() { 2, 3 }; //if i ask for 1 or two primes, return what asked for if (retrieve <= _foundPrimes.Count()) return _foundPrimes.Take(retrieve); //the next number to look at int _analyzing = 4; //since I already determined I don't have enough //execute at least once, and until quantity is sufficed do { //assume prime until otherwise determined bool isPrime = true; //start dividing at 2 //divide until number is reached, or determined not prime for (int i = 2; i < _analyzing && isPrime; i++) { //if (i) goes into _analyzing without a remainder, //_analyzing is NOT prime if (_analyzing % i == 0) isPrime = false; } //if it is prime, add to found list if (isPrime) _foundPrimes.Add(_analyzing); //increment number to analyze next _analyzing++; } while (_foundPrimes.Count() < retrieve); return _foundPrimes; } } This is the simplest way to get primes in my opinion.  Checking each number by the straight definition of a prime – is it divisible by anything besides 1 and itself. I have included this code in a base class library for my solution, as I am going to use it to demonstrate a couple of features of ANTS.  This class library is consumed by a simple non-MVVM WPF application, and a simple MVC4 website.  I will not post the WPF code here inline, as it is simply an ObservableCollection<int>, a label, two textbox’s, and a button. Starting a new Profiling Session So, in Visual Studio, I have just completed my first stint developing the GUI and DumbPrimes IPrimes class, so now I want to check my codes efficiency by profiling it.  All I have to do is build the solution (surprised initiating a profiling session doesn’t do this, but I suppose I can understand it), and then click the ANTS menu, followed by Profile Performance.  I am then greeted by the profiler starting up and already monitoring my program live: You are provided with a realtime graph at the top, and a pane at the bottom giving you information on how to proceed.  I am going to start by asking my program to show me the first 15000 primes: After the program finally began responding again (I did all the work on the main UI thread – how bad!), I stopped the profiler, which did kill the process of my program too.  One important thing to note, is that the profiler by default wants to give you a lot of detail about the operation – line hit counts, time per line, percent time per line, etc…  The important thing to remember is that this itself takes a lot of time.  When running my program without the profiler attached, it can generate the 15000 primes in 5.18 seconds, compared to 74.5 seconds – almost a 1500 percent increase.  While this may seem like a lot, remember that there is a trade off.  It may be WAY more inefficient, however, I am able to drill down and make improvements to specific problem areas, and then decrease execution time all around. Analyzing the Profiling Session After clicking ‘Stop Profiling’, the process running my application stopped, and the entire execution time was automatically selected by ANTS, and the results shown below: Now there are a number of interesting things going on here, I am going to cover each in a section of its own: Real Time Performance Counter Bar (top of screen) At the top of the screen, is the real time performance bar.  As your application is running, this will constantly update with the currently selected performance counters status.  A couple of cool things to note are the fact that you can drag a selection around specific time periods to drill down the detail views in the lower 2 panels to information pertaining to only that period. After selecting a time period, you can bookmark a section and name it, so that it is easy to find later, or after reloaded at a later time.  You can also zoom in, out, or fit the graph to the space provided – useful for drilling down. It may be hard to see, but at the top of the processor time graph below the time ticks, but above the red usage graph, there is a green bar. This bar shows at what times a method that is selected in the ‘Call tree’ panel is called. Very cool to be able to click on a method and see at what times it made an impact. As I said before, ANTS provides 43 different performance counters you can hook into.  Click the arrow next to the Performance tab at the top will allow you to change between different counters if you have them selected: Method Call Tree, ADO.Net Database Calls, File IO – Detail Panel Red Gate really hit the mark here I think. When you select a section of the run with the graph, the call tree populates to fill a hierarchical tree of method calls, with information regarding each of the methods.   By default, methods are hidden where the source is not provided (framework type code), however, Red Gate has integrated Reflector into ANTS, so even if you don’t have source for something, you can select a method and get the source if you want.  Methods are also hidden where the impact is seen as insignificant – methods that are only executed for 1% of the time of the overall calling methods time; in other words, working on making them better is not where your efforts should be focused. – Smart! Source Panel – Detail Panel The source panel is where you can see line level information on your code, showing the code for the currently selected method from the Method Call Tree.  If the code is not available, Reflector takes care of it and shows the code anyways! As you can notice, there does seem to be a problem with how ANTS determines what line is the actual line that a call is completed on.  I have suspicions that this may be due to some of the inline code optimizations that the CLR applies upon compilation of the assembly.  In a method with comments, the problem is much more severe: As you can see here, apparently the most offending code in my base library was a comment – *gasp*!  Removing the comments does help quite a bit, however I hope that Red Gate works on their counter algorithm soon to improve the logic on positioning for statistics: I did a small test just to demonstrate the lines are correct without comments. For me, it isn’t a deal breaker, as I can usually determine the correct placements by looking at the application code in the region and determining what makes sense, but it is something that would probably build up some irritation with time. Feature – Suggest Method for Optimization A neat feature to really help those in need of a pointer, is the menu option under tools to automatically suggest methods to optimize/improve: Nice feature – clicking it filters the call tree and stars methods that it thinks are good candidates for optimization.  I do wish that they would have made it more visible for those of use who aren’t great on sight: Process Integration I do think that this could have a place in my process.  After experimenting with the profiler, I do think it would be a great benefit to do some development, testing, and then after all the bugs are worked out, use the profiler to check on things to make sure nothing seems like it is hogging more than its fair share.  For example, with this program, I would have developed it, ran it, tested it – it works, but slowly. After looking at the profiler, and seeing the massive amount of time spent in 1 method, I might go ahead and try to re-implement IPrimes (I actually would probably rewrite the offending code, but so that I can distribute both sets of code easily, I’m just going to make another implementation of IPrimes).  Using two pieces of knowledge about prime numbers can make this method MUCH more efficient – prime numbers fall into two buckets 6k+/-1 , and a number is prime if it is not divisible by any other primes before it: public class SmartPrimes : IPrimes { public IEnumerable<int> GetPrimes(int retrieve) { //store a list of primes already found var _foundPrimes = new List<int>() { 2, 3 }; //if i ask for 1 or two primes, return what asked for if (retrieve <= _foundPrimes.Count()) return _foundPrimes.Take(retrieve); //the next number to look at int _k = 1; //since I already determined I don't have enough //execute at least once, and until quantity is sufficed do { //assume prime until otherwise determined bool isPrime = true; int potentialPrime; //analyze 6k-1 //assign the value to potential potentialPrime = 6 * _k - 1; //if there are any primes that divise this, it is NOT a prime number //using PLINQ for quick boost isPrime = !_foundPrimes.AsParallel() .Any(prime => potentialPrime % prime == 0); //if it is prime, add to found list if (isPrime) _foundPrimes.Add(potentialPrime); if (_foundPrimes.Count() == retrieve) break; //analyze 6k+1 //assign the value to potential potentialPrime = 6 * _k + 1; //if there are any primes that divise this, it is NOT a prime number //using PLINQ for quick boost isPrime = !_foundPrimes.AsParallel() .Any(prime => potentialPrime % prime == 0); //if it is prime, add to found list if (isPrime) _foundPrimes.Add(potentialPrime); //increment k to analyze next _k++; } while (_foundPrimes.Count() < retrieve); return _foundPrimes; } } Now there are definitely more things I can do to help make this more efficient, but for the scope of this example, I think this is fine (but still hideous)! Profiling this now yields a happy surprise 27 seconds to generate the 15000 primes with the profiler attached, and only 1.43 seconds without.  One important thing I wanted to call out though was the performance graph now: Notice anything odd?  The %Processor time is above 100%.  This is because there is now more than 1 core in the operation.  A better label for the chart in my mind would have been %Core time, but to each their own. Another odd thing I noticed was that the profiler seemed to be spot on this time in my DumbPrimes class with line details in source, even with comments..  Odd. Profiling Web Applications The last thing that I wanted to cover, that means a lot to me as a web developer, is the great amount of work that Red Gate put into the profiler when profiling web applications.  In my solution, I have a simple MVC4 application setup with 1 page, a single input form, that will output prime values as my WPF app did.  Launching the profiler from Visual Studio as before, nothing is really different in the profiler window, however I did receive a UAC prompt for a Red Gate helper app to integrate with the web server without notification. After requesting 500, 1000, 2000, and 5000 primes, and looking at the profiler session, things are slightly different from before: As you can see, there are 4 spikes of activity in the processor time graph, but there is also something new in the call tree: That’s right – ANTS will actually group method calls by get/post operations, so it is easier to find out what action/page is giving the largest problems…  Pretty cool in my mind! Overview Overall, I think that Red Gate ANTS CLR Profiler has a lot to offer, however I think it also has a long ways to go.  3 Biggest Pros: Ability to easily drill down from time graph, to method calls, to source code Wide variety of counters to choose from when profiling your application Excellent integration/grouping of methods being called from web applications by request – BRILLIANT! 3 Biggest Cons: Issue regarding line details in source view Nit pick – Processor time vs. Core time Nit pick – Lack of full integration with Visual Studio Ratings Ease of Use (7/10) – I marked down here because of the problems with the line level details and the extra work that that entails, and the lack of better integration with Visual Studio. Effectiveness (10/10) – I believe that the profiler does EXACTLY what it purports to do.  Especially with its large variety of performance counters, a definite plus! Features (9/10) – Besides the real time performance monitoring, and the drill downs that I’ve shown here, ANTS also has great integration with ADO.Net, with the ability to show database queries run by your application in the profiler.  This, with the line level details, the web request grouping, reflector integration, and various options to customize your profiling session I think create a great set of features! Customer Service (10/10) – My entire experience with Red Gate personnel has been nothing but good.  their people are friendly, helpful, and happy! UI / UX (8/10) – The interface is very easy to get around, and all of the options are easy to find.  With a little bit of poking around, you’ll be optimizing Hello World in no time flat! Overall (8/10) – Overall, I am happy with the Performance Profiler and its features, as well as with the service I received when working with the Red Gate personnel.  I WOULD recommend you trying the application and seeing if it would fit into your process, BUT, remember there are still some kinks in it to hopefully be worked out. My next post will definitely be shorter (hopefully), but thank you for reading up to here, or skipping ahead!  Please, if you do try the product, drop me a message and let me know what you think!  I would love to hear any opinions you may have on the product. Code Feel free to download the code I used above – download via DropBox

    Read the article

  • Understanding and Implementing a Force based graph layout algorithm

    - by zcourts
    I'm trying to implement a force base graph layout algorithm, based on http://en.wikipedia.org/wiki/Force-based_algorithms_(graph_drawing) My first attempt didn't work so I looked at http://blog.ivank.net/force-based-graph-drawing-in-javascript.html and https://github.com/dhotson/springy I changed my implementation based on what I thought I understood from those two but I haven't managed to get it right and I'm hoping someone can help? JavaScript isn't my strong point so be gentle... If you're wondering why write my own. In reality I have no real reason to write my own I'm just trying to understand how the algorithm is implemented. Especially in my first link, that demo is brilliant. This is what I've come up with //support function.bind - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis || window, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); function Graph(o){ this.options=o; this.vertices={}; this.edges={};//form {vertexID:{edgeID:edge}} } /** *Adds an edge to the graph. If the verticies in this edge are not already in the *graph then they are added */ Graph.prototype.addEdge=function(e){ //if vertex1 and vertex2 doesn't exist in this.vertices add them if(typeof(this.vertices[e.vertex1])==='undefined') this.vertices[e.vertex1]=new Vertex(e.vertex1); if(typeof(this.vertices[e.vertex2])==='undefined') this.vertices[e.vertex2]=new Vertex(e.vertex2); //add the edge if(typeof(this.edges[e.vertex1])==='undefined') this.edges[e.vertex1]={}; this.edges[e.vertex1][e.id]=e; } /** * Add a vertex to the graph. If a vertex with the same ID already exists then * the existing vertex's .data property is replaced with the @param v.data */ Graph.prototype.addVertex=function(v){ if(typeof(this.vertices[v.id])==='undefined') this.vertices[v.id]=v; else this.vertices[v.id].data=v.data; } function Vertex(id,data){ this.id=id; this.data=data?data:{}; //initialize to data.[x|y|z] or generate random number for each this.x = this.data.x?this.data.x:-100 + Math.random()*200; this.y = this.data.y?this.data.y:-100 + Math.random()*200; this.z = this.data.y?this.data.y:-100 + Math.random()*200; //set initial velocity to 0 this.velocity = new Point(0, 0, 0); this.mass=this.data.mass?this.data.mass:Math.random(); this.force=new Point(0,0,0); } function Edge(vertex1ID,vertex2ID){ vertex1ID=vertex1ID?vertex1ID:Math.random() vertex2ID=vertex2ID?vertex2ID:Math.random() this.id=vertex1ID+"->"+vertex2ID; this.vertex1=vertex1ID; this.vertex2=vertex2ID; } function Point(x, y, z) { this.x = x; this.y = y; this.z = z; } Point.prototype.plus=function(p){ this.x +=p.x this.y +=p.y this.z +=p.z } function ForceLayout(o){ this.repulsion = o.repulsion?o.repulsion:200; this.attraction = o.attraction?o.attraction:0.06; this.damping = o.damping?o.damping:0.9; this.graph = o.graph?o.graph:new Graph(); this.total_kinetic_energy =0; this.animationID=-1; } ForceLayout.prototype.draw=function(){ //vertex velocities initialized to (0,0,0) when a vertex is created //vertex positions initialized to random position when created cc=0; do{ this.total_kinetic_energy =0; //for each vertex for(var i in this.graph.vertices){ var thisNode=this.graph.vertices[i]; // running sum of total force on this particular node var netForce=new Point(0,0,0) //for each other node for(var j in this.graph.vertices){ if(thisNode!=this.graph.vertices[j]){ //net-force := net-force + Coulomb_repulsion( this_node, other_node ) netForce.plus(this.CoulombRepulsion( thisNode,this.graph.vertices[j])) } } //for each spring connected to this node for(var k in this.graph.edges[thisNode.id]){ //(this node, node its connected to) //pass id of this node and the node its connected to so hookesattraction //can update the force on both vertices and return that force to be //added to the net force this.HookesAttraction(thisNode.id, this.graph.edges[thisNode.id][k].vertex2 ) } // without damping, it moves forever // this_node.velocity := (this_node.velocity + timestep * net-force) * damping thisNode.velocity.x=(thisNode.velocity.x+thisNode.force.x)*this.damping; thisNode.velocity.y=(thisNode.velocity.y+thisNode.force.y)*this.damping; thisNode.velocity.z=(thisNode.velocity.z+thisNode.force.z)*this.damping; //this_node.position := this_node.position + timestep * this_node.velocity thisNode.x=thisNode.velocity.x; thisNode.y=thisNode.velocity.y; thisNode.z=thisNode.velocity.z; //normalize x,y,z??? //total_kinetic_energy := total_kinetic_energy + this_node.mass * (this_node.velocity)^2 this.total_kinetic_energy +=thisNode.mass*((thisNode.velocity.x+thisNode.velocity.y+thisNode.velocity.z)* (thisNode.velocity.x+thisNode.velocity.y+thisNode.velocity.z)) } cc+=1; }while(this.total_kinetic_energy >0.5) console.log(cc,this.total_kinetic_energy,this.graph) this.cancelAnimation(); } ForceLayout.prototype.HookesAttraction=function(v1ID,v2ID){ var a=this.graph.vertices[v1ID] var b=this.graph.vertices[v2ID] var force=new Point(this.attraction*(b.x - a.x),this.attraction*(b.y - a.y),this.attraction*(b.z - a.z)) // hook's attraction a.force.x += force.x; a.force.y += force.y; a.force.z += force.z; b.force.x += this.attraction*(a.x - b.x); b.force.y += this.attraction*(a.y - b.y); b.force.z += this.attraction*(a.z - b.z); return force; } ForceLayout.prototype.CoulombRepulsion=function(vertex1,vertex2){ //http://en.wikipedia.org/wiki/Coulomb's_law // distance squared = ((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)) + ((z1-z2)*(z1-z2)) var distanceSquared = ( (vertex1.x-vertex2.x)*(vertex1.x-vertex2.x)+ (vertex1.y-vertex2.y)*(vertex1.y-vertex2.y)+ (vertex1.z-vertex2.z)*(vertex1.z-vertex2.z) ); if(distanceSquared==0) distanceSquared = 0.001; var coul = this.repulsion / distanceSquared; return new Point(coul * (vertex1.x-vertex2.x),coul * (vertex1.y-vertex2.y), coul * (vertex1.z-vertex2.z)); } ForceLayout.prototype.animate=function(){ if(this.animating) this.animationID=requestAnimationFrame(this.animate.bind(this)); this.draw(); } ForceLayout.prototype.cancelAnimation=function(){ cancelAnimationFrame(this.animationID); this.animating=false; } ForceLayout.prototype.redraw=function(){ this.animating=true; this.animate(); } $(document).ready(function(){ var g= new Graph(); for(var i=0;i<=100;i++){ var v1=new Vertex(Math.random(), {}) var v2=new Vertex(Math.random(), {}) var e1= new Edge(v1.id,v2.id); g.addEdge(e1); } console.log(g); var l=new ForceLayout({ graph:g }); l.redraw(); });

    Read the article

  • Silverlight Recruiting Application Part 6 - Adding an Interview Scheduling Module/View

    Between the last post and this one I went ahead and carried the ideas for the Jobs module and view into the Applicants module and view- they're both doing more or less the same thing, except with different objects being at their core.  Made for an easy cut-and-paste operation with a few items being switched from one to another.  Now that we have the ability to add postings and applicants, wouldn't it be nice if we could schedule an interview?  Of course it would! Scheduling Module I think you get the drift from previous posts that these project structures start looking somewhat similar.  The interview scheduling module is no different than the rest- it gets a SchedulingModule.cs file at the root that inherits from IModule, and there is a single SchedulerView.xsml and SchedulerViewModel.cs setup for our V+VM.  We have one unique concern as we enter into this- RadScheduler deals with AppointmentsSource, not ItemsSource, so there are some special considerations to take into account when planning this module. First, I need something which inherits from AppointmentBase.  This is the core of the RadScheduler appointment, and if you are planning to do any form of custom appointment, you'll want it to inherit from this.  Then you can add-on functionality as needed.  Here is my addition to the mix, the InterviewAppointment: 01.public class InterviewAppointment : AppointmentBase 02.{ 03.    private int _applicantID; 04.    public int ApplicantID 05.    { 06.        get { return this._applicantID; } 07.        set 08.        { 09.            if (_applicantID != value) 10.            { 11.                _applicantID = value; 12.                OnPropertyChanged("ApplicantID"); 13.            } 14.        } 15.    } 16.   17.    private int _postingID; 18.    public int PostingID 19.    { 20.        get { return _postingID; } 21.        set 22.        { 23.            if (_postingID != value) 24.            { 25.                _postingID = value; 26.                OnPropertyChanged("PostingID"); 27.            } 28.        } 29.    } 30.   31.    private string _body; 32.    public string Body 33.    { 34.        get { return _body; } 35.        set 36.        { 37.            if (_body != value) 38.            { 39.                _body = value; 40.                OnPropertyChanged("Body"); 41.            } 42.        } 43.    } 44.   45.    private int _interviewID; 46.    public int InterviewID 47.    { 48.        get { return _interviewID; } 49.        set 50.        { 51.            if (_interviewID != value) 52.            { 53.                _interviewID = value; 54.                OnPropertyChanged("InterviewID"); 55.            } 56.        } 57.    } 58.   59.    public override IAppointment Copy() 60.    { 61.        IAppointment appointment = new InterviewAppointment(); 62.        appointment.CopyFrom(this);             63.        return appointment; 64.    } 65.   66.    public override void CopyFrom(IAppointment other) 67.    {             68.        base.CopyFrom(other); 69.        var appointment = other as InterviewAppointment; 70.        if (appointment != null) 71.        { 72.            ApplicantID = appointment.ApplicantID; 73.            PostingID = appointment.PostingID; 74.            Body = appointment.Body; 75.            InterviewID = appointment.InterviewID; 76.        } 77.    } 78.} Nothing too exciting going on here, we just make sure that our custom fields are persisted (specifically set in CopyFrom at the bottom) and notifications are fired- otherwise this ends up exactly like the standard appointment as far as interactions, etc.  But if we've got custom appointment items... that also means we need to customize what our appointment dialog window will look like. Customizing the Edit Appointment Dialog This initially sounds a lot more intimidating than it really is.  The first step here depends on what you're dealing with for theming, but for ease of everything I went ahead and extracted my templates in Blend for RadScheduler so I could modify it as I pleased.  For the faint of heart, the RadScheduler template is a few thousand lines of goodness since there are some very complex things going on in that control.  I've gone ahead and trimmed down the template parts I don't need as much as possible, so what is left is all that is relevant to the Edit Appointment Dialog.  Here's the resulting Xaml, with line numbers, so I can explain further: 001.<UserControl.Resources> 002.    <!-- begin Necessary Windows 7 Theme Resources for EditAppointmentTemplate --> 003.    <helpers:DataContextProxy x:Key="DataContextProxy" /> 004.       005.    <telerik:Windows7Theme x:Key="Theme" /> 006.    <SolidColorBrush x:Key="DialogWindowBackground" 007.                     Color="White" /> 008.    <SolidColorBrush x:Key="CategorySelectorBorderBrush" 009.                     Color="#FFB1B1B1" /> 010.    <LinearGradientBrush x:Key="RadToolBar_InnerBackground" 011.                         EndPoint="0.5,1" 012.                         StartPoint="0.5,0"> 013.        <GradientStop Color="#FFFDFEFF" 014.                      Offset="0" /> 015.        <GradientStop Color="#FFDDE9F7" 016.                      Offset="1" /> 017.        <GradientStop Color="#FFE6F0FA" 018.                      Offset="0.5" /> 019.        <GradientStop Color="#FFDCE6F4" 020.                      Offset="0.5" /> 021.    </LinearGradientBrush> 022.    <Style x:Key="FormElementTextBlockStyle" 023.           TargetType="TextBlock"> 024.        <Setter Property="HorizontalAlignment" 025.                Value="Right" /> 026.        <Setter Property="VerticalAlignment" 027.                Value="Top" /> 028.        <Setter Property="Margin" 029.                Value="15, 15, 0, 2" /> 030.    </Style> 031.    <Style x:Key="FormElementStyle" 032.           TargetType="FrameworkElement"> 033.        <Setter Property="Margin" 034.                Value="10, 10, 0, 2" /> 035.    </Style> 036.    <SolidColorBrush x:Key="GenericShallowBorderBrush" 037.                     Color="#FF979994" /> 038.    <telerik:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> 039.    <telerikScheduler:ImportanceToBooleanConverter x:Key="ImportanceToBooleanConverter" /> 040.    <telerikScheduler:NullToVisibilityConverter x:Key="NullToVisibilityConverter" /> 041.    <telerikScheduler:InvertedNullToVisibilityConverter x:Key="InvertedNullToVisibilityConverter" /> 042.    <scheduler:ResourcesSeparatorConverter x:Key="ResourcesSeparatorConverter" /> 043.    <DataTemplate x:Key="IconDataEditTemplate"> 044.        <Image Source="/Telerik.Windows.Controls.Scheduler;component/Themes/Office/Images/cal.png" 045.               Margin="3,3,0,0" 046.               Width="16" 047.               Height="16" /> 048.    </DataTemplate> 049.    <DataTemplate x:Key="SingleSelectionTemplate"> 050.        <Grid VerticalAlignment="Stretch" 051.              HorizontalAlignment="Stretch"> 052.            <Grid.RowDefinitions> 053.                <RowDefinition Height="Auto" /> 054.            </Grid.RowDefinitions> 055.            <Grid.ColumnDefinitions> 056.                <ColumnDefinition Width="Auto" 057.                                  MinWidth="84" /> 058.                <ColumnDefinition Width="Auto" 059.                                  MinWidth="200" /> 060.            </Grid.ColumnDefinitions> 061.            <TextBlock x:Name="SelectionNameLabel" 062.                       Margin="0,13,4,2" 063.                       Text="{Binding ResourceType.DisplayName}" 064.                       Style="{StaticResource FormElementTextBlockStyle}" 065.                       Grid.Column="0" /> 066.            <telerikInput:RadComboBox ItemsSource="{Binding ResourceItems}" 067.                                      Width="185" 068.                                      Margin="5,10,20,2" 069.                                      HorizontalAlignment="Left" 070.                                      Grid.Column="1" 071.                                      ClearSelectionButtonVisibility="Visible" 072.                                      ClearSelectionButtonContent="Clear All" 073.                                      DisplayMemberPath="Resource.DisplayName" 074.                                      telerik:StyleManager.Theme="{StaticResource Theme}" 075.                                      SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> 076.        </Grid> 077.    </DataTemplate> 078.    <DataTemplate x:Key="MultipleSelectionTemplate"> 079.        <Grid VerticalAlignment="Stretch" 080.              HorizontalAlignment="Stretch"> 081.            <Grid.RowDefinitions> 082.                <RowDefinition Height="Auto" /> 083.            </Grid.RowDefinitions> 084.            <Grid.ColumnDefinitions> 085.                <ColumnDefinition Width="Auto" 086.                                  MinWidth="84" /> 087.                <ColumnDefinition Width="Auto" 088.                                  MinWidth="200" /> 089.            </Grid.ColumnDefinitions> 090.            <TextBlock x:Name="SelectionNameLabel" 091.                       Grid.Column="0" 092.                       Text="{Binding ResourceType.DisplayName}" 093.                       Margin="0,13,4,2" 094.                       Style="{StaticResource FormElementTextBlockStyle}" /> 095.            <telerikInput:RadComboBox Grid.Column="1" 096.                                      Width="185" 097.                                      HorizontalAlignment="Left" 098.                                      Margin="5,10,20,2" 099.                                      ItemsSource="{Binding ResourceItems}" 100.                                      SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" 101.                                      ClearSelectionButtonVisibility="Visible" 102.                                      ClearSelectionButtonContent="Clear All" 103.                                      telerik:StyleManager.Theme="{StaticResource Theme}"> 104.                <telerikInput:RadComboBox.ItemTemplate> 105.                    <DataTemplate> 106.                        <Grid HorizontalAlignment="Stretch" 107.                              VerticalAlignment="Stretch"> 108.                            <CheckBox VerticalAlignment="Center" 109.                                      HorizontalContentAlignment="Stretch" 110.                                      VerticalContentAlignment="Center" 111.                                      IsChecked="{Binding IsChecked, Mode=TwoWay}" 112.                                      Content="{Binding Resource.DisplayName}"> 113.                                <CheckBox.ContentTemplate> 114.                                    <DataTemplate> 115.                                        <TextBlock HorizontalAlignment="Stretch" 116.                                                   VerticalAlignment="Stretch" 117.                                                   Text="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" /> 118.                                    </DataTemplate> 119.                                </CheckBox.ContentTemplate> 120.                            </CheckBox> 121.                        </Grid> 122.                    </DataTemplate> 123.                </telerikInput:RadComboBox.ItemTemplate> 124.            </telerikInput:RadComboBox> 125.        </Grid> 126.    </DataTemplate> 127.    <scheduler:ResourceTypeTemplateSelector x:Key="ItemTemplateSelector" 128.                                            MultipleSelectionTemplate="{StaticResource MultipleSelectionTemplate}" 129.                                            SingleSelectionTemplate="{StaticResource SingleSelectionTemplate}" /> 130.    <!-- end Necessary Windows 7 Theme Resources for EditAppointmentTemplate -->  131.       132.    <ControlTemplate x:Key="EditAppointmentTemplate" 133.                     TargetType="telerikScheduler:AppointmentDialogWindow"> 134.        <StackPanel Background="{TemplateBinding Background}" 135.                    UseLayoutRounding="True"> 136.            <StackPanel Grid.Row="0" 137.                        Orientation="Horizontal" 138.                        Background="{StaticResource RadToolBar_InnerBackground}" 139.                        Grid.ColumnSpan="2" 140.                        Height="0"> 141.                <!-- Recurrence buttons --> 142.                <Border Margin="1,1,0,0" 143.                        Background="#50000000" 144.                        HorizontalAlignment="Left" 145.                        VerticalAlignment="Center" 146.                        Width="2" 147.                        Height="16"> 148.                    <Border Margin="0,0,1,1" 149.                            Background="#80FFFFFF" 150.                            HorizontalAlignment="Left" 151.                            Width="1" /> 152.                </Border> 153.                <Border Margin="1,1,0,0" 154.                        Background="#50000000" 155.                        HorizontalAlignment="Left" 156.                        VerticalAlignment="Center" 157.                        Width="2" 158.                        Height="16"> 159.                    <Border Margin="0,0,1,1" 160.                            Background="#80FFFFFF" 161.                            HorizontalAlignment="Left" 162.                            Width="1" /> 163.                </Border> 164.                <TextBlock telerik:LocalizationManager.ResourceKey="ShowAs" 165.                           VerticalAlignment="Center" 166.                           Margin="5,0,0,0" /> 167.                <telerikInput:RadComboBox ItemsSource="{TemplateBinding TimeMarkers}" 168.                                          Width="100" 169.                                          Height="20" 170.                                          VerticalAlignment="Center" 171.                                          Margin="5,0,0,0" 172.                                          ClearSelectionButtonVisibility="Visible" 173.                                          ClearSelectionButtonContent="Clear" 174.                                          SelectedItem="{Binding TimeMarker,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}" 175.                                          telerik:StyleManager.Theme="{StaticResource Theme}"> 176.                    <telerikInput:RadComboBox.ItemTemplate> 177.                        <DataTemplate> 178.                            <StackPanel Orientation="Horizontal"> 179.                                <Rectangle Fill="{Binding TimeMarkerBrush}" 180.                                           Margin="2" 181.                                           Width="12" 182.                                           Height="12" /> 183.                                <TextBlock Text="{Binding TimeMarkerName}" 184.                                           Margin="2" /> 185.                            </StackPanel> 186.                        </DataTemplate> 187.                    </telerikInput:RadComboBox.ItemTemplate> 188.                </telerikInput:RadComboBox> 189.                <telerik:RadToggleButton x:Name="High" 190.                                         BorderThickness="0" 191.                                         Background="{StaticResource RadToolBar_InnerBackground}" 192.                                         DataContext="{TemplateBinding EditedAppointment}" 193.                                         telerik:StyleManager.Theme="{StaticResource Theme}" 194.                                         IsChecked="{Binding Importance,Mode=TwoWay, Converter={StaticResource ImportanceToBooleanConverter},ConverterParameter=High}" 195.                                         Margin="2,2,0,2" 196.                                         Width="23" 197.                                         Height="23" 198.                                         HorizontalContentAlignment="Center" 199.                                         ToolTipService.ToolTip="High importance" 200.                                         CommandParameter="High" 201.                                         Command="telerikScheduler:RadSchedulerCommands.SetAppointmentImportance"> 202.                    <StackPanel HorizontalAlignment="Center"> 203.                        <Path Stretch="Fill" 204.                              Height="10" 205.                              HorizontalAlignment="Center" 206.                              VerticalAlignment="Top" 207.                              Width="5.451" 208.                              Data="M200.39647,58.840393 C200.39337,58.336426 201.14566,57.683922 202.56244,57.684292 C204.06589,57.684685 204.73764,58.357765 204.72783,58.992363 C205.04649,61.795574 203.04713,64.181099 202.47388,66.133446 C201.93753,64.154961 199.9471,61.560352 200.39647,58.840393 z"> 209.                            <Path.Fill> 210.                                <LinearGradientBrush EndPoint="1.059,0.375" 211.                                                     StartPoint="-0.457,0.519"> 212.                                    <GradientStop Color="#FFFF0606" 213.                                                  Offset="0.609" /> 214.                                    <GradientStop Color="#FFBF0303" 215.                                                  Offset="0.927" /> 216.                                </LinearGradientBrush> 217.                            </Path.Fill> 218.                        </Path> 219.                        <Ellipse Height="3" 220.                                 HorizontalAlignment="Center" 221.                                 Margin="0,-1,0,0" 222.                                 VerticalAlignment="Top" 223.                                 Width="3"> 224.                            <Ellipse.Fill> 225.                                <RadialGradientBrush> 226.                                    <GradientStop Color="#FFFF0606" 227.                                                  Offset="0" /> 228.                                    <GradientStop Color="#FFBF0303" 229.                                                  Offset="1" /> 230.                                </RadialGradientBrush> 231.                            </Ellipse.Fill> 232.                        </Ellipse> 233.                    </StackPanel> 234.                </telerik:RadToggleButton> 235.                <telerik:RadToggleButton x:Name="Low" 236.                                         HorizontalContentAlignment="Center" 237.                                         BorderThickness="0" 238.                                         Background="{StaticResource RadToolBar_InnerBackground}" 239.                                         DataContext="{TemplateBinding EditedAppointment}" 240.                                         IsChecked="{Binding Importance,Mode=TwoWay, Converter={StaticResource ImportanceToBooleanConverter},ConverterParameter=Low}" 241.                                         Margin="0,2,0,2" 242.                                         Width="23" 243.                                         Height="23" 244.                                         ToolTipService.ToolTip="Low importance" 245.                                         CommandParameter="Low" 246.                                         telerik:StyleManager.Theme="{StaticResource Theme}" 247.                                         Command="telerikScheduler:RadSchedulerCommands.SetAppointmentImportance"> 248.                    <Path Stretch="Fill" 249.                          Height="12" 250.                          HorizontalAlignment="Center" 251.                          VerticalAlignment="Top" 252.                          Width="9" 253.                          Data="M222.40353,60.139881 L226.65768,60.139843 L226.63687,67.240196 L229.15347,67.240196 L224.37816,71.394943 L219.65274,67.240196 L222.37572,67.219345 z" 254.                          Stroke="#FF0365A7"> 255.                        <Path.Fill> 256.                            <LinearGradientBrush EndPoint="1.059,0.375" 257.                                                 StartPoint="-0.457,0.519"> 258.                                <GradientStop Color="#FFBBE4FF" /> 259.                                <GradientStop Color="#FF024572" 260.                                              Offset="0.836" /> 261.                                <GradientStop Color="#FF43ADF4" 262.                                              Offset="0.466" /> 263.                            </LinearGradientBrush> 264.                        </Path.Fill> 265.                    </Path> 266.                </telerik:RadToggleButton> 267.            </StackPanel > 268.            <Border DataContext="{TemplateBinding EditedAppointment}" 269.                    Background="{Binding Category.CategoryBrush}" 270.                    Visibility="{Binding Category,Converter={StaticResource NullToVisibilityConverter}}" 271.                    CornerRadius="3" 272.                    Height="20" 273.                    Margin="5,10,5,0"> 274.                <TextBlock Text="{Binding Category.DisplayName}" 275.                           VerticalAlignment="Center" 276.                           Margin="5,0,0,0" /> 277.            </Border> 278.            <Grid VerticalAlignment="Stretch" 279.                  HorizontalAlignment="Stretch" 280.                  DataContext="{TemplateBinding EditedAppointment}" 281.                  Background="{TemplateBinding Background}"> 282.                <Grid.RowDefinitions> 283.                    <RowDefinition Height="Auto" /> 284.                    <RowDefinition Height="Auto" /> 285.                    <RowDefinition Height="Auto" /> 286.                    <RowDefinition Height="Auto" /> 287.                    <RowDefinition Height="Auto" /> 288.                    <RowDefinition Height="Auto" /> 289.                    <RowDefinition Height="Auto" /> 290.                    <RowDefinition Height="Auto" /> 291.                    <RowDefinition Height="Auto" /> 292.                    <RowDefinition Height="Auto" /> 293.                </Grid.RowDefinitions> 294.                <Grid.ColumnDefinitions> 295.                    <ColumnDefinition Width="Auto" 296.                                      MinWidth="100" /> 297.                    <ColumnDefinition Width="Auto" 298.                                      MinWidth="200" /> 299.                </Grid.ColumnDefinitions> 300.                <!-- Subject --> 301.                <TextBlock x:Name="SubjectLabel" 302.                           Grid.Row="0" 303.                           Grid.Column="0" 304.                           Margin="0,15,0,2" 305.                           telerik:LocalizationManager.ResourceKey="Subject" 306.                           Style="{StaticResource FormElementTextBlockStyle}" /> 307.                <TextBox x:Name="Subject" 308.                         Grid.Row="0" 309.                         Grid.Column="1" 310.                         MinHeight="22" 311.                         Padding="4 2" 312.                         Width="340" 313.                         HorizontalAlignment="Left" 314.                         Text="{Binding Subject, Mode=TwoWay}" 315.                         MaxLength="255" 316.                         telerik:StyleManager.Theme="{StaticResource Theme}" 317.                         Margin="10,12,20,2" /> 318.                <!-- Description --> 319.                <TextBlock x:Name="DescriptionLabel" 320.                           Grid.Row="1" 321.                           Grid.Column="0" 322.                           Margin="0,13,0,2" 323.                           telerik:LocalizationManager.ResourceKey="Body" 324.                           Style="{StaticResource FormElementTextBlockStyle}" /> 325.                <TextBox x:Name="Body" 326.                         VerticalAlignment="top" 327.                         Grid.Row="1" 328.                         Grid.Column="1" 329.                         Height="Auto" 330.                         MaxHeight="82" 331.                         Width="340" 332.                         HorizontalAlignment="Left" 333.                         MinHeight="22" 334.                         Padding="4 2" 335.                         TextWrapping="Wrap" 336.                         telerik:StyleManager.Theme="{StaticResource Theme}" 337.                         Text="{Binding Body, Mode=TwoWay}" 338.                         AcceptsReturn="true" 339.                         Margin="10,10,20,2" 340.                         HorizontalScrollBarVisibility="Auto" 341.                         VerticalScrollBarVisibility="Auto" /> 342.                <!-- Start/End date --> 343.                <TextBlock x:Name="StartDateLabel" 344.                           Grid.Row="2" 345.                           Grid.Column="0" 346.                           Margin="0,13,0,2" 347.                           telerik:LocalizationManager.ResourceKey="StartTime" 348.                           Style="{StaticResource FormElementTextBlockStyle}" /> 349.                <telerikScheduler:DateTimePicker x:Name="StartDateTime" 350.                                                 Height="22" 351.                                                 Grid.Row="2" 352.                                                 Grid.Column="1" 353.                                                 HorizontalAlignment="Left" 354.                                                 Margin="10,10,20,2" 355.                                                 Style="{StaticResource FormElementStyle}" 356.                                                 SelectedDateTime="{Binding Start, Mode=TwoWay}" 357.                                                 telerikScheduler:StartEndDatePicker.EndPicker="{Binding ElementName=EndDateTime}" 358.                                                 IsTabStop="False" 359.                                                 IsEnabled="False" /> 360.                <TextBlock x:Name="EndDateLabel" 361.                           Grid.Row="3" 362.                           Grid.Column="0" 363.                           Margin="0,13,0,2" 364.                           telerik:LocalizationManager.ResourceKey="EndTime" 365.                           Style="{StaticResource FormElementTextBlockStyle}" /> 366.                <telerikScheduler:DateTimePicker x:Name="EndDateTime" 367.                                                 Height="22" 368.                                                 Grid.Row="3" 369.                                                 Grid.Column="1" 370.                                                 HorizontalAlignment="Left" 371.                                                 Margin="10,10,20,2" 372.                                                 Style="{StaticResource FormElementStyle}" 373.                                                 IsTabStop="False" 374.                                                 IsEnabled="False" 375.                                                 SelectedDateTime="{Binding End, Mode=TwoWay}" /> 376.                <!-- Is-all-day selector --> 377.                <CheckBox x:Name="AllDayEventCheckbox" 378.                          IsChecked="{Binding IsAllDayEvent, Mode=TwoWay}" 379.                          Grid.Row="4" 380.                          Grid.Column="1" 381.                          Margin="10,10,20,2" 382.                          HorizontalAlignment="Left" 383.                          telerik:StyleManager.Theme="{StaticResource Theme}" 384.                          telerik:LocalizationManager.ResourceKey="AllDayEvent"> 385.                    <telerik:CommandManager.InputBindings> 386.                        <telerik:InputBindingCollection> 387.                            <telerik:MouseBinding Command="telerikScheduler:RadSchedulerCommands.ChangeTimePickersVisibility" 388.                                                  Gesture="LeftClick" /> 389.                        </telerik:InputBindingCollection> 390.                    </telerik:CommandManager.InputBindings> 391.                </CheckBox> 392.                <Grid Grid.Row="5" 393.                      Grid.ColumnSpan="2"> 394.                    <Grid.ColumnDefinitions> 395.                        <ColumnDefinition Width="Auto" 396.                                          MinWidth="100" /> 397.                        <ColumnDefinition Width="Auto" 398.                                          MinWidth="200" /> 399.                    </Grid.ColumnDefinitions> 400.                    <Grid.RowDefinitions> 401.                        <RowDefinition Height="Auto" /> 402.                        <RowDefinition Height="Auto" /> 403.                    </Grid.RowDefinitions> 404.                    <TextBlock Text="Applicant" 405.                               Margin="0,13,0,2" 406.                               Style="{StaticResource FormElementTextBlockStyle}" /> 407.                    <telerikInput:RadComboBox IsEditable="False" 408.                                              Grid.Column="1" 409.                                              Height="24" 410.                                              VerticalAlignment="Center" 411.                                              ItemsSource="{Binding Source={StaticResource DataContextProxy}, Path=DataSource.ApplicantList}" 412.                                              SelectedValue="{Binding ApplicantID, Mode=TwoWay}" 413.                                              SelectedValuePath="ApplicantID" 414.                                              DisplayMemberPath="FirstName" /> 415.                       416.                    <TextBlock Text="Job" 417.                               Margin="0,13,0,2" 418.                               Grid.Row="1" 419.                               Style="{StaticResource FormElementTextBlockStyle}" /> 420.                    <telerikInput:RadComboBox IsEditable="False" 421.                                              Grid.Column="1" 422.                                              Grid.Row="1" 423.                                              Height="24" 424.                                              VerticalAlignment="Center" 425.                                              ItemsSource="{Binding Source={StaticResource DataContextProxy}, Path=DataSource.JobsList}" 426.                                              SelectedValue="{Binding PostingID, Mode=TwoWay}" 427.                                              SelectedValuePath="PostingID" 428.                                              DisplayMemberPath="JobTitle"/> 429.                </Grid> 430.                    <!-- Resources --> 431.                <Grid x:Name="ResourcesLayout" 432.                      Grid.Row="7" 433.                      Grid.Column="0" 434.                      Grid.ColumnSpan="2" 435.                      MaxHeight="130" 436.                      Margin="20,5,20,0"> 437.                    <Border Margin="0" 438.                            BorderThickness="1" 439.                            BorderBrush="{StaticResource GenericShallowBorderBrush}" 440.                            Visibility="{Binding ElementName=ResourcesScrollViewer, Path=ComputedVerticalScrollBarVisibility}"></Border> 441.                    <ScrollViewer x:Name="ResourcesScrollViewer" 442.                                  IsTabStop="false" 443.                                  Grid.Row="6" 444.                                  Grid.Column="0" 445.                                  Grid.ColumnSpan="2" 446.                                  Margin="1" 447.                                  telerik:StyleManager.Theme="{StaticResource Theme}" 448.                                  VerticalScrollBarVisibility="Auto"> 449.                        <scheduler:ResourcesItemsControl x:Name="PART_Resources" 450.                                                         HorizontalAlignment="Left" 451.                                                         Padding="0,2,0,5" 452.                                                         IsTabStop="false" 453.                                                         ItemsSource="{TemplateBinding ResourceTypeModels}" 454.                                                         ItemTemplateSelector="{StaticResource ItemTemplateSelector}" /> 455.                    </ScrollViewer> 456.                </Grid> 457.                <StackPanel x:Name="FooterControls" 458.                            Margin="5 10 10 10" 459.                            Grid.Row="8" 460.                            Grid.Column="1" 461.                            HorizontalAlignment="Left" 462.                            Orientation="Horizontal"> 463.                    <telerik:RadButton x:Name="OKButton" 464.                                       Margin="5" 465.                                       Padding="10 0" 466.                                       MinWidth="80" 467.                                       Command="telerikScheduler:RadSchedulerCommands.SaveAppointment" 468.                                       telerik:StyleManager.Theme="{StaticResource Theme}" 469.                                       telerikNavigation:RadWindow.ResponseButton="Accept" 470.                                       telerik:LocalizationManager.ResourceKey="SaveAndCloseCommandText"> 471.                    </telerik:RadButton> 472.                    <telerik:RadButton x:Name="CancelButton" 473.                                       Margin="5" 474.                                       Padding="10 0" 475.                                       MinWidth="80" 476.                                       telerik:LocalizationManager.ResourceKey="Cancel" 477.                                       telerik:StyleManager.Theme="{StaticResource Theme}" 478.                                       telerikNavigation:RadWindow.ResponseButton="Cancel" 479.                                       Command="telerik:WindowCommands.Close"> 480.                    </telerik:RadButton> 481.                </StackPanel> 482.            </Grid> 483.            <vsm:VisualStateManager.VisualStateGroups> 484.                <vsm:VisualStateGroup x:Name="RecurrenceRuleState"> 485.                    <vsm:VisualState x:Name="RecurrenceRuleIsNull"> 486.                        <Storyboard> 487.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="StartDateTime" 488.                                                           Storyboard.TargetProperty="IsEnabled" 489.                                                           Duration="0"> 490.                                <DiscreteObjectKeyFrame KeyTime="0" 491.                                                        Value="True" /> 492.                            </ObjectAnimationUsingKeyFrames> 493.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="EndDateTime" 494.                                                           Storyboard.TargetProperty="IsEnabled" 495.                                                           Duration="0"> 496.                                <DiscreteObjectKeyFrame KeyTime="0" 497.                                                        Value="True" /> 498.                            </ObjectAnimationUsingKeyFrames> 499.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AllDayEventCheckbox" 500.                                                           Storyboard.TargetProperty="IsEnabled" 501.                                                           Duration="0"> 502.                                <DiscreteObjectKeyFrame KeyTime="0" 503.                                                        Value="True" /> 504.                            </ObjectAnimationUsingKeyFrames> 505.                        </Storyboard> 506.                    </vsm:VisualState> 507.                    <vsm:VisualState x:Name="RecurrenceRuleIsNotNull"> 508.                        <Storyboard> 509.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="StartDateTime" 510.                                                           Storyboard.TargetProperty="IsEnabled" 511.                                                           Duration="0"> 512.                                <DiscreteObjectKeyFrame KeyTime="0" 513.                                                        Value="False" /> 514.                            </ObjectAnimationUsingKeyFrames> 515.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="EndDateTime" 516.                                                           Storyboard.TargetProperty="IsEnabled" 517.                                                           Duration="0"> 518.                                <DiscreteObjectKeyFrame KeyTime="0" 519.                                                        Value="False" /> 520.                            </ObjectAnimationUsingKeyFrames> 521.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AllDayEventCheckbox" 522.                                                           Storyboard.TargetProperty="IsEnabled" 523.                                                           Duration="0"> 524.                                <DiscreteObjectKeyFrame KeyTime="0" 525.                                                        Value="False" /> 526.                            </ObjectAnimationUsingKeyFrames> 527.                        </Storyboard> 528.                    </vsm:VisualState> 529.                </vsm:VisualStateGroup> 530.            </vsm:VisualStateManager.VisualStateGroups> 531.        </StackPanel> 532.    </ControlTemplate> 533.    <DataTemplate x:Key="AppointmentDialogWindowHeaderDataTemplate"> 534.        <StackPanel Orientation="Horizontal" 535.                    MaxWidth="400"> 536.            <TextBlock telerik:LocalizationManager.ResourceKey="Event" 537.                       Visibility="{Binding Appointment.IsAllDayEvent, Converter={StaticResource BooleanToVisibilityConverter}}" /> 538.            <TextBlock telerik:LocalizationManager.ResourceKey="Appointment" 539.                       Visibility="{Binding Appointment.IsAllDayEvent, Converter={StaticResource InvertedBooleanToVisibilityConverter}}" /> 540.            <TextBlock Text=" - " /> 541.            <TextBlock x:Name="SubjectTextBlock" 542.                       Visibility="{Binding Appointment.Subject, Converter={StaticResource NullToVisibilityConverter}}" 543.                       Text="{Binding Appointment.Subject}" /> 544.            <TextBlock telerik:LocalizationManager.ResourceKey="Untitled" 545.                       Visibility="{Binding Appointment.Subject, Converter={StaticResource InvertedNullToVisibilityConverter}}" /> 546.        </StackPanel> 547.    </DataTemplate> 548.    <Style x:Key="EditAppointmentStyle" 549.           TargetType="telerikScheduler:AppointmentDialogWindow"> 550.        <Setter Property="IconTemplate" 551.                Value="{StaticResource IconDataEditTemplate}" /> 552.        <Setter Property="HeaderTemplate" 553.                Value="{StaticResource AppointmentDialogWindowHeaderDataTemplate}" /> 554.        <Setter Property="Background" 555.                Value="{StaticResource DialogWindowBackground}" /> 556.        <Setter Property="Template" 557.                Value="{StaticResource EditAppointmentTemplate}" /> 558.    </Style> 559.</UserControl.Resources> The first line there is the DataContextProxy I mentioned previously- we use that again to work a bit of magic in this template. Where we start getting into the dialog in question is line 132, but line 407 is where things start getting interesting.  The ItemsSource is pointing at a list that exists in my ViewModel (or code-behind, if it is used as a DataContext), the SelectedValue is the item I am actually binding from the applicant (note the TwoWay binding), and SelectedValuePath and DisplayMemberPath ensure the proper applicant is being displayed from the collection.  You will also see similar starting on line 420 where I do the same for the Jobs we'll be displaying. Just to wrap-up the Xaml, here's the RadScheduler declaraction that ties this all together and will be the main focus of our view: 01.<telerikScheduler:RadScheduler x:Name="xJobsScheduler" 02.                  Grid.Row="1" 03.                  Grid.Column="1" 04.                  Width="800" 05.                  MinWidth="600" 06.                  Height="500" 07.                  MinHeight="300" 08.                  AppointmentsSource="{Binding Interviews}" 09.                  EditAppointmentStyle="{StaticResource EditAppointmentStyle}" 10.                  command:AppointmentAddedEventClass.Command="{Binding AddAppointmentCommand}" 11.                  command:ApptCreatedEventClass.Command="{Binding ApptCreatingCommand}" 12.                  command:ApptEditedEventClass.Command="{Binding ApptEditedCommand}" 13.                  command:ApptDeletedEventClass.Command="{Binding ApptDeletedCommand}"> 14.</telerikScheduler:RadScheduler> Now, we get to the ViewModel and what it takes to get that rigged up.  And for those of you who remember the jobs post, those command:s in the Xaml are pointing to attached behavior commands that reproduce the respective events.  This becomes very handy when we're setting up the code-behind version. ;) ViewModel I've been liking this approach so far, so I'm going to put the entire ViewModel here and then go into the lines of interest.  Of course, feel free to ask me questions about anything that isn't clear (by line number, ideally) so I can help out if I have missed anything important: 001.public class SchedulerViewModel : ViewModelBase 002.{ 003.    private readonly IEventAggregator eventAggregator; 004.    private readonly IRegionManager regionManager; 005.   006.    public RecruitingContext context; 007.   008.    private ObservableItemCollection<InterviewAppointment> _interviews = new ObservableItemCollection<InterviewAppointment>(); 009.    public ObservableItemCollection<InterviewAppointment> Interviews 010.    { 011.        get { return _interviews; } 012.        set 013.        { 014.            if (_interviews != value) 015.            { 016.                _interviews = value; 017.                NotifyChanged("Interviews"); 018.            } 019.        } 020.    } 021.   022.    private QueryableCollectionView _jobsList; 023.    public QueryableCollectionView JobsList 024.    { 025.        get { return this._jobsList; } 026.        set 027.        { 028.            if (this._jobsList != value) 029.            { 030.                this._jobsList = value; 031.                this.NotifyChanged("JobsList"); 032.            } 033.        } 034.    } 035.   036.    private QueryableCollectionView _applicantList; 037.    public QueryableCollectionView ApplicantList 038.    { 039.        get { return _applicantList; } 040.        set 041.        { 042.            if (_applicantList != value) 043.            { 044.                _applicantList = value; 045.                NotifyChanged("ApplicantList"); 046.            } 047.        } 048.    } 049.   050.    public DelegateCommand<object> AddAppointmentCommand { get; set; } 051.    public DelegateCommand<object> ApptCreatingCommand { get; set; } 052.    public DelegateCommand<object> ApptEditedCommand { get; set; } 053.    public DelegateCommand<object> ApptDeletedCommand { get; set; } 054.   055.    public SchedulerViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 056.    { 057.        // set Unity items 058.        this.eventAggregator = eventAgg; 059.        this.regionManager = regionmanager; 060.   061.        // load our context 062.        context = new RecruitingContext(); 063.        LoadOperation<Interview> loadOp = context.Load(context.GetInterviewsQuery()); 064.        loadOp.Completed += new EventHandler(loadOp_Completed); 065.   066.        this._jobsList = new QueryableCollectionView(context.JobPostings); 067.        context.Load(context.GetJobPostingsQuery()); 068.   069.        this._applicantList = new QueryableCollectionView(context.Applicants); 070.        context.Load(context.GetApplicantsQuery()); 071.   072.        AddAppointmentCommand = new DelegateCommand<object>(this.AddAppt); 073.        ApptCreatingCommand = new DelegateCommand<object>(this.ApptCreating); 074.        ApptEditedCommand = new DelegateCommand<object>(this.ApptEdited); 075.        ApptDeletedCommand = new DelegateCommand<object>(this.ApptDeleted); 076.   077.    } 078.   079.    void loadOp_Completed(object sender, EventArgs e) 080.    { 081.        LoadOperation loadop = sender as LoadOperation; 082.   083.        foreach (var ent in loadop.Entities) 084.        { 085.            _interviews.Add(EntityToAppointment(ent as Interview)); 086.        } 087.    } 088.   089.    #region Appointment Adding 090.   091.    public void AddAppt(object obj) 092.    { 093.        // now we have a new InterviewAppointment to add to our QCV :) 094.        InterviewAppointment newInterview = obj as InterviewAppointment; 095.   096.        this.context.Interviews.Add(AppointmentToEntity(newInterview)); 097.        this.context.SubmitChanges((s) => 098.        { 099.            ActionHistory myAction = new ActionHistory(); 100.            myAction.InterviewID = newInterview.InterviewID; 101.            myAction.PostingID = newInterview.PostingID; 102.            myAction.ApplicantID = newInterview.ApplicantID; 103.            myAction.Description = String.Format("Interview with {0} has been created by {1}", newInterview.ApplicantID.ToString(), "default user"); 104.            myAction.TimeStamp = DateTime.Now; 105.            eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 106.        } 107.            , null); 108.    } 109.   110.    public void ApptCreating(object obj) 111.    { 112.        // handled in the behavior, just a placeholder to ensure it runs :) 113.    } 114.   115.    #endregion 116.   117.    #region Appointment Editing 118.   119.    public void ApptEdited(object obj) 120.    { 121.        Interview editedInterview = (from x in context.Interviews 122.                            where x.InterviewID == (obj as InterviewAppointment).InterviewID 123.                            select x).SingleOrDefault(); 124.   125.        CopyAppointmentEdit(editedInterview, obj as InterviewAppointment); 126.   127.        context.SubmitChanges((s) => { 128.            ActionHistory myAction = new ActionHistory(); 129.            myAction.InterviewID = editedInterview.InterviewID; 130.            myAction.PostingID = editedInterview.PostingID; 131.            myAction.ApplicantID = editedInterview.ApplicantID; 132.            myAction.Description = String.Format("Interview with {0} has been modified by {1}", editedInterview.ApplicantID.ToString(), "default user"); 133.            myAction.TimeStamp = DateTime.Now; 134.            eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); } 135.            , null); 136.    } 137.   138.    #endregion 139.   140.    #region Appointment Deleting 141.   142.    public void ApptDeleted(object obj) 143.    { 144.        Interview deletedInterview = (from x in context.Interviews 145.                                      where x.InterviewID == (obj as InterviewAppointment).InterviewID 146.                                      select x).SingleOrDefault(); 147.   148.        context.Interviews.Remove(deletedInterview); 149.        context.SubmitChanges((s) => 150.        { 151.            ActionHistory myAction = new ActionHistory(); 152.            myAction.InterviewID = deletedInterview.InterviewID; 153.            myAction.PostingID = deletedInterview.PostingID; 154.            myAction.ApplicantID = deletedInterview.ApplicantID; 155.            myAction.Description = String.Format("Interview with {0} has been deleted by {1}", deletedInterview.ApplicantID.ToString(), "default user"); 156.            myAction.TimeStamp = DateTime.Now; 157.            eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 158.        } 159.            , null); 160.    } 161.   162.    #endregion 163.   164.    #region Appointment Helpers :) 165.   166.    public Interview AppointmentToEntity(InterviewAppointment ia) 167.    { 168.        Interview newInterview = new Interview(); 169.        newInterview.Subject = ia.Subject; 170.        newInterview.Body = ia.Body; 171.        newInterview.Start = ia.Start; 172.        newInterview.End = ia.End; 173.        newInterview.ApplicantID = ia.ApplicantID; 174.        newInterview.PostingID = ia.PostingID; 175.        newInterview.InterviewID = ia.InterviewID; 176.   177.        return newInterview; 178.    } 179.   180.    public InterviewAppointment EntityToAppointment(Interview ia) 181.    { 182.        InterviewAppointment newInterview = new InterviewAppointment(); 183.        newInterview.Subject = ia.Subject; 184.        newInterview.Body = ia.Body; 185.        newInterview.Start = ia.Start; 186.        newInterview.End = ia.End; 187.        newInterview.ApplicantID = ia.ApplicantID; 188.        newInterview.PostingID = ia.PostingID; 189.        newInterview.InterviewID = ia.InterviewID; 190.   191.        return newInterview; 192.    } 193.   194.    public void CopyAppointmentEdit(Interview entityInterview, InterviewAppointment appointmentInterview) 195.    { 196.        entityInterview.Subject = appointmentInterview.Subject; 197.        entityInterview.Body = appointmentInterview.Body; 198.        entityInterview.Start = appointmentInterview.Start; 199.        entityInterview.End = appointmentInterview.End; 200.        entityInterview.ApplicantID = appointmentInterview.ApplicantID; 201.        entityInterview.PostingID = appointmentInterview.PostingID; 202.    } 203.   204.    #endregion 205.} One thing we're doing here which you won't see in any of the other ViewModels is creating a duplicate collection.  I know this is something which will be fixed down the line for using RadScheduler, simplifying this process, but with WCF RIA changing as it does I wanted to ensure functionality would remain consistent as I continued development on this application.  So, I do a little bit of duplication, but for the greater good.  This all takes place starting on line 79, so for every entity that comes back we add it to the collection that is bound to RadScheduler.  Otherwise, the DelegateCommands that you see correspond directly to the events they are named after.  In each case, rather than sending over the full event arguments, I just send in the appointment in question (coming through as the object obj in all cases) so I can add (line 91), edit (line 119), and delete appointments (line 142) like normal.  This just ensures they get updated back to my database.  Also, the one bit of code you won't see is for the Appointment Creating (line 110) event- that is because in the command I've created I simply make the replacement I need to: 1.void element_AppointmentCreating(object sender, AppointmentCreatingEventArgs e) 2.{ 3.    e.NewAppointment = new InterviewAppointment(); 4.    base.ExecuteCommand(); 5.} And the ViewModel is none the wiser, the appointments just work as far as it is concerned since as they are created they become InterviewAppointments.  End result?  I've customized my EditAppointmentDialog as follows: And adding, editing, and deleting appointments works like a charm.  I can even 'edit' by moving appointments around RadScheduler, so as they are dropped into a timeslot they perform their full edit routine and things get updated. And then, the Code-Behind Version Perhaps the thing I like the most about doing one then the other is I get to steal 90% or more of the code from the MVVM version.  For example, the only real changes to the Code-Behind Xaml file exist in the control declaration, in which I use events instead of attached-behavior-event-commands: 01.<telerikScheduler:RadScheduler x:Name="xJobsScheduler" 02.                  Grid.Row="1" 03.                  Grid.Column="1" 04.                  Width="800" 05.                  MinWidth="600" 06.                  Height="500" 07.                  MinHeight="300" 08.                  EditAppointmentStyle="{StaticResource EditAppointmentStyle}" 09.                  AppointmentAdded="xJobsScheduler_AppointmentAdded" 10.                  AppointmentCreating="xJobsScheduler_AppointmentCreating" 11.                  AppointmentEdited="xJobsScheduler_AppointmentEdited" 12.                  AppointmentDeleted="xJobsScheduler_AppointmentDeleted"> 13.</telerikScheduler:RadScheduler> Easy, right?  Otherwise, all the same styling in UserControl.Resources was re-used, right down to the DataContextProxy that lets us bind to a collection from our viewmodel (in this case, our code-behind) to use within the DataTemplate.  The code conversion gets even easier, as I could literally copy and paste almost everything from the ViewModel to my Code-Behind, just a matter of pasting the right section into the right event.  Here's the code-behind as proof: 001.public partial class SchedulingView : UserControl, INotifyPropertyChanged 002.{ 003.    public RecruitingContext context; 004.   005.    private QueryableCollectionView _jobsList; 006.    public QueryableCollectionView JobsList 007.    { 008.        get { return this._jobsList; } 009.        set 010.        { 011.            if (this._jobsList != value) 012.            { 013.                this._jobsList = value; 014.                this.NotifyChanged("JobsList"); 015.            } 016.        } 017.    } 018.   019.    private QueryableCollectionView _applicantList; 020.    public QueryableCollectionView ApplicantList 021.    { 022.        get { return _applicantList; } 023.        set 024.        { 025.            if (_applicantList != value) 026.            { 027.                _applicantList = value; 028.                NotifyChanged("ApplicantList"); 029.            } 030.        } 031.    } 032.   033.    private ObservableItemCollection<InterviewAppointment> _interviews = new ObservableItemCollection<InterviewAppointment>(); 034.    public ObservableItemCollection<InterviewAppointment> Interviews 035.    { 036.        get { return _interviews; } 037.        set 038.        { 039.            if (_interviews != value) 040.            { 041.                _interviews = value; 042.                NotifyChanged("Interviews"); 043.            } 044.        } 045.    } 046.   047.    public SchedulingView() 048.    { 049.        InitializeComponent(); 050.   051.        this.DataContext = this; 052.   053.        this.Loaded += new RoutedEventHandler(SchedulingView_Loaded); 054.    } 055.   056.    void SchedulingView_Loaded(object sender, RoutedEventArgs e) 057.    { 058.        this.xJobsScheduler.AppointmentsSource = Interviews; 059.   060.        context = new RecruitingContext(); 061.           062.        LoadOperation loadop = context.Load(context.GetInterviewsQuery()); 063.        loadop.Completed += new EventHandler(loadop_Completed); 064.   065.        this._applicantList = new QueryableCollectionView(context.Applicants); 066.        context.Load(context.GetApplicantsQuery()); 067.   068.        this._jobsList = new QueryableCollectionView(context.JobPostings); 069.        context.Load(context.GetJobPostingsQuery()); 070.    } 071.   072.    void loadop_Completed(object sender, EventArgs e) 073.    { 074.        LoadOperation loadop = sender as LoadOperation; 075.   076.        _interviews.Clear(); 077.   078.        foreach (var ent in loadop.Entities) 079.        { 080.            _interviews.Add(EntityToAppointment(ent as Interview)); 081.        } 082.    } 083.   084.    private void xJobsScheduler_AppointmentAdded(object sender, Telerik.Windows.Controls.AppointmentAddedEventArgs e) 085.    { 086.        // now we have a new InterviewAppointment to add to our QCV :) 087.        InterviewAppointment newInterview = e.Appointment as InterviewAppointment; 088.   089.        this.context.Interviews.Add(AppointmentToEntity(newInterview)); 090.        this.context.SubmitChanges((s) => 091.        { 092.            ActionHistory myAction = new ActionHistory(); 093.            myAction.InterviewID = newInterview.InterviewID; 094.            myAction.PostingID = newInterview.PostingID; 095.            myAction.ApplicantID = newInterview.ApplicantID; 096.            myAction.Description = String.Format("Interview with {0} has been created by {1}", newInterview.ApplicantID.ToString(), "default user"); 097.            myAction.TimeStamp = DateTime.Now; 098.            context.ActionHistories.Add(myAction); 099.            context.SubmitChanges(); 100.        } 101.            , null); 102.    } 103.   104.    private void xJobsScheduler_AppointmentCreating(object sender, Telerik.Windows.Controls.AppointmentCreatingEventArgs e) 105.    { 106.        e.NewAppointment = new InterviewAppointment(); 107.    } 108.   109.    private void xJobsScheduler_AppointmentEdited(object sender, Telerik.Windows.Controls.AppointmentEditedEventArgs e) 110.    { 111.        Interview editedInterview = (from x in context.Interviews 112.                                     where x.InterviewID == (e.Appointment as InterviewAppointment).InterviewID 113.                                     select x).SingleOrDefault(); 114.   115.        CopyAppointmentEdit(editedInterview, e.Appointment as InterviewAppointment); 116.   117.        context.SubmitChanges((s) => 118.        { 119.            ActionHistory myAction = new ActionHistory(); 120.            myAction.InterviewID = editedInterview.InterviewID; 121.            myAction.PostingID = editedInterview.PostingID; 122.            myAction.ApplicantID = editedInterview.ApplicantID; 123.            myAction.Description = String.Format("Interview with {0} has been modified by {1}", editedInterview.ApplicantID.ToString(), "default user"); 124.            myAction.TimeStamp = DateTime.Now; 125.            context.ActionHistories.Add(myAction); 126.            context.SubmitChanges(); 127.        } 128.            , null); 129.    } 130.   131.    private void xJobsScheduler_AppointmentDeleted(object sender, Telerik.Windows.Controls.AppointmentDeletedEventArgs e) 132.    { 133.        Interview deletedInterview = (from x in context.Interviews 134.                                      where x.InterviewID == (e.Appointment as InterviewAppointment).InterviewID 135.                                      select x).SingleOrDefault(); 136.   137.        context.Interviews.Remove(deletedInterview); 138.        context.SubmitChanges((s) => 139.        { 140.            ActionHistory myAction = new ActionHistory(); 141.            myAction.InterviewID = deletedInterview.InterviewID; 142.            myAction.PostingID = deletedInterview.PostingID; 143.            myAction.ApplicantID = deletedInterview.ApplicantID; 144.            myAction.Description = String.Format("Interview with {0} has been deleted by {1}", deletedInterview.ApplicantID.ToString(), "default user"); 145.            myAction.TimeStamp = DateTime.Now; 146.            context.ActionHistories.Add(myAction); 147.            context.SubmitChanges(); 148.        } 149.            , null); 150.    } 151.   152.    #region Appointment Helpers :) 153.   154.    public Interview AppointmentToEntity(InterviewAppointment ia) 155.    { 156.        Interview newInterview = new Interview(); 157.        newInterview.Subject = ia.Subject; 158.        newInterview.Body = ia.Body; 159.        newInterview.Start = ia.Start; 160.        newInterview.End = ia.End; 161.        newInterview.ApplicantID = ia.ApplicantID; 162.        newInterview.PostingID = ia.PostingID; 163.        newInterview.InterviewID = ia.InterviewID; 164.   165.        return newInterview; 166.    } 167.   168.    public InterviewAppointment EntityToAppointment(Interview ia) 169.    { 170.        InterviewAppointment newInterview = new InterviewAppointment(); 171.        newInterview.Subject = ia.Subject; 172.        newInterview.Body = ia.Body; 173.        newInterview.Start = ia.Start; 174.        newInterview.End = ia.End; 175.        newInterview.ApplicantID = ia.ApplicantID; 176.        newInterview.PostingID = ia.PostingID; 177.        newInterview.InterviewID = ia.InterviewID; 178.   179.        return newInterview; 180.    } 181.   182.    public void CopyAppointmentEdit(Interview entityInterview, InterviewAppointment appointmentInterview) 183.    { 184.        entityInterview.Subject = appointmentInterview.Subject; 185.        entityInterview.Body = appointmentInterview.Body; 186.        entityInterview.Start = appointmentInterview.Start; 187.        entityInterview.End = appointmentInterview.End; 188.        entityInterview.ApplicantID = appointmentInterview.ApplicantID; 189.        entityInterview.PostingID = appointmentInterview.PostingID; 190.    } 191.   192.    #endregion 193.   194.    #region INotifyPropertyChanged Members 195.   196.    public event PropertyChangedEventHandler PropertyChanged; 197.   198.    public void NotifyChanged(string propertyName) 199.    { 200.        if (string.IsNullOrEmpty(propertyName)) 201.            throw new ArgumentException("propertyName"); 202.   203.        PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 204.    } 205.   206.    #endregion 207.} Nice... right? :) One really important thing to note as well.  See on line 51 where I set the DataContext before the Loaded event?  This is super important, as if you don't have this set before the usercontrol is loaded, the DataContextProxy has no context to use and your EditAppointmentDialog Job/Applicant dropdowns will be blank and empty.  Trust me on this, took a little bit of debugging to figure out that by setting the DataContext post-loaded would only lead to disaster and frustration.  Otherwise, the only other real difference is that instead of sending an ActionHistory item through an event to get added to the database and saved, I do those right in the callback from submitting.  The Result Again, I only have to post one picture because these bad boys used nearly identical code for both the MVVM and the code-behind views, so our end result is... So what have we learned here today?  One, for the most part this MVVM thing is somewhat easy.  Yeah, you sometimes have to write a bunch of extra code, but with the help of a few useful snippits you can turn the process into a pretty streamlined little workflow.  Heck, this story gets even easier as you can see in this blog post by Michael Washington- specifically run a find on 'InvokeCommandAction' and you'll see the section regarding the command on TreeView in Blend 4.  Brilliant!  MVVM never looked so sweet! Otherwise, it is business as usual with RadScheduler for Silverlight whichever path you're choosing for your development.  Between now and the next post, I'll be cleaning up styles a bit (those RadComboBoxes are a little too close to my labels!) and adding some to the RowDetailsViews for Applicants and Jobs, so you can see all the info for an appointment in the dropdown tab view.  Otherwise, we're about ready to call a wrap on this oneDid you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Silverlight Recruiting Application Part 6 - Adding an Interview Scheduling Module/View

    Between the last post and this one I went ahead and carried the ideas for the Jobs module and view into the Applicants module and view- they're both doing more or less the same thing, except with different objects being at their core.  Made for an easy cut-and-paste operation with a few items being switched from one to another.  Now that we have the ability to add postings and applicants, wouldn't it be nice if we could schedule an interview?  Of course it would! Scheduling Module I think you get the drift from previous posts that these project structures start looking somewhat similar.  The interview scheduling module is no different than the rest- it gets a SchedulingModule.cs file at the root that inherits from IModule, and there is a single SchedulerView.xsml and SchedulerViewModel.cs setup for our V+VM.  We have one unique concern as we enter into this- RadScheduler deals with AppointmentsSource, not ItemsSource, so there are some special considerations to take into account when planning this module. First, I need something which inherits from AppointmentBase.  This is the core of the RadScheduler appointment, and if you are planning to do any form of custom appointment, you'll want it to inherit from this.  Then you can add-on functionality as needed.  Here is my addition to the mix, the InterviewAppointment: 01.public class InterviewAppointment : AppointmentBase 02.{ 03.    private int _applicantID; 04.    public int ApplicantID 05.    { 06.        get { return this._applicantID; } 07.        set 08.        { 09.            if (_applicantID != value) 10.            { 11.                _applicantID = value; 12.                OnPropertyChanged("ApplicantID"); 13.            } 14.        } 15.    } 16.   17.    private int _postingID; 18.    public int PostingID 19.    { 20.        get { return _postingID; } 21.        set 22.        { 23.            if (_postingID != value) 24.            { 25.                _postingID = value; 26.                OnPropertyChanged("PostingID"); 27.            } 28.        } 29.    } 30.   31.    private string _body; 32.    public string Body 33.    { 34.        get { return _body; } 35.        set 36.        { 37.            if (_body != value) 38.            { 39.                _body = value; 40.                OnPropertyChanged("Body"); 41.            } 42.        } 43.    } 44.   45.    private int _interviewID; 46.    public int InterviewID 47.    { 48.        get { return _interviewID; } 49.        set 50.        { 51.            if (_interviewID != value) 52.            { 53.                _interviewID = value; 54.                OnPropertyChanged("InterviewID"); 55.            } 56.        } 57.    } 58.   59.    public override IAppointment Copy() 60.    { 61.        IAppointment appointment = new InterviewAppointment(); 62.        appointment.CopyFrom(this);             63.        return appointment; 64.    } 65.   66.    public override void CopyFrom(IAppointment other) 67.    {             68.        base.CopyFrom(other); 69.        var appointment = other as InterviewAppointment; 70.        if (appointment != null) 71.        { 72.            ApplicantID = appointment.ApplicantID; 73.            PostingID = appointment.PostingID; 74.            Body = appointment.Body; 75.            InterviewID = appointment.InterviewID; 76.        } 77.    } 78.} Nothing too exciting going on here, we just make sure that our custom fields are persisted (specifically set in CopyFrom at the bottom) and notifications are fired- otherwise this ends up exactly like the standard appointment as far as interactions, etc.  But if we've got custom appointment items... that also means we need to customize what our appointment dialog window will look like. Customizing the Edit Appointment Dialog This initially sounds a lot more intimidating than it really is.  The first step here depends on what you're dealing with for theming, but for ease of everything I went ahead and extracted my templates in Blend for RadScheduler so I could modify it as I pleased.  For the faint of heart, the RadScheduler template is a few thousand lines of goodness since there are some very complex things going on in that control.  I've gone ahead and trimmed down the template parts I don't need as much as possible, so what is left is all that is relevant to the Edit Appointment Dialog.  Here's the resulting Xaml, with line numbers, so I can explain further: 001.<UserControl.Resources> 002.    <!-- begin Necessary Windows 7 Theme Resources for EditAppointmentTemplate --> 003.    <helpers:DataContextProxy x:Key="DataContextProxy" /> 004.       005.    <telerik:Windows7Theme x:Key="Theme" /> 006.    <SolidColorBrush x:Key="DialogWindowBackground" 007.                     Color="White" /> 008.    <SolidColorBrush x:Key="CategorySelectorBorderBrush" 009.                     Color="#FFB1B1B1" /> 010.    <LinearGradientBrush x:Key="RadToolBar_InnerBackground" 011.                         EndPoint="0.5,1" 012.                         StartPoint="0.5,0"> 013.        <GradientStop Color="#FFFDFEFF" 014.                      Offset="0" /> 015.        <GradientStop Color="#FFDDE9F7" 016.                      Offset="1" /> 017.        <GradientStop Color="#FFE6F0FA" 018.                      Offset="0.5" /> 019.        <GradientStop Color="#FFDCE6F4" 020.                      Offset="0.5" /> 021.    </LinearGradientBrush> 022.    <Style x:Key="FormElementTextBlockStyle" 023.           TargetType="TextBlock"> 024.        <Setter Property="HorizontalAlignment" 025.                Value="Right" /> 026.        <Setter Property="VerticalAlignment" 027.                Value="Top" /> 028.        <Setter Property="Margin" 029.                Value="15, 15, 0, 2" /> 030.    </Style> 031.    <Style x:Key="FormElementStyle" 032.           TargetType="FrameworkElement"> 033.        <Setter Property="Margin" 034.                Value="10, 10, 0, 2" /> 035.    </Style> 036.    <SolidColorBrush x:Key="GenericShallowBorderBrush" 037.                     Color="#FF979994" /> 038.    <telerik:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> 039.    <telerikScheduler:ImportanceToBooleanConverter x:Key="ImportanceToBooleanConverter" /> 040.    <telerikScheduler:NullToVisibilityConverter x:Key="NullToVisibilityConverter" /> 041.    <telerikScheduler:InvertedNullToVisibilityConverter x:Key="InvertedNullToVisibilityConverter" /> 042.    <scheduler:ResourcesSeparatorConverter x:Key="ResourcesSeparatorConverter" /> 043.    <DataTemplate x:Key="IconDataEditTemplate"> 044.        <Image Source="/Telerik.Windows.Controls.Scheduler;component/Themes/Office/Images/cal.png" 045.               Margin="3,3,0,0" 046.               Width="16" 047.               Height="16" /> 048.    </DataTemplate> 049.    <DataTemplate x:Key="SingleSelectionTemplate"> 050.        <Grid VerticalAlignment="Stretch" 051.              HorizontalAlignment="Stretch"> 052.            <Grid.RowDefinitions> 053.                <RowDefinition Height="Auto" /> 054.            </Grid.RowDefinitions> 055.            <Grid.ColumnDefinitions> 056.                <ColumnDefinition Width="Auto" 057.                                  MinWidth="84" /> 058.                <ColumnDefinition Width="Auto" 059.                                  MinWidth="200" /> 060.            </Grid.ColumnDefinitions> 061.            <TextBlock x:Name="SelectionNameLabel" 062.                       Margin="0,13,4,2" 063.                       Text="{Binding ResourceType.DisplayName}" 064.                       Style="{StaticResource FormElementTextBlockStyle}" 065.                       Grid.Column="0" /> 066.            <telerikInput:RadComboBox ItemsSource="{Binding ResourceItems}" 067.                                      Width="185" 068.                                      Margin="5,10,20,2" 069.                                      HorizontalAlignment="Left" 070.                                      Grid.Column="1" 071.                                      ClearSelectionButtonVisibility="Visible" 072.                                      ClearSelectionButtonContent="Clear All" 073.                                      DisplayMemberPath="Resource.DisplayName" 074.                                      telerik:StyleManager.Theme="{StaticResource Theme}" 075.                                      SelectedItem="{Binding SelectedItem, Mode=TwoWay}" /> 076.        </Grid> 077.    </DataTemplate> 078.    <DataTemplate x:Key="MultipleSelectionTemplate"> 079.        <Grid VerticalAlignment="Stretch" 080.              HorizontalAlignment="Stretch"> 081.            <Grid.RowDefinitions> 082.                <RowDefinition Height="Auto" /> 083.            </Grid.RowDefinitions> 084.            <Grid.ColumnDefinitions> 085.                <ColumnDefinition Width="Auto" 086.                                  MinWidth="84" /> 087.                <ColumnDefinition Width="Auto" 088.                                  MinWidth="200" /> 089.            </Grid.ColumnDefinitions> 090.            <TextBlock x:Name="SelectionNameLabel" 091.                       Grid.Column="0" 092.                       Text="{Binding ResourceType.DisplayName}" 093.                       Margin="0,13,4,2" 094.                       Style="{StaticResource FormElementTextBlockStyle}" /> 095.            <telerikInput:RadComboBox Grid.Column="1" 096.                                      Width="185" 097.                                      HorizontalAlignment="Left" 098.                                      Margin="5,10,20,2" 099.                                      ItemsSource="{Binding ResourceItems}" 100.                                      SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" 101.                                      ClearSelectionButtonVisibility="Visible" 102.                                      ClearSelectionButtonContent="Clear All" 103.                                      telerik:StyleManager.Theme="{StaticResource Theme}"> 104.                <telerikInput:RadComboBox.ItemTemplate> 105.                    <DataTemplate> 106.                        <Grid HorizontalAlignment="Stretch" 107.                              VerticalAlignment="Stretch"> 108.                            <CheckBox VerticalAlignment="Center" 109.                                      HorizontalContentAlignment="Stretch" 110.                                      VerticalContentAlignment="Center" 111.                                      IsChecked="{Binding IsChecked, Mode=TwoWay}" 112.                                      Content="{Binding Resource.DisplayName}"> 113.                                <CheckBox.ContentTemplate> 114.                                    <DataTemplate> 115.                                        <TextBlock HorizontalAlignment="Stretch" 116.                                                   VerticalAlignment="Stretch" 117.                                                   Text="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" /> 118.                                    </DataTemplate> 119.                                </CheckBox.ContentTemplate> 120.                            </CheckBox> 121.                        </Grid> 122.                    </DataTemplate> 123.                </telerikInput:RadComboBox.ItemTemplate> 124.            </telerikInput:RadComboBox> 125.        </Grid> 126.    </DataTemplate> 127.    <scheduler:ResourceTypeTemplateSelector x:Key="ItemTemplateSelector" 128.                                            MultipleSelectionTemplate="{StaticResource MultipleSelectionTemplate}" 129.                                            SingleSelectionTemplate="{StaticResource SingleSelectionTemplate}" /> 130.    <!-- end Necessary Windows 7 Theme Resources for EditAppointmentTemplate -->  131.       132.    <ControlTemplate x:Key="EditAppointmentTemplate" 133.                     TargetType="telerikScheduler:AppointmentDialogWindow"> 134.        <StackPanel Background="{TemplateBinding Background}" 135.                    UseLayoutRounding="True"> 136.            <StackPanel Grid.Row="0" 137.                        Orientation="Horizontal" 138.                        Background="{StaticResource RadToolBar_InnerBackground}" 139.                        Grid.ColumnSpan="2" 140.                        Height="0"> 141.                <!-- Recurrence buttons --> 142.                <Border Margin="1,1,0,0" 143.                        Background="#50000000" 144.                        HorizontalAlignment="Left" 145.                        VerticalAlignment="Center" 146.                        Width="2" 147.                        Height="16"> 148.                    <Border Margin="0,0,1,1" 149.                            Background="#80FFFFFF" 150.                            HorizontalAlignment="Left" 151.                            Width="1" /> 152.                </Border> 153.                <Border Margin="1,1,0,0" 154.                        Background="#50000000" 155.                        HorizontalAlignment="Left" 156.                        VerticalAlignment="Center" 157.                        Width="2" 158.                        Height="16"> 159.                    <Border Margin="0,0,1,1" 160.                            Background="#80FFFFFF" 161.                            HorizontalAlignment="Left" 162.                            Width="1" /> 163.                </Border> 164.                <TextBlock telerik:LocalizationManager.ResourceKey="ShowAs" 165.                           VerticalAlignment="Center" 166.                           Margin="5,0,0,0" /> 167.                <telerikInput:RadComboBox ItemsSource="{TemplateBinding TimeMarkers}" 168.                                          Width="100" 169.                                          Height="20" 170.                                          VerticalAlignment="Center" 171.                                          Margin="5,0,0,0" 172.                                          ClearSelectionButtonVisibility="Visible" 173.                                          ClearSelectionButtonContent="Clear" 174.                                          SelectedItem="{Binding TimeMarker,RelativeSource={RelativeSource TemplatedParent},Mode=TwoWay}" 175.                                          telerik:StyleManager.Theme="{StaticResource Theme}"> 176.                    <telerikInput:RadComboBox.ItemTemplate> 177.                        <DataTemplate> 178.                            <StackPanel Orientation="Horizontal"> 179.                                <Rectangle Fill="{Binding TimeMarkerBrush}" 180.                                           Margin="2" 181.                                           Width="12" 182.                                           Height="12" /> 183.                                <TextBlock Text="{Binding TimeMarkerName}" 184.                                           Margin="2" /> 185.                            </StackPanel> 186.                        </DataTemplate> 187.                    </telerikInput:RadComboBox.ItemTemplate> 188.                </telerikInput:RadComboBox> 189.                <telerik:RadToggleButton x:Name="High" 190.                                         BorderThickness="0" 191.                                         Background="{StaticResource RadToolBar_InnerBackground}" 192.                                         DataContext="{TemplateBinding EditedAppointment}" 193.                                         telerik:StyleManager.Theme="{StaticResource Theme}" 194.                                         IsChecked="{Binding Importance,Mode=TwoWay, Converter={StaticResource ImportanceToBooleanConverter},ConverterParameter=High}" 195.                                         Margin="2,2,0,2" 196.                                         Width="23" 197.                                         Height="23" 198.                                         HorizontalContentAlignment="Center" 199.                                         ToolTipService.ToolTip="High importance" 200.                                         CommandParameter="High" 201.                                         Command="telerikScheduler:RadSchedulerCommands.SetAppointmentImportance"> 202.                    <StackPanel HorizontalAlignment="Center"> 203.                        <Path Stretch="Fill" 204.                              Height="10" 205.                              HorizontalAlignment="Center" 206.                              VerticalAlignment="Top" 207.                              Width="5.451" 208.                              Data="M200.39647,58.840393 C200.39337,58.336426 201.14566,57.683922 202.56244,57.684292 C204.06589,57.684685 204.73764,58.357765 204.72783,58.992363 C205.04649,61.795574 203.04713,64.181099 202.47388,66.133446 C201.93753,64.154961 199.9471,61.560352 200.39647,58.840393 z"> 209.                            <Path.Fill> 210.                                <LinearGradientBrush EndPoint="1.059,0.375" 211.                                                     StartPoint="-0.457,0.519"> 212.                                    <GradientStop Color="#FFFF0606" 213.                                                  Offset="0.609" /> 214.                                    <GradientStop Color="#FFBF0303" 215.                                                  Offset="0.927" /> 216.                                </LinearGradientBrush> 217.                            </Path.Fill> 218.                        </Path> 219.                        <Ellipse Height="3" 220.                                 HorizontalAlignment="Center" 221.                                 Margin="0,-1,0,0" 222.                                 VerticalAlignment="Top" 223.                                 Width="3"> 224.                            <Ellipse.Fill> 225.                                <RadialGradientBrush> 226.                                    <GradientStop Color="#FFFF0606" 227.                                                  Offset="0" /> 228.                                    <GradientStop Color="#FFBF0303" 229.                                                  Offset="1" /> 230.                                </RadialGradientBrush> 231.                            </Ellipse.Fill> 232.                        </Ellipse> 233.                    </StackPanel> 234.                </telerik:RadToggleButton> 235.                <telerik:RadToggleButton x:Name="Low" 236.                                         HorizontalContentAlignment="Center" 237.                                         BorderThickness="0" 238.                                         Background="{StaticResource RadToolBar_InnerBackground}" 239.                                         DataContext="{TemplateBinding EditedAppointment}" 240.                                         IsChecked="{Binding Importance,Mode=TwoWay, Converter={StaticResource ImportanceToBooleanConverter},ConverterParameter=Low}" 241.                                         Margin="0,2,0,2" 242.                                         Width="23" 243.                                         Height="23" 244.                                         ToolTipService.ToolTip="Low importance" 245.                                         CommandParameter="Low" 246.                                         telerik:StyleManager.Theme="{StaticResource Theme}" 247.                                         Command="telerikScheduler:RadSchedulerCommands.SetAppointmentImportance"> 248.                    <Path Stretch="Fill" 249.                          Height="12" 250.                          HorizontalAlignment="Center" 251.                          VerticalAlignment="Top" 252.                          Width="9" 253.                          Data="M222.40353,60.139881 L226.65768,60.139843 L226.63687,67.240196 L229.15347,67.240196 L224.37816,71.394943 L219.65274,67.240196 L222.37572,67.219345 z" 254.                          Stroke="#FF0365A7"> 255.                        <Path.Fill> 256.                            <LinearGradientBrush EndPoint="1.059,0.375" 257.                                                 StartPoint="-0.457,0.519"> 258.                                <GradientStop Color="#FFBBE4FF" /> 259.                                <GradientStop Color="#FF024572" 260.                                              Offset="0.836" /> 261.                                <GradientStop Color="#FF43ADF4" 262.                                              Offset="0.466" /> 263.                            </LinearGradientBrush> 264.                        </Path.Fill> 265.                    </Path> 266.                </telerik:RadToggleButton> 267.            </StackPanel > 268.            <Border DataContext="{TemplateBinding EditedAppointment}" 269.                    Background="{Binding Category.CategoryBrush}" 270.                    Visibility="{Binding Category,Converter={StaticResource NullToVisibilityConverter}}" 271.                    CornerRadius="3" 272.                    Height="20" 273.                    Margin="5,10,5,0"> 274.                <TextBlock Text="{Binding Category.DisplayName}" 275.                           VerticalAlignment="Center" 276.                           Margin="5,0,0,0" /> 277.            </Border> 278.            <Grid VerticalAlignment="Stretch" 279.                  HorizontalAlignment="Stretch" 280.                  DataContext="{TemplateBinding EditedAppointment}" 281.                  Background="{TemplateBinding Background}"> 282.                <Grid.RowDefinitions> 283.                    <RowDefinition Height="Auto" /> 284.                    <RowDefinition Height="Auto" /> 285.                    <RowDefinition Height="Auto" /> 286.                    <RowDefinition Height="Auto" /> 287.                    <RowDefinition Height="Auto" /> 288.                    <RowDefinition Height="Auto" /> 289.                    <RowDefinition Height="Auto" /> 290.                    <RowDefinition Height="Auto" /> 291.                    <RowDefinition Height="Auto" /> 292.                    <RowDefinition Height="Auto" /> 293.                </Grid.RowDefinitions> 294.                <Grid.ColumnDefinitions> 295.                    <ColumnDefinition Width="Auto" 296.                                      MinWidth="100" /> 297.                    <ColumnDefinition Width="Auto" 298.                                      MinWidth="200" /> 299.                </Grid.ColumnDefinitions> 300.                <!-- Subject --> 301.                <TextBlock x:Name="SubjectLabel" 302.                           Grid.Row="0" 303.                           Grid.Column="0" 304.                           Margin="0,15,0,2" 305.                           telerik:LocalizationManager.ResourceKey="Subject" 306.                           Style="{StaticResource FormElementTextBlockStyle}" /> 307.                <TextBox x:Name="Subject" 308.                         Grid.Row="0" 309.                         Grid.Column="1" 310.                         MinHeight="22" 311.                         Padding="4 2" 312.                         Width="340" 313.                         HorizontalAlignment="Left" 314.                         Text="{Binding Subject, Mode=TwoWay}" 315.                         MaxLength="255" 316.                         telerik:StyleManager.Theme="{StaticResource Theme}" 317.                         Margin="10,12,20,2" /> 318.                <!-- Description --> 319.                <TextBlock x:Name="DescriptionLabel" 320.                           Grid.Row="1" 321.                           Grid.Column="0" 322.                           Margin="0,13,0,2" 323.                           telerik:LocalizationManager.ResourceKey="Body" 324.                           Style="{StaticResource FormElementTextBlockStyle}" /> 325.                <TextBox x:Name="Body" 326.                         VerticalAlignment="top" 327.                         Grid.Row="1" 328.                         Grid.Column="1" 329.                         Height="Auto" 330.                         MaxHeight="82" 331.                         Width="340" 332.                         HorizontalAlignment="Left" 333.                         MinHeight="22" 334.                         Padding="4 2" 335.                         TextWrapping="Wrap" 336.                         telerik:StyleManager.Theme="{StaticResource Theme}" 337.                         Text="{Binding Body, Mode=TwoWay}" 338.                         AcceptsReturn="true" 339.                         Margin="10,10,20,2" 340.                         HorizontalScrollBarVisibility="Auto" 341.                         VerticalScrollBarVisibility="Auto" /> 342.                <!-- Start/End date --> 343.                <TextBlock x:Name="StartDateLabel" 344.                           Grid.Row="2" 345.                           Grid.Column="0" 346.                           Margin="0,13,0,2" 347.                           telerik:LocalizationManager.ResourceKey="StartTime" 348.                           Style="{StaticResource FormElementTextBlockStyle}" /> 349.                <telerikScheduler:DateTimePicker x:Name="StartDateTime" 350.                                                 Height="22" 351.                                                 Grid.Row="2" 352.                                                 Grid.Column="1" 353.                                                 HorizontalAlignment="Left" 354.                                                 Margin="10,10,20,2" 355.                                                 Style="{StaticResource FormElementStyle}" 356.                                                 SelectedDateTime="{Binding Start, Mode=TwoWay}" 357.                                                 telerikScheduler:StartEndDatePicker.EndPicker="{Binding ElementName=EndDateTime}" 358.                                                 IsTabStop="False" 359.                                                 IsEnabled="False" /> 360.                <TextBlock x:Name="EndDateLabel" 361.                           Grid.Row="3" 362.                           Grid.Column="0" 363.                           Margin="0,13,0,2" 364.                           telerik:LocalizationManager.ResourceKey="EndTime" 365.                           Style="{StaticResource FormElementTextBlockStyle}" /> 366.                <telerikScheduler:DateTimePicker x:Name="EndDateTime" 367.                                                 Height="22" 368.                                                 Grid.Row="3" 369.                                                 Grid.Column="1" 370.                                                 HorizontalAlignment="Left" 371.                                                 Margin="10,10,20,2" 372.                                                 Style="{StaticResource FormElementStyle}" 373.                                                 IsTabStop="False" 374.                                                 IsEnabled="False" 375.                                                 SelectedDateTime="{Binding End, Mode=TwoWay}" /> 376.                <!-- Is-all-day selector --> 377.                <CheckBox x:Name="AllDayEventCheckbox" 378.                          IsChecked="{Binding IsAllDayEvent, Mode=TwoWay}" 379.                          Grid.Row="4" 380.                          Grid.Column="1" 381.                          Margin="10,10,20,2" 382.                          HorizontalAlignment="Left" 383.                          telerik:StyleManager.Theme="{StaticResource Theme}" 384.                          telerik:LocalizationManager.ResourceKey="AllDayEvent"> 385.                    <telerik:CommandManager.InputBindings> 386.                        <telerik:InputBindingCollection> 387.                            <telerik:MouseBinding Command="telerikScheduler:RadSchedulerCommands.ChangeTimePickersVisibility" 388.                                                  Gesture="LeftClick" /> 389.                        </telerik:InputBindingCollection> 390.                    </telerik:CommandManager.InputBindings> 391.                </CheckBox> 392.                <Grid Grid.Row="5" 393.                      Grid.ColumnSpan="2"> 394.                    <Grid.ColumnDefinitions> 395.                        <ColumnDefinition Width="Auto" 396.                                          MinWidth="100" /> 397.                        <ColumnDefinition Width="Auto" 398.                                          MinWidth="200" /> 399.                    </Grid.ColumnDefinitions> 400.                    <Grid.RowDefinitions> 401.                        <RowDefinition Height="Auto" /> 402.                        <RowDefinition Height="Auto" /> 403.                    </Grid.RowDefinitions> 404.                    <TextBlock Text="Applicant" 405.                               Margin="0,13,0,2" 406.                               Style="{StaticResource FormElementTextBlockStyle}" /> 407.                    <telerikInput:RadComboBox IsEditable="False" 408.                                              Grid.Column="1" 409.                                              Height="24" 410.                                              VerticalAlignment="Center" 411.                                              ItemsSource="{Binding Source={StaticResource DataContextProxy}, Path=DataSource.ApplicantList}" 412.                                              SelectedValue="{Binding ApplicantID, Mode=TwoWay}" 413.                                              SelectedValuePath="ApplicantID" 414.                                              DisplayMemberPath="FirstName" /> 415.                       416.                    <TextBlock Text="Job" 417.                               Margin="0,13,0,2" 418.                               Grid.Row="1" 419.                               Style="{StaticResource FormElementTextBlockStyle}" /> 420.                    <telerikInput:RadComboBox IsEditable="False" 421.                                              Grid.Column="1" 422.                                              Grid.Row="1" 423.                                              Height="24" 424.                                              VerticalAlignment="Center" 425.                                              ItemsSource="{Binding Source={StaticResource DataContextProxy}, Path=DataSource.JobsList}" 426.                                              SelectedValue="{Binding PostingID, Mode=TwoWay}" 427.                                              SelectedValuePath="PostingID" 428.                                              DisplayMemberPath="JobTitle"/> 429.                </Grid> 430.                    <!-- Resources --> 431.                <Grid x:Name="ResourcesLayout" 432.                      Grid.Row="7" 433.                      Grid.Column="0" 434.                      Grid.ColumnSpan="2" 435.                      MaxHeight="130" 436.                      Margin="20,5,20,0"> 437.                    <Border Margin="0" 438.                            BorderThickness="1" 439.                            BorderBrush="{StaticResource GenericShallowBorderBrush}" 440.                            Visibility="{Binding ElementName=ResourcesScrollViewer, Path=ComputedVerticalScrollBarVisibility}"></Border> 441.                    <ScrollViewer x:Name="ResourcesScrollViewer" 442.                                  IsTabStop="false" 443.                                  Grid.Row="6" 444.                                  Grid.Column="0" 445.                                  Grid.ColumnSpan="2" 446.                                  Margin="1" 447.                                  telerik:StyleManager.Theme="{StaticResource Theme}" 448.                                  VerticalScrollBarVisibility="Auto"> 449.                        <scheduler:ResourcesItemsControl x:Name="PART_Resources" 450.                                                         HorizontalAlignment="Left" 451.                                                         Padding="0,2,0,5" 452.                                                         IsTabStop="false" 453.                                                         ItemsSource="{TemplateBinding ResourceTypeModels}" 454.                                                         ItemTemplateSelector="{StaticResource ItemTemplateSelector}" /> 455.                    </ScrollViewer> 456.                </Grid> 457.                <StackPanel x:Name="FooterControls" 458.                            Margin="5 10 10 10" 459.                            Grid.Row="8" 460.                            Grid.Column="1" 461.                            HorizontalAlignment="Left" 462.                            Orientation="Horizontal"> 463.                    <telerik:RadButton x:Name="OKButton" 464.                                       Margin="5" 465.                                       Padding="10 0" 466.                                       MinWidth="80" 467.                                       Command="telerikScheduler:RadSchedulerCommands.SaveAppointment" 468.                                       telerik:StyleManager.Theme="{StaticResource Theme}" 469.                                       telerikNavigation:RadWindow.ResponseButton="Accept" 470.                                       telerik:LocalizationManager.ResourceKey="SaveAndCloseCommandText"> 471.                    </telerik:RadButton> 472.                    <telerik:RadButton x:Name="CancelButton" 473.                                       Margin="5" 474.                                       Padding="10 0" 475.                                       MinWidth="80" 476.                                       telerik:LocalizationManager.ResourceKey="Cancel" 477.                                       telerik:StyleManager.Theme="{StaticResource Theme}" 478.                                       telerikNavigation:RadWindow.ResponseButton="Cancel" 479.                                       Command="telerik:WindowCommands.Close"> 480.                    </telerik:RadButton> 481.                </StackPanel> 482.            </Grid> 483.            <vsm:VisualStateManager.VisualStateGroups> 484.                <vsm:VisualStateGroup x:Name="RecurrenceRuleState"> 485.                    <vsm:VisualState x:Name="RecurrenceRuleIsNull"> 486.                        <Storyboard> 487.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="StartDateTime" 488.                                                           Storyboard.TargetProperty="IsEnabled" 489.                                                           Duration="0"> 490.                                <DiscreteObjectKeyFrame KeyTime="0" 491.                                                        Value="True" /> 492.                            </ObjectAnimationUsingKeyFrames> 493.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="EndDateTime" 494.                                                           Storyboard.TargetProperty="IsEnabled" 495.                                                           Duration="0"> 496.                                <DiscreteObjectKeyFrame KeyTime="0" 497.                                                        Value="True" /> 498.                            </ObjectAnimationUsingKeyFrames> 499.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AllDayEventCheckbox" 500.                                                           Storyboard.TargetProperty="IsEnabled" 501.                                                           Duration="0"> 502.                                <DiscreteObjectKeyFrame KeyTime="0" 503.                                                        Value="True" /> 504.                            </ObjectAnimationUsingKeyFrames> 505.                        </Storyboard> 506.                    </vsm:VisualState> 507.                    <vsm:VisualState x:Name="RecurrenceRuleIsNotNull"> 508.                        <Storyboard> 509.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="StartDateTime" 510.                                                           Storyboard.TargetProperty="IsEnabled" 511.                                                           Duration="0"> 512.                                <DiscreteObjectKeyFrame KeyTime="0" 513.                                                        Value="False" /> 514.                            </ObjectAnimationUsingKeyFrames> 515.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="EndDateTime" 516.                                                           Storyboard.TargetProperty="IsEnabled" 517.                                                           Duration="0"> 518.                                <DiscreteObjectKeyFrame KeyTime="0" 519.                                                        Value="False" /> 520.                            </ObjectAnimationUsingKeyFrames> 521.                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="AllDayEventCheckbox" 522.                                                           Storyboard.TargetProperty="IsEnabled" 523.                                                           Duration="0"> 524.                                <DiscreteObjectKeyFrame KeyTime="0" 525.                                                        Value="False" /> 526.                            </ObjectAnimationUsingKeyFrames> 527.                        </Storyboard> 528.                    </vsm:VisualState> 529.                </vsm:VisualStateGroup> 530.            </vsm:VisualStateManager.VisualStateGroups> 531.        </StackPanel> 532.    </ControlTemplate> 533.    <DataTemplate x:Key="AppointmentDialogWindowHeaderDataTemplate"> 534.        <StackPanel Orientation="Horizontal" 535.                    MaxWidth="400"> 536.            <TextBlock telerik:LocalizationManager.ResourceKey="Event" 537.                       Visibility="{Binding Appointment.IsAllDayEvent, Converter={StaticResource BooleanToVisibilityConverter}}" /> 538.            <TextBlock telerik:LocalizationManager.ResourceKey="Appointment" 539.                       Visibility="{Binding Appointment.IsAllDayEvent, Converter={StaticResource InvertedBooleanToVisibilityConverter}}" /> 540.            <TextBlock Text=" - " /> 541.            <TextBlock x:Name="SubjectTextBlock" 542.                       Visibility="{Binding Appointment.Subject, Converter={StaticResource NullToVisibilityConverter}}" 543.                       Text="{Binding Appointment.Subject}" /> 544.            <TextBlock telerik:LocalizationManager.ResourceKey="Untitled" 545.                       Visibility="{Binding Appointment.Subject, Converter={StaticResource InvertedNullToVisibilityConverter}}" /> 546.        </StackPanel> 547.    </DataTemplate> 548.    <Style x:Key="EditAppointmentStyle" 549.           TargetType="telerikScheduler:AppointmentDialogWindow"> 550.        <Setter Property="IconTemplate" 551.                Value="{StaticResource IconDataEditTemplate}" /> 552.        <Setter Property="HeaderTemplate" 553.                Value="{StaticResource AppointmentDialogWindowHeaderDataTemplate}" /> 554.        <Setter Property="Background" 555.                Value="{StaticResource DialogWindowBackground}" /> 556.        <Setter Property="Template" 557.                Value="{StaticResource EditAppointmentTemplate}" /> 558.    </Style> 559.</UserControl.Resources> The first line there is the DataContextProxy I mentioned previously- we use that again to work a bit of magic in this template. Where we start getting into the dialog in question is line 132, but line 407 is where things start getting interesting.  The ItemsSource is pointing at a list that exists in my ViewModel (or code-behind, if it is used as a DataContext), the SelectedValue is the item I am actually binding from the applicant (note the TwoWay binding), and SelectedValuePath and DisplayMemberPath ensure the proper applicant is being displayed from the collection.  You will also see similar starting on line 420 where I do the same for the Jobs we'll be displaying. Just to wrap-up the Xaml, here's the RadScheduler declaraction that ties this all together and will be the main focus of our view: 01.<telerikScheduler:RadScheduler x:Name="xJobsScheduler" 02.                  Grid.Row="1" 03.                  Grid.Column="1" 04.                  Width="800" 05.                  MinWidth="600" 06.                  Height="500" 07.                  MinHeight="300" 08.                  AppointmentsSource="{Binding Interviews}" 09.                  EditAppointmentStyle="{StaticResource EditAppointmentStyle}" 10.                  command:AppointmentAddedEventClass.Command="{Binding AddAppointmentCommand}" 11.                  command:ApptCreatedEventClass.Command="{Binding ApptCreatingCommand}" 12.                  command:ApptEditedEventClass.Command="{Binding ApptEditedCommand}" 13.                  command:ApptDeletedEventClass.Command="{Binding ApptDeletedCommand}"> 14.</telerikScheduler:RadScheduler> Now, we get to the ViewModel and what it takes to get that rigged up.  And for those of you who remember the jobs post, those command:s in the Xaml are pointing to attached behavior commands that reproduce the respective events.  This becomes very handy when we're setting up the code-behind version. ;) ViewModel I've been liking this approach so far, so I'm going to put the entire ViewModel here and then go into the lines of interest.  Of course, feel free to ask me questions about anything that isn't clear (by line number, ideally) so I can help out if I have missed anything important: 001.public class SchedulerViewModel : ViewModelBase 002.{ 003.    private readonly IEventAggregator eventAggregator; 004.    private readonly IRegionManager regionManager; 005.   006.    public RecruitingContext context; 007.   008.    private ObservableItemCollection<InterviewAppointment> _interviews = new ObservableItemCollection<InterviewAppointment>(); 009.    public ObservableItemCollection<InterviewAppointment> Interviews 010.    { 011.        get { return _interviews; } 012.        set 013.        { 014.            if (_interviews != value) 015.            { 016.                _interviews = value; 017.                NotifyChanged("Interviews"); 018.            } 019.        } 020.    } 021.   022.    private QueryableCollectionView _jobsList; 023.    public QueryableCollectionView JobsList 024.    { 025.        get { return this._jobsList; } 026.        set 027.        { 028.            if (this._jobsList != value) 029.            { 030.                this._jobsList = value; 031.                this.NotifyChanged("JobsList"); 032.            } 033.        } 034.    } 035.   036.    private QueryableCollectionView _applicantList; 037.    public QueryableCollectionView ApplicantList 038.    { 039.        get { return _applicantList; } 040.        set 041.        { 042.            if (_applicantList != value) 043.            { 044.                _applicantList = value; 045.                NotifyChanged("ApplicantList"); 046.            } 047.        } 048.    } 049.   050.    public DelegateCommand<object> AddAppointmentCommand { get; set; } 051.    public DelegateCommand<object> ApptCreatingCommand { get; set; } 052.    public DelegateCommand<object> ApptEditedCommand { get; set; } 053.    public DelegateCommand<object> ApptDeletedCommand { get; set; } 054.   055.    public SchedulerViewModel(IEventAggregator eventAgg, IRegionManager regionmanager) 056.    { 057.        // set Unity items 058.        this.eventAggregator = eventAgg; 059.        this.regionManager = regionmanager; 060.   061.        // load our context 062.        context = new RecruitingContext(); 063.        LoadOperation<Interview> loadOp = context.Load(context.GetInterviewsQuery()); 064.        loadOp.Completed += new EventHandler(loadOp_Completed); 065.   066.        this._jobsList = new QueryableCollectionView(context.JobPostings); 067.        context.Load(context.GetJobPostingsQuery()); 068.   069.        this._applicantList = new QueryableCollectionView(context.Applicants); 070.        context.Load(context.GetApplicantsQuery()); 071.   072.        AddAppointmentCommand = new DelegateCommand<object>(this.AddAppt); 073.        ApptCreatingCommand = new DelegateCommand<object>(this.ApptCreating); 074.        ApptEditedCommand = new DelegateCommand<object>(this.ApptEdited); 075.        ApptDeletedCommand = new DelegateCommand<object>(this.ApptDeleted); 076.   077.    } 078.   079.    void loadOp_Completed(object sender, EventArgs e) 080.    { 081.        LoadOperation loadop = sender as LoadOperation; 082.   083.        foreach (var ent in loadop.Entities) 084.        { 085.            _interviews.Add(EntityToAppointment(ent as Interview)); 086.        } 087.    } 088.   089.    #region Appointment Adding 090.   091.    public void AddAppt(object obj) 092.    { 093.        // now we have a new InterviewAppointment to add to our QCV :) 094.        InterviewAppointment newInterview = obj as InterviewAppointment; 095.   096.        this.context.Interviews.Add(AppointmentToEntity(newInterview)); 097.        this.context.SubmitChanges((s) => 098.        { 099.            ActionHistory myAction = new ActionHistory(); 100.            myAction.InterviewID = newInterview.InterviewID; 101.            myAction.PostingID = newInterview.PostingID; 102.            myAction.ApplicantID = newInterview.ApplicantID; 103.            myAction.Description = String.Format("Interview with {0} has been created by {1}", newInterview.ApplicantID.ToString(), "default user"); 104.            myAction.TimeStamp = DateTime.Now; 105.            eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 106.        } 107.            , null); 108.    } 109.   110.    public void ApptCreating(object obj) 111.    { 112.        // handled in the behavior, just a placeholder to ensure it runs :) 113.    } 114.   115.    #endregion 116.   117.    #region Appointment Editing 118.   119.    public void ApptEdited(object obj) 120.    { 121.        Interview editedInterview = (from x in context.Interviews 122.                            where x.InterviewID == (obj as InterviewAppointment).InterviewID 123.                            select x).SingleOrDefault(); 124.   125.        CopyAppointmentEdit(editedInterview, obj as InterviewAppointment); 126.   127.        context.SubmitChanges((s) => { 128.            ActionHistory myAction = new ActionHistory(); 129.            myAction.InterviewID = editedInterview.InterviewID; 130.            myAction.PostingID = editedInterview.PostingID; 131.            myAction.ApplicantID = editedInterview.ApplicantID; 132.            myAction.Description = String.Format("Interview with {0} has been modified by {1}", editedInterview.ApplicantID.ToString(), "default user"); 133.            myAction.TimeStamp = DateTime.Now; 134.            eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); } 135.            , null); 136.    } 137.   138.    #endregion 139.   140.    #region Appointment Deleting 141.   142.    public void ApptDeleted(object obj) 143.    { 144.        Interview deletedInterview = (from x in context.Interviews 145.                                      where x.InterviewID == (obj as InterviewAppointment).InterviewID 146.                                      select x).SingleOrDefault(); 147.   148.        context.Interviews.Remove(deletedInterview); 149.        context.SubmitChanges((s) => 150.        { 151.            ActionHistory myAction = new ActionHistory(); 152.            myAction.InterviewID = deletedInterview.InterviewID; 153.            myAction.PostingID = deletedInterview.PostingID; 154.            myAction.ApplicantID = deletedInterview.ApplicantID; 155.            myAction.Description = String.Format("Interview with {0} has been deleted by {1}", deletedInterview.ApplicantID.ToString(), "default user"); 156.            myAction.TimeStamp = DateTime.Now; 157.            eventAggregator.GetEvent<AddActionEvent>().Publish(myAction); 158.        } 159.            , null); 160.    } 161.   162.    #endregion 163.   164.    #region Appointment Helpers :) 165.   166.    public Interview AppointmentToEntity(InterviewAppointment ia) 167.    { 168.        Interview newInterview = new Interview(); 169.        newInterview.Subject = ia.Subject; 170.        newInterview.Body = ia.Body; 171.        newInterview.Start = ia.Start; 172.        newInterview.End = ia.End; 173.        newInterview.ApplicantID = ia.ApplicantID; 174.        newInterview.PostingID = ia.PostingID; 175.        newInterview.InterviewID = ia.InterviewID; 176.   177.        return newInterview; 178.    } 179.   180.    public InterviewAppointment EntityToAppointment(Interview ia) 181.    { 182.        InterviewAppointment newInterview = new InterviewAppointment(); 183.        newInterview.Subject = ia.Subject; 184.        newInterview.Body = ia.Body; 185.        newInterview.Start = ia.Start; 186.        newInterview.End = ia.End; 187.        newInterview.ApplicantID = ia.ApplicantID; 188.        newInterview.PostingID = ia.PostingID; 189.        newInterview.InterviewID = ia.InterviewID; 190.   191.        return newInterview; 192.    } 193.   194.    public void CopyAppointmentEdit(Interview entityInterview, InterviewAppointment appointmentInterview) 195.    { 196.        entityInterview.Subject = appointmentInterview.Subject; 197.        entityInterview.Body = appointmentInterview.Body; 198.        entityInterview.Start = appointmentInterview.Start; 199.        entityInterview.End = appointmentInterview.End; 200.        entityInterview.ApplicantID = appointmentInterview.ApplicantID; 201.        entityInterview.PostingID = appointmentInterview.PostingID; 202.    } 203.   204.    #endregion 205.} One thing we're doing here which you won't see in any of the other ViewModels is creating a duplicate collection.  I know this is something which will be fixed down the line for using RadScheduler, simplifying this process, but with WCF RIA changing as it does I wanted to ensure functionality would remain consistent as I continued development on this application.  So, I do a little bit of duplication, but for the greater good.  This all takes place starting on line 79, so for every entity that comes back we add it to the collection that is bound to RadScheduler.  Otherwise, the DelegateCommands that you see correspond directly to the events they are named after.  In each case, rather than sending over the full event arguments, I just send in the appointment in question (coming through as the object obj in all cases) so I can add (line 91), edit (line 119), and delete appointments (line 142) like normal.  This just ensures they get updated back to my database.  Also, the one bit of code you won't see is for the Appointment Creating (line 110) event- that is because in the command I've created I simply make the replacement I need to: 1.void element_AppointmentCreating(object sender, AppointmentCreatingEventArgs e) 2.{ 3.    e.NewAppointment = new InterviewAppointment(); 4.    base.ExecuteCommand(); 5.} And the ViewModel is none the wiser, the appointments just work as far as it is concerned since as they are created they become InterviewAppointments.  End result?  I've customized my EditAppointmentDialog as follows: And adding, editing, and deleting appointments works like a charm.  I can even 'edit' by moving appointments around RadScheduler, so as they are dropped into a timeslot they perform their full edit routine and things get updated. And then, the Code-Behind Version Perhaps the thing I like the most about doing one then the other is I get to steal 90% or more of the code from the MVVM version.  For example, the only real changes to the Code-Behind Xaml file exist in the control declaration, in which I use events instead of attached-behavior-event-commands: 01.<telerikScheduler:RadScheduler x:Name="xJobsScheduler" 02.                  Grid.Row="1" 03.                  Grid.Column="1" 04.                  Width="800" 05.                  MinWidth="600" 06.                  Height="500" 07.                  MinHeight="300" 08.                  EditAppointmentStyle="{StaticResource EditAppointmentStyle}" 09.                  AppointmentAdded="xJobsScheduler_AppointmentAdded" 10.                  AppointmentCreating="xJobsScheduler_AppointmentCreating" 11.                  AppointmentEdited="xJobsScheduler_AppointmentEdited" 12.                  AppointmentDeleted="xJobsScheduler_AppointmentDeleted"> 13.</telerikScheduler:RadScheduler> Easy, right?  Otherwise, all the same styling in UserControl.Resources was re-used, right down to the DataContextProxy that lets us bind to a collection from our viewmodel (in this case, our code-behind) to use within the DataTemplate.  The code conversion gets even easier, as I could literally copy and paste almost everything from the ViewModel to my Code-Behind, just a matter of pasting the right section into the right event.  Here's the code-behind as proof: 001.public partial class SchedulingView : UserControl, INotifyPropertyChanged 002.{ 003.    public RecruitingContext context; 004.   005.    private QueryableCollectionView _jobsList; 006.    public QueryableCollectionView JobsList 007.    { 008.        get { return this._jobsList; } 009.        set 010.        { 011.            if (this._jobsList != value) 012.            { 013.                this._jobsList = value; 014.                this.NotifyChanged("JobsList"); 015.            } 016.        } 017.    } 018.   019.    private QueryableCollectionView _applicantList; 020.    public QueryableCollectionView ApplicantList 021.    { 022.        get { return _applicantList; } 023.        set 024.        { 025.            if (_applicantList != value) 026.            { 027.                _applicantList = value; 028.                NotifyChanged("ApplicantList"); 029.            } 030.        } 031.    } 032.   033.    private ObservableItemCollection<InterviewAppointment> _interviews = new ObservableItemCollection<InterviewAppointment>(); 034.    public ObservableItemCollection<InterviewAppointment> Interviews 035.    { 036.        get { return _interviews; } 037.        set 038.        { 039.            if (_interviews != value) 040.            { 041.                _interviews = value; 042.                NotifyChanged("Interviews"); 043.            } 044.        } 045.    } 046.   047.    public SchedulingView() 048.    { 049.        InitializeComponent(); 050.   051.        this.DataContext = this; 052.   053.        this.Loaded += new RoutedEventHandler(SchedulingView_Loaded); 054.    } 055.   056.    void SchedulingView_Loaded(object sender, RoutedEventArgs e) 057.    { 058.        this.xJobsScheduler.AppointmentsSource = Interviews; 059.   060.        context = new RecruitingContext(); 061.           062.        LoadOperation loadop = context.Load(context.GetInterviewsQuery()); 063.        loadop.Completed += new EventHandler(loadop_Completed); 064.   065.        this._applicantList = new QueryableCollectionView(context.Applicants); 066.        context.Load(context.GetApplicantsQuery()); 067.   068.        this._jobsList = new QueryableCollectionView(context.JobPostings); 069.        context.Load(context.GetJobPostingsQuery()); 070.    } 071.   072.    void loadop_Completed(object sender, EventArgs e) 073.    { 074.        LoadOperation loadop = sender as LoadOperation; 075.   076.        _interviews.Clear(); 077.   078.        foreach (var ent in loadop.Entities) 079.        { 080.            _interviews.Add(EntityToAppointment(ent as Interview)); 081.        } 082.    } 083.   084.    private void xJobsScheduler_AppointmentAdded(object sender, Telerik.Windows.Controls.AppointmentAddedEventArgs e) 085.    { 086.        // now we have a new InterviewAppointment to add to our QCV :) 087.        InterviewAppointment newInterview = e.Appointment as InterviewAppointment; 088.   089.        this.context.Interviews.Add(AppointmentToEntity(newInterview)); 090.        this.context.SubmitChanges((s) => 091.        { 092.            ActionHistory myAction = new ActionHistory(); 093.            myAction.InterviewID = newInterview.InterviewID; 094.            myAction.PostingID = newInterview.PostingID; 095.            myAction.ApplicantID = newInterview.ApplicantID; 096.            myAction.Description = String.Format("Interview with {0} has been created by {1}", newInterview.ApplicantID.ToString(), "default user"); 097.            myAction.TimeStamp = DateTime.Now; 098.            context.ActionHistories.Add(myAction); 099.            context.SubmitChanges(); 100.        } 101.            , null); 102.    } 103.   104.    private void xJobsScheduler_AppointmentCreating(object sender, Telerik.Windows.Controls.AppointmentCreatingEventArgs e) 105.    { 106.        e.NewAppointment = new InterviewAppointment(); 107.    } 108.   109.    private void xJobsScheduler_AppointmentEdited(object sender, Telerik.Windows.Controls.AppointmentEditedEventArgs e) 110.    { 111.        Interview editedInterview = (from x in context.Interviews 112.                                     where x.InterviewID == (e.Appointment as InterviewAppointment).InterviewID 113.                                     select x).SingleOrDefault(); 114.   115.        CopyAppointmentEdit(editedInterview, e.Appointment as InterviewAppointment); 116.   117.        context.SubmitChanges((s) => 118.        { 119.            ActionHistory myAction = new ActionHistory(); 120.            myAction.InterviewID = editedInterview.InterviewID; 121.            myAction.PostingID = editedInterview.PostingID; 122.            myAction.ApplicantID = editedInterview.ApplicantID; 123.            myAction.Description = String.Format("Interview with {0} has been modified by {1}", editedInterview.ApplicantID.ToString(), "default user"); 124.            myAction.TimeStamp = DateTime.Now; 125.            context.ActionHistories.Add(myAction); 126.            context.SubmitChanges(); 127.        } 128.            , null); 129.    } 130.   131.    private void xJobsScheduler_AppointmentDeleted(object sender, Telerik.Windows.Controls.AppointmentDeletedEventArgs e) 132.    { 133.        Interview deletedInterview = (from x in context.Interviews 134.                                      where x.InterviewID == (e.Appointment as InterviewAppointment).InterviewID 135.                                      select x).SingleOrDefault(); 136.   137.        context.Interviews.Remove(deletedInterview); 138.        context.SubmitChanges((s) => 139.        { 140.            ActionHistory myAction = new ActionHistory(); 141.            myAction.InterviewID = deletedInterview.InterviewID; 142.            myAction.PostingID = deletedInterview.PostingID; 143.            myAction.ApplicantID = deletedInterview.ApplicantID; 144.            myAction.Description = String.Format("Interview with {0} has been deleted by {1}", deletedInterview.ApplicantID.ToString(), "default user"); 145.            myAction.TimeStamp = DateTime.Now; 146.            context.ActionHistories.Add(myAction); 147.            context.SubmitChanges(); 148.        } 149.            , null); 150.    } 151.   152.    #region Appointment Helpers :) 153.   154.    public Interview AppointmentToEntity(InterviewAppointment ia) 155.    { 156.        Interview newInterview = new Interview(); 157.        newInterview.Subject = ia.Subject; 158.        newInterview.Body = ia.Body; 159.        newInterview.Start = ia.Start; 160.        newInterview.End = ia.End; 161.        newInterview.ApplicantID = ia.ApplicantID; 162.        newInterview.PostingID = ia.PostingID; 163.        newInterview.InterviewID = ia.InterviewID; 164.   165.        return newInterview; 166.    } 167.   168.    public InterviewAppointment EntityToAppointment(Interview ia) 169.    { 170.        InterviewAppointment newInterview = new InterviewAppointment(); 171.        newInterview.Subject = ia.Subject; 172.        newInterview.Body = ia.Body; 173.        newInterview.Start = ia.Start; 174.        newInterview.End = ia.End; 175.        newInterview.ApplicantID = ia.ApplicantID; 176.        newInterview.PostingID = ia.PostingID; 177.        newInterview.InterviewID = ia.InterviewID; 178.   179.        return newInterview; 180.    } 181.   182.    public void CopyAppointmentEdit(Interview entityInterview, InterviewAppointment appointmentInterview) 183.    { 184.        entityInterview.Subject = appointmentInterview.Subject; 185.        entityInterview.Body = appointmentInterview.Body; 186.        entityInterview.Start = appointmentInterview.Start; 187.        entityInterview.End = appointmentInterview.End; 188.        entityInterview.ApplicantID = appointmentInterview.ApplicantID; 189.        entityInterview.PostingID = appointmentInterview.PostingID; 190.    } 191.   192.    #endregion 193.   194.    #region INotifyPropertyChanged Members 195.   196.    public event PropertyChangedEventHandler PropertyChanged; 197.   198.    public void NotifyChanged(string propertyName) 199.    { 200.        if (string.IsNullOrEmpty(propertyName)) 201.            throw new ArgumentException("propertyName"); 202.   203.        PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 204.    } 205.   206.    #endregion 207.} Nice... right? :) One really important thing to note as well.  See on line 51 where I set the DataContext before the Loaded event?  This is super important, as if you don't have this set before the usercontrol is loaded, the DataContextProxy has no context to use and your EditAppointmentDialog Job/Applicant dropdowns will be blank and empty.  Trust me on this, took a little bit of debugging to figure out that by setting the DataContext post-loaded would only lead to disaster and frustration.  Otherwise, the only other real difference is that instead of sending an ActionHistory item through an event to get added to the database and saved, I do those right in the callback from submitting.  The Result Again, I only have to post one picture because these bad boys used nearly identical code for both the MVVM and the code-behind views, so our end result is... So what have we learned here today?  One, for the most part this MVVM thing is somewhat easy.  Yeah, you sometimes have to write a bunch of extra code, but with the help of a few useful snippits you can turn the process into a pretty streamlined little workflow.  Heck, this story gets even easier as you can see in this blog post by Michael Washington- specifically run a find on 'InvokeCommandAction' and you'll see the section regarding the command on TreeView in Blend 4.  Brilliant!  MVVM never looked so sweet! Otherwise, it is business as usual with RadScheduler for Silverlight whichever path you're choosing for your development.  Between now and the next post, I'll be cleaning up styles a bit (those RadComboBoxes are a little too close to my labels!) and adding some to the RowDetailsViews for Applicants and Jobs, so you can see all the info for an appointment in the dropdown tab view.  Otherwise, we're about ready to call a wrap on this oneDid you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

< Previous Page | 7 8 9 10 11