CRM Dynamics Plugin Error - Given Key not found in Dictionary - 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.

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

Insert data in Value Object Table

Inserting Data By POSTMAN, but some error occurred.
My Code is given below:
public async Task<BusinessProfile> Save(string ID,bool Status,string Logo,string TaxNumber,string StateRegisterNumber,string StreetName,string Number
,string Complement,string PostalCode,string Neighborhood,string City,string State,string AreaCode,string Department
,string PhoneNo,string Type,string Website,string EDepartment,string EmailAddress)
{
try
{
int EnumPhoneNumber = 0;
string[] values = Enum.GetNames(typeof(PhoneNumberEnum.PhoneNumber));
if (values[0] == Type)
{
EnumPhoneNumber = (int)PhoneNumber.FixedPhone;
}
else if (values[1] == Type)
{
EnumPhoneNumber = (int)PhoneNumber.MobilePhone;
}
var businessProfile = new BusinessProfile() { ID = ID, Status = Status, Logo = Logo, TaxNumber = TaxNumber, StateRegisterNumber = StateRegisterNumber, Website = Website };
businessProfile.AssignAddress(new Address(StreetName, Number, Complement, PostalCode, Neighborhood, City, State));
businessProfile.AssignPhones(new Phones(Convert.ToString(EnumPhoneNumber), AreaCode, PhoneNo, Department));
businessProfile.AssignEmail(new Emails(EmailAddress, EDepartment));
//_db.Add(businessProfile);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BusinessProfile> x = await _db.AddAsync(businessProfile);
// _db.SaveChanges();
//await _db.BusinessProfiles.AddAsync(businessProfile);
await _db.SaveChangesAsync();
return businessProfile;
}
catch(Exception ex)
{
throw ex;
}
}
Output (Error:):
An unhandled exception occurred while processing the request.
InvalidOperationException: The entity of type BusinessProfile is sharing the table BusinessProfiles with entities of type Address, but there is no entity of this type with the same key value that has been marked as Added. Consider using DbContextOptionsBuilder.EnableSensitiveDataLogging to see the key values.
public async Task Save(BusinessProfile bp)
{
try
{
int EnumPhoneNumber = 0;
string[] values = Enum.GetNames(typeof(PhoneNumberEnum.PhoneNumber));
if (values[0] == bp.Phones.Type)
{
EnumPhoneNumber = (int)PhoneNumber.FixedPhone;
}
else if (values[1] == bp.Phones.Type)
{
EnumPhoneNumber = (int)PhoneNumber.MobilePhone;
}
var businessProfile = new BusinessProfile() { ID = bp.ID, IsActive = bp.IsActive, Logo = bp.Logo, TaxNumber = bp.TaxNumber, StateRegisterNumber = bp.StateRegisterNumber, Website = bp.Website };
businessProfile.Address = new Address(bp.Address.StreetName, bp.Address.Number, bp.Address.Complement, bp.Address.PostalCode, bp.Address.Neighborhood, bp.Address.City, bp.Address.State);
businessProfile.Phones = new Phones(Convert.ToString(EnumPhoneNumber), bp.Phones.AreaCode, bp.Phones.PhoneNumber, bp.Phones.Department);
businessProfile.Emails = new Emails(bp.Emails.EmailAddress, bp.Emails.Department);
Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<BusinessProfile> x = await _db.AddAsync(businessProfile);
await _db.SaveChangesAsync();
return businessProfile;
}
catch (Exception ex)
{
throw ex;
}
}

Retrieve an Entity value to add to return parameter

I have this method:
private List < ReportParameter > ParametrosReporte() {
List < ReportParameter > Parametros = new List < ReportParameter > ();
try {
int ? int_Ejercicio = this.radcmbEjercicio.SelectedItem == null ? 0 : this.radcmbEjercicio.SelectedValue.ToInt();
int ? int_Periodo = this.radcmbPeriodo.SelectedItem == null ? 0 : this.radcmbPeriodo.SelectedValue.ToInt();
int ? int_BSC = this.radcmbBSC.SelectedItem == null ? 0 : this.radcmbBSC.SelectedValue.ToInt();
Parametros.Add(Reportes.ParametrosReporte("pe_Ejercicio", int_Ejercicio.ToString()));
Parametros.Add(Reportes.ParametrosReporte("pe_Mes", int_Periodo.ToString()));
Parametros.Add(Reportes.ParametrosReporte("pe_BSC", int_BSC.ToString()));
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = ((Usuario) Session["User"]).UsuarioID,
}
};
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", UsuarioID ));
return Parametros;
} catch (Exception ex) {
throw new System.ArgumentException("Error en ParametrosReporte", ex);
}
}
As you can see I have logic to retrieve user who is logged in as:
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = ((Usuario) Session["User"]).UsuarioID,
}
};
but before retrieve it, I want to call it into Parametros.Add like:
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", UsuarioID ));
But I canĀ“t because UsuarioID is out of scope and it throws me
UsuarioID does not exist in the current context
How can I call it and attach to my Parametros.Add?
You can just create a local variable above your creation of catBSC and then use that in both locations:
var usuarioID = ((Usuario) Session["User"]).UsuarioID
catBSC _catBSC = new catBSC() {
mdUsuarioCaptura = new Entidades.Usuario() {
UsuarioID = usuarioID
}
};
Parametros.Add(Reportes.ParametrosReporte("pe_Usuario", usuarioID));
You can replace var with the actual type, but I didn't want to make an assumption about what this was in your scenario.

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

