Update Contact details to an Opportunity through Salesforce API - salesforce

Need to create new relationship to Contact and Opportunity.
Trying to insert data to Case_Relation__c table for fields Opportunity__c SFDC_ContactID__c, etc. but it throws error:
Unable to create/update fields: Name. Please check the security settings of this field and verify that it is read/write for your profile or permission set.
API Code:
soqlQuery = "Select Case_Name__c,Case_Ranking__c,Company_Name__c,Contact_Role__c,Contact__c,Name,Opportunity__c,RUST_Case_Relationship_Legacy_ID__c,Relationship_Level__c,SFDC_ContactID__c FROM Case_Relation__c";
SalesForceProxy.QueryResult qrR = binding.query(soqlQuery);
done = false;
if (qrR.size > 0)
{
while (!done)
{
SalesForceProxy.sObject[] records = qrR.records;
for (int i = 0; i < records.Length; i++)
{
SalesForceProxy.Case_Relation__c con = (SalesForceProxy.Case_Relation__c)records[i];
oCmd.CreateParameter();
con.Opportunity__c = "006R0000008r0hdIAA";
con.SFDC_ContactID__c = "006R0000008r0hdIAA";
SFService.SalesForceProxy.sObject[] Case_Relation__c = new SalesForceProxy.sObject[1];
Case_Relation__c[0] = con;
if (qr.records != null)
{
try
{
SFService.SalesForceProxy.SaveResult[] saveResults = binding.create(Case_Relation__c);
for (int j = 0; j < saveResults.Length; j++)
{
if (saveResults[j].success)
{
}
else
{
foreach (SFService.SalesForceProxy.Error ex in saveResults[j].errors)
{
SendMail(ex.message);
TraceService(ex.message);
}
}
}
}
catch (Exception ex)
{
SendMail(ex.Message);
TraceService(ex.Message);
}
}
}
if (qrR.done)
{
done = true;
}
else
{
qrR = binding.queryMore(qrR.queryLocator);
}
}
}

check the field accessibility for every field in Case_Relation__c object

Related

Share a TXT file between two android application Android 11 and Android 12

I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.
I tried with MediaStore:
MAIN APP :
private static void saveLanguageOnFile(String lang, String country){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
boolean success;
if (!folderDocuments.exists()) {
try {
folderDocuments.mkdir();
} catch (Exception ex) {
ex.printStackTrace();
}
}
success = folderDocuments.exists();
if (success) {
try {
FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
fos.write((lang + "-" + country).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);
long idFile = -1;
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
String fileName = cursor.getString(columnIndexDisplayName);
if (fileName.equals("language.txt")) {
idFile = cursor.getLong(columnIndexId);
break;
}
}
}
cursor.close();
}
Uri uriFile;
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt"); // file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
uriFile = contentResolver.insert(contentUri, values);
}
try {
if (uriFile != null) {
OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
if (outputStream != null) {
outputStream.write((lang + "-" + country).getBytes());
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ANDROID LAUNCHER APP :
private fun setLanguage() {
var lang = Locale.getDefault().language
var country = Locale.getDefault().country
val previousLang = lang
val previousCountry = country
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
if (language.exists()) {
try {
val br = BufferedReader(FileReader(language))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
Log.e("LauncherDMD", ".loadFile: err: " + e.message)
}
}
} else {
val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentResolver: ContentResolver = application.applicationContext.contentResolver
val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)
var idFile: Long = -1
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
val fileName = cursor.getString(columnIndexDisplayName)
if (fileName.contains("language")) {
idFile = cursor.getLong(columnIndexId)
break
}
}
}
cursor.close()
}
val uriFile: Uri
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile)
try {
val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
val locale = Locale(lang,country)
Lingver.getInstance().setLocale(this.applicationContext, locale)
if(!previousCountry.equals(country) && !previousLang.equals(lang)){
recreate()
}
Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}
This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.
Thanks in advance!

RSSService item with the same key multiple times

