CRM 2011/2013 Dialog’s and Custom Workflow example

I had piece of functionality I did at work recently and it had a few interesting parts, so I thought I would blog it down.  You can read the blog or watch the video

The required functionality required the ability to update multiple appointments, in this deployment we have created a new appointment entity called Client appointment but basically I needed to update multiple appointments.

The user wanted to specify a cancellation reason.

I was initial thinking of using a workflow and selecting lots of appointments but because they needed to specify a cancellation reason then this wasn’t an option

With input required a dialog seemed like a good option.

The problem I quickly found was Dialog’s can only be triggered on one record at a time and not multiple records like workflows.

Contact Dialog

So the plan was changed to be run on the contact.  I would have a dialog which ran on the contact entity the user would be prompted for a start date, end date and a cancellation reason.

I would call a Custom Workflow from with the dialog and pass selected values to it and then the custom workflow would do a query, select all the appointments, cancel them and then create a reschedule task and assign it to a reschedule queue.

I usually trigger code changes from plugins and wondered what circumstances would I move that code to be triggered into a Custom Workflow but this a good example.

This code isn’t really suitable to be triggered from a plugin because there isn’t anything being changed/updated or created so there is no natural plugin trigger point.

Thinking about this I can see that within certain workflows and dialog’s is the perfect place to call a custom workflow, particularly when nothing has been updated or modified and you want to trigger those changes and the changes are going to be complex which needs a code to do.  This is a good example because the code needs to retrieve a lot of appointments linked to a contact, this functionality couldn’t be achieved in workflow or definitely not easily.

After re-reading the requirements I noticed we needed to specify a start time and end time and this would also work in a slightly unusual manner.  If the user specified 08:00 to 12:00 with a start date and end date which went over more than one day.  The user wanted the morning appointments to be cancelled for each day specified but the afternoon appointments to be left alone.  This would provide a tricky piece of querying which I will go into later.

In theory this seemed like it would work, so I initially created a skeleton Dialog and a Custom workflow which logged the fields.

 

The first little problem I had was, how to show the time.  The choices I had were text single response, this would involve the user typing in the time, I didn’t like this option because it wasn’t easy for the user and had the potential for them to mistype.

The other option was to create an optionset with an hour value for each hour.  e.g. 01:00, 02:00 etc.  In then end I chose this option.

The user also wanted the ability to not select a time and this would mean they wanted to cancel the whole days appointments.

So I created the the optionSet with a default value of – Full Day and then 01:00 label would have the value of 1, 23:00 would have the value of 23.

 

dialog example

SET THE CORRECT DATA TYPE

One mistake I made at this point was to incorrectly set the Data type to text.  This is a real schoolboy error because once you set this you can’t change it.  So I had set it to text gone through adding all 24 hours and then realizing and had to do it all again, very frustrating.

What is also very frustrating is the fact you can use an optionSet created in CRM, you have to copy the values again.  This means there isn’t any schronisation between the OptionSet in your dialog and entity.  It also means you may have to create the values numerous times in a dialog because you can’t reuse it in a dialog.

In this example I had to create the same OptionSet for start date and end date.  Tedious indeed.

dialog example 1

 

The cancellation reason was the same kind of thing, I had to copy an OptionSet inside CRM and recreate it and give the OptionSet values the same as the values in the CRM OptionSet field, this way I could pass the value into the Custom Workflow and then it could use the value to set the OptionSet.

 

Warning Popup Message

When I did a demo of the functionality to the client, they said they would like a warning to pop up, if the dates specified were within 3 days.  The reason for this is if you cancel appointments with 3 days of today, it’s difficult to reorganize these so users should be certain they want to cancel these appointments.

Sometimes when someone asks you about how to achieve some functionality in CRM, you can be momentary stumped and can’t see how to do it and this was one of those moments.

I couldn’t see anyway to pop up a warning message.

It was only later that I was talking through the problem with the team that the obvious answer came to light.

Dialog’s are made up of pages and on each page you have a one or more prompt and responses.

So if I wanted a warning message all I needed to do was to create a new page, show the information the user had entered earlier in the dialog and ask them to confirm if they wanted to proceed with the changes using an OptionSet with Yes/No.

 

What I did was to check if the start date was greater than three days, if so put a confirmation page but if the start date was less than three days I would add the words warning.

dialog example 2

 

Sensible variable names

This is the same for workflows but when you are adding conditions or adding steps/prompt and responses make sure you use easily understood variable names because later you will need to use these fields to update an entity/pass to a custom workflow so you need to be able to easily understand what each field is.

