CommentThreads amount changes by order - youtube-api

CommentThreads amount changes by order
Hi I'm trying to fetch all comments of a video. For testing purpose I'm using this video Id U55NGD9Jm7M.
When I order by time I get 1538 comments the last wrote on the 02.05.2015.
If I’m using the relevance I only receive 1353 comment and the last was wrote on the 29.04.2015
This doesn’t seem right to me. I expected to receive the same comments but in a different order and not different comments.
I also tried this on a different video and the results were the same.
My code cut down to minimum
Thank you for your help
public class foo
{
public void bar(string videoId)
{
var allTopLevelComments = new List<CommentThread>();
var searchListResponse = getThread(videoId);
allTopLevelComments.AddRange(searchListResponse.Items);
string nextPage = searchListResponse.NextPageToken;
while (!String.IsNullOrEmpty(nextPage))
{
searchListResponse = getThread(videoId, searchListResponse.NextPageToken);
nextPage = searchListResponse.NextPageToken;
allTopLevelComments.AddRange(searchListResponse.Items);
}
var first = allTopLevelComments.OrderBy(c => c.Snippet.TopLevelComment.Snippet.PublishedAt).First();
}
private CommentThreadListResponse getThread(string videoId, string nextPageToken = "")
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer
{
ApiKey = "my key",
ApplicationName = "my app"
});
var searchListRequest = youtubeService.CommentThreads.List("id, replies, snippet");
searchListRequest.VideoId = videoId;
searchListRequest.MaxResults = 100;
searchListRequest.Order = CommentThreadsResource.ListRequest.OrderEnum.Time;
searchListRequest.TextFormat = CommentThreadsResource.ListRequest.TextFormatEnum.PlainText;
if (!String.IsNullOrEmpty(nextPageToken))
{
searchListRequest.PageToken = nextPageToken;
}
return searchListRequest.Execute();
}
}

Related

Bad request when posting to OData Data Entity in Dynamics 365

