CRM 2011 Online Plugin works fine but no Update committed - plugins

I'm a new developper in CRM 2011. I've made that simple code for tests.
It appears that the plugin works fine (checked with the ITracingService) but it seems that the attributes doesn't take the new values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
namespace AgeUpdatePlugin
{
public class AgeUpdatePlugin:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
try
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (tracingService == null)
throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
tracingService.Trace("Plugin has started..");
//l'expression de condition
ConditionExpression condition = new ConditionExpression("new_datenaissance", ConditionOperator.NotNull);
FilterExpression filter = new FilterExpression();
filter.Conditions.Add(condition);
ColumnSet cols = new ColumnSet();
//cols.AddColumn("Id");
cols.AddColumn("new_candidatid");
cols.AddColumn("new_age");
cols.AddColumn("new_datenaissance");
QueryExpression query = new QueryExpression();
query.Criteria = filter;
query.EntityName = "new_candidat";
query.ColumnSet = cols;
tracingService.Trace("appel retrieve multiple with date=" + DateTime.Now.ToString() + "/"+DateTime.Now.ToLocalTime().ToString());
var retrieve = service.RetrieveMultiple(query).Entities;
foreach (var c in retrieve)
{
var dt =(DateTime)c.Attributes["new_datenaissance"];
tracingService.Trace(dt.ToString());
if (dt.Month == DateTime.Now.Month && dt.Day == DateTime.Now.Day)
{
tracingService.Trace((DateTime.Now.Year - DateTime.Parse(c["new_datenaissance"].ToString()).Year).ToString());
c.Attributes["new_age"] = DateTime.Now.Year - DateTime.Parse(c["new_datenaissance"].ToString()).Year;
tracingService.Trace(c.Attributes["new_candidatid"].ToString() +" - "+c.Attributes["new_age"].ToString());
service.Update(c);
tracingService.Trace("updated");
}
}
tracingService.Trace("Plugin done working");
throw new InvalidPluginExecutionException("This is from a plugin that Mehdi has created ");
}
catch (Exception exc)
{
throw exc;
}
}
}
}

Whenever you throw an exception within a plugin the transaction is aborted so you won't see your changes applied. Remove the following line:
throw new InvalidPluginExecutionException("This is from a plugin that Mehdi has created ");
I assume you added this to see the trace output which is only available when an exception is thrown. With CRM Online your best bet for tracing is to write to a custom trace entity.

Related

Working on pre-operation plug-in to update "Modified By" field in MSCRM -- Need help fixing code