Here is the Custom Workflow being called from within the dialog

dialog example 3

 

Below you can see the main code for the Custom Workflow, you can match it up with the screen shot above.  The actual code is in this class commonClientAppointment class

 


public sealed class CwaBulkAppointmentStatusChange : CodeActivity
{

/// <summary>
/// Gets or sets Min Wait Time
/// </summary>
[Input("Start Date")]
[RequiredArgument]
public InArgument<DateTime> StartDate { get; set; }

/// <summary>
/// Gets or sets Max Wait Time
/// </summary>
[Input("End Date")]
[RequiredArgument]
public InArgument<DateTime> EndDate { get; set; }

/// <summary>
/// Gets or sets Max Wait Time
/// </summary>
[Input("Start Time")]
[RequiredArgument]
public InArgument<int> StartTime { get; set; }

/// <summary>
/// Gets or sets Max Wait Time
/// </summary>
[Input("EndTime")]
[RequiredArgument]
public InArgument<int> EndTime { get; set; }

/// <summary>
/// Gets or sets Max Wait Time
/// </summary>
[Input("Cancellation Reason")]
[RequiredArgument]
public InArgument<int> CancellationReason { get; set; }

/// <summary>
/// Gets or sets Task Reference
/// </summary>
[Input("Contact")]
[ReferenceTarget("contact")]
public InArgument<EntityReference> Contact { get; set; }

/// <summary>
/// Executes the workflow activity.
/// </summary>
/// <param name="executionContext">The execution context.</param>
protected override void Execute(CodeActivityContext executionContext)
{
// Create the tracing service
ITracingService tracingService = executionContext.GetExtension<ITracingService>();

if (tracingService == null)
{
throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
}

tracingService.Trace("Entered CwaBulkAppointmentStatusChange.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
executionContext.ActivityInstanceId,
executionContext.WorkflowInstanceId);

// Create the context
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

if (context == null)
{
throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
}

tracingService.Trace("CwaBulkAppointmentStatusChange.Execute(), Correlation Id: {0}, Initiating User: {1}",
context.CorrelationId,
context.InitiatingUserId);

IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

try
{

DateTime startDate = this.StartDate.Get(executionContext).ToLocalTime();
DateTime endDate = this.EndDate.Get(executionContext).ToLocalTime();
int startTime = this.StartTime.Get(executionContext);
int endTime = this.EndTime.Get(executionContext);
int cancellationReason = this.CancellationReason.Get(executionContext);
EntityReference contactRef = this.Contact.Get(executionContext);

CommonClientAppointment commonClientAppointment = new CommonClientAppointment();
commonClientAppointment.CancelHPAppointments(service, contactRef, startDate, endDate, startTime, endTime, cancellationReason);

}
catch (FaultException<OrganizationServiceFault> e)
{
tracingService.Trace("Exception: {0}", e.ToString());
}

tracingService.Trace("Exiting CwaBulkAppointmentStatusChange.Execute(), Correlation Id: {0}", context.CorrelationId);
}
}

 

Other interesting bits of code, below I set the start date to add the hours selected in the start time, unless it’s value is zero (which means whole day), which I then use the default time 00:00 and for enddate I give the value of 23:59 (e.g. the whole day)


if (startTime > 0)
{
startDate = startDate.Date;
startDate = startDate.AddHours(startTime);
}
else
{
startDate = startDate.Date;
}

if (endTime > 0)
{
endDate = endDate.Date;
endDate = endDate.AddHours(endTime);
}
else
{
endDate = endDate.Date;
endDate = endDate.AddHours(23).AddMinutes(59);
}

 

The other tricky bit of code was time specified code.  To recap if a time was specified then the appointments between the time should be cancelled on every day specified in the date criteria.  To do this I calculated the difference in days and then looped around that many times and added a day each time I went round  the loop.

e.g.

start date 01/01/2014

end date 07/01/2014

start time 07:00

end time 12:00

 

This would cancel all morning appointments for all the days (01, 02, 03, 04, 05 , 06, 07)

I had two options, I could either create one query with multiple date conditions or I could create one query and then repeatedly call this with the start and end date changed.

I couldn’t quite invisage doing one query so I called the query once for each day in the date range.

List<Entity> bookedAppointments = new List<Entity>();
if (startTime == 0 || endTime == 0)
{
//full days
bookedAppointments = CancelAppointmentsRetrieve(service, hpEntityRef, startDate, endDate, statusCode);
}
else
{
//time specified
int days = calculateDays(startDate, endDate);
int counter = 0;
DateTime loopEndDate = startDate.Date.AddHours(endDate.Hour);
while (counter <= days)
{
bookedAppointments.AddRange(CancelAppointmentsRetrieve(service, hpEntityRef, startDate, loopEndDate, statusCode));
startDate = startDate.AddDays(1);
loopEndDate = loopEndDate.AddDays(1);
counter++;
}
}

