Error at pushbroker.StopAllServices (PushSharp) - push-notification

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

Related

Your app(s) are using a WebView that is vulnerable to cross-app scripting

My android app keeps getting rejected because of this reason:
Your app(s) are using a WebView that is vulnerable to cross-app scripting.
I already did an extensive search and found some thing I could do:
Follow the steps on https://support.google.com/faqs/answer/9084685. Since I'm using a launcher, I have to follow option 2.
I added this code in my manifest.xml: android.webkit.WebView.EnableSafeBrowsing
I'm sure the problem lies in the code posted below, where I don't use a fixed url for my loadURL, but I let it change via intent, being a notificiation url or a mail link. I'm aware this gives serious security issues, but I don't know how to fix it. In the link I provided above I want to follow option 2 but:
I can't disable javascript (my webpage won't load without it)
I don't know how to validate/secure the url in loadURL in such a way that Google allows me to upload my app to the Play Store.
Can someone please help me?
#Override
protected void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("send-url"));
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
String default_url = "https://www.playday.be/app/";
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(task -> {
if (task.isSuccessful() && task.getResult() != null) {
String refreshedToken = task.getResult();
Log.v("newToken",refreshedToken);
sendRegistrationToServer(refreshedToken);
}
});
if(getIntent().getExtras() != null){
if (getIntent().getExtras().getString("pushUrl") != null) {
String url_from_notif = getIntent().getExtras().getString("pushUrl");
if(Patterns.WEB_URL.matcher(url_from_notif).matches()) {
default_url = url_from_notif;
Log.v("url_from_notif = ", default_url);
}
}
if (getIntent().getData() != null) {
String url_from_mail = getIntent().getData().toString();
url_from_mail = url_from_mail.replace("playday://", "");
if(Patterns.WEB_URL.matcher(url_from_mail).matches()) {
default_url = url_from_mail;
Log.v("url_from_mail = ", default_url);
}
}
}
Log.v("default_url_new = ", "" +default_url);
webView = findViewById(R.id.ifView);
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setGeolocationEnabled(false);
webView.setWebViewClient(new Callback());
webView.setWebViewClient(new MyAppWebViewClient(){
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
Log.v("method:", "onReceivedError");
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Je bent niet online...");
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage("Gelieve je internetconnectie te herstellen en probeer dan opnieuw.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Probeer opnieuw", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
try {
alertDialog.show();
} catch(Exception e){
Log.e(TAG,"show dialog error no internet connection");
}
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
webView.loadUrl(default_url);
webView.setWebChromeClient(new WebChromeClient() {
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
Log.d(TAG,"111 ShowFileChooser For Android 5.0 ");
if (Build.VERSION.SDK_INT >= 23) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePath;
Log.d(TAG,"ShowFileChooser For Android 5.0 SDK_INT>=23 chk permission");
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_CAMERA);
} else {
Log.d(TAG,"112 ShowFileChooser For Android 5.0 in IF SDK_INT>=23 permission grant");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (Exception ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File 1", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
}
} else {
Log.d(TAG,"113 ShowFileChooser For Android 5.0 in else SDK_INT>=23");
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (Exception ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File 2", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
}
// Double check that we don't have any existing callbacks
return true;
}
});
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "1";
String channel2 = "2";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
assert notificationManager != null; //edit 1402
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2", NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
}
I finally figured it out myself and got my app approved in the app store.
I just needed to validate/sanitize the url that was loaded in the webview.
I changed the code:
if(getIntent().getExtras() != null){
if (getIntent().getExtras().getString("pushUrl") != null) {
String url_from_notif = getIntent().getExtras().getString("pushUrl");
if(Patterns.WEB_URL.matcher(url_from_notif).matches()) {
default_url = url_from_notif;
Log.v("url_from_notif = ", default_url);
}
}
if (getIntent().getData() != null) {
String url_from_mail = getIntent().getData().toString();
url_from_mail = url_from_mail.replace("playday://", "");
if(Patterns.WEB_URL.matcher(url_from_mail).matches()) {
default_url = url_from_mail;
Log.v("url_from_mail = ", default_url);
}
}
}
To:
if(getIntent().getExtras() != null){
String url_from_notif = getIntent().getExtras().getString("pushUrl");
if (url_from_notif != null) {
if(URLUtil.isValidUrl(url_from_notif) && Patterns.WEB_URL.matcher(url_from_notif).matches()) {
default_url = url_from_notif;
Log.v("url_from_notif = ", default_url);
}
}
if (getIntent().getData() != null) {
String url_from_mail = getIntent().getData().toString();
url_from_mail = url_from_mail.replace("playday://", "");
if(URLUtil.isValidUrl(url_from_mail) && Patterns.WEB_URL.matcher(url_from_mail).matches()) {
default_url = url_from_mail;
Log.v("url_from_mail = ", default_url);
}
}
}
And:
webView.loadUrl(default_url);
To:
URI uri;
try {
uri = new URI(default_url);
String domain = uri.getHost();
if (!default_url.startsWith("https://www.playday.be") || !domain.equals("www.playday.be") || !URLUtil.isValidUrl(default_url) || !Patterns.WEB_URL.matcher(default_url).matches()) {
webView.loadUrl("about:blank");
} else {
webView.loadUrl(default_url);
}
} catch (URISyntaxException e) {
e.printStackTrace();
}

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.

