Invoke static method using Introspection in Flex - apache-flex

All,
While this is similar to another post, that post (does not indicate how to perform this (if it can be done) without instantiating an object. Also, without success I have tried multiple variations on the theme of:
class[method](arg)
class[method].call(arg)
method.apply(class, arg)
I am new to Flex, but have used Reflection in both C# and Java. BTW, the code that I am attempting to get to work in Flex is mirrored in both those languages and works as expected.
Any help is appreciated,
Thanks,
Todd
Non-functioning Flex Code:
private function ipMethodTester( ipMethodName:String,
shouldPass:Array, shouldFail:Array):void
{
var message:String;
var entry:String;
for each(entry in shouldPass)
{
message = ipMethodName + ": " + entry + " should pass";
try
{
Assert.assertTrue(message,
FieldValidator[ipMethodName](entry));
}
catch(e:Error)
{
Assert.fail(e.message + " " + message);
}
}
for each(entry in shouldFail)
{
message = ipMethodName + ": " + entry + " should fail";
try
{
Assert.assertFalse(message,
FieldValidator[ipMethodName](entry));
}
catch(e:Error)
{
Assert.fail(e.message + " " + message);
}
}
}
Java Code:
private void ipMethodTester(final String ipMethodName,
final String[] shouldPass, final String[] shouldFail)
{
Method method;
try
{
method = InetUtil.class.getDeclaredMethod(ipMethodName, String.class);
method.setAccessible(true);
for(String entry : shouldPass)
{
Object[] invokeArgs = { entry };
boolean passed = (Boolean)method.invoke(null, invokeArgs);
assertTrue(ipMethodName + ": " + entry + " should pass", passed);
}
for(String entry : shouldFail)
{
Object[] invokeArgs = { entry };
boolean passed = (Boolean)method.invoke(null, invokeArgs);
assertFalse(ipMethodName + ": " + entry + " should fail", passed);
}
}
catch (final Exception e)
{
fail(e.getClass().toString());
}
}
C# code:
private void ipMethodTester(string ipMethodName, string[] shouldPass, string[] shouldFail)
{
Type type = typeof (ValidateUtil);
BindingFlags bindingFlags = BindingFlags.InvokeMethod
| BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
MethodInfo method = type.GetMethod(ipMethodName, bindingFlags);
foreach(string entry in shouldPass)
{
object[] invokeArgs = { entry };
bool passed = (bool)method.Invoke(null, invokeArgs);
Assert.IsTrue(passed, ipMethodName + ": " + entry + " should pass");
}
foreach(string entry in shouldFail)
{
object[] invokeArgs = { entry };
bool passed = (bool)method.Invoke(null, invokeArgs);
Assert.IsFalse(passed, ipMethodName + ": " + entry + " should fail");
}
}

This works for me:
MyClass['myMethod']('arg1','arg2');
This also works:
MyClass['myMethod'].call(MyClass, 'arg1', 'arg2');
Note: the first argument of the 'call' method (MyClass in this case) just specifies which object is referenced when you use the 'this' keyword inside the function.

Related

how to use HttpContext.Current in net core 5 (no necromenssing)

before we use net 5 we use net framework.
// Net Framework
ClsLog.WriteLog(HttpContex.Current, GetType(), "GetManualWeightData", ActionType.Action_Read, model.UID, model, clsResponse, clsResponse.ErrorMsg, model.LogCode);
//
but now we use net 5 and net 5 cant use current...
how to instaed of "current"?
+
public class ClsLog
{
public static void WriteLog(HttpContext current, Type type, string strMethodName, string strActionType, string strUID, object strParam, object strResponse, string strErrorMsg = "", string strLogCode = "")
{
string strLocalIP = "";
string strBrowser = "";
string strMemID = "";
string strCustomerID = "";
if (current != null)
{
//strLocalIP = current.Session("LocalIP"] + "";
//strBrowser = current.Session["BrowserInfo"] + "";
//strMemID = current.Session["LogID"] + "";
//strCustomerID = current.Session["CustomerID"] + "";
}
try
{
Task.Run(() => ClsWriteLog.getInstance().WriteLogServer(new ClsVariableAppLog("AppAPILog", strLocalIP, strBrowser, strMemID, strCustomerID, type.Module.Name, strMethodName, strUID, strActionType, type.FullName, strErrorMsg, strParam, strResponse, strLogCode)));
//await ClsWriteLog.getInstance().WriteLogServer(new ClsVariableAppLog("AppAPILog", strLocalIP, strBrowser, strMemID, strCustomerID, type.Module.Name, strMethodName, strUID, strActionType, type.FullName, strErrorMsg, strParam, strResponse));
}
catch (Exception ex)
{
Trace.WriteLine("LogError - " + ex.Message);
}
}
}```
Inject the IHttpContextAccessor type and read its HttpContext property.

Ballerina : How to send attachment with email

I am using wso2/gmail package to send an email notification. According to the documentation (https://central.ballerina.io/wso2/gmail) we can send an attachment with the mail through the package. However, when I try to define attachment paths as a parameter, I get an error as follows.
incompatible types: expected 'wso2/gmail:0.9.7:AttachmentPath', found 'string'
What is AttachmentPath type? Can we parse string array of attachment paths to AttachmentPath? Here is my function to send mail.
import wso2/gmail;
import ballerina/io;
import ballerina/log;
import ballerina/config;
import ballerina/http;
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
//What is the attachment path?
AttachmentPath attachmentPath = "./org/wso2/logs/loginfo.txt";
messageRequest.attachmentPaths = attachmentPath;
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
Yes. As #pasan has mentioned, AttachmentPath is a record. Following is the updated code if someone wants to refer.
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"Text/plain"
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
messageRequest.attachmentPaths = [attachmentPath];
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
AttachmentPath is defined in [wso2/gmail][1] as a record. The attachmentPaths field needs an array of such AttachmentPath objects. So following should work.
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"text/plain"
};
messageRequest.attachmentPaths = [attachmentPaths];

Include moment.js in vaadin charts 4.0 to set axis format

Hello I am using Vaadin 8 and Vaadin charts 4.0 and am trying to format one of the data axis of the chart to different date time formats depending on user format input and locale. I try to inject the moment.js library and get a reference exception saying that moment variable does not exist. I have tried 2 different approaches which I list below:
(1) Use the #JavaScript annotation to inject moment.js.
#JavaScript({"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js", "https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"})
#WebServlet(urlPatterns = "/*", name = "IeUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = IeUI.class, productionMode = true, heartbeatInterval = 500, closeIdleSessions = false, widgetset = "softcom.ievaadin.AppWidgetSet")
public static class IeUIServlet extends VaadinServlet implements SessionInitListener {//, SessionDestroyListener {
#Override
protected void servletInitialized() throws ServletException {
super.servletInitialized();
// Add any system level init here
//Main.initSystem();
}
#Override
public void destroy() {
super.destroy(); //To change body of generated methods, choose Tools | Templates.
Main.destroy();
}
#Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
event.getSession().getSession().setMaxInactiveInterval(-1);
}
}
And the one where set the formatter
YAxis ya = new YAxis();
String js = "function() {";
js += "try {"
+ "var g = moment.tz(\"2014-06-01 12:00\", \"America/New_York\");"
+ "alert(g);"
+ "return g;}"
+ "catch(e) {"
+ "alert(e);}}";
ya.getLabels().setFormatter(js);
(2) I try to append the script tag at the head in the function itself.
String js = "attempt {"
+ "var script = document.createElement('script');"
+ "script.src = \"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js\";"
+ "document.head.appendChild(script);"
+ "} catch(e) {"
+ "alert('first one'); }"
+ "try {"
+ "var b = moment().format();"
+ "return b;"
+ "} catch (e) {"
+ "alert(e); }";
JavaScript.getCurrent().execute(attempt);
String js = "function() {";
js += "try {"
+ "var g = moment.tz(\"2014-06-01 12:00\", \"America/New_York\");"
+ "alert(g);"
+ "return g;}"
+ "catch(e) {"
+ "alert(e);}}";
ya.getLabels().setFormatter(js);
Any help would be appreciated.
You can inject the script tag in the head of the document by registering a BootstrapListener in your IeUIServlet:
#Override
protected void servletInitialized() {
getService().addSessionInitListener(event -> {
event.getSession().addBootstrapListener(new BootstrapListener() {
#Override
public void modifyBootstrapPage(BootstrapPageResponse response) {
response.getDocument().head().append("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js\"></script>");
response.getDocument().head().append("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js\"></script>");
}
#Override
public void modifyBootstrapFragment(BootstrapFragmentResponse response) {
}
});
});
}
And preprend $wnd to moment in your javascript, like this:
var g = $wnd.moment.tz(\"2014-06-01 12:00\", \"America/New_York\");
Some possible (pure Vaadin) approaches:
1) Customizing the labels: mychart.getConfiguration().getxAxis().setDateTimeLabelFormats(dateTimeLabelFormats);
2) Customizing the timezone & offset:
JavaScript.getCurrent().execute("Highcharts.setOptions({\n" +
" global: {\n" +
" useUTC: true,\n" +
" timezoneOffset: "+ timezoneOffsetInMinutes + "\n" +
" }\n" +
"});");
3) Configuring the tooltip with a user-friendly datetime format:
DataSeriesItem dataSeriesItem;
Date datetime = ...;
if (useUTC) {
dataSeriesItem = new DataSeriesItem(datetime.toInstant(), value);
} else {
dataSeriesItem = new DataSeriesItem(datetime, value);
}
dataSeriesItem.setId(xxxxx); // <= string with desired user/locale-dependant formatting of related datetime

Unable to modify xaml controls following NFC tag read

I have a method that adds a label with some text to an existing xaml StackLayout.
The method is called from a couple of places, an event fired by xaml ListView and an NFC tag read. In both scenarios, the method is hit in the code-behind.
The methods both call another method that creates the label and adds it on screen. The one that originates from the ListView event works fine but the one from the NFC tag does nothing. It passes over each row of code without causing an exception but does not add anything to the screen. I can see after this that the child count of the StackLayout is 1 and remains as 1 if you do it again.
The NFC method:
public async void HandleNFC(string convertedtag)
{
int result = 0;
try
{
var mp = (MainPage)App.Current.MainPage;
Label sl1 = mp.CurrentPage.FindByName<Label>("timeLabel");
}
catch (Exception e)
{ }
Label sl = timeLabel;
string time = sl.Text;
PeopleLocationsForUserRoot peoplelocationforuser = await WebDataAccess.GetPeopleLocationForUser(UserInfoRepository.GetUserName(), _locationID);
DateTime dt = Convert.ToDateTime(time);
long timeticks = (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
getServerTime();
string name = "";
try
{
foreach (var person in peoplelocationforuser.locationPeople)
{
if (person.TATokenValue == convertedtag)
{
var action = await DisplayActionSheet(person.FirstName + " " + person.LastName, "Cancel", null, "IN", "OUT");
string act = action;
string formattedact = act;
int swipedirection = 0;
name = person.FirstName + " " + person.LastName;
if (act == "IN")
{
formattedact = "in";
swipedirection = 1;
}
if (act == "OUT")
{
formattedact = "out";
swipedirection = 0;
}
if (act != "Cancel")
{
result = SwipeRepository.ClockUserInOut(person.EB_Counter, _locationID, swipedirection, dt, timeticks, 1, UserInfoRepository.GetLatt(), UserInfoRepository.GetLongi());
addToReadout(name, time, formattedact);
}
}
}
if (name == "")
{
await DisplayAlert("Tag Error", "Tag not recognised", "cancel");
}
}
catch (Exception ex)
{
ErrorRepository.InsertError(ex.ToString());
}
await WebDataAccess.SaveSwipesToCloud();
}
The 'addToReadOut' method that it calls:
public void addToReadout(string name, string time, string inout)
{
try
{
Label label1 = new Label { Text = name + " Successfully clocked " + inout + " # " + time, TextColor = Color.Black };
try
{
readOut.Children.Add(label1);
StackLayout sl = this.FindByName<StackLayout>("readOut");
sl.Children.Add(label1);
sl.Focus();
timeLabel.Text = "test";
}
catch (Exception e)
{ }
// StackLayout sl = mp.CurrentPage.FindByName<StackLayout>("readOut");
if (readOut.Children.Count() < 6)
{
readOut.Children.Add(label1);
readOut.Children.Count();
}
else
{
readOut.Children.RemoveAt(0);
readOut.Children.Add(label1);
readOut.Children.Count();
}
}
catch (Exception ex)
{
ErrorRepository.InsertError(ex.ToString());
}
}
You can see that I have also tried to modify the object called 'timelabel' but does also does not change on screen.
The must be something different happening following the NFC event which is causing an issue here but I can't find what's causing it.
You NFC event is firing on a background thread; your UI updates need to happen on the UI thread
Device.BeingInvokeOnMainThread( () => {
// UI Code goes here
});

CRM Dynamics Plugin Error - Given Key not found in Dictionary

Hi i developed a plugin and once deployed, i'm getting an error on save of a record.
Given key was not found in Dictionary. It's a pretty generic error, do you see anything or possibly know of a way to go about debugging ? `
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Quad.SalesEstimating.MSCRMPlugins.PluginHelpers;
using Sybase.Data.AseClient;
namespace CRMSolution.Plugins
{
public class PreTitleUpdate : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity entity;
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target business entity from the input parmameters.
entity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents an contact.);
if (entity.LogicalName != "qg_title") { return; }
}
else
{
return;
}
try
{
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)
serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(
context.UserId);
IOrganizationService elevatedService = serviceFactory.CreateOrganizationService(null);
Entity preImage = context.PreEntityImages["PreImage"];
//Entity postImage = context.PostEntityImages["PostImage"];
#region Variable Setup
const string PREMEDIA_PC = "100000000";
const string RETAIL_INSERTS_PC = "9";
const string COMMERCIAL_PC = "12";
const string DIRECT_MAIL_PC = "7";
const string INSTORE_PC = "13";
string creditAccountID = null;
string creditCustomerID = null;
//string previousTitleCode = null;
string accountId = null;
string creditId = null;
string productType = string.Empty;
int vertisId = 0;
string vertisCustId = string.Empty;
string vertisParentCustId = string.Empty;
string message = string.Empty;
#endregion
#region Get Entity Values
EntityReference titleidLookup = new EntityReference();
if (entity.Contains("qg_titleid"))
{
var titleGuid = (Guid)entity["qg_titleid"];
titleidLookup = (EntityReference)new EntityReference("qg_title", titleGuid);
}
else if (preImage.Contains("qg_titleid"))
{
var titleGuid = (Guid)preImage["qg_titleid"];
titleidLookup = (EntityReference)new EntityReference("qg_title", titleGuid);
}
EntityReference accountIdLookup = new EntityReference();
if (entity.Contains("qg_accountid"))
{
accountIdLookup = (EntityReference)entity["qg_accountid"];
accountId = accountIdLookup.Id.ToString();
}
else if (preImage.Contains("qg_accountid"))
{
accountIdLookup = (EntityReference)preImage["qg_accountid"];
accountId = accountIdLookup.Id.ToString();
}
EntityReference creditIdLookup = new EntityReference();
if (entity.Contains("qg_creditid"))
{
creditIdLookup = (EntityReference)entity["qg_creditid"];
if (creditIdLookup != null)
{
creditId = creditIdLookup.Id.ToString();
}
else
{
entity.SetValue("qg_customerid", string.Empty);
}
}
else if (preImage.Contains("qg_creditid"))
{
creditIdLookup = (EntityReference)preImage["qg_creditid"];
if (creditIdLookup != null)
{
creditId = creditIdLookup.Id.ToString();
}
else
{
entity.SetValue("qg_customerid", string.Empty);
}
}
//if (entity.Contains("qg_previoustitlecode"))
//{
// previousTitleCode = entity.GetValue("qg_previoustitlecode");
//}
//else if (preImage.Contains("qg_previoustitlecode"))
//{
// previousTitleCode = preImage.GetValue("qg_previoustitlecode");
//}
if (entity.Contains("qg_producttype"))
{
productType = entity.GetValue("qg_producttype");
//this.LogItemToFile("QG_TitlePreUpdate productType from entity.");
}
else if (preImage.Contains("qg_producttype"))
{
productType = preImage.GetValue("qg_producttype");
//this.LogItemToFile("QG_TitlePreUpdate productType from preImage.");
}
if (entity.Contains("qg_vertiscustomerid"))
{
vertisCustId = entity.GetValue("qg_vertiscustomerid");
//this.LogItemToFile("QG_TitlePreUpdate qg_vertiscustomerid from entity.");
}
else if (preImage.Contains("qg_vertiscustomerid"))
{
vertisCustId = preImage.GetValue("qg_vertiscustomerid");
//this.LogItemToFile("QG_TitlePreUpdate qg_vertiscustomerid from preImage.");
}
#endregion
if (accountId != null)
{
#region Credit Business Unit
if (creditId != null)
{
// get credit business unit
ColumnSet creditcolumns = new ColumnSet(new string[] {"qg_accountid", "qg_customerid"});
Guid creditIdGUID = new Guid(creditId);
Entity qg_credit = elevatedService.Retrieve("qg_credit", creditIdGUID, creditcolumns);
if (qg_credit.Attributes.Contains("qg_accountid"))
{
EntityReference creditAccount = (EntityReference)qg_credit["qg_accountid"];
creditAccountID = creditAccount.Id.ToString();
}
if (qg_credit.Attributes.Contains("qg_customerid"))
{
creditCustomerID = qg_credit.GetValue("qg_customerid").ToString();
}
}
#endregion
#region Validate Customer ID
// If the Customer has been selected, validate account and get the customer ID.
// Validate that the Credit record and Title are under the same Account
if (creditId != null)
{
if (creditAccountID != accountId)
{
throw new InvalidPluginExecutionException(" " +
"Credit Record must be under the same Account as the Title.");
}
if (creditCustomerID != null)
{
// Set the customerid on the Title
entity.SetValue("qg_customerid", creditCustomerID);
// service.Update(entity);
}
else
{
// something went wrong so stop processing...
throw new InvalidPluginExecutionException(" " + "Could not update the Customer ID.");
}
}
#endregion
//#region Validate Previous Title Code
//// if a previous title code has been selected, validate that it exists...
//if (!String.IsNullOrEmpty(previousTitleCode))
//{
// if (!TitleCodeExists(previousTitleCode))
// {
// throw new InvalidPluginExecutionException(" " + "Previous Title Code is not valid. Please select a Title Code that previously existed.");
// }
//}
//#endregion
#region Approved for QG Paper
try
{
string ownerDomainName = null;
string aprvdForQGPaper = "";
ColumnSet ownerColumns = new ColumnSet(new string[] { "businessunitid", "domainname", });
Entity systemuser = service.Retrieve("systemuser", context.InitiatingUserId, ownerColumns);
if (entity.Contains("qg_aprvdforqgppr"))
{
aprvdForQGPaper = entity.GetValue("qg_aprvdforqgppr");
}
if (systemuser.Attributes.Contains("domainname"))
{
ownerDomainName = systemuser.GetValue("domainname").ToString();
}
// Set the Approved for QG Paper last changed
if (aprvdForQGPaper == "1")
{
entity.SetValue("qg_aprvdforqgpprdt", DateTime.Now);
entity.SetValue("qg_aprvdforqgpprby", ownerDomainName);
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(
" " + "An error occurred in the plug-in." + ex.Message, ex);
}
#endregion
#region Validate Classification
//try
//{
// if (entity.Contains("qg_producttype") && preImage.Contains("qg_producttype"))
// {
// bool validateProdType = true;
// // Allow Credit to change product type regardless of Sales Staff being assigned.
// if (this.DoesUserHaveRole(context.InitiatingUserId, service, "Quad Credit") ||
// this.DoesUserHaveRole(context.InitiatingUserId, service, "System Administrator"))
// {
// validateProdType = false;
// }
// if (validateProdType)
// {
// OptionSetValue preProdType = (OptionSetValue)preImage["qg_producttype"];
// OptionSetValue postProdType = (OptionSetValue)entity["qg_producttype"];
// if (preProdType.Value != postProdType.Value)
// {
// // The only valid Product Classification change is within MagCat/SIP.
// List<int> validprodclasschangelist = new List<int>(new int[] { 2, 3, 5 });
// List<int> salesRoles = new List<int>(new int[] { 52, 30, 33, 35, 41, 48 });
// QueryExpression query = new QueryExpression();
// query.NoLock = true;
// ColumnSet columns = new ColumnSet(new string[] { "qg_titleid", "qg_employeerole" });
// ConditionExpression condition = new ConditionExpression();
// condition.AttributeName = "qg_employeerole";
// condition.Operator = ConditionOperator.In;
// foreach (var role in salesRoles)
// {
// condition.Values.Add(role);
// }
// query.EntityName = "qg_titleemployeerole";
// query.ColumnSet = columns;
// query.Criteria.AddCondition("qg_titleid", ConditionOperator.Equal, titleidLookup.Id);
// query.Criteria.AddCondition(condition);
// EntityCollection resultSet = service.RetrieveMultiple(query);
// if (resultSet.Entities.Count > 0)
// {
// if (!validprodclasschangelist.Contains(preProdType.Value) ||
// !validprodclasschangelist.Contains(postProdType.Value))
// {
// throw new InvalidPluginExecutionException("Product Classification change is not valid.");
// }
// }
// }
// }
// }
//}
//catch (Exception ex)
//{
// throw new InvalidPluginExecutionException(
// " " + "An error occurred in the plug-in." + ex.Message, ex);
//}
#endregion
#region Vertis Ids
string accountBUID = null;
string accountBUName = null;
// if the account doesn't have a VertisParentCustomerID get the last five digits of the VMAC ID
// to build the parent customer id
ColumnSet accountcolumns = new ColumnSet(new string[] { "owningbusinessunit", "qg_vertisparentcustid" });
Guid accountIdGUID = new Guid(accountId);
Entity accountService = service.Retrieve("account", accountIdGUID, accountcolumns);
if (accountService.Attributes.Contains("owningbusinessunit"))
{
EntityReference accountBusinessUnit = (EntityReference)accountService["owningbusinessunit"];
accountBUID = accountBusinessUnit.Id.ToString();
}
if (accountService.Attributes.Contains("qg_vertisparentcustid"))
{
vertisParentCustId = accountService.GetValue("qg_vertisparentcustid");
}
ColumnSet buColumns = new ColumnSet(new string[] { "name" });
// GUID from above
Guid buIdGUID = new Guid(accountBUID);
Entity buService = service.Retrieve("businessunit", buIdGUID, buColumns);
if (buService.Attributes.Contains("name"))
{
accountBUName = buService.GetValue("name").ToString();
}
// if productClass has been selected, see if we need to pull VertisCustIds..
if (accountBUName.Equals("Corporate Print") && string.IsNullOrEmpty(vertisCustId))
{
// if product class is 'Retail Inserts', 'Premedia', or 'Commercial' we need to pull Vertis Ids
if (productType.Equals(RETAIL_INSERTS_PC) || productType.Equals(DIRECT_MAIL_PC) ||
productType.Equals(COMMERCIAL_PC) || productType.Equals(PREMEDIA_PC) || productType.Equals(INSTORE_PC))
{
bool vertisIdResult = false;
// get the last five digits of the VMAC ID to build the customer id
vertisIdResult = this.GetNextId("VERTIS_CUST_ID", "TITLE", ref vertisId, ref message);
if (string.IsNullOrEmpty(vertisParentCustId))
{
// get the last five digits of the VMAC ID to build the parent customer id
//vertisIdResult = this.GetNextId("VERTIS_CUST_ID", "TITLE", ref vertisId, ref message);
accountService.SetValue("qg_vertisparentcustid", "9" + vertisId.ToString());
service.Update(accountService);
}
if (vertisIdResult)
{
if (productType.Equals(DIRECT_MAIL_PC))
{
vertisCustId = "5" + vertisId.ToString();
}
else if (productType.Equals(RETAIL_INSERTS_PC))
{
vertisCustId = "0" + vertisId.ToString();
}
else { vertisCustId = "1" + vertisId.ToString(); }
//this.LogItemToFile("TitlePreCreate vertisCustId: " + vertisCustId);
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
}
}
else if (!string.IsNullOrEmpty(vertisCustId))
{
// if the product class changed, we may need to change the VertisCustomerID
if (entity.Contains("qg_producttype") && preImage.Contains("qg_producttype"))
{
OptionSetValue preProdType = (OptionSetValue)preImage["qg_producttype"];
OptionSetValue postProdType = (OptionSetValue)entity["qg_producttype"];
if (preProdType.Value != postProdType.Value)
{
//if (Convert.ToInt32(vertisCustId.Substring(1)) < 67000)
//{
// throw new InvalidPluginExecutionException(" " + "Product Class may not be changed for Customers that originated from Vertis.");
//}
//else
//{
// check the validity of the VertisId
// if (productType.Equals(DIRECT_MAIL_PC)) vertisCustId = "5" + vertisId.ToString();
// if (productType.Equals(RETAIL_INSERTS_PC)) vertisCustId = "0" + vertisId.ToString();
// else { vertisCustId = "1" + vertisId.ToString();
if (productType.Equals(DIRECT_MAIL_PC) && !vertisCustId.Substring(0, 1).Equals("5"))
{
vertisCustId = vertisCustId.Substring(1);
vertisCustId = "5" + vertisCustId;
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
else if (productType.Equals(RETAIL_INSERTS_PC) && !vertisCustId.Substring(0, 1).Equals("0"))
{
vertisCustId = vertisCustId.Substring(1);
vertisCustId = "0" + vertisCustId;
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
else if (productType.Equals(PREMEDIA_PC) && !vertisCustId.Substring(0, 1).Equals("1"))
{
vertisCustId = vertisCustId.Substring(1);
vertisCustId = "1" + vertisCustId;
entity.SetValue("qg_vertiscustomerid", vertisCustId);
}
//}
}
}
}
#endregion
}
else
{
throw new InvalidPluginExecutionException(" " + "An error occurred in the plug-in. Owner ID, Account ID or Credit ID is Null.");
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(" " + "An error occurred in the plug-in." + ex.Message, ex);
}
}
/// <summary>
/// Use Ase command to determine is title code exists
/// </summary>
/// <param name="titlecode">The title code to use in the select </param>
/// <returns>A true/false value indicating success or failure</returns>
public bool TitleCodeExists(string titlecode)
{
int TitleCodeCount = 0;
string CmndText = "select count(*) as cnt from QUAD0024.dbo.TITLE_VW where _TITLE_CODE = '" + titlecode + "'";
// connect to Sybase to see if Title Code exists in the Title View.
try
{
using (AseConnection dbcon = new AseConnection(this.GetSybaseDbConnectionString()))
{
dbcon.Open();
AseCommand cmd = new AseCommand(CmndText, dbcon);
IDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
TitleCodeCount = (int)reader["cnt"];
}
if (TitleCodeCount == 0)
{
//throw new InvalidPluginExecutionException(" " + " TitleCodeExists: Return False.");
return false;
}
else
{
//throw new InvalidPluginExecutionException(" " + " TitleCodeExists: Return True.");
return true;
}
}
}
catch (Exception e)
{
this.LogExceptionEvent(new Exception("Message", e));
throw new InvalidPluginExecutionException(" " + " TitleCodeExists Failed" + e.Message);
}
}
}
}
`
Its better to check before we are trying to access any attribute in an object.
In this particular code, one catch is that while accessing the images we are not trying to check whether the object contains that image or not.
Similar way check any other miss.
It may also be possible that we are checking for a particular attribute and accessing a different one because of a typo.
Hope this helps you to pin point the issue.

Resources