if (bookedAppointments != null && bookedAppointments.Count > 0)
{
this.UpdateBookedAppointments(service, bookedAppointments, cancelReasonInt);
}

&nbsp;
<pre>

 

 

 

CRM MVP Question and Answer – Demian Adolfo Raschkovan

Today we say Hola because this weeks CRM MVP is currently residing in Spain (although he is from Argentinian stock).

He supports an average football team Getafe (although they are better than Ipswich as most teams are) who are hovering above the relegation zone, so it will be a nervous weekend for Demian coming up.

Not only has Demian won to MCC awards (you get this for answering lots of forum questions), an MVP, he is also a MAP  (Microsoft Active Professional) 2014.   This is a local distinction in Spain, which rewards partners communities in Spain and other countries.

He also deserves respect because he used CRM version 1.2, which I believe was a notebook with a calculator sellotaped on to it.  CRM 1.2 is also known as evil CRM, which instead of helping you with CRM did everything it could to stop you 🙂

 

Here is Demian’s CRM MVP Biography

Microsoft Community Contributor (MCC) awarded in october 2012 and january 2013

Technical consultant with extensive experience in Microsoft Dynamics CRM and Microsoft technologies. 
I am currently working at Development and Technical Solutions Architect for Infoavan Soluciones, a Microsoft Dynamics CRM Gold Certified partner in Madrid, Spain.
I worked in more than 60 CRM implementations in different positions (as developer, project leader, etc) and different areas (banking, construction, telecommunications, engineers, services, etc.). I also worked in some international projects.
I am passionate about CRM and all the possibilities that Microsoft Dynamics delivers, and I have a CRM blog (in Spanish). I also collaborate in other blogs and forums in Spanish:http://www.elblogdedynamicscrm.com/ and http://social.microsoft.com/Forums/es-ES/crmspanish/threads (Microsoft Spanish CRM Forum).

Here are some Rockstar highlights

demian rockstar 1

 

demian rockstar 2

 

demian rockstar 3

Thanks for Demian for answering my questions, greatly appreciated

If you want to read previous CRM MVP Q&A by clicking the link on the header – HOSK’S CRM MVP Q&A

 

QUESTIONS

Name, current job title and social media links please
Demian Adolfo Raschkovan
Dynamics CRM Technical Specialist, Infoavan Soluciones
Blog: www.demianrasko.com
Twitter: @demian_rasko
Email: mvp@demianrasko.com

What does an average day at work look like
Prepare my children to school
Walking to work (4 minutes)
Working with CRM all day
Breakfast at 10:00 (at work)
Lunch at home
Every day I find a new cool stuff around Dynamics CRM and Microsoft stack and I think to implement in my next project, the problem is that I don’t start a new project every day, so I have to wait to finish the actual ones, to use this new cool stuff. If I cannot use it, I blog it to test and learn it.
When I finish, I get back to home, sleep my children and start blogging, tweeting and online training.

What different roles/Job titles have you had whilst using CRM
Developer, Developer, Developer
Project manager
Trainer
Solution Architect
Presales

What job did you did before you starting using CRM
Developer in 3d Games, and with ASP.NET/SQL Server web sites and Windows forms solutions.

What was the first version of Microsoft Dynamics CRM you worked with and how long have you been using Microsoft Dynamics CRM
I started with the 1.2 version (more than 8 years ago).

How do you stay up to date with the CRM
Tweeting, Bloging and participating in online communities like MSDN and Dynamics forums / ComunidadCRM.com Spanish community.
I also try to learn the lasts developing technologies.

How do you find time to contribute to the CRM community whilst doing your job
I just have time when my children are sleeping, so I need to take them to bed, and then I start my “Community” life.

What advice would you give to someone who wants to have a successful career in Microsoft Dynamics CRM?
Learn and share your knowledge. When you share knowledge, you also learn and grow as a professional. Always say the truth to all the customers, be open and try to explain everything to customers helps you to finish your projects successfully.

What where your first impressions of CRM 2013 and what do you think now.
I started with the 1.2 version, and if see the solution today, It’s just awesome! I think Microsoft made not only have the best CRM solution in the market, it’s also the one who makes the best changes in the solution. If I see to the future, I think Dynamics CRM will take advantage of other competitors. The big changes in CRM 2013 are in the User Interface, and I think it’s more clean, fast and nice.