How display a json error message?

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 {
......
......
}

Push notification not received, windows universal 8.1

HI i have implemented push notification in my application, serer is sending notification but not receiving at my end.
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string typeString = String.Empty;
string notificationContent = String.Empty;
switch (e.NotificationType)
{
case PushNotificationType.Badge:
typeString = "Badge";
notificationContent = e.BadgeNotification.Content.GetXml();
break;
case PushNotificationType.Tile:
notificationContent = e.TileNotification.Content.GetXml();
typeString = "Tile";
break;
case PushNotificationType.Toast:
notificationContent = e.ToastNotification.Content.GetXml();
typeString = "Toast";
// Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts:
// if your application is already on the screen, there's no need to display a toast from push notifications.
e.Cancel = true;
break;
case PushNotificationType.Raw:
notificationContent = e.RawNotification.Content;
typeString = "Raw";
break;
}
// string text = "Received a " + typeString + " notification, containing: " + notificationContent;
var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// rootPage.NotifyUser(text, NotifyType.StatusMessage);
if (typeString == "Toast")
{
PushNotificationHelper.AddTostNotification(0, notificationContent);
}
else if (typeString == "Badge")
{
PushNotificationHelper.AddBadgeNotification(0, notificationContent);
}
});
}
public async void InitChannel()
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
try
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (channel != null)
{
//String existingChannel = (String)roamingSettings.Values["ExistingPushChannel"];
roamingSettings.Values["ExistingPushChannel"] = channel.Uri;
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
channel.PushNotificationReceived += OnPushNotificationReceived;
}
else
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
catch
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
public async void InitNotificationsAsync()
{
try
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
String existingChannel = (String)roamingSettings.Values["ExistingPushChannel"];
string tempDevelopmentKey = "";
string Platform = "";
List<string> arrayTags = new List<string>();
#if WINDOWS_APP
Platform = "windows-tablet";
tempDevelopmentKey = "dev_WindowsTabletNotification";
#endif
#if WINDOWS_PHONE_APP
Platform = "windows-phone";
tempDevelopmentKey ="dev_WindowsPhoneNotification";
#endif
arrayTags.Add(Platform) ;
arrayTags.Add(tempDevelopmentKey) ;
string TMBNotification = (string)roamingSettings.Values["TMBNotification"];
if(TMBNotification != null)
{
if(TMBNotification == "on")
{
arrayTags.Add("TMB");
}
}
string TRSNotification = (string)roamingSettings.Values["TRSNotification"];
if (TRSNotification != null)
{
if (TRSNotification == "on")
{
arrayTags.Add("TRS");
}
}
string IMNotification = (string)roamingSettings.Values["IMNotification"];
if (IMNotification != null)
{
if (IMNotification == "on")
{
arrayTags.Add("IM");
}
}
string SWSNotification = (string)roamingSettings.Values["SWSNotification"];
if (SWSNotification != null)
{
if (SWSNotification == "on")
{
arrayTags.Add("ANC");
}
}
string VIDNotification = (string)roamingSettings.Values["VIDNotification"];
if (VIDNotification != null)
{
if (VIDNotification == "on")
{
arrayTags.Add("videos");
}
}
var hub = new NotificationHub("hubname", "endpoint");
var result = await hub.RegisterNativeAsync(existingChannel, arrayTags);
// Displays the registration ID so you know it was successful
if (result.RegistrationId != null)
{
}
}catch
{
}
}
So how can i confirm that there is no issue in my implementation or there is issue from server end.
There are couple of steps you can take to debug this problem:-
There is broadcast and sending notification, using notification hub, option available on azure portal(you can do from VS also from left side server explorer). When you did this there is a log that will show you whether a notifications sent successfully or not.
First just delete all your registrations with notification hub and for very new registration check is your device getting registered with correct tags/channel uri or not(this you cad do from server explorer too)
Make sure you are sending/registering the correct templates that are corresponding to WNS service.
make sure you are using WNS service this different from what is for
WP8 silverlight one.
You can see the errors just at the bottom of this page if any.
There is option for device registrations from where you can alter the registrations.

Resources