I have a RSSService with an item like the one show below
<item>
<title>Accessori per la cura della persona</title>
<link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
<comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
<pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
<dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
<category><![CDATA[News]]></category>
<category><![CDATA[Offerte]]></category>
<category><![CDATA[Callifugo]]></category>
<category><![CDATA[Raspa piedi]]></category>
<category><![CDATA[Spazzola ceramica]]></category>
<category><![CDATA[Spazzola piatta]]></category>
<category><![CDATA[Spazzola tonda]]></category>
<category><![CDATA[Spazzole capelli]]></category>
<guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
<description>.....
To read all the content I use this:
List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
Button b = new Button((String)m.get("title"));
if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}
When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:
String[] mc = (String[]) m.get("category");
Thank's in advance for any help.
Davide.
This looks like a missing feature in RSSService that expects to find only one category entry and so it parses it into a hash map which effectively allows only one such entry.
I would suggest implementing your own RSS reading and go to the XML directly to get the full power of the protocol. You can use the existing class as a reference on how to do the RSS/ATOM parsing.
This is my idea
protected void textElement(String text) {
if(lastTag != null && current != null) {
// make "ATOM" seem like RSS
if("summary".equals(lastTag)) {
current.put("details", text);
} else {
if("content".equals(lastTag)) {
current.put("description", text);
} else {
if(current.get(lastTag) != null){
try {
List list = (List) current.get(lastTag);
list.add(text);
current.put(lastTag, list);
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
List list = new ArrayList();
list.add((String)current.get(lastTag));
list.add(text);
current.put(lastTag, list);
}
} else {
current.put(lastTag, text);
}
}
}
}
}
Used in my Form like this:
for (Map m : records) {
Button b = new Button((String)m.get("title"));
try{
String category = (String)m.get("category");
if(category.equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
} else {
b.setIcon(iconNews);
}
} catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
b.setIcon(iconNews);
List list = (List) m.get("category");
for(int i=0; i < list.size(); i++){
if(((String)list.get(i)).equals(CATEGORY_OFFERTE)){
b.setIcon(iconStar);
}
}
}
b.addActionListener((l)->{
Boolean can = Display.getInstance().canExecute((String)m.get("link"));
if(can != null && can) {
Display.getInstance().execute((String)m.get("link"));
} else {
ToastBar.Status status = ToastBar.getInstance().createStatus();
status.setMessage("Non riesco a connettermi");
status.setExpires(3000);
status.show();
}
});
recordsContainer.addComponent(b);
}

Can we call explicitly Watch in the controller

Can we call watch expliciltly in the controller?
Requirements:
Currently there are two angular tree structured checkboxes. one is carriergorup and another one is modes. I'm retrieving mode values based on carriergroup list. whenever the carrier group list is updated automatically modes list is updated for this i used watch.
current functionality is like.
Whenever the carriergroup list is updated then only modes list is updated. Suppose there is no change in the carrier group list, but I want to make a call for watch explicitly. Is this possible?
$scope.$watch(
'carrierGroups',
function(carrierGroups) {
alert("in carrier List");
$scope.selectedCarrierList = [];
$scope.isAllChecked = true;
for (var i = 0; i < $scope.carrierGroups.length; i++) {
/*if($scope.carrierGroups[i].checked){
cntGroupChecked = cntGroupChecked + 1;
}*/
for (var j = 0; j < $scope.carrierGroups[i].categories.length; j++) {
if ($scope.carrierGroups[i].categories[j].checked) {
$scope.selectedCarrierList
.push($scope.carrierGroups[i].categories[j]);
}else{
$scope.carrierGroups[i].checked = false;
$scope.isAllChecked = false;
}
}
}
alert("$scope.isModesWatch"+$scope.isModesWatch);
if($scope.isModesWatch){
$scope.modesList = DashboardsDataService.getModesData($scope.selectedCarrierList);
}else{
alert("$scope.filterModesList-->"+JSON.stringify($scope.filterModesList));
$scope.modesList = $scope.filterModesList;
$scope.isModesWatch = true;
}
},
true);
Like below, you can do this..
var myCustomFun = function(carrierGroups) {
alert("in carrier List");
$scope.selectedCarrierList = [];
$scope.isAllChecked = true;
for (var i = 0; i < $scope.carrierGroups.length; i++) {
/*if($scope.carrierGroups[i].checked){
cntGroupChecked = cntGroupChecked + 1;
}*/
for (var j = 0; j < $scope.carrierGroups[i].categories.length; j++) {
if ($scope.carrierGroups[i].categories[j].checked) {
$scope.selectedCarrierList
.push($scope.carrierGroups[i].categories[j]);
}else{
$scope.carrierGroups[i].checked = false;
$scope.isAllChecked = false;
}
}
}
alert("$scope.isModesWatch"+$scope.isModesWatch);
if($scope.isModesWatch){
$scope.modesList = DashboardsDataService.getModesData($scope.selectedCarrierList);
}else{
alert("$scope.filterModesList-->"+JSON.stringify($scope.filterModesList));
$scope.modesList = $scope.filterModesList;
$scope.isModesWatch = true;
}
}
$scope.$watch('carrierGroups',myCustomFun,true);
Now where you want to call custom watch function, you can simply call your function.
myCustomFun(param);

