Tag: programming

Simple Automation with Quartz.net

Simple Automation with Quartz.net

I’ve found that Quartz offers great flexibility and ease of use when implementing scheduled tasks within an application.

With the release of Quartz 2.0 the code to run jobs has been changed quite drastically. The following is an example that allows a user to start and stop a job manually based on a time frequency in seconds that they set.

private IScheduler _scheduler; private ITrigger _jobTrigger; private IJobDetail _job; private int _timeInterval = 30; public int TimeInterval { get { return _timeInterval; } set { _timeInterval = value;} } internal void InitializeJob() { _job = JobBuilder.Create(typeof(JobQueueJob)) .WithIdentity("JobQueueJob") .Build(); buildTrigger(); } private void buildTrigger() { _jobTrigger = TriggerBuilder.Create() .WithIdentity("JobTrigger") .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(_timeInterval)) .StartNow() .Build(); } internal void StartJob() { ISchedulerFactory sf = new StdSchedulerFactory(); _scheduler = sf.GetScheduler(); _scheduler.Start(); buildTrigger(); _scheduler.ScheduleJob(_job, _jobTrigger); } internal void StopJob() { _scheduler.Shutdown(true); }

And the class that implements IJob

public class JobQueueJob : IJob { public void Execute(IJobExecutionContext context) { //Do your thing here } }

Elmah Error Logging with ASP.NET MVC

Elmah Error Logging with ASP.NET MVC

I’ve pieced this together from a few different articles to give you a one stop shop on how to implement Elmah with your MVC site.

You’ll want to install Elmah through the Package Manager. Use the command Install-Package elmah

First we’ll tackle the config file. To implement just copy and paste into the appropriate sections of your web.config.

<configSections> <sectionGroup name="elmah"> <section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" /> <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" /> <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" /> <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" /> </sectionGroup> </configSections>

<appSettings> <add key="elmah.mvc.disableHandler" value="false" /> <add key="elmah.mvc.disableHandleErrorFilter" value="false" /> <add key="elmah.mvc.requiresAuthentication" value="false" /> <add key="elmah.mvc.allowedRoles" value="*" /> <add key="elmah.mvc.route" value="elmah" /> </appSettings>

<system.web> <httpModules> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" /> <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" /> <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" /> </httpModules> <httpHandlers> <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /> </httpHandlers> </system.web>

Within the system.webserver section:

<handlers> <add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /> </handlers> <modules> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" /> <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" /> <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" /> </modules>

Last but not least, outside of your system.webserver and just before the end configuration tag. This piece will log into a SQL DB of your choice based on a connection string named ElmahLogging.

<elmah> <security allowRemoteAccess="1" /> <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="ElmahLogging" applicationName="MyExcellentApp"/> </elmah>

The SQL Server ddl to run in your logging database:

/* ELMAH - Error Logging Modules and Handlers for ASP.NET Copyright (c) 2004-9 Atif Aziz. All rights reserved. Author(s): Atif Aziz, http://www.raboof.com Phil Haacked, http://haacked.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ -- ELMAH DDL script for Microsoft SQL Server 2000 or later. -- $Id: SQLServer.sql 677 2009-09-29 18:02:39Z azizatif $ DECLARE @DBCompatibilityLevel INT DECLARE @DBCompatibilityLevelMajor INT DECLARE @DBCompatibilityLevelMinor INT SELECT @DBCompatibilityLevel = cmptlevel FROM master.dbo.sysdatabases WHERE name = DB_NAME() IF @DBCompatibilityLevel <> 80 BEGIN SELECT @DBCompatibilityLevelMajor = @DBCompatibilityLevel / 10, @DBCompatibilityLevelMinor = @DBCompatibilityLevel % 10 PRINT N' =========================================================================== WARNING! --------------------------------------------------------------------------- This script is designed for Microsoft SQL Server 2000 (8.0) but your database is set up for compatibility with version ' + CAST(@DBCompatibilityLevelMajor AS NVARCHAR(80)) + N'.' + CAST(@DBCompatibilityLevelMinor AS NVARCHAR(80)) + N'. Although the script should work with later versions of Microsoft SQL Server, you can ensure compatibility by executing the following statement: ALTER DATABASE [' + DB_NAME() + N'] SET COMPATIBILITY_LEVEL = 80 If you are hosting ELMAH in the same database as your application database and do not wish to change the compatibility option then you should create a separate database to host ELMAH where you can set the compatibility level more freely. If you continue with the current setup, please report any compatibility issues you encounter over at: http://code.google.com/p/elmah/issues/list =========================================================================== ' END GO /* ------------------------------------------------------------------------ TABLES ------------------------------------------------------------------------ */ CREATE TABLE [dbo].[ELMAH_Error] ( [ErrorId] UNIQUEIDENTIFIER NOT NULL, [Application] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Host] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Type] NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Source] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Message] NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [User] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [StatusCode] INT NOT NULL, [TimeUtc] DATETIME NOT NULL, [Sequence] INT IDENTITY (1, 1) NOT NULL, [AllXml] NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER TABLE [dbo].[ELMAH_Error] WITH NOCHECK ADD CONSTRAINT [PK_ELMAH_Error] PRIMARY KEY NONCLUSTERED ([ErrorId]) ON [PRIMARY] GO ALTER TABLE [dbo].[ELMAH_Error] ADD CONSTRAINT [DF_ELMAH_Error_ErrorId] DEFAULT (NEWID()) FOR [ErrorId] GO CREATE NONCLUSTERED INDEX [IX_ELMAH_Error_App_Time_Seq] ON [dbo].[ELMAH_Error] ( [Application] ASC, [TimeUtc] DESC, [Sequence] DESC ) ON [PRIMARY] GO /* ------------------------------------------------------------------------ STORED PROCEDURES ------------------------------------------------------------------------ */ SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml] ( @Application NVARCHAR(60), @ErrorId UNIQUEIDENTIFIER ) AS SET NOCOUNT ON SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId AND [Application] = @Application GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO CREATE PROCEDURE [dbo].[ELMAH_GetErrorsXml] ( @Application NVARCHAR(60), @PageIndex INT = 0, @PageSize INT = 15, @TotalCount INT OUTPUT ) AS SET NOCOUNT ON DECLARE @FirstTimeUTC DATETIME DECLARE @FirstSequence INT DECLARE @StartRow INT DECLARE @StartRowIndex INT SELECT @TotalCount = COUNT(1) FROM [ELMAH_Error] WHERE [Application] = @Application -- Get the ID of the first error for the requested page SET @StartRowIndex = @PageIndex * @PageSize + 1 IF @StartRowIndex <= @TotalCount BEGIN SET ROWCOUNT @StartRowIndex SELECT @FirstTimeUTC = [TimeUtc], @FirstSequence = [Sequence] FROM [ELMAH_Error] WHERE [Application] = @Application ORDER BY [TimeUtc] DESC, [Sequence] DESC END ELSE BEGIN SET @PageSize = 0 END -- Now set the row count to the requested page size and get -- all records below it for the pertaining application. SET ROWCOUNT @PageSize SELECT errorId = [ErrorId], application = [Application], host = [Host], type = [Type], source = [Source], message = [Message], [user] = [User], statusCode = [StatusCode], time = CONVERT(VARCHAR(50), [TimeUtc], 126) + 'Z' FROM [ELMAH_Error] error WHERE [Application] = @Application AND [TimeUtc] <= @FirstTimeUTC AND [Sequence] <= @FirstSequence ORDER BY [TimeUtc] DESC, [Sequence] DESC FOR XML AUTO GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_NULLS ON GO CREATE PROCEDURE [dbo].[ELMAH_LogError] ( @ErrorId UNIQUEIDENTIFIER, @Application NVARCHAR(60), @Host NVARCHAR(30), @Type NVARCHAR(100), @Source NVARCHAR(60), @Message NVARCHAR(500), @User NVARCHAR(50), @AllXml NTEXT, @StatusCode INT, @TimeUtc DATETIME ) AS SET NOCOUNT ON INSERT INTO [ELMAH_Error] ( [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [AllXml], [StatusCode], [TimeUtc] ) VALUES ( @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @AllXml, @StatusCode, @TimeUtc ) GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO

Now that the web.config and database are configured, a few more tweaks to your MVC project and you’re ready to go. By default Elmah will only handle unhandled exceptions. To handle all exceptions that application processes, we can write a custom action filter to intercept the error and log it!

using System.Web.Mvc; using Elmah; namespace MVCproj.ActionFilters { public class ElmahHandledErrorLoggerFilter : IExceptionFilter { public void OnException(ExceptionContext context) { // Log only handled exceptions, because all other will be caught by ELMAH anyway. if (context.ExceptionHandled) ErrorSignal.FromCurrentContext().Raise(context.Exception); } } }

Modify your FilterConfig in the AppStart to look like this:

public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ElmahHandledErrorLoggerFilter()); filters.Add(new HandleErrorAttribute()); } }

Elmah error logging is now configured for your ASP.NET MVC application. Let’s just hope it doesn’t get used that often. Ha ha… I know bad joke.

Enjoy

Developing a RSS Feed Display in Windows Phone 8

Developing a RSS Feed Display in Windows Phone 8

Pretty much any site that has a blog comes with a RSS feed for free use. To display a RSS feed from a web site in your Windows Phone 8 App is fairly straight forward with the help of the SyndicationItem object in the System.ServiceModel.Syndication dll. Since Windows 8 Apps do not reference this automatically, you’ll likely find it at this location: C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\System.ServiceModel.Syndication.dll

Once you have the dll referenced you will create a List of of SyndicationItem objects. You can also create a property to bind to the SelectedItem of the LongListSelector. In this property example I am using BindableBase as my ViewModel base class. BindableBase comes with SetProperty to implement INotifyPropertyChanged.

private SyndicationItem _selectedSyndicationItem; public SyndicationItem SelectedSyndicationItem { get { return _selectedSyndicationItem; } set { _selectedSyndicationItem = value; SelectionChanged(); } } private IEnumerable<SyndicationItem> _syndicationItems; public IEnumerable<SyndicationItem> SyndicationItems { get { return _syndicationItems; } set { SetProperty(ref _syndicationItems, value); } }

The rest of the code in my ViewModel handles loading the RSS feed and responding to the SelectedItem binding event. The example here uses the RSS feed from the Colorado Technology Association.

public void LoadRss() { string url = "http://www.coloradotechnology.org/members/blog_rss.asp?id=432063&rss=zGF1zZtI"; try { var request = (HttpWebRequest)WebRequest.Create(new Uri(url)); request.BeginGetResponse(ResponseHandler, request); } catch (Exception exception) { ErrorHandling(exception); } } void ErrorHandling(Exception e) { ProgressVisible = false; ErrorMessage = "An error occured loading the news feed. " + e.Message; ErrorVisible = true; } private void ResponseHandler(IAsyncResult asyncResult) { try { var request = (HttpWebRequest) asyncResult.AsyncState; var response = (HttpWebResponse) request.EndGetResponse(asyncResult); if (response.StatusCode == HttpStatusCode.OK) { var reader = XmlReader.Create(response.GetResponseStream()); var feed = SyndicationFeed.Load(reader); SyndicationItems = feed.Items; ProgressVisible = false; ErrorMessage = string.Empty; ErrorVisible = false; } } catch (Exception exception) { ErrorHandling(exception); } } private void SelectionChanged() { AppSession.RSSUrl = _selectedSyndicationItem.Id; AppSession.RSSTitle = _selectedSyndicationItem.Title.Text; if (NavigationEvent != null) NavigationEvent(this, "/WebArticle.xaml"); }

The remaining implementation is in the xaml, which is shown here:

<LongListSelector ItemsSource="{Binding SyndicationItems}" SelectedItem="{Binding SelectedSyndicationItem,Mode=TwoWay}"> <LongListSelector.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Title.Text}" Foreground="Chocolate" FontWeight="Bold" FontSize="20" TextWrapping="Wrap"></TextBlock> <TextBlock Text="{Binding PublishDate}" FontSize="14" Margin="0,5,0,8"></TextBlock> </StackPanel> </DataTemplate> </LongListSelector.ItemTemplate> </LongListSelector>