I am trying to update the "Modified By" field based on a text field called "Prepared By", which contains the name of a user. I've created a pre-operation plug-in to do this and believe I am close to done. However, the "Modified By" field is still not successfully getting updated. I am relatively new to coding and CRM, and could use some help modifying the code and figuring out how I can get this to work.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Linq;
namespace TimClassLibrary1.Plugins
{
public class CreateUpdateContact : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var service = factory.CreateOrganizationService(context.UserId);
tracingService.Trace("Start plugin");
tracingService.Trace("Validate Target");
if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
return;
tracingService.Trace("Retrieve Target");
var target = (Entity)context.InputParameters["Target"];
String message = context.MessageName.ToLower();
SetCreatedByAndModifiedBy(tracingService, service, target, message);
}
private void SetCreatedByAndModifiedBy(ITracingService tracingService, IOrganizationService service, Entity target, string message)
{
tracingService.Trace("Start SetPriceList");
tracingService.Trace("Validate Message is Create or Update");
if (!message.Equals("create", StringComparison.OrdinalIgnoreCase) && !message.Equals("update", StringComparison.OrdinalIgnoreCase))
return;
tracingService.Trace("Retrieve Attributes");
var createdByReference = target.GetAttributeValue<EntityReference>("new_createdby");
var modifiedByReference = target.GetAttributeValue<EntityReference>("new_modifiedby");
tracingService.Trace("Retrieve And Set User for Created By");
RetrieveAndSetUser(tracingService, service, target, createdByReference, "createdby");
tracingService.Trace("Retrieve And Set User for Modified By");
RetrieveAndSetUser(tracingService, service, target, modifiedByReference, "modifiedby");
}
private void RetrieveAndSetUser(ITracingService tracingService, IOrganizationService service, Entity target, EntityReference reference, string targetAttribute)
{
tracingService.Trace("Validating Reference");
if (reference == null)
return;
tracingService.Trace("Retrieving and Validating User");
var user = RetrieveUserByName(service, reference.Name, new ColumnSet(false));
if (user == null)
return;
tracingService.Trace("Setting Target Attribute");
target[targetAttribute] = user.ToEntityReference();
}
private Entity RetrieveUserByName(IOrganizationService service, string name, ColumnSet columns)
{
var query = new QueryExpression
{
EntityName = "systemuser",
ColumnSet = columns,
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = "fullname",
Operator = ConditionOperator.Equal,
Values = { name }
}
}
}
};
var retrieveResponse = service.RetrieveMultiple(query);
if (retrieveResponse.Entities.Count == 1)
{
return retrieveResponse.Entities.FirstOrDefault();
}
else
{
return null;
}
}
}
}
If you do get use from method Retreiveusernyname then you have to use below code
target[“modifiedby”] = new EntityRefrence(user.logicalname,user.id);
I don't see anything obviously wrong with your update, however you are taking a complicated and unnecessary step with your RetrieveUserByName() method. You already have EntityReference objects from your new_createdby and new_modifiedby fields, you can simply assign those to the target:
if (message.Equals("create", StringComparison.OrdinalIgnoreCase))
{
target["createdby"] = target["new_createdby];
}
else if (message.Equals("update", StringComparison.OrdinalIgnoreCase))
{
target["modifiedby"] = target["new_modifiedby];
}
If new_createdby and new_modifiedby are not entity references, then that would explain why your existing code does not work, if they are, then use my approach.

MS CRM 2015, plugins don't seem to fire

I'm having some trouble with the new MS CRM 2015 as I cannot make my plugins fire.
I even tried to take some of the very simple plugin samples from the 2015 SDK and register them 'non sandbox' but the result is the same.
The only thing I cant actually get to do anything on the triggering event is the plugin profiler, but that doesn't really help me much.
Has anyone else had this problem?
I could really use some advice on what to try/check next because Google doesn't appear to be my friend in this case?
The current deployment is on-premise by the way but there is no Visual Studio available on the server.
Here is the code from sample which I have altered just a tiny bit to only trigger on 1 specific account.
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
namespace Microsoft.Crm.Sdk.Samples
{
public class FollowupPlugin: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
//</snippetFollowupPlugin1>
//<snippetFollowupPlugin2>
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
//</snippetFollowupPlugin2>
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "account")
return;
try
{
if (entity.Attributes.ContainsKey("accountid"))
{
if (entity.GetAttributeValue<Guid>("accountid").ToString().ToLower() == "ee03d883-5b18-de11-a0d1-000c2962895d") // specific test account
{
// Create a task activity to follow up with the account customer in 7 days.
Entity followup = new Entity("task");
followup["subject"] = "Send e-mail to the new customer.";
followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
followup["scheduledstart"] = DateTime.Now.AddDays(7);
followup["scheduledend"] = DateTime.Now.AddDays(7);
followup["category"] = context.PrimaryEntityName;
// Refer to the account in the task activity.
if (context.OutputParameters.Contains("id"))
{
Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
string regardingobjectidType = "account";
followup["regardingobjectid"] = new EntityReference(regardingobjectidType, regardingobjectid);
}
//<snippetFollowupPlugin4>
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//</snippetFollowupPlugin4>
// Create the task in Microsoft Dynamics CRM.
tracingService.Trace("FollowupPlugin: Creating the task activity.");
service.Create(followup);
}
}
}
//<snippetFollowupPlugin3>
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the FollupupPlugin plug-in.", ex);
}
//</snippetFollowupPlugin3>
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
}
}
Registration screenshots:
Try to use following code:
using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
namespace Microsoft.Crm.Sdk.Samples
{
public class FollowupPlugin: IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in debugging sandboxed plug-ins.
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
//</snippetFollowupPlugin1>
//<snippetFollowupPlugin2>
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
//</snippetFollowupPlugin2>
// Verify that the target entity represents an account.
// If not, this plug-in was not registered correctly.
if (entity.LogicalName != "account")
return;
try
{
if (entity.Id.Equals(new Guid("ee03d883-5b18-de11-a0d1-000c2962895d")) // specific test account
{
// Create a task activity to follow up with the account customer in 7 days.
Entity followup = new Entity("task");
followup["subject"] = "Send e-mail to the new customer.";
followup["description"] = "Follow up with the customer. Check if there are any new issues that need resolution.";
followup["scheduledstart"] = DateTime.Now.AddDays(7);
followup["scheduledend"] = DateTime.Now.AddDays(7);
followup["category"] = context.PrimaryEntityName;
followup["regardingobjectid"] = entity.ToEntityReference();
//<snippetFollowupPlugin4>
// Obtain the organization service reference.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//</snippetFollowupPlugin4>
// Create the task in Microsoft Dynamics CRM.
tracingService.Trace("FollowupPlugin: Creating the task activity.");
service.Create(followup);
}
}
//<snippetFollowupPlugin3>
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the FollupupPlugin plug-in.", ex);
}
//</snippetFollowupPlugin3>
catch (Exception ex)
{
tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
throw;
}
}
}
}
}