Google Drive - Authorize once on a single machine

I am new to Google Drive and have following scenarios for which I am not able to find anything (not sure if anything exists or not)
–> I am creating a Windows app which will be SAAS based. Different Users will register and create their company logins and subusers under them. Now I want them to put the google drive credentials in one of the form and this should work for rest of the users. Currently the problem is that while development I got the google log in done and it never asks for the login again but when testing on a different system with different login, it keeps asking for google login. I simply want admin users to put their google drive credentials and it should work for upload and download files for all the users for that company.
–> I want to keep versions of the same file (just like google drive does by default) on google drive. Lets say user A uploaded file xyz and then user B downloaded and changed file xyz and uploaded it on the drive again.
I want 2 things here – only the changed content should get uploaded and not the whole file (this will save time for the user)
2ndly I want to have history of the same file so I can show in my Windows application
#region Get Service Object
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "GoogleDriveClientID",
ClientSecret = "GoogleDriveClientSecret"
},
new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;
// Create the service.
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AppName",
});
#endregion
#region Uploading
public void uploadOnGoogleDrive(ObservableCollection<JobAttachments> AttachmentsColl, bool IsDocSaved)
{
try
{
service = getServiceObject();
List<Google.Apis.Drive.v2.Data.File> fileList = retrieveAllFiles(service);
List<Google.Apis.Drive.v2.Data.File> directoryList = GetDirectoryList(service);
if (IsDocSaved)
{
#region for checking if the file already exists
foreach (Google.Apis.Drive.v2.Data.File item in fileList)
{
foreach (JobAttachments attach in AttachmentsColl)
{
if (item.Title == attach.AttachmtGUID)
{
MessageBoxResult result = System.Windows.MessageBox.Show(LogMessages.GetResourceMessage(LogMessages.MessageEnumeration.GD_AlreadyExistsMsg), "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
//DeleteFile(service, item);
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = attach.AttachmtGUID;
body.MimeType = item.MimeType;
fileSize = body.FileSize;
byte[] byteArray = System.IO.File.ReadAllBytes(attach.AttachmentName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.UpdateMediaUpload request = service.Files.Update(body, item.Id, stream, item.MimeType);
request.Upload();
}
else
{
return;
}
break;
}
}
}
#endregion
}
else
{
#region for direct uploading on google drive
if (AttachmentsCollection != null && AttachmentsCollection.Count > 0)
{
string folderID = string.Empty;
if (_IsProject)
{
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_ProjectName))
{
folderID = dir.Id;
break;
}
}
}
if (string.IsNullOrEmpty(folderID))
{
Google.Apis.Drive.v2.Data.File foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _ProjectName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
folderID = file.Id;
}
}
else
{
//project folder
string prjFolder = string.Empty;
string tskFolder = string.Empty;
Google.Apis.Drive.v2.Data.File foldbody;
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_ProjectName))
{
prjFolder = dir.Id;
break;
}
}
}
if (string.IsNullOrEmpty(prjFolder))
{
foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _ProjectName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
Google.Apis.Drive.v2.Data.File file = service.Files.Insert(foldbody).Execute();
prjFolder = file.Id;
}
//task folder
if (directoryList != null && directoryList.Count > 0)
{
foreach (var dir in directoryList)
{
if (dir.Title.Equals(_TaskName) && dir.Parents[0].Id.Equals(prjFolder))
{
folderID = dir.Id;
break;
}
}
}
if (string.IsNullOrWhiteSpace(folderID))
{
foldbody = new Google.Apis.Drive.v2.Data.File();
foldbody.Title = _TaskName;
foldbody.MimeType = "application/vnd.google-apps.folder";
foldbody.Parents = new List<ParentReference>() { new ParentReference() { Id = prjFolder } };
Google.Apis.Drive.v2.Data.File file1 = service.Files.Insert(foldbody).Execute();
folderID = file1.Id;
}
}
foreach (JobAttachments item in AttachmentsColl)
{
if (!string.IsNullOrEmpty(item.AttachmentName))
{
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = item.AttachmtGUID;
body.MimeType = item.MimeType;
body.Parents = new List<ParentReference>() { new ParentReference() { Id = folderID } };
//fileSize = body.FileSize;
byte[] byteArray = System.IO.File.ReadAllBytes(item.AttachmentName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, item.MimeType);
request.Upload();
}
}
}
#endregion
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
throw ex.InnerException;
}
}
#endregion
#region Download File
private async Task DownloadFile(DriveService service, string url, string title, long? fSize)
{
service = getServiceObject();
var downloader = new MediaDownloader(service);
//downloader.ChunkSize = 256 * 1024;
downloader.ProgressChanged += Download_ProgressChanged;
var fileName = string.Empty;
//for downloading on system
var SaveFileDialog = new SaveFileDialog();
SaveFileDialog.Title = "Save As";
SaveFileDialog.FileName = title;
Nullable<bool> result = SaveFileDialog.ShowDialog();
if (result == true)
fileName = SaveFileDialog.FileName;
else if (result == false)
{
prgrsBar.StyleSettings = new ProgressBarStyleSettings();
prgrsBar.Value = 0;
return;
}
else
{
if (Directory.Exists(#"\Downloads"))
fileName = #"\Downloads\" + title;
}
if (!string.IsNullOrWhiteSpace(fileName))
using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
fileSize = fSize;
var progress = await downloader.DownloadAsync(url, fileStream);
if (progress.Status.ToString() == DownloadStatus.Completed.ToString())
{
fName = fileStream.Name;
prgrsBar.StyleSettings = new ProgressBarStyleSettings();
prgrsBar.Value = 0;
fileStream.Flush();
}
if (progress.Status.ToString() == DownloadStatus.Failed.ToString())
{
HandleDocuments.IsEditButtonClicked = false;
MessageBox.Show("Failed......." + progress.Exception.Message);
}
}
}
#endregion
#region Delete File
private Task DeleteFile(DriveService service, Google.Apis.Drive.v2.Data.File file)
{
service = getServiceObject(); //comment this if calling from another function; create the service object in that function and pass it as parameter to this function.
service.Files.Delete(file.Id).ExecuteAsync();
service.Files.EmptyTrash();
return null;
}
#endregion
#region Get all Directories and Files from Google Drive
public List<Google.Apis.Drive.v2.Data.File> GetDirectoryList(DriveService service)
{
//Creating the global list
List<Google.Apis.Drive.v2.Data.File> AllDirectories = new List<Google.Apis.Drive.v2.Data.File>();
//setting up the Request.
FilesResource.ListRequest request = service.Files.List();
//MaxResults: How many we want back at a time max is 1000
request.MaxResults = 1000;
//Q: Search results. all i want are folders that havent been trashed (deleted)
request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";
do
{
try
{
// getting the results
FileList files = request.Execute();
// adding the results to the list.
AllDirectories.AddRange(files.Items);
// If there are more results then your MaxResults you will have a nextPageToken to get the rest of the results.
request.PageToken = files.NextPageToken;
}
catch (Exception ex)
{
request.PageToken = null;
if (ex.InnerException != null)
throw ex.InnerException;
}
} while (!String.IsNullOrEmpty(request.PageToken));
List<Google.Apis.Drive.v2.Data.File> DirsInRoot = AllDirectories.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().IsRoot.Value : false).ToList<Google.Apis.Drive.v2.Data.File>();
List<string> HirearcyList = new List<string>();
// The first Dir is Root it doesnt get returned. But we need it if we
// Want to be able to list the files that are in the root dir.
HirearcyList.Add("Root");
// recersive magic here.
foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInRoot)
{
HirearcyList.Add(" " + myDir.Title);
HirearcyList.AddRange(RecsiveDir(AllDirectories, myDir.Id, " "));
}
return AllDirectories;
}
public List<String> RecsiveDir(List<Google.Apis.Drive.v2.Data.File> allDirs, string ParentId, string Prefix)
{
List<string> result = new List<string>();
List<Google.Apis.Drive.v2.Data.File> DirsInParentId = allDirs.Where(a => (a.Parents.Count > 0 && a.Parents.FirstOrDefault().IsRoot.HasValue) ? a.Parents.FirstOrDefault().Id == ParentId : false).ToList<Google.Apis.Drive.v2.Data.File>();
foreach (Google.Apis.Drive.v2.Data.File myDir in DirsInParentId)
{
result.Add(Prefix + myDir.Title);
result.AddRange(RecsiveDir(allDirs, myDir.Id, Prefix + " "));
}
return result;
}
public static List<Google.Apis.Drive.v2.Data.File> retrieveAllFiles(DriveService service)
{
List<Google.Apis.Drive.v2.Data.File> result = new List<Google.Apis.Drive.v2.Data.File>();
FilesResource.ListRequest request = service.Files.List();
request.MaxResults = 1000;
do
{
try
{
FileList files = request.Execute();
result.AddRange(files.Items);
request.PageToken = files.NextPageToken;
//service.Revisions.List(files.Items[0].Id) // for getting the file Revision history
}
catch (Exception ex)
{
request.PageToken = null;
if (ex.InnerException != null)
throw ex.InnerException;
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
#endregion
Thanks
Jatinder

How to retrieve parentaccountid from account using queryexpression and silverlight

My query returns account.name, account.account and account.parentaccountid.
I'm using Silverlight and CRM2011.
Now I'm having trouble to find out how to extract value from parentaccountid attribute.
I have silverlightextensionmethods.cs file included in my VS project, and I'm using GetAttributeValue<Guid>("parentaccountid") to get the value from parentaccountid.
The value returned is empty.
Has anyone any ideas how to accomplish this?
I can get any other attribute value, but parentaccountid in account and parentcustomerid in contact are making my life very difficult.
Code:
FIRST I CREATE QUERYEXPRESSION:
string temp="name;accountid;parentaccountid";
string[] fields = temp.Split(';');
QueryExpression query = new QueryExpression()
{
EntityName = entity,
ColumnSet = new ColumnSet { Columns = new System.Collections.ObjectModel.ObservableCollection<string>(fields) },
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression
{
AttributeName = parentidfield,
Operator = ConditionOperator.Equal,
Values = { id }
}
}
}
};
OrganizationRequest req = new OrganizationRequest();
req.RequestName = "RetrieveMultiple";
req["Query"] = query;
service.BeginExecute(req, new AsyncCallback(GetChildren_ExecuteCallBack), service);
NEXT I TY TO READ VALUES FORM RESPONSE
void GetChildren_ExecuteCallBack(IAsyncResult childresult)
{
List<TreeRecord> listc = new List<TreeRecord>();
try
{
OrganizationResponse childresponse = ((IOrganizationService)childresult.AsyncState).EndExecute(childresult);
EntityCollection childresults = (EntityCollection)childresponse["EntityCollection"];
if (childresults.Entities.Count > 0)
{
TreeConfig sitm = new TreeConfig();
string sdisplay = "";
string[] fields = "".Split(';');
string sid = "";
string pid = "";
foreach (Entity childentity in childresults.Entities)
{
foreach (TreeConfig sitem in Configs)
{
if (sitem.EntityName == childentity.LogicalName)
{
sitm = sitem;
}
}
TreeRecord childitem = new TreeRecord();
string sValue = "";
sdisplay = "name;accountid;parentaccountid";
fields = sdisplay.Split(';');
sid = "accountid";
pid = "parentaccountid";
int i = sdisplay.Split(';').Length;
for (int j = 0; j < i; j++)
{
try { sValue += childentity.GetAttributeValue<string>(fields[j]) + " "; }
catch (Exception ex)
{
//s = "sValue haku: " + ex.Message.ToString();
//this.ReportMessage(s.ToString());
}
}
childitem.Name = sValue;
childitem.EntityName = childentity.LogicalName;
childitem.Level = sitm.Level;
childitem.ParentEntityName = sitm.EntityName;
childitem.Color = sitm.Color;
childitem.RecordId = childentity.GetEntityId<Guid>(sid);
try { childitem.ParentId = childentity.GetAttributeValue<Guid>(pid); }
catch
{
//sb.AppendLine("guid: parentid tietoa ei löydy");
//this.ReportMessage(sb.ToString());
}
listc.Add(childitem);
}
}
}
Instead of
childentity.GetAttributeValue<Guid>(pid)
use
childentity.GetAttributeValue<EntityReference>(pid)

Resources