To see how SelectedItem is implemented as a Dependency Property, you can see my article on that here: http://www.new.surfdew.com/?p=181

Upgrading to LongListSelector

Upgrading to LongListSelector

The Windows Phone 8 SDK officially ships with the LongListSelector control.  Microsoft is encouraging developers to use this control instead of the ListBox.  ListBox is still supported, but the control is not optimized for the phone experience.  Read more about the features of the LongListSelector here: http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/05/23/windows-phone-8-xaml-longlistselector.aspx

It’s fairly easy to upgrade your ListBox references to LongListSelector.  You can simply replace ListBox with phone:LongListSelector in your xaml.  There is one thing that Microsoft messed up on though and that is not making SelectedItem a dependency property.  If you’re using MVVM with TwoWay binding, you’re hosed with this out the box control.  Never fear though, the class can be extended to allow for TwoWay binding.  The following is the full implementation of the custom class:

publicclass LongListSelector : Microsoft.Phone.Controls.LongListSelector { public LongListSelector() { SelectionChanged += LongListSelector_SelectionChanged; } void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e) { SelectedItem =base.SelectedItem; } publicstaticreadonly DependencyProperty SelectedItemProperty = DependencyProperty.Register( SelectedItem, typeof(object), typeof(LongListSelector), new PropertyMetadata(null, OnSelectedItemChanged) ); privatestaticvoid OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var selector = (LongListSelector)d; selector.SetSelectedItem(e); } privatevoid SetSelectedItem(DependencyPropertyChangedEventArgs e) { base.SelectedItem = e.NewValue; } publicnewobject SelectedItem { get { return GetValue(SelectedItemProperty); } set { SetValue(SelectedItemProperty, value); } } }

