Cannot instantiate the type EventHandler - event-handling

if (savedInstanceState != null)
mHandler = new EventHandler(Main.this, mFileMag, savedInstanceState.getString("location"));
else
mHandler = new EventHandler(Main.this, mFileMag);
Error is
Cannot instantiate the type EventHandler
How can I solve this Error?

Related

Get Property of Observable

Back in E3 the following was the correct way to create an IObservableValue:
modelObservable = PojoObservables.observeDetailValue((IObservableValue) this.model, this.property, null);
// or
modelObservable = PojoObservables.observeValue(this.model, this.property);
Then you could get the property from this modelObservable via:
String property = ((IBeanObservable) modelObservable).getPropertyDescriptor().getName();
Now with E4, the correct way to create an IObservableValue is:
modelObservable = PojoProperties.value(this.property).observeDetail((IObservableValue) this.model);
// or
modelObservable = PojoProperties.value(this.property).observe(this.model);
However, the method getPropertyDescriptor() now returns null. How can I get the property of this modelObservable in a general way?
The best I can do is this method:
public static final String findProperty(final IObservable target) {
String property = null;
if (target instanceof IBeanObservable) {
final PropertyDescriptor desc = ((IBeanObservable) target).getPropertyDescriptor();
property = desc == null ? null : desc.getName();
}
if (property == null && target instanceof DecoratingObservableValue) {
property = getPropertyOfDecorator((DecoratingObservableValue<?>) target);
}
return property;
}
private static String getPropertyOfDecorator(DecoratingObservableValue<?> target) {
try {
final Field decoratedField = DecoratingObservableValue.class.getDeclaredField("decorated");
decoratedField.setAccessible(true);
final Object decorated = decoratedField.get(target);
if (decorated != null) {
return findProperty((IObservable) decorated);
}
return null;
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}

Spring Batch Job Parameters in Item Reader

My parameter (workingDirectory) is always null and I do not understand why?
I am using the job launcher to kick off the job.
I see the job parameter in the database but it is not getting injected into my reader.
This is my reader.
#Component("customerReader")
#StepScope
public class CustomReader implements ItemReader<Customer> {
#Value("#{jobParameters['workingDirectory']}")
protected String workingDirectory;
private BufferedReader reader;
protected ObjectMapper objectMapper = new ObjectMapper();
private int fileIdx = 1;
#Override
public Customer read() throws IOException {
if(reader == null) {
reader = new BufferedReader(new FileReader(new File(workingDirectory + "output1.json")));
}
String line = reader.readLine();
if (line == null) {
try {
fileIdx++;
reader = new BufferedReader(
new FileReader(new File(workingDirectory + "output" + fileIdx + ".json")));
}
catch (FileNotFoundException ex) {
return null;
}
line = reader.readLine();
}
return objectMapper.readValue(line, Customer.class);
}
}
I am launching by calling:
JobParameters p = new JobParametersBuilder().addString("workingDirectory", workingDirectory).toJobParameters();
JobExecution e = jobLauncher.run(
recordGenerator.getJob(file, "/Users/abc/data/"), p);

How to Repeat Previous Actions in Exception in EF 6

I am having a problem with repeating previous operations when there is an error in the SaveChanges method of Entity Framework.
Below is the code block
public static int SaveChangesTask(this DbContext db)
{
int result = -1;int countLoop = 0;
bool continueLoop = true;
var modifiedOrAddedEntities = db.ChangeTracker.Entries().Where(a => a.State != EntityState.Detached
&& a.State != EntityState.Unchanged).ToList();
while (continueLoop && countLoop<3)
{
try
{
result= db.SaveChanges();
continueLoop = false;
}
catch(Exception ex)
{
string error = ex.ToSystemException();
if(error.ToLowerInvariant().Contains("ORA-00060".ToLowerInvariant()) || error.ToLowerInvariant().Contains("deadlock"))
{
foreach (var item in modifiedOrAddedEntities)
{
db.Entry(item).State = item.State;
}
countLoop++;
Random rnd = new Random();
System.Threading.Thread.Sleep(rnd.Next(1, 5)* 1000);
}
else
{
throw ex;
}
}
}
return result;
}
But when I want to add old tracking objects to context, Entity Framework Throws Exception like that
"The entity type DbEntityEntry is not part of the model for the current context"

How can I get all Validation Errors?

I want to get all validation errors.
Can I get errors in DbEntityValidationException ?
DbEntityValidationException ex = exception as DbEntityValidationException
public static string GetAllExceptionTree(Exception exception)
{
if (exception is DbEntityValidationException)
{
StringBuilder validationErrors = new StringBuilder();
DbEntityValidationException ex = exception as DbEntityValidationException;
foreach (var error in ex.EntityValidationErrors)
foreach (var err in error.ValidationErrors)
validationErrors.Append(String.Format("{0}<br/>", err.ErrorMessage));
return validationErrors.ToString();
}
StringBuilder sb = new StringBuilder();
do
{
if (sb.Length != 0)
sb.Append("...");
sb.Append(exception.Message);
exception = exception.InnerException;
} while (exception != null);
return sb.ToString();
}

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;
}
}
}