Program crashes when exe is copied to different computer

I have written a program in c# on my Windows 7 computer with .NET 4.0 using Sharp Develop 4.2.
I then changed it to a release within Sharp Develop, built it, and copied the .exe in the bin\Release folder to another Windows 7 computer with .NET 4.0. It crashes immediately without loading the initial form and gives no specific error. My MainForm method is like this:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Drawing.Printing;
using System.Diagnostics;
using System.Text;
namespace BiasTracker1._
{
public partial class MainForm : Form
{
//Here are my initial variables
public static SqlConnectionStringBuilder sqlBldr = new SqlConnectionStringBuilder();
public static DataSet ds = new DataSet();
public static DataTable DisplayTable = ds.Tables.Add("DisplayTable");
SqlDataAdapter RawDataDA;
SqlCommandBuilder RawSampleSCB;
public static DataTable InstrumentDetail = ds.Tables.Add("InstrumentDetail");
public static string DatabaseOwner;
System.Windows.Forms.DataVisualization.Charting.Chart CurrentChart;
public static DataTable ImportDataTable = new DataTable();
public static string NewTransfer;
public static bool ValidatePerCell = true;
public static Image chart1Image;
public static string Title;
public static string NIRLabString;
bool ChangesNotDisplayed = false;
Point PreviousChartLocation;
List<System.Windows.Forms.DataVisualization.Charting.DataPoint> SelectedPoints = new List<System.Windows.Forms.DataVisualization.Charting.DataPoint>();
List<DataRow> SelectedRows = new List<DataRow>();
static double EPS = 2.22045e-016;
double FPMIN = 2.22507e-308 / EPS;
public static CustomPrintDoc pd = new CustomPrintDoc();
int NumOfParametersInReport = 0;
public static SqlConnectionStringBuilder SimPlusConn;
public static string SimPlusProductGUID;
public static string SimPlusSiteCode;
public double[] cof = new double[] {-1.3026537197817904,0.64196979235649026,0.019476473204185836,-0.009561514786808631,-0.000946595344482036,0.000366839497852761,0.000042523324806907,-0.000020278578112534,-0.000001624290004647,0.00000130365583558,0.000000015626441722,-0.000000085238095915,0.000000006529054439,0.000000005059343495,-0.000000000991364156,-0.000000000227365122,0.000000000096467911,0.000000000002394038,-0.000000000006886027,0.000000000000894487,0.000000000000313092,-0.000000000000112708,0.000000000000000381,0.000000000000007106,-0.000000000000001523,-0.000000000000000094,0.000000000000000121,-0.000000000000000028};
Point? prevPosition = null;
ToolTip tooltip = new ToolTip();
public MainForm()
{
try
{
InitializeComponent();
}
catch(Exception ex)
{
MessageBox.Show("Failed in Initialization.\n" + ex.ToString());
}
//Test SQL Connection
FileStream ConnectionStream;
try
{
ConnectionStream = new FileStream(#"C:\BiasTracker\settings.ini",FileMode.OpenOrCreate);
}
catch(DirectoryNotFoundException ex)
{
MessageBox.Show("Not able to find ini... Creating one.");
Directory.CreateDirectory(#"C:\BiasTracker");
ConnectionStream = new FileStream(#"C:\BiasTracker\settings.ini",FileMode.OpenOrCreate);
}
try
{
StreamReader ConnectionRdr = new StreamReader(ConnectionStream);
string line = null;
if((line = ConnectionRdr.ReadLine()) != null)
{
sqlBldr.DataSource = line;
sqlBldr.Password = ConnectionRdr.ReadLine();
sqlBldr.UserID = ConnectionRdr.ReadLine();
sqlBldr.InitialCatalog = ConnectionRdr.ReadLine();
}
else
{
sqlBldr.DataSource = ".\\SQLEXPRESS";
sqlBldr.Password = "password";
sqlBldr.UserID = "sa";
sqlBldr.InitialCatalog = "BiasMaster";
StreamWriter ConnectionWtr = new StreamWriter(ConnectionStream);
ConnectionWtr.WriteLine(".\\SQLEXPRESS");
ConnectionWtr.WriteLine("password");
ConnectionWtr.WriteLine("sa");
ConnectionWtr.WriteLine("BiasMaster");
ConnectionWtr.WriteLine("applications\\SQLEXPRESS");
ConnectionWtr.WriteLine("password");
ConnectionWtr.WriteLine("sa");
ConnectionWtr.WriteLine("BiasMaster");
ConnectionWtr.Dispose();
}
ConnectionStream.Close();
ConnectionStream.Dispose();
ConnectionRdr.Dispose();
}
catch(Exception ex)
{
MessageBox.Show("Not Able to read connection string\n" + ex.ToString());
}
System.Data.SqlClient.SqlConnection tmpConn;
tmpConn = new SqlConnection(sqlBldr.ConnectionString);
try //Test the connection and existence of the database
{
tmpConn.Open();
tmpConn.Close();
}
catch
{
MessageBox.Show("Database Connection not Found.");
tmpConn.Close();
}
SqlDataAdapter SettingsDA = new SqlDataAdapter("SELECT * FROM Settings WHERE SettingDesc = 'Owner'",sqlBldr.ConnectionString);
DataTable SettingsTable = new DataTable();
SettingsDA.Fill(SettingsTable);
DatabaseOwner = SettingsTable.Rows[0][1].ToString();
MakeTreeView();
}
MakeTreeView is surrounded by a try catch with a messagebox.
My Form loads these controls:
privateSystem.Windows.Forms.ToolStripMenuItemsimPlusImportToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripStatusLabeltoolStripStatusLabel1;
privateSystem.Windows.Forms.ToolStripMenuItemsyncWithSharedServerToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsyncToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsetDBConnectionToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtestToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemdetectOutliersToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemsaveToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemexcludeSelectedToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemgraphActionsToolStripMenuItem;
privateSystem.Windows.Forms.ComboBoxcomboBox7;
privateSystem.Windows.Forms.ToolStripMenuItemprintReportToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddToReportToolStripMenuItem;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart4;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart3;
privateSystem.Windows.Forms.Panelpanel2;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart2;
privateSystem.Windows.Forms.ComboBoxcomboBox6;
privateSystem.Windows.Forms.Labellabel7;
privateSystem.Windows.Forms.Buttonbutton3;
privateSystem.Windows.Forms.DataVisualization.Charting.Chartchart1;
privateSystem.Windows.Forms.Buttonbutton2;
privateSystem.Windows.Forms.ToolStripMenuItemremoveProductFormInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcopyInstrumentProductListToAnotherInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddProductToInstrumentToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemaddParameterToProductToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtablesToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemtXTToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcSVToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItembiasDataToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemimportToolStripMenuItem;
privateSystem.Windows.Forms.Labellabel1;
privateSystem.Windows.Forms.ComboBoxcomboBox1;
privateSystem.Windows.Forms.Labellabel2;
privateSystem.Windows.Forms.ComboBoxcomboBox2;
privateSystem.Windows.Forms.Labellabel3;
privateSystem.Windows.Forms.ComboBoxcomboBox3;
privateSystem.Windows.Forms.Labellabel4;
privateSystem.Windows.Forms.ComboBoxcomboBox4;
privateSystem.Windows.Forms.Labellabel5;
privateSystem.Windows.Forms.ComboBoxcomboBox5;
privateSystem.Windows.Forms.Labellabel6;
privateSystem.Windows.Forms.DateTimePickerdateTimePicker1;
privateSystem.Windows.Forms.DateTimePickerdateTimePicker2;
privateSystem.Windows.Forms.ToolStripMenuItemparameterToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemproductToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuIteminstrumentToolStripMenuItem1;
privateSystem.Windows.Forms.ToolStripMenuItemlocationToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemcompanyToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemnewToolStripMenuItem;
privateSystem.Windows.Forms.ToolStripMenuItemfileToolStripMenuItem;
privateSystem.Windows.Forms.MenuStripmenuStrip1;
privateSystem.Windows.Forms.StatusStripstatusStrip1;
privateSystem.Windows.Forms.TabPagetabPage2;
privateSystem.Windows.Forms.DataGridViewdataGridView1;
privateSystem.Windows.Forms.TreeViewtreeView1;
privateSystem.Windows.Forms.Buttonbutton1;
privateSystem.Windows.Forms.Panelpanel1;
privateSystem.Windows.Forms.TabPagetabPage1;
privateSystem.Windows.Forms.TabControltabControl1;
The only thing I can think is that I am using a reference to something that the other computer does not have access to. I thought it was the chart controls, but .NET 4.0 has those included. Any help would be immensely appreciated.
I found the culprit. It was the line:
DatabaseOwner = SettingsTable.Rows[0][1].ToString();
I found it using AppDomain.UnhandledException. It was a great tool if anyone else is running into a similar issue.
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

Autofac Contrib Multi Tenant throws "Request is not available in this context" exception

I am using http://code.google.com/p/autofac/wiki/MultitenantIntegration version 2.4.4 with Autofac 2.4.4 on an ASP.Net MVC 3.0.
I use the new Asp.Net MVC 3 support (using AutofacDependencyResolver). I encounter a problem that the tenant identification strategy class (implementing ITenantIdentificationStrategy) throws "Request is not available in this context" exception.
I tried using AutofacContrib.Multitenant.Web.RequestParameterTenantIdentificationStrategy class and it also throws the same exception.
My application_start looks as follow
protected void Application_Start()
{
//wire up all the necessary objects used in this web application
IContainer container = BootStrap.RegisterAll().Build();
//multi tenant support
MultitenantContainer multiTenant = new MultiTenancy().Register(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(multiTenant.BeginLifetimeScope()));
}
Never mind. HttpContext.Current.Request is not available at Application_Start in IIS 7.0. The only solution to this is to capture the HTTPException and set the TenantId to null at Catch and return false.
public bool TryIdentifyTenant(out object tenantId)
{
var current = HttpContext.Current;
try
{
if (current == null)
{
tenantId = null;
return false;
}
var request = current.Request;
}
catch (HttpException)
{
tenantId = null;
return false;
}
//continue with your tenant identification
}