Marketing Your Windows Phone App

Marketing Your Windows Phone App

When I first submitted my Windows Phone App to the Marketplace it was an exciting time.  How would the public react to my app?  How many downloads would I get?  Would somebody actually press on an Ad?

During the first few days of my app being in the Marketplace, I had 1 download and it was from India.  Confused by the lack of interest I tried searching for my app.  The only way I could find my app was to search for it by name.  It wasn’t even coming up in the search results for a golf app.  What did I do wrong?

The app I designed is to help facilitate golf betting.  The app keeps track of who owes what throughout the round.  It calculates generically, so it can be used with any and multiple betting games.  Here is the link to the app.

What I first discovered was that I was not adding Keywords to my app.  When I submit my app I always think the keyword input is kind of hidden.  I never saw it when I first submitted.  Adding keywords instantly put my app in the search results with all of the other golf related apps.  Here’s a screenshot of the keywords I’m currently using:

SideBetKeywords

 

After I submitted an update and added keywords, my downloads started to increase to 1 or 2 a day.  It was going too slow still so I threw out the link to my app on LinkedIn, Twitter and Facebook.  I also added Analytics using the free service from Localytics.  Localytics is very easy to plug into your app and offers pretty good free analytic data.  You can see a chart of your user sessions per day, and a map of where your users are.