What one feature would you add to CRM 2013
Inline editing in all the subgrids, like in Qoutes.

Most annoying feature of CRM 2013
Why I cannot add security roles to field level security profiles?

You favourite 2 CRM blogs (I have filled the first one in for you)

            1.  Hosks Dynamic CRM blog
            2. http://mscrmtools.blogspot.com.es/ (Tanguy CRM Blog) – Best Tools for CRM
3. http://www.stunnware.com/ (this is an old one, not active right now)

What year will Microsoft Dynamics CRM have more customers than Sales force
I’m not following the numbers but my background is Technical and I think Microsoft is winning in this part.

Are you doing more CRM projects with CRM online?  Do you think it will all be online in the future
Right now, my customers select more OnPremise, but there is a movement to change this wave, and more and more customers want to go to the cloud. I think that the online option will increase, but the Onpremise implementations will stay there for a long time for some kind of customers.

What is the best tool/solution you have used recently
XrmToolbox and RibbonWorkbench, kingswaysoft, and XrmServiceToolkit

What CRM certifications do you have, do you try and keep up to date with CRM certifications
CRM 3.0, CRM 4.0, Dynamics CRM 2011 and 2013. I also passed Sure Step exams and presales assessment. I want to take this year the application and installation ones (in 2013 I have only the customization exam)

How important is it to have good business analytical skills working with Microsoft Dynamics CRM.
It’s important to have profiles in the projects that have technical skills, but more important is to have someone that understand the customer needs, so you can focus your technical solution to that requirements. Sometimes the best technical solutions, doesn’t fits with customer needs, so the project fails.

How useful is it to have programming knowledge to become a good Microsoft Dynamics CRM Professional?
It’s important but it is not required at all. It is very useful because in almost all the CRM projects you need some kind of development, but you can be an excellent CRM professional with no programming knowledge at all.

What knowledge/experience do you have with software/systems which integrate with Microsoft Dynamics CRM e.g. (sharepoint, SQL Server, Scribe, Etc)
Each project is different, but almost all the project needs some integration. Depending on the volume, the time gap and the systems to integrate, I used a lot of different solutions. From custom development (mostly used) to kingswaysoft, online integration with web services, Dynamics Connector, etc.

How often do you travel as a Microsoft Dynamics CRM Professional?
More or less twice a month.

Can you see yourself not using CRM in your career in the future
No way!

What is favourite part of being a CRM MVP
MVP Summit!

What are your hobbies outside of CRM
Running, Tennis, watch Football and travel

 What was the last book you read and what was the last film you watched
Toy Story and Toy Story, my daughter….

Has CRM ever got you in trouble with your partner/family.
Every night…when I turns on my PC at home…

Have you friends ever told you to stop talking/tweeting/blogging about CRM? What does your partner/family member(s) think of CRM
Yes, sometimes, but I really love it and if I find anybody with interest to talk about technology, I cannot stop. My 3 years old daughter already “played” with moca in her Surface 2 tablet.

Tell me something interesting/unusual about yourself
I was born in Buenos Aires, Argentina, and I lived in Madrid, Spain for the last 12 years. I really love football and I go every Sunday to the Stadium to watch my favorite team (Getafe).

Who is the first CRM MVP you remember reading/seeing
Marco Amoedo (now in Microsoft UK)

Tips for someone who wants to become a CRM MVP
Just start sharing knowledge, and collaborate with others. One important thing is to do it for a long time, with no stop, at the end Microsoft recognize people who really want to help others.

Quickfire questions (choose one option and no explanation)

Steve Jobs or Bill Gates
BILL GATES

Javascript or .NET
Javascript

Internet Explorer/Chrome/Firefox/Safari
Chrome

Wine/Beer/Soft Drink
Beer

Certifications or Use CRM
Use CRM

twerking or tweeting
Tweeting

books or ebooks
Ebooks

save or autosave
Save (I’m from the old school)

OnLine or On Premise
OnPrem
Windows 7/Windows 8/Linux/Mac/Other
Windows 8.1
work from home or work from office
From office

Miley Cyrus or Billy Ray Cyrus
….

Vinyl/CD’s/MP3’s/Subscribe
Youtube?

Zero Inbox/Overflowing Inbox
Overflowing inbox

Early Bird/Night Owl
Early Bird

Do Today/Do Tomorrow
Do Today

CRM Developer/CRM Consultant
CRM Developer

Hot Weather/Cold Weather
Hot Weather

Half Full/Half Empty
Half Full