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

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

Related

Xamarin.Azure.Notification.Hub (3.1.1) crashing in iOS 16.1

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
try
{
string ConnectionString = AppConfiguration.NotificationHubConnectionString;
string hubPath = AppConfiguration.NotificationHubPath;
if (!string.IsNullOrEmpty(ApplicationContext.Instance.APIVersion))
{
ConnectionString = AppConfiguration.NotificationHubConnectionStringv2;
hubPath = AppConfiguration.NotificationHubPath2;
}
NSSet tags = null;
SBNotificationHub hub;
byte[] bytes = deviceToken.ToArray();
string[] hexArray = bytes.Select(b => b.ToString("x2")).ToArray();
var tokenString = string.Join(string.Empty, hexArray);
hub = new SBNotificationHub(ConnectionString, hubPath);
tags = new NSSet(new string[] {
Mvx.IoCProvider.Resolve<IDeviceIdentifier>()?.GetRestaurantId()?.ToLower() });
hub.UnregisterAll(deviceToken, error =>
{
if (error != null)
{
LazyServiceFromIOC<IAnalytics>.Instance.RequestedService?.LogEvent(Enums.CustomEvents.Notifications.ToString(), error.Description);
return;
}
hub.RegisterNative(deviceToken, tags, errorCallback =>
{
if (errorCallback != null)
{
LazyServiceFromIOC<IAnalytics>.Instance.RequestedService?.LogEvent(Enums.CustomEvents.Notifications.ToString(), errorCallback.Description);
}
});
});
Preferences.Set("DeviceTokens", tokenString);
PushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
}
catch (Exception ex)
{
LazyServiceFromIOC<IAnalytics>.Instance.RequestedService?.LogException(nameof(RegisteredForRemoteNotifications), ex);
}
}
Xamarin.Azure.Notification.Hub (3.1.1) - iOS 16.1
App is crashing at RegisterNative method... This logic was working all this while..till ios was upgraded to 16 on ipad
What changed in iOS 16

Unity - The name 'auth' does not exist in the current context

I am currently trying to create user authentication in unity and I am having some issues.
The code below is what I have at the moment and I keep receiving the error saying Auth does not exist in the current context.
Does anyone have any idea why this is? Probably a simple fix that I am just overlooking.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Text.RegularExpressions;
using Firebase;
using Firebase.Auth;
public class Register : MonoBehaviour {
public GameObject email;
public GameObject password;
public GameObject confPassword;
private string Email;
private string Password;
private string ConfPassword;
private string form;
private bool EmailValid = false;
private string[] Characters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","_","-"};
public void RegisterButton(){
bool EM = false;
bool PW = false;
bool CPW = false;
if (Email != ""){
EmailValidation();
if (EmailValid){
if(Email.Contains("#")){
if(Email.Contains(".")){
EM = true;
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email is Incorrect");
}
} else {
Debug.LogWarning("Email Field Empty");
}
if (Password != ""){
if(Password.Length > 5){
PW = true;
} else {
Debug.LogWarning("Password Must Be atleast 6 Characters long");
}
} else {
Debug.LogWarning("Password Field Empty");
}
if (ConfPassword != ""){
if (ConfPassword == Password){
CPW = true;
} else {
Debug.LogWarning("Passwords Don't Match");
}
} else {
Debug.LogWarning("Confirm Password Field Empty");
}
if (EM == true&&PW == true&&CPW == true)
{
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.FirebaseUser newUser = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
}
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Tab)){
if (email.GetComponent<InputField>().isFocused){
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused){
confPassword.GetComponent<InputField>().Select();
}
}
if (Input.GetKeyDown(KeyCode.Return)){
if (Password != ""&&Email != ""&&Password != ""&&ConfPassword != ""){
RegisterButton();
}
}
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confPassword.GetComponent<InputField>().text;
}
void EmailValidation(){
bool SW = false;
bool EW = false;
for(int i = 0;i<Characters.Length;i++){
if (Email.StartsWith(Characters[i])){
SW = true;
}
}
for(int i = 0;i<Characters.Length;i++){
if (Email.EndsWith(Characters[i])){
EW = true;
}
}
if(SW == true&&EW == true){
EmailValid = true;
} else {
EmailValid = false;
}
}
}
I do not see you ever creating the variable auth?
While you refer to it here:
auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
So I assume you will have to create a variable auth and instantiate it with something related to FireBase.Auth (unless I am overlooking something).

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.

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.

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

Resources