Create Multimedia component with Metadata fields.using core service

I am creating Multimedia components using core service and everything is working fine. But when Metadata schema fields are defined on the Multimedia schema using which I am creating my Multimedia components then I am getting following error:-
Unable to find http://www.tridion.com/ContentManager/5.0/DefaultMultimediaSchema:Metadata.
This message is displayed when I have given Default Multimedia schema's TCM ID for Multimedia component. As metadata fields are saved in Tridion Database so I first have to retrieve these fields from broker or what is the best solution for this, please suggest. Below is the sample code. Please modify it if someone have any idea for providing default value for metadatafields and how to retrieve them (with/without querying broker DB):-
public static string UploadMultiMediaComponent(string folderUri, string title, string schemaID)
{
core_service.ServiceReference1.SessionAwareCoreService2010Client client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword"; client.Open();
ComponentData multimediaComponent = (ComponentData)client.GetDefaultData(
ItemType.Component, folderUri);
multimediaComponent.Title = title;
multimediaComponent.ComponentType = ComponentType.Multimedia;
multimediaComponent.Schema.IdRef =schemaID;
//multimediaComponent.Metadata = "";
StreamUpload2010Client streamClient = new StreamUpload2010Client();
FileStream objfilestream = new FileStream(#"\My Documents\images.jpg",
FileMode.Open, FileAccess.Read);
string tempLocation = streamClient.UploadBinaryContent("images.jpg",
objfilestream);
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = tempLocation;
binaryContent.Filename = "images.jpg";
binaryContent.MultimediaType = new LinkToMultimediaTypeData()
{
// for jpg file
IdRef = "tcm:0-2-65544"
};
multimediaComponent.BinaryContent = binaryContent;
IdentifiableObjectData savedComponent = client.Save(multimediaComponent,
new ReadOptions());
client.CheckIn(savedComponent.Id, null);
streamClient.Close();
client.Close();
Console.WriteLine(savedComponent.Id);
//}
}
I don't know why your code not working but following code is working for me
public static ComponentData GenerateMultiMediaComponent(TridionGeneration tridionGeneration, XmlData newsArticle, string componentName)
{
try
{
Dictionary<string, object> dicTridion = Common.GetTridionObject(tridionGeneration.client, ItemType.Component, tridionGeneration.Settings.ComponentFolderUri, componentName);
int objectCount = (int)dicTridion["count"];
SchemaFieldsData schemaFields = tridionGeneration.client.ReadSchemaFields(tridionGeneration.Settings.SchemaUri, true, new ReadOptions());
ComponentData componentData = (ComponentData)tridionGeneration.client.GetDefaultData(ItemType.Component, tridionGeneration.Settings.ComponentFolderUri);
if (schemaFields.Fields != null)
{
var fields = Fields.ForContentOf(schemaFields);
Helper.FillSchemaFields(tridionGeneration, fields);
componentData.Content = fields.ToString();
}
if (schemaFields.MetadataFields != null)
{
var metafields = Fields.ForMetadataOf(schemaFields, componentData);
Helper.FillSchemaFields(tridionGeneration, metafields);
componentData.Metadata = metafields.ToString();
}
componentData.Title = (objectCount == 0) ? componentName : componentName + " " + (objectCount + 1).ToString();
componentData.ComponentType = ComponentType.Multimedia;
StreamUpload2010Client streamClient = new StreamUpload2010Client();
FileStream objfilestream = new FileStream(#"[IMAGE_PATH]", FileMode.Open, FileAccess.Read);
string tempLocation = streamClient.UploadBinaryContent("images.jpg", objfilestream);
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = tempLocation;
binaryContent.Filename = "[IMAGE_NAME]";
componentData.BinaryContent = binaryContent;
binaryContent.MultimediaType = new LinkToMultimediaTypeData()
{
IdRef = "tcm:0-2-65544"
};
componentData = (ComponentData)tridionGeneration.client.Create(componentData, new ReadOptions());
return componentData;
}
catch (Exception ex)
{
return null;
}
}
Here is the Helper class:
public static class Helper
{
public static void FillSchemaFields(TridionGeneration tridionGeneration, Fields fields)
{
List<XmlData> data = XmlHelper.xmlData;
var ofield = fields.GetEnumerator();
while (ofield.MoveNext())
{
Field f = ofield.Current;
FillFieldValue(tridionGeneration, fields, f, data[0]);
}
}
private static void FillFieldValue(TridionGeneration tridionGeneration, Fields fields, Field f, XmlData data)
{
if (f.Type == typeof(MultimediaLinkFieldDefinitionData))
{
fields[f.Name].Value = tridionGeneration.Settings.DefaultImageUri;
}
else if (f.Type != typeof(EmbeddedSchemaFieldDefinitionData))
{
foreach (XmlData fieldvalue in data.Attributes)
{
if (f.Type == typeof(DateFieldDefinitionData))
{
if (fieldvalue.text.ToLower() == f.Name.ToLower())
{
fields[f.Name].Value = Convert.ToDateTime(fieldvalue.value).ToString("yyyy-MM-ddTHH:mm:ss");
}
else
{
string val = FindSchemaValue(tridionGeneration, fieldvalue.Attributes, f.Name);
if (!string.IsNullOrEmpty(val))
{
fields[f.Name].Value = Convert.ToDateTime(val).ToString("yyyy-MM-ddTHH:mm:ss");
}
}
}
else
{
if (fieldvalue.text.ToLower() == f.Name.ToLower())
{
fields[f.Name].Value = System.Net.WebUtility.HtmlEncode(fieldvalue.value);
}
else
{
string val = FindSchemaValue(tridionGeneration, fieldvalue.Attributes, f.Name);
if (!string.IsNullOrEmpty(val))
{
fields[f.Name].Value = System.Net.WebUtility.HtmlEncode(val);
}
}
}
}
}
else
{
Fields fs = f.GetSubFields();
var ofield = fs.GetEnumerator();
while (ofield.MoveNext())
{
Field ff = ofield.Current;
FillFieldValue(tridionGeneration, fs, ff, data);
}
}
}
private static string FindSchemaValue(TridionGeneration tridionGeneration, List<XmlData> data, string fieldname)
{
foreach (XmlData fieldvalue in data)
{
if (fieldvalue.text.ToLower() == fieldname.ToLower())
{
return fieldvalue.value;
}
else
{
FindSchemaValue(tridionGeneration, fieldvalue.Attributes, fieldname);
}
}
return "";
}
}
and the Fields class:
public class Fields
{
private ItemFieldDefinitionData[] definitions;
private XmlNamespaceManager namespaceManager;
private XmlElement root; // the root element under which these fields live
// at any point EITHER data OR parent has a value
private SchemaFieldsData data; // the schema fields data as retrieved from the core service
private Fields parent; // the parent fields (so we're an embedded schema), where we can find the data
public Fields(SchemaFieldsData _data, ItemFieldDefinitionData[] _definitions, string _content = null, string _rootElementName = null)
{
data = _data;
definitions = _definitions;
var content = new XmlDocument();
if (!string.IsNullOrEmpty(_content))
{
content.LoadXml(_content);
}
else
{
content.AppendChild(content.CreateElement(string.IsNullOrEmpty(_rootElementName) ? _data.RootElementName : _rootElementName, _data.NamespaceUri));
}
root = content.DocumentElement;
namespaceManager = new XmlNamespaceManager(content.NameTable);
namespaceManager.AddNamespace("custom", _data.NamespaceUri);
}
public Fields(Fields _parent, ItemFieldDefinitionData[] _definitions, XmlElement _root)
{
definitions = _definitions;
parent = _parent;
root = _root;
}
public static Fields ForContentOf(SchemaFieldsData _data)
{
return new Fields(_data, _data.Fields);
}
public static Fields ForContentOf(SchemaFieldsData _data, ComponentData _component)
{
return new Fields(_data, _data.Fields, _component.Content);
}
public static Fields ForMetadataOf(SchemaFieldsData _data, RepositoryLocalObjectData _item)
{
return new Fields(_data, _data.MetadataFields, _item.Metadata, "Metadata");
}
public string NamespaceUri
{
get { return data != null ? data.NamespaceUri : parent.NamespaceUri; }
}
public XmlNamespaceManager NamespaceManager
{
get { return parent != null ? parent.namespaceManager : namespaceManager; }
}
internal IEnumerable<XmlElement> GetFieldElements(ItemFieldDefinitionData definition)
{
return root.SelectNodes("custom:" + definition.Name, NamespaceManager).OfType<XmlElement>();
}
internal XmlElement AddFieldElement(ItemFieldDefinitionData definition)
{
var newElement = root.OwnerDocument.CreateElement(definition.Name, NamespaceUri);
XmlNodeList nodes = root.SelectNodes("custom:" + definition.Name, NamespaceManager);
XmlElement referenceElement = null;
if (nodes.Count > 0)
{
referenceElement = (XmlElement)nodes[nodes.Count - 1];
}
else
{
// this is the first value for this field, find its position in the XML based on the field order in the schema
bool foundUs = false;
for (int i = definitions.Length - 1; i >= 0; i--)
{
if (!foundUs)
{
if (definitions[i].Name == definition.Name)
{
foundUs = true;
}
}
else
{
var values = GetFieldElements(definitions[i]);
if (values.Count() > 0)
{
referenceElement = values.Last();
break; // from for loop
}
}
} // for every definition in reverse order
} // no existing values found
root.InsertAfter(newElement, referenceElement); // if referenceElement is null, will insert as first child
return newElement;
}
public IEnumerator<Field> GetEnumerator()
{
return (IEnumerator<Field>)new FieldEnumerator(this, definitions);
}
public Field this[string _name]
{
get
{
var definition = definitions.First<ItemFieldDefinitionData>(ifdd => ifdd.Name == _name);
if (definition == null) throw new ArgumentOutOfRangeException("Unknown field '" + _name + "'");
return new Field(this, definition);
}
}
public override string ToString()
{
return root.OuterXml;
}
}
public class FieldEnumerator : IEnumerator<Field>
{
private Fields fields;
private ItemFieldDefinitionData[] definitions;
// Enumerators are positioned before the first element until the first MoveNext() call
int position = -1;
public FieldEnumerator(Fields _fields, ItemFieldDefinitionData[] _definitions)
{
fields = _fields;
definitions = _definitions;
}
public bool MoveNext()
{
position++;
return (position < definitions.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Field Current
{
get
{
try
{
return new Field(fields, definitions[position]);
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
public void Dispose()
{
}
}
public class Field
{
private Fields fields;
private ItemFieldDefinitionData definition;
public Field(Fields _fields, ItemFieldDefinitionData _definition)
{
fields = _fields;
definition = _definition;
}
public string Name
{
get { return definition.Name; }
}
public Type Type
{
get { return definition.GetType(); }
}
public string Value
{
get
{
return Values.Count > 0 ? Values[0] : null;
}
set
{
if (Values.Count == 0) fields.AddFieldElement(definition);
Values[0] = value;
}
}
public ValueCollection Values
{
get
{
return new ValueCollection(fields, definition);
}
}
public void AddValue(string value = null)
{
XmlElement newElement = fields.AddFieldElement(definition);
if (value != null) newElement.InnerText = value;
}
public void RemoveValue(string value)
{
var elements = fields.GetFieldElements(definition);
foreach (var element in elements)
{
if (element.InnerText == value)
{
element.ParentNode.RemoveChild(element);
}
}
}
public void RemoveValue(int i)
{
var elements = fields.GetFieldElements(definition).ToArray();
elements[i].ParentNode.RemoveChild(elements[i]);
}
public IEnumerable<Fields> SubFields
{
get
{
var embeddedFieldDefinition = definition as EmbeddedSchemaFieldDefinitionData;
if (embeddedFieldDefinition != null)
{
var elements = fields.GetFieldElements(definition);
foreach (var element in elements)
{
yield return new Fields(fields, embeddedFieldDefinition.EmbeddedFields, (XmlElement)element);
}
}
}
}
public Fields GetSubFields(int i = 0)
{
var embeddedFieldDefinition = definition as EmbeddedSchemaFieldDefinitionData;
if (embeddedFieldDefinition != null)
{
var elements = fields.GetFieldElements(definition);
if (i == 0 && !elements.Any())
{
// you can always set the first value of any field without calling AddValue, so same applies to embedded fields
AddValue();
elements = fields.GetFieldElements(definition);
}
return new Fields(fields, embeddedFieldDefinition.EmbeddedFields, elements.ToArray()[i]);
}
else
{
throw new InvalidOperationException("You can only GetSubField on an EmbeddedSchemaField");
}
}
// The subfield with the given name of this field
public Field this[string name]
{
get { return GetSubFields()[name]; }
}
// The subfields of the given value of this field
public Fields this[int i]
{
get { return GetSubFields(i); }
}
}
Can you try this?
multimediaComponent.Metadata = "<Metadata/>";

Resources