How to get the user activity using tweetsharp library? - wpf

I am creating a demo application using wpf with tweetsharp library and I need to get the user acitvity such as TweetDeck activity.
How can we achieve this task?
Please help me.
Any help will be appreciated.

You should use below line of code for getting the twitter activity for tweetsharp library with the help of site stream.
public void Can_stream_from_user_stream()
{
const int maxStreamEvents = 5;
var block = new AutoResetEvent(false);
var count = 0;
var service = GetAuthenticatedService();
service.StreamUser((streamEvent, response) =>
{
if (streamEvent is TwitterUserStreamEnd)
{
block.Set();
}
if (response.StatusCode == 0)
{
if (streamEvent is TwitterUserStreamFriends)
{
var friends = (TwitterUserStreamFriends)streamEvent;
Assert.IsNotNull(friends);
Assert.IsNotNull(friends.RawSource);
Assert.IsTrue(friends.Ids.Any());
}
if (streamEvent is TwitterUserStreamEvent)
{
var #event = (TwitterUserStreamEvent)streamEvent;
Assert.IsNotNull(#event);
Assert.IsNotNull(#event.TargetObject);
Assert.IsNotNull(#event.RawSource);
}
if (streamEvent is TwitterUserStreamStatus)
{
var tweet = ((TwitterUserStreamStatus)streamEvent).Status;
Assert.IsNotNull(tweet);
Assert.IsNotNull(tweet.Id);
Assert.IsNotNull(tweet.User);
Assert.IsNotNull(tweet.RawSource);
Assert.IsNotNull(tweet.User.ScreenName);
}
if (streamEvent is TwitterUserStreamDirectMessage)
{
var dm = ((TwitterUserStreamDirectMessage)streamEvent).DirectMessage;
Assert.IsNotNull(dm);
Assert.IsNotNull(dm.Id);
Assert.IsNotNull(dm.Sender);
Assert.IsNotNull(dm.Recipient);
Assert.IsNotNull(dm.RawSource);
}
if (streamEvent is TwitterUserStreamDeleteStatus)
{
var deleted = (TwitterUserStreamDeleteStatus)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.StatusId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
if (streamEvent is TwitterUserStreamDeleteDirectMessage)
{
var deleted = (TwitterUserStreamDeleteDirectMessage)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.DirectMessageId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
count++;
if (count == maxStreamEvents)
{
block.Set();
}
}
else
{
Assert.Ignore("Stream responsed with status code: {0}", response.StatusCode);
}
});
block.WaitOne();
service.CancelStreaming();
}
above line of code I am getting from this Link

Related

Assigns me no mail after user creation - Does Logic Apps make a mistake?

This is the case, for example, if a user now creates a page. So the next day I need Azure Logic apps to send an email after 1 day.
The problem is: right now, it is by no means sending any email to me if I sign up yesterday. But it sends me an email that now it has gone through with succe.
I would like to know what goes wrong since it by no means email me as I set up yesterday.
My Logic app (From Azure) - Images
However, be aware that the code can be made short but I just need to find out if Logic apps are making mistakes or if thus my code previously works without problems.
[Route("/api/cronjob")]
[HttpGet]
public async Task<IActionResult> NewSletterUserEmail()
{
await Newsletter();
return Ok("Godkendt!");
}
public async Task<IActionResult> Newsletter()
{
var m = new Settings.ArdklarMail();
var dtt = DateTime.Now;
var days = _dbContext.OfferUser.Max(i => i.Days);
var MaxDays = DateTime.Now.AddDays(-days);
var userlist = _dbContext.Users.Where(i => i.Opretdate >= MaxDays && i.TilmeldtNyhedsbrev == true).ToList();
if (userlist != null)
{
foreach (var item in userlist)
{
string mail = item.Brugernavn;
string fullname = item.Navn;
var memberData = _dbContext.MemberShipValue.FirstOrDefault(r => r.UserId == item.UserId);
if (memberData == null)
{
//alm bruger
var result = _dbContext.OfferUser.Where(x => x.Value == 1).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
else
{
var result = _dbContext.OfferUser.Where(x => x.Value == 2).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;//hvis den ingen antal har så giver den 0.
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Opretdate.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);//return Null here
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(item.Brugernavn);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(2200);
}
}
}
}
}
}
//Det er til dem fra nyhedsbrevet som få tilsendt nyhedsbrev omkring div ting.
var newsletterlist = _dbContext.NewsletterList.Where(i => i.Tilmeldtdato >= MaxDays).ToList();
if (newsletterlist != null)
{
foreach (var item in newsletterlist)
{
string mail = item.Email;
string fullname = item.Email;
//til de nyhedsbrevet område
var result = _dbContext.OfferUser.Where(x => x.Value == 3).ToList();
if (result != null)
{
foreach (var itemValue in result)
{
int itemValueDays = itemValue.Days;
var daysValue = DateTime.Now.AddDays(-itemValueDays);
if (item.Tilmeldtdato.Date == daysValue)
{
var title = itemValue.Title;
var viewModel = new EmailModel
{
getUrl = m.RemoveLinkUrl(),
Title = title,
FullName = fullname,
Text = itemValue.Text.ToHtmlString()
};
var resultMail = await _viewRenderService.RenderToStringAsync("~/Views/Templates/OfferToUsers.cshtml", viewModel);
MailMessageControl mailA = new MailMessageControl();
mailA.SetCredentials(m.azureName(), m.password());
mailA.SetSender(m.mailFrom());
mailA.AddAddressSee(mail);
mailA.SetSubject(title);
mailA.SetBody(resultMail);
mailA.SendEmail();
await Task.Delay(3500);
}
}
}
}
}
return Ok("Godkendt!");
}
No, I don't see mistake in Azure Logic Apps. Since the Logic App uses a recurrence trigger, it triggers the Logic App at the defined interval of time.
As there was send email action both side on the parallel branch, it will somehow send you an email by no means.

EWS - appointment.body created by outlook365 client returns empty

I have a problem: cannot get appointment body if it was created by outlook365 client.
When i run the code all properties values are being received except body.
After some searching i've found out that appointment bodies are not being received if appointments were made by outlook365.
Please, help!
The code:
public static List<Appointment> SetupConnection()
{
ServicePointManager.ServerCertificateValidationCallback = CallbackMethods.CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("Someuser#somedomain.com", "SomePassword");
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
Folder calendarFolder = GetCalendarFolder(service, #"\");
return GetMeetings(calendarFolder, service);
}
public static List<Appointment> GetMeetings(Folder calendarFolder, ExchangeService service)
{
if (calendarFolder == null)
{
return null;
}
SearchFilter.SearchFilterCollection filters = new SearchFilter.SearchFilterCollection(LogicalOperator.And)
{
new SearchFilter.IsGreaterThan(AppointmentSchema.Start, DateTime.Today)
};
List<Appointment> meetings = new List<Appointment>();
const Int32 pageSize = 30;
ItemView itemView = new ItemView(pageSize);
PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly);
itemView.PropertySet = propertySet;
FindItemsResults<Item> findResults = null;
do
{
findResults = calendarFolder.FindItems(filters, itemView);
itemView.Offset += pageSize;
meetings.AddRange(findResults.Cast<Appointment>());
} while (findResults.MoreAvailable);
PropertySet propertySet1 = new PropertySet(BasePropertySet.IdOnly);
propertySet1.Add(ItemSchema.Body);
propertySet1.Add(ItemSchema.Subject);
propertySet1.Add(AppointmentSchema.Organizer);
propertySet1.Add(AppointmentSchema.Start);
propertySet1.Add(AppointmentSchema.End);
propertySet1.Add(AppointmentSchema.Duration);
propertySet1.Add(AppointmentSchema.AppointmentType);
propertySet1.Add(AppointmentSchema.ConferenceType);
propertySet1.Add(AppointmentSchema.IsOnlineMeeting);
propertySet1.Add(AppointmentSchema.IsMeeting);
propertySet1.Add(AppointmentSchema.IsRecurring);
propertySet1.Add(AppointmentSchema.HasAttachments);
propertySet1.Add(AppointmentSchema.RequiredAttendees);
propertySet1.Add(AppointmentSchema.Resources);
propertySet1.Add(AppointmentSchema.InternetMessageHeaders);
propertySet1.RequestedBodyType = Microsoft.Exchange.WebServices.Data.BodyType.Text;
service.LoadPropertiesForItems(meetings, propertySet1);
return meetings;
}
}
Your code is only returning IdOnly
Try changing BasePropertySet.IdOnly to BasePropertySet.FirstClassProperties

AngularJS : why is searching not working properly?

I am trying to search text on table using angular ..I am able to search text in table .But my search works when I press enter or “search button” .Example when I write “Active” it not show the result but when I press enter or press search button it show the output .can we do the like search like autocomplete .Example when I press “a’ it show all item which start from “a” .Then if user write “ac” then show “ac” value ..same like that .when user write “active “ it show rows which have “active” without using search button or enter .can we make add filter so that it works properly ?
here is my code
$scope.searchInvoices = function(evt, queryval) {
$scope.haveNorecordFound = true;
if (typeof queryval != "undefined" && queryval.length === 0 || evt.keyCode === 13 || evt.type === 'click') {
if (typeof queryval == "undefined" || queryval.length === 0) {
console.log("if===")
isfilterOccured = false;
$scope.tasklist_records = $scope.total_tasklist_records;
$scope.totalNumberOfrecord = $scope.tasklist_records.length + " records found."
} else {
console.log("esle===")
var recordset = $scope.serachObject;
results = [];
var recordsetLength = recordset.length;
var searchVal = queryval.toLowerCase();
var i, j;
for (i = 0; i < recordsetLength; i++) {
var record = recordset[i].columns;
for (j = 0; j < record.length; j++) {
if (record[j].value != null) {
var invoice = record[j].value.toLowerCase();
if (invoice.indexOf(searchVal) >= 0) {
results.push(recordset[i]);
}
}
}
}
var nameOrPathValues = results.map(function(o) {
var result = {};
o.columns.forEach(function(c) {
result[c.fieldNameOrPath] = c.value;
});
return result;
});
console.log("serach");
console.log(nameOrPathValues);
var objectarray = nameOrPathValues.map(function(o) {
var result = {};
collectNameOrPath.forEach(function(name) {
result[name] = o[name];
});
return result;
});
isfilterOccured = true;
$scope.tasklist_records = objectarray;
if ($scope.tasklist_records.length == 0) {
$scope.haveNorecordFound = false;
} else {
$scope.totalNumberOfrecord = $scope.tasklist_records.length + " records found."
}
}
}
};
After debugging in code, I found that you're biding function on either enter button press or search click. That's why it was not working on ng-keyup. Please replace your function from below code.
$scope.searchInvoices = function(evt, queryval) {
console.log(queryval)
$scope.haveNorecordFound = true;
var recordset = $scope.serachObject;
results = [];
var recordsetLength = recordset.length;
var searchVal = queryval.toLowerCase();
var i, j;
for (i = 0; i < recordsetLength; i++) {
var record = recordset[i].columns;
for (j = 0; j < record.length; j++) {
if (record[j].value != null) {
var invoice = record[j].value.toLowerCase();
if (invoice.indexOf(searchVal) >= 0) {
results.push(recordset[i]);
}
}
}
}
var nameOrPathValues = results.map(function(o) {
var result = {};
o.columns.forEach(function(c) {
result[c.fieldNameOrPath] = c.value;
});
return result;
});
console.log("serach");
console.log(nameOrPathValues);
var objectarray = nameOrPathValues.map(function(o) {
var result = {};
collectNameOrPath.forEach(function(name) {
result[name] = o[name];
});
return result;
});
isfilterOccured = true;
$scope.tasklist_records = objectarray;
if ($scope.tasklist_records.length == 0) {
$scope.haveNorecordFound = false;
} else {
$scope.totalNumberOfrecord = $scope.tasklist_records.length + " records found."
}
};

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

For each string in Array

Just as the name says, I want that for each certain name in an array a value is added to a int.
For example: if there are 3 strings of the same name in the array, then 3 times 50 will be added to the value.
This is my script I have now:
var lootList = new Array();
var interaction : Texture;
var interact = false;
var position : Rect;
var ching : AudioClip;
var lootPrice = 0;
function Update()
{
print(lootList);
if ("chalice" in lootList){
lootPrice += 50;
}
}
function Start()
{
position = Rect( ( Screen.width - interaction.width ) /2, ( Screen.height - interaction.height ) /2, interaction.width, interaction.height );
}
function OnTriggerStay(col : Collider)
{
if(col.gameObject.tag == "loot")
{
interact = true;
if(Input.GetKeyDown("e"))
{
if(col.gameObject.name == "chalice")
{
Destroy(col.gameObject);
print("chaliceObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("chalice");
}
if(col.gameObject.name == "moneyPouch")
{
Destroy(col.gameObject);
print("moneyPouchObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("moneyPouch");
}
if(col.gameObject.name == "ring")
{
Destroy(col.gameObject);
print("ringObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("ring");
}
if(col.gameObject.name == "goldCoins")
{
Destroy(col.gameObject);
print("coldCoinsObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("goldCoins");
}
if(col.gameObject.name == "plate")
{
Destroy(col.gameObject);
print("plateObtained");
audio.clip = ching;
audio.pitch = Random.Range(0.8,1.2);
audio.Play();
interact = false;
lootList.Add("plate");
}
}
}
}
function OnTriggerExit(col : Collider)
{
if(col.gameObject.tag == "pouch")
{
interact = false;
}
}
function OnGUI()
{
if(interact == true)
{
GUI.DrawTexture(position, interaction);
GUI.color.a = 1;
}
}
It's for a game I'm making where you can steal items for extra score points.
I've tried using the for(i = 0; i < variable.Length; i++) but that didn't seem to work.
The only thing I can think of now is using booleans to add it once. But that isn't memory friendly.
Help is appreciated and thanks in advance!
You could use the standard .forEach(callback) method:
lootList.forEach(function(value, index, array)
{
if (value === "chalice") { lootPrice += 50; }
});
If you don't have that method, you could implement it like this:
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback) {
for(var i = 0; i < this.length; i++) { callback(this[i], i, this); }
}
}

Resources