LocalyticsChart

 

 

LocalyticsMap

 

This was helpful to know where my app was being downloaded in the world.  I then decided to localize my app by adding a resource file for all of the text in my app.  Once everything was in resource files it was easy to add new languages.  Here’s a great post on localizing your Windows Phone App:  http://kb.tethras.com/localizing-your-windows-phone-8-app

Side Bet is now in 6 languages which include Spanish, Italian, German, English, Chinese and Russian.  My app’s downloads are now in the 5 – 10 per day range.  I hope these tips were helpful with increasing downloads for all you app newbies out there.

 

What’s the deal with Silverlight?

What’s the deal with Silverlight?

Most people in the development community have conceded that Microsoft is no longer putting any energy into Silverlight. And why should they? There isn’t a tablet or phone that will support the technology. Even desktop support is getting spotty with many support issues on Macs running the latest versions of Firefox and Safari.

I get why Microsoft is has given up on the technology, but it’s quite a shame. To develop a cross-browser saas application is not trivial using html and css. Silverlight makes development easy. It allows a developer to code the application just like it’s a desktop application without having to code in javascript and css.

If the web moves forward with html5 and leaves behind third party plug ins, the browser consumers are going to lose out. I don’t think we will get back to the same responsiveness and overall great experience until we hit html6. So will that be IE 17, Firefox 45, and Chrome version 89? I’m just being humorous about html6, but I’m serious when I say that I will miss Silverlight on the web.

I will move forward and get on whatever web bandwagon I need to get on. But I’m sad that other companies (Apple) are dictating what technologies we can use on the web.

Solving the document domain

Solving the document domain

I recently ran across an issue where a web page in a separate web site was trying to communicate with a web page on another site, through javascript. It was trying to do a window.parent.parent.somefunction call and was failing with an access denied script error. The site is full of Iframes, with asp.net embedding classic asp. Fun stuff!

The last few browser updates have locked down on javascript cross-site communication. The solution is to set the document.domain to equal values. The key is to have both sites sit on the same sub domain. Example site names and how they need to be set in script:

Site 1: tiger.surfdew.com
Site 2: woods.surdew.com

In your javascript you’ll need to set the document.domain to surfdew.com on each page, in each site, that interacts with each other.

If your users are on IE, have them add your site to their trusted sites. There is also an IE setting to allow cross site scripting. Just setting this to enabled didn’t solve the problem with my scripts, so I’m not sure how effective it is.