How display a json error message? - json.net

I cannot display the Json message, Im trying prevente that user upload files with same name this is my controller code:
//POST: /Quote/Create Save the Uploaded file
public ActionResult SaveUploadedFile(int? chunk, string name)
{
bool exists;
var fileUpload = Request.Files[0];
var uploadPath = "C:\\Files";
chunk = chunk ?? 0;
if (System.IO.File.Exists(Path.Combine(uploadPath, name)))
{
exists = true;
}
else {
exists = false;
}
if (!exists)
{
using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
else {
return Json(new { success = false, Message = "The file" + name +"already exists" }, JsonRequestBehavior.AllowGet);
}
}
This is my view code, if files success is false, then display the Json message:
UploadComplete: function (up, files) {
if (!files.success) {
alert(files.Message);
console.log(up);
} else {
var j = 0;
if (count > 0) {
j = count;
} else {
j = #i + '';
}
$.each(files, function (i, file) {
var extension = file.name.split(".");
$('.files').append('<input type=\"hidden\" name=\"Files[' + j + '].Name\" value=\"' + file.name + '\" />');
$('.files').append('<input type=\"hidden\" name=\"Files[' + j + '].Date\" value=\"' + "#DateTime.Now" + '\" />');
j++;
});
}
}
Thanks in advance !!

It seems that you need to be returning a string result rather than an ActionResult, since all you really want is if it passed or not. Also shortened your code a little to reflect the changes.
If you did want to return an object (meaning you wanted more than one property), I would create a model (class and then object), then return JsonResult rather than ActionResult.
Good documentation on how to return JsonResult object
C#
public string SaveUploadedFile(int? chunk, string name)
{
bool exists = false;
var fileUpload = Request.Files[0];
var uploadPath = "C:\\Files";
chunk = chunk ?? 0;
exists = System.IO.File.Exists(Path.Combine(uploadPath, name));
if (!exists)
{
using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
}
return message = !exists ? string.Empty
: "The file" + name + " already exists";
}
Javascript
if (files.message != '') { // meaning "exists" is true
console.log(up);
} else {
......
......
}

Related

parsing signed and encrypted email

I am writing an application that must be able to read signed and encrypted emails and parse through their contents. I am able to get everything working fine for emails that are only encrypted, but do not know what to do when I get an email that is also signed. Once I decrypt this email instead of having an anticipated 4 parts in a Multipart object, I have only 1 part in a MimePart object with the file name smime.p7m. I do not know how to break this file up or verify the signature. I have found the documentation on verifying a signature (http://www.mimekit.net/docs/html/Working-With-SMime.htm#Verify), but I don't see how this does anything. Obviously there is something that I am just not understanding at this point.
Below is a sample of the code that I am using. Note that this will be refactored after I get everything figured out, but this code is thus far working fine for all emails that I have tested so far that are not signed (may or may not be encrypted).
public void decryptAndSendEmails()
{
List<EmailMessage> emails = getEmails();
foreach (var email in emails)
{
var decryptedEmailMessage = new EmailMessage(service);
MimeMessage message;
using (var stream = new MemoryStream(email.MimeContent.Content, false))
{
message = MimeMessage.Load(stream);
}
var pkcs7 = message.BodyParts.OfType<ApplicationPkcs7Mime>().FirstOrDefault();
if (pkcs7 != null)
{
//If the SecureMimeType has not been set as it should, set it to EnvelopedData
if (pkcs7.SecureMimeType == SecureMimeType.Unknown)
{
var content = new MemoryStream();
pkcs7.Content.DecodeTo(content);
content.Position = 0;
pkcs7 = new ApplicationPkcs7Mime(SecureMimeType.EnvelopedData, content);
}
using (var ctx = new TemporarySecureMimeContext())
{
using (var stream = File.OpenRead(ConfigurationManager.AppSettings["certLocation"]))
{
ctx.Import(stream, ConfigurationManager.AppSettings["certPassword"]);
}
var decrypted = pkcs7.Decrypt(ctx);
var decryptedParts = new List<MimePart>();
if (decrypted is Multipart)
{
decryptedParts = breakMultiPart((Multipart)decrypted);
}
else if (decrypted is MimePart)
{
decryptedParts.Add((MimePart)decrypted);
}
else
{
throw new InvalidOperationException("Unknown Mime part found");
}
var textParts = decryptedParts.Where(r => r is TextPart);
var htmlParts = textParts.Where(x => ((TextPart)x).IsHtml);
var textBodyParts = textParts.Where(x => !((TextPart)x).IsHtml);
var attachmentParts = decryptedParts.Where(r => !(r is TextPart));
if (htmlParts.Any())
{
if (htmlParts.Count() > 1)
{
throw new InvalidOperationException("multiple html body parts.");
}
var htmlPart = (TextPart)htmlParts.First();
decryptedEmailMessage.Body = new MessageBody(BodyType.HTML, htmlPart.Text);
}
else
{
//Text body
if (textBodyParts.Count() > 1)
{
throw new InvalidOperationException("multiple text body parts.");
}
var textPart = (TextPart)textBodyParts.First();
decryptedEmailMessage.Body = new MessageBody(BodyType.Text, textPart.Text);
}
foreach (var part in attachmentParts)
{
var content = new MemoryStream();
part.Content.DecodeTo(content);
content.Position = 0;
decryptedEmailMessage.Attachments.AddFileAttachment(part.FileName, content);
if (!part.IsAttachment)
{
decryptedEmailMessage.Attachments.First(r => r.Name == part.FileName).IsInline = true;
decryptedEmailMessage.Attachments.First(r => r.Name == part.FileName).ContentId = part.ContentId;
}
}
}
////do stuff with decrypted Email
}
else
{
//The email is not encrypted
decryptedEmailMessage = email;
//do stuff with decrypted Email
}
}
}
I have finally figured this out using a combination of the comment from #jstedfast and the information I found in Unable to decrypt p7m using MimeKit. The following is the resulting code to fix this issue:
public void decryptAndSendEmails()
{
List<EmailMessage> emails = getEmails();
foreach (var email in emails)
{
var decryptedEmailMessage = new EmailMessage(service);
MimeMessage message;
using (var stream = new MemoryStream(email.MimeContent.Content, false))
{
message = MimeMessage.Load(stream);
}
var pkcs7 = message.BodyParts.OfType<ApplicationPkcs7Mime>().FirstOrDefault();
if (pkcs7 != null)
{
using (var ctx = new TemporarySecureMimeContext())
{
using (var stream = File.OpenRead(ConfigurationManager.AppSettings["certLocation"]))
{
ctx.Import(stream, ConfigurationManager.AppSettings["certPassword"]);
}
var decrypted = pkcs7.Decrypt(ctx);
if (decrypted != null && decrypted is MimePart && ((MimePart)decrypted).FileName == "smime.p7m")
{
//We need to verify the signature
var signedDecryptedEntity = decrypted as ApplicationPkcs7Mime;
signedDecryptedEntity.Verify(ctx, out decrypted); //the real decrypted data
}
var decryptedParts = new List<MimePart>();
if (decrypted is Multipart)
{
decryptedParts = breakMultiPart((Multipart)decrypted);
}
else if (decrypted is MimePart)
{
decryptedParts.Add((MimePart)decrypted);
}
else
{
throw new InvalidOperationException("Unknown Mime part found");
}
var textParts = decryptedParts.Where(r => r is TextPart);
var htmlParts = textParts.Where(x => ((TextPart)x).IsHtml);
var textBodyParts = textParts.Where(x => !((TextPart)x).IsHtml);
var attachmentParts = decryptedParts.Where(r => !(r is TextPart));
if (htmlParts.Any())
{
if (htmlParts.Count() > 1)
{
throw new InvalidOperationException("multiple html body parts.");
}
var htmlPart = (TextPart)htmlParts.First();
decryptedEmailMessage.Body = new MessageBody(BodyType.HTML, htmlPart.Text);
}
else
{
//Text body
if (textBodyParts.Count() > 1)
{
throw new InvalidOperationException("multiple text body parts.");
}
var textPart = (TextPart)textBodyParts.First();
decryptedEmailMessage.Body = new MessageBody(BodyType.Text, textPart.Text);
}
foreach (var part in attachmentParts)
{
var content = new MemoryStream();
part.Content.DecodeTo(content);
content.Position = 0;
decryptedEmailMessage.Attachments.AddFileAttachment(part.FileName, content);
if (!part.IsAttachment)
{
decryptedEmailMessage.Attachments.First(r => r.Name == part.FileName).IsInline = true;
decryptedEmailMessage.Attachments.First(r => r.Name == part.FileName).ContentId = part.ContentId;
}
}
}
//Do Something with email (decryptedEmailMessage)
}
else
{
//The email is not encrypted
decryptedEmailMessage = email;
//Do Something with email (decryptedEmailMessage)
}
}
}

GWT read mime type client side

I'm trying to read the mime type in GWT client side in order to validate a file before upload it. To do this I use JSNI to read the file header using HTML5 filereader API. However my problem is that GWT does not wait for the result of the reading and continue the code execution. The side effect is that my boolean is not set yet and my condition goes wrong. Is there any mechanism like promise implemented in GWT?
Any help on this would be much appreciated!
UploadImageButtonWidget.java
private boolean isMimeTypeValid = false;
private String mimeType = null;
public native boolean isValid(Element element)/*-{
var widget = this;
var files = element.files;
var reader = new FileReader();
var CountdownLatch = function (limit){
this.limit = limit;
this.count = 0;
this.waitBlock = function (){};
};
CountdownLatch.prototype.countDown = function (){
this.count = this.count + 1;
if(this.limit <= this.count){
return this.waitBlock();
}
};
CountdownLatch.prototype.await = function(callback){
this.waitBlock = callback;
};
var barrier = new CountdownLatch(1);
reader.readAsArrayBuffer(files[0]);
reader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
widget.#com.portal.client.widgets.base.UploadImageButtonWidget::setMimeType(Ljava/lang/String;)(header);
barrier.countDown();
}
return barrier.await(function(){
return widget.#com.portal.client.widgets.base.UploadImageButtonWidget::isMimeTypeValid();
});
}-*/
public void setMimeType(String headerString) {
boolean mimeValid = true;
if (headerString.equalsIgnoreCase(PNG_HEADER)) {
mimeType = PNG_MIMETYPE;
} else if (headerString.equalsIgnoreCase(GIF_HEADER)) {
mimeType = GIF_MIMETYPE;
} else if (headerString.equalsIgnoreCase(JPG_HEADER1) || headerString.equalsIgnoreCase(JPG_HEADER2) || headerString.equalsIgnoreCase(JPG_HEADER3)) {
mimeType = JPG_MIMETYPE;
} else {
mimeValid = false;
setValidationError(i18n.uploadErrorNotImageBasedOnMimeType());
fileChooser.getElement().setPropertyJSO("files", null);
setErrorStatus();
}
setMimeTypeValid(mimeValid);
}
public boolean isMimeTypeValid() {
GWT.log("mimeType" + mimeType);
GWT.log("isMimetypeValid" + String.valueOf(isMimeTypeValid));
return mimeType != null;
}
in the activity:
public void validateAndUpload() {
UploadImageButtonWidget uploadImageButtonWidget = view.getUpload();
if (uploadImageButtonWidget.isValid()) {
GWT.log("mime ok: will be uploaded");
uploadImage();
} else {
GWT.log("mime not ok: will not be uploaded");
}
}

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.

Error at pushbroker.StopAllServices (PushSharp)

I am encountering an exception (not always but frequently) in my push service when pushing to Windows Phone. Exception is showing "one or more errors occurred" at the point where StopAllServices is called. The push service reports these errors only when pushing to windows phone, so I am at this point thinking I am doing something wrong with the Windows code. Could a pushsharp guru please have a look at the code and advise? (i.e. Redth - Im pretty new to asking questions here, can we tag people to get their attention?) The ambiguous error is returned in the catch of the StopAllBrokers() method
protected override void OnTimer(ElapsedEventArgs e, ref bool StopService)
{
try
{
if (!ServiceState.Instance.RequestLock())
{
WriteLogEntry("Skipping MobileEx.Push.Service[" + Lib.AppPath + "]. In use", LogBase.EEventType.Warning);
return;
}
int LoopCount = 0;
while (LoopCount < Panztel.Shared.General.Settings.AppSettings.GetSettingValue("ProcessLimit", "100"))
{
LoopCount += 1;
if (StopRequested)
break;
using (var MyScope = new TransactionScope())
{
var MyContext = DataContextHelper.NewContext;
var MyId = Guid.NewGuid();
Mobile.API.BusinessLogic.Data.Push MyItem = null;
try
{
MyItem = PushLogic.GrabItemToProcess(MyId, ref MyContext);
}
catch (Exception ex)
{
WriteLogEntry("Unable to get push item to process. " + ex.Message, LogBase.EEventType.Error);
}
if (MyItem == null)
break; // Drop out as nothing to process.
MyItem.ProcessId = MyId;
var MyApplications = PushLogic.GetPushApplicationListByPushId(MyItem.PushId, MyItem.CompanyLinkId, ref MyContext);
foreach (var MyPushApp in MyApplications)
{
var MyPhoneApp = PhoneLogic.GetPhoneApplicationItem(MyPushApp.PhoneId, MyPushApp.ApplicationId);
if (MyPhoneApp == null || string.IsNullOrEmpty(MyPhoneApp.PushChannelUri))
{
// Mark as failed and continue
MyPushApp.ProcessState = 15;
continue;
}
var MyQueue = GetPushBroker(MyItem.Phone.OsType, MyPhoneApp);
if (MyQueue == null)
{
MyPushApp.ProcessState = 16;
continue;
}
switch (MyItem.Phone.OsType)
{
case 1: // Android
var MyMsgHelper = new PushMessageHelper();
if (!string.IsNullOrEmpty(MyItem.Message))
MyMsgHelper.AddItem("alert", MyItem.Message);
MyMsgHelper.AddItem("badge", "1");
MyMsgHelper.AddItem("pushtypeid", MyItem.PushTypeId.ToString());
MyMsgHelper.AddItem("notify", MyItem.IsNotificationRequired ? "1" : "0");
if (MyItem.LastrvNo.HasValue)
MyMsgHelper.AddItem("lastrvno", MyItem.LastrvNo.Value.ToString());
var MessageInJson = MyMsgHelper.GetJsonMessage();
var MyNotification = new GcmNotification()
.ForDeviceRegistrationId(MyPhoneApp.PushChannelUri)
.WithCollapseKey("key_" + MyItem.PushId)
.WithJson(MessageInJson)
.WithTag(MyId.ToString());
MyQueue.QueueNotification(MyNotification);
break;
case 2: // Windows
//****************** RAW *********************************//
var ThisMsgHelper = new PushMessageHelper();
if (!string.IsNullOrEmpty(MyItem.Message))
{
ThisMsgHelper.AddItem("alert", MyItem.Message);
}
ThisMsgHelper.AddItem("badge", "1");
ThisMsgHelper.AddItem("pushtypeid", MyItem.PushTypeId.ToString());
ThisMsgHelper.AddItem("notify", MyItem.IsNotificationRequired ? "1" : "0");
if (MyItem.LastrvNo.HasValue)
ThisMsgHelper.AddItem("lastrvno", MyItem.LastrvNo.Value.ToString());
var MessageInXml = ThisMsgHelper.GetWp8PushMessage();
var MyWindowsNotification = new WindowsPhoneRawNotification();
MyWindowsNotification.ForEndpointUri(new Uri(MyPhoneApp.PushChannelUri));
MyWindowsNotification.ForOSVersion(WindowsPhoneDeviceOSVersion.Eight);
MyWindowsNotification.WithBatchingInterval(BatchingInterval.Immediate);
MyWindowsNotification.WithRaw(MessageInXml);
MyWindowsNotification.Tag = MyId.ToString();
MyQueue.QueueNotification(MyWindowsNotification);
break;
case 3: // iPhone
var MyAppleNotification = new AppleNotification()
.ForDeviceToken(MyPhoneApp.PushChannelUri)
.WithTag(MyId.ToString())
.WithCustomItem("pushtypeid", MyItem.PushTypeId.ToString(CultureInfo.InvariantCulture));
var MyMsg = MyItem.Message;
if (string.IsNullOrEmpty(MyMsg))
{
if (MyItem.IsNotificationRequired)
{
switch (MyItem.PushTypeId)
{
case 3:
MyMsg = "New schedule(s) received";
break;
case 4:
MyMsg = "New message(s) received";
break;
}
}
}
// if request location, add in the bit to do a background notification
// http://docs.xamarin.com/guides/cross-platform/application_fundamentals/backgrounding/part_3_ios_backgrounding_techniques/updating_an_application_in_the_background/
if (MyItem.PushTypeId == 5)
MyAppleNotification = MyAppleNotification.WithContentAvailable(1);
if (!string.IsNullOrEmpty(MyMsg))
MyAppleNotification = MyAppleNotification.WithAlert(MyMsg).WithBadge(1);
if (MyItem.IsNotificationRequired)
MyAppleNotification = MyAppleNotification.WithSound("beep.aiff").WithBadge(1);
if (MyItem.LastrvNo.HasValue)
MyAppleNotification = MyAppleNotification.WithCustomItem("lastrvno", MyItem.LastrvNo.Value.ToString());
MyQueue.QueueNotification(MyAppleNotification);
break;
}
MyPushApp.ProcessState = 5;
}
MyItem.ProcessState = 5;
PushLogic.UpdateItem(ref MyContext, MyItem);
MyScope.Complete();
}
}
}
catch (Exception ex)
{
WriteLogEntry("Error in MobileEx.Push.Service.PushWorker.OnTimer - " + ex.Message, LogBase.EEventType.Error);
}
finally
{
try
{
StopAllBrokers();
}
catch (Exception Ex)
{
WriteLogEntry("Error in MobileEx.Push.Service.PushWorker.OnTimer.StopAllBrokers - " + Ex.Message, LogBase.EEventType.Error);
}
}
ServiceState.Instance.ReleaseLock();
}
private PushBroker GetPushBroker(short OsType, PhoneApplication MyPhoneApp)
{
PushBroker MyBroker;
string Key = OsType + "." + MyPhoneApp.Application.PackageName.ToLower();
if (_PushList == null)
_PushList = new Dictionary<string, PushBroker>();
if (_PushList.ContainsKey(Key))
{
MyBroker = _PushList[Key];
}
else
{
MyBroker = new PushBroker();
MyBroker.OnNotificationFailed += Push_OnNotificationFailed;
MyBroker.OnDeviceSubscriptionExpired += Push_OnDeviceSubscriptionExpired;
MyBroker.OnNotificationSent += Push_OnNotificationSent;
MyBroker.OnChannelException += MyBroker_OnChannelException;
MyBroker.OnServiceException += MyBroker_OnServiceException;
switch (OsType)
{
case 1: // Android
var SenderId = MyPhoneApp.Application.ProductGroup.SenderId;
var SenderAuth = MyPhoneApp.Application.ProductGroup.SenderAuth;
var PackageName = MyPhoneApp.Application.PackageName;
var MyGoogleChannelSettings = new GcmPushChannelSettings(SenderId, SenderAuth, PackageName);
MyBroker.RegisterGcmService(MyGoogleChannelSettings);
break;
case 2: // Windows
MyBroker.RegisterWindowsPhoneService();
break;
case 3: // iPhone
var CertificateFile = Panztel.Shared.General.Settings.AppSettings.GetSetting("ApplePushCertificate", "");
var CertificatePassword = Panztel.Shared.General.Settings.AppSettings.GetSetting("ApplePushCertificatePassword", "");
var IsProduction = Panztel.Shared.General.Settings.AppSettings.GetSettingValue("ApplePushProduction", "0") == 1;
if (string.IsNullOrEmpty(CertificateFile) || string.IsNullOrEmpty(CertificatePassword))
throw new Exception("Apple Push Certificate settings not configured");
if (!File.Exists(CertificateFile))
throw new Exception("Apple Push Certificate [" + CertificateFile + "] not found");
var CertificateData = File.ReadAllBytes(CertificateFile);
var MyAppleChannelSettings = new ApplePushChannelSettings(IsProduction, CertificateData, CertificatePassword);
// need to limit the number of channels we have for Apple otherwise they can return
// "The maximum number of Send attempts to send the notification was reached!"
var MyServiceSettings = new PushServiceSettings();
MyServiceSettings.MaxAutoScaleChannels = 5;
MyServiceSettings.AutoScaleChannels = true;
MyBroker.RegisterAppleService(MyAppleChannelSettings, MyServiceSettings);
break;
}
_PushList.Add(Key, MyBroker);
}
return MyBroker;
}
private void StopAllBrokers()
{
if (_PushList == null)
return;
foreach (var MyItem in _PushList)
{
try
{
MyItem.Value.StopAllServices();
}
catch (Exception Ex)
{
WriteLogEntry("Error in MobileEx.Push.Service.PushWorker.OnTimer.StopAllBrokers.StopAllServices - " + Ex.Message, LogBase.EEventType.Error);
}
}
_PushList = null;
}
`

AjaxControlToolkit is undefined - Error when bringing an extender up to date

I am looking for some way to warn the user if a form is 'dirty' and they try and navigate away from it.
This project seemed to do exactly what I needed.
However, it was written back in 2007, and when I tried to use it "as-is" in my .NET 4.0 app with the latest version of the Ajax Control Toolkit it didn't work.
So, I downloaded the source (available from the CodeProject article) and tried to bring it up-to-date. But this is the first time I've attempted such a task and I'm a bit lost.
The error I'm now getting is as follows:
Microsoft JScript runtime error: 'AjaxControlToolkit' is undefined
The line in the DirtyPanelExtenderBehaviour.js which gives the error is:
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', AjaxControlToolkit.BehaviorBase);
Here's what I've done so far:
1. Downloaded the source from the Codeproject article
2. Opened in Visual Studio 2010 and completed the upgrade wizard
3. Deleted references to AjaxControlToolkit.dll and replaced with a new reference to the latest version of the toolkit
4. Amended references to ScriptManager with ToolkitScriptManager (Not sure if this was needed)
5. Amended the sample website to use a ToolkitScriptManager on the page in place of a ScriptManager
Sooo, any ideas what I've done wrong? Or what I'm missing? So that I can recompile the DirtyPanelExtender.dll and use it in my .NET 4.0 project?
The full code is below that I am using. The original author wrote this with exception of my amendments as detailed above - I'm not taking credit!
DirtyPanelExtender.cs:
using System;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Text;
using AjaxControlToolkit;
[assembly: System.Web.UI.WebResource("DirtyPanelExtender.DirtyPanelExtenderBehavior.js", "text/javascript")]
namespace DirtyPanelExtender
{
[Designer(typeof(DirtyPanelExtenderDesigner))]
[ClientScriptResource("DirtyPanelExtender.DirtyPanelExtenderBehavior", "DirtyPanelExtender.DirtyPanelExtenderBehavior.js")]
[TargetControlType(typeof(Panel))]
[TargetControlType(typeof(UpdatePanel))]
public class DirtyPanelExtender : ExtenderControlBase
{
[ExtenderControlProperty]
[DefaultValue("Data has not been saved.")]
public string OnLeaveMessage
{
get
{
return GetPropertyValue("OnLeaveMessage", "");
}
set
{
SetPropertyValue("OnLeaveMessage", value);
}
}
protected override void OnPreRender(EventArgs e)
{
string values_id = string.Format("{0}_Values", TargetControl.ClientID);
string values = (Page.IsPostBack ? Page.Request.Form[values_id] : String.Join(",", GetValuesArray()));
ToolkitScriptManager.RegisterHiddenField(this, values_id, values);
base.OnPreRender(e);
}
private string[] GetValuesArray()
{
return GetValuesArray(TargetControl.Controls);
}
private string[] GetValuesArray(ControlCollection coll)
{
List<string> values = new List<string>();
foreach (Control control in coll)
{
if (control is RadioButtonList)
{
for (int i = 0; i < ((RadioButtonList)control).Items.Count; i++)
{
values.Add(string.Format("{0}_{1}:{2}", control.ClientID, i, ((RadioButtonList)control).Items[i].Selected.ToString().ToLower()));
}
}
else if (control is ListControl)
{
StringBuilder data = new StringBuilder();
StringBuilder selection = new StringBuilder();
foreach (ListItem item in ((ListControl) control).Items)
{
data.AppendLine(item.Text);
selection.AppendLine(item.Selected.ToString().ToLower());
}
values.Add(string.Format("{0}:data:{1}", control.ClientID, Uri.EscapeDataString(data.ToString())));
values.Add(string.Format("{0}:selection:{1}", control.ClientID, Uri.EscapeDataString(selection.ToString())));
}
else if (control is IEditableTextControl)
{
values.Add(string.Format("{0}:{1}", control.ClientID, Uri.EscapeDataString(((IEditableTextControl)control).Text)));
}
else if (control is ICheckBoxControl)
{
values.Add(string.Format("{0}:{1}", control.ClientID, ((ICheckBoxControl)control).Checked.ToString().ToLower()));
}
values.AddRange(GetValuesArray(control.Controls));
}
return values.ToArray();
}
public void ResetDirtyFlag()
{
ToolkitScriptManager.RegisterClientScriptBlock(TargetControl, TargetControl.GetType(),
string.Format("{0}_Values_Update", TargetControl.ClientID), string.Format("document.getElementById('{0}').value = '{1}';",
string.Format("{0}_Values", TargetControl.ClientID), String.Join(",", GetValuesArray())), true);
}
}
}
DirtyPanelExtenderBehaviour.js:
Type.registerNamespace('DirtyPanelExtender');
DirtyPanelExtender.DirtyPanelExtenderBehavior = function(element) {
DirtyPanelExtender.DirtyPanelExtenderBehavior.initializeBase(this, [element]);
this._OnLeaveMessageValue = null;
}
DirtyPanelExtender.DirtyPanelExtenderBehavior.prototype = {
isDirty : function() {
var values_control = document.getElementById(this.get_element().id + "_Values");
var values = values_control["value"].split(",");
for (i in values) {
var namevalue = values[i];
var namevaluepair = namevalue.split(":");
var name = namevaluepair[0];
var value = (namevaluepair.length > 1 ? namevaluepair[1] : "");
var control = document.getElementById(name);
if (control == null) continue;
// alert(control.id + " -> " + control.type);
if (control.type == 'checkbox' || control.type == 'radio') {
var boolvalue = (value == "true" ? true : false);
if(control.checked != boolvalue) {
// alert("checkbox changed: " + control.checked + " vs. " + boolvalue);
return true;
}
} else if (control.type == 'select-one' || control.type == 'select-multiple') {
if (namevaluepair.length > 2) {
if ( control.options.length > 0) {
// control is listbox
// there's data:value and selection:value
var code = value;
value = (namevaluepair.length > 2 ? namevaluepair[2] : "");
var optionValues = "";
// concat all listbox items
for( var cnt = 0; cnt < control.options.length; cnt++) {
if (code == 'data') {
optionValues += control.options[cnt].text;
} else if (code == 'selection') {
optionValues += control.options[cnt].selected;
}
optionValues += "\r\n";
}
if( encodeURIComponent(optionValues) != value ) {
// items in the listbox have changed
// alert("listbox " + code + " changed: " + encodeURIComponent(optionValues) + " vs. " + value);
return true;
}
}
} else if(control.selectedIndex != value) {
// alert("dropdown selection changed: " + control.selectedIndex + " vs. " + value);
return true;
}
} else {
if(encodeURIComponent(control.value) != value) {
// alert("control " + control.type + " changed: " + control.value + " vs. " + value);
return true;
}
}
}
return false;
},
initialize : function() {
DirtyPanelExtender.DirtyPanelExtenderBehavior.callBaseMethod(this, 'initialize');
DirtyPanelExtender_dirtypanels[DirtyPanelExtender_dirtypanels.length] = this;
},
dispose : function() {
DirtyPanelExtender.DirtyPanelExtenderBehavior.callBaseMethod(this, 'dispose');
},
get_OnLeaveMessage : function() {
return this._OnLeaveMessageValue;
},
set_OnLeaveMessage : function(value) {
this._OnLeaveMessageValue = value;
}
}
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', AjaxControlToolkit.BehaviorBase);
var DirtyPanelExtender_dirtypanels = new Array()
function DirtyPanelExtender_SuppressDirtyCheck()
{
window.onbeforeunload = null;
}
function __newDoPostBack(eventTarget, eventArgument)
{
// supress prompting on postback
DirtyPanelExtender_SuppressDirtyCheck();
return __savedDoPostBack (eventTarget, eventArgument);
}
var __savedDoPostBack = __doPostBack;
__doPostBack = __newDoPostBack;
window.onbeforeunload = function (eventargs)
{
for (i in DirtyPanelExtender_dirtypanels)
{
var panel = DirtyPanelExtender_dirtypanels[i];
if (panel.isDirty())
{
if(! eventargs) eventargs = window.event;
eventargs.returnValue = panel.get_OnLeaveMessage();
break;
}
}
}
The BehaviorBase class now resides in a different namespace. You need to replace the line...
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', AjaxControlToolkit.BehaviorBase);
with...
DirtyPanelExtender.DirtyPanelExtenderBehavior.registerClass('DirtyPanelExtender.DirtyPanelExtenderBehavior', Sys.Extended.UI.BehaviorBase);

Resources