I've created a public Data Entity in dynamics with the following fields:
I keep getting a bad request response, but I'm not sure why.
I've tried to make a POST request in two ways:
1.
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionStatus = "Created" };
string jsonMessage = JsonConvert.SerializeObject(hireAction);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "MyDynamicsEnvironmentName/data/HireActions?cross-company=true");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("Authorization", AuthResult.AuthorizationHeader);
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Logic
}
}
var url = "MyDynamicsEnvironmentName/data/HireActions?cross-company=true";
var req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers["Authorization"] = AuthResult.AuthorizationHeader;
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionId = "12345", HireActionStatus = "Created" };
var jsonSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var postString = "CompanyName='DEMF'" + "&MovieId='DEMF-000000014'" + "&HireActionId=132&HireActionStatus='Created'";
var data = JsonConvert.SerializeObject(postString, jsonSettings);
var bytes = Encoding.Default.GetBytes(postString);
var newStream = req.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
using (var resp = req.GetResponse())
{
var results = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
Some keypoints:
-Of course you'd replace MyDynamicsEnvironmentName with the URL for the environment. The URL is correct and verified however, by the fact that GET requests do work
-The Authresult.AuthorizationHeader contains a valid token, also validated by working GET requests
As said before, both of these result in a bad request. Does someone know what is wrong or missing?

Create team in GraphAPI returns always null

I am using GraphAPI SDK to create a new Team in Microsoft Teams:
var newTeam = new Team()
{
DisplayName = teamName,
Description = teamName,
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
},
Members = new TeamMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", $"https://graph.microsoft.com/v1.0/users/{userId}"}
}
}
}
};
var team = await this.graphStableClient.Teams
.Request()
.AddAsync(newTeam);
The problem is that I get always null. According documentation this method returns a 202 response (teamsAsyncOperation), but the AddAsync method from SDK returns a Team object. Is there any way to get the tracking url to check if the team creation has been finished with the SDK?
Documentation and working SDK works different... As they wrote in microsoft-graph-docs/issues/10840, we can only get the teamsAsyncOperation header values if we use HttpRequestMessage as in contoso-airlines-teams-sample. They wrote to the people who asks this problem, look to the joined teams :)) :)
var newTeam = new Team()
{
DisplayName = model.DisplayName,
Description = model.Description,
AdditionalData = new Dictionary<string, object>
{
["template#odata.bind"] = $"{graph.BaseUrl}/teamsTemplates('standard')",
["members"] = owners.ToArray()
}
};
// we cannot use 'await client.Teams.Request().AddAsync(newTeam)'
// as we do NOT get the team ID back (object is always null) :(
BaseRequest request = (BaseRequest)graph.Teams.Request();
request.ContentType = "application/json";
request.Method = "POST";
string location;
using (HttpResponseMessage response = await request.SendRequestAsync(newTeam, CancellationToken.None))
location = response.Headers.Location.ToString();
// looks like: /teams('7070b1fd-1f14-4a06-8617-254724d63cde')/operations('c7c34e52-7ebf-4038-b306-f5af2d9891ac')
// but is documented as: /teams/7070b1fd-1f14-4a06-8617-254724d63cde/operations/c7c34e52-7ebf-4038-b306-f5af2d9891ac
// -> this split supports both of them
string[] locationParts = location.Split(new[] { '\'', '/', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
string teamId = locationParts[1];
string operationId = locationParts[3];
// before querying the first time we must wait some secs, else we get a 404
int delayInMilliseconds = 5_000;
while (true)
{
await Task.Delay(delayInMilliseconds);
// lets see how far the teams creation process is
TeamsAsyncOperation operation = await graph.Teams[teamId].Operations[operationId].Request().GetAsync();
if (operation.Status == TeamsAsyncOperationStatus.Succeeded)
break;
if (operation.Status == TeamsAsyncOperationStatus.Failed)
throw new Exception($"Failed to create team '{newTeam.DisplayName}': {operation.Error.Message} ({operation.Error.Code})");
// according to the docs, we should wait > 30 secs between calls
// https://learn.microsoft.com/en-us/graph/api/resources/teamsasyncoperation?view=graph-rest-1.0
delayInMilliseconds = 30_000;
}
// finally, do something with your team...
I found a solution from another question... Tried and saw that it's working...

Filter Query in Mongodb using multiple Id's(Inner array)

CommentCollection
{
"_id":"5b63f0f23846b70011330889",
"CommentType":"task",
"EntityReferenceId":"6082ef25-6f9a-4874-a832-f72e0f693409",
"Threads":[
{
"_id":"69bcef71-3695-4340-bdec-4a6e4c58c490",
"CommentType":"task",
"UserId":ObjectId("52ffc4a5d85242602e000000"),
"CommentByUserType":"Admin",
"EntityReferenceId":"6082ef25-6f9a-4874-a832-f72e0f693409",
"Content":"fdffd",
},
{
"_id":"69bcef71-3695-4340-bdec-4a6e4c58c490",
"CommentType":"task",
"UserId":ObjectId("52ffc4a5d85242602e000000"),
"CommentByUserType":"Admin",
"EntityReferenceId":"6082ef25-6f9a-4874-a832-f72e0f693409",
"Content":"fdffd",
}
]
}
Here I have to write a Mongodb filter query from asp.net core based on two conditions,
first I want to get CommentCollection by EntityReferenceId, then want to find the specific thread by id from the first result.
Any help will be appreciated.
I got the answer,I have wrote my method like below
public async Task<bool> UpdateCommentAsync(Threads thread)
{
var builder = Builders<Comments>.Filter;
var filter = builder.Empty;
var update = Builders<Comments>.Update.Set("Threads.$[i].Content", thread.Content);
var arrayFilters = new List<ArrayFilterDefinition> { new JsonArrayFilterDefinition<Threads>("{'i._id': '" + thread.Id + "'}") };
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
var result = await _context.Comments.UpdateManyAsync(filter, update, updateOptions);
return result.ModifiedCount > 0;
}

Youtube Livestream Api LiveChatMessages List

Im trying to get the Messages from a Youtube Livestream, works, but i dont get new Messages. The NextPageToken is included.
Sometimes i get new messages, but it takes arround 5-10min.
Youtube Chat Sending works also fine.
Any Idea?
This is from the Docs: https://developers.google.com/youtube/v3/live/docs/liveChatMessages/list
private async Task GetMessagesAsync(string liveChatId, string nextPageToken, long? pollingIntervalMillis)
{
liveChatId = "EiEKGFVDVUQ3WGNXTk92SlpvaHFMM3dZTi1uZxIFL2xpdmU";
if (!updatingChat)
{
if (!string.IsNullOrEmpty(liveChatId))
{
newMessages = true;
var chatMessages = youTubeService.LiveChatMessages.List(liveChatId, "id,snippet,authorDetails");
var chatResponse = await chatMessages.ExecuteAsync();
PageInfo pageInfo = chatResponse.PageInfo;
newMessages = false;
if (pageInfo.TotalResults.HasValue)
{
if (!prevCount.Equals(pageInfo.TotalResults.Value))
{
prevCount = pageInfo.TotalResults.Value;
newMessages = true;
}
}
if (newMessages)
{
Messages = new List<YouTubeMessage>();
foreach (var chatMessage in chatResponse.Items)
{
string messageId = chatMessage.Id;
string displayName = chatMessage.AuthorDetails.DisplayName;
string displayMessage = chatMessage.Snippet.DisplayMessage;
string NextPagetoken = chatResponse.NextPageToken;
YouTubeMessage message = new YouTubeMessage(messageId, displayName, displayMessage);
if (!Messages.Contains(message))
{
Messages.Add(message);
string output = "[" + displayName + "]: " + displayMessage;
Console.WriteLine(time + output);
}
}
}
await GetMessagesAsync(liveChatId, chatResponse.NextPageToken, chatResponse.PollingIntervalMillis);
}
}
updatingChat = false;
await Task.Delay(100);
}
public async Task YouTubeChatSend(string message)
{
try
{
LiveChatMessage liveMessage = new LiveChatMessage();
liveMessage.Snippet = new LiveChatMessageSnippet()
{
LiveChatId = "EiEKGFVDVUQ3WGNXTk92SlpvaHFMM3dZTi1uZxIFL2xpdmU",
Type = "textMessageEvent",
TextMessageDetails = new LiveChatTextMessageDetails() { MessageText = message }
};
var insert = this.youTubeService.LiveChatMessages.Insert(liveMessage, "snippet");
var response = await insert.ExecuteAsync();
if (response != null)
{
}
}
catch
{
Console.WriteLine("Failed to chat send");
}
}

templateService.Parse not able to parese Tuple used in view(MVC)

I am trying to parse a .cshtml with tuple and tuple used for acces two models in the view same time, but it is not working throwing error, but if I am using only one model than same this is wotking.
Here is my code:
Controller:
var deviceModel = new DevicesInformationDataViewModel { };
var eventModel = new EventsInformationDataViewModel{ };
var templateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Views\\EmailTemplates");
var emailTemplatePath = Path.Combine(templateFolderPath, "EmailTemplates.cshtml");
var templateService = new TemplateService();
var emailHtmlBody = "";
string email = data[1];
ViewBag.info = data[0];
if (data[0] == "DeviceInfo")
{
deviceModel.Address = data[2];
deviceModel.Description = data[3];
deviceModel.eDescription = data[4];
deviceModel.Fault = data[5];
deviceModel.Type = data[6];
deviceModel.TypeCode = Int32.Parse(data[7]);
deviceModel.DriftCompensation = Int32.Parse(data[8]);
deviceModel.AlarmSensitivity = data[9];
deviceModel.Status = data[10];
emailHtmlBody = templateService.Parse(System.IO.File.ReadAllText(emailTemplatePath), deviceModel, ViewBag.info, null);
}
View:
If using like this, not working:
#model Tuple<DevicesInformationDataViewModel,EventsInformationDataViewModel>
but if using like this, it is working:
#model DevicesInformationDataViewModel
Can any body tell me what I am doing wrong and please tell me how can I resolve
this issue?

Resources