UpdateItemAsync() публичный статический Метод

public static UpdateItemAsync ( string id, item ) : Task
id string
Результат Task
Пример #1
0
        private static async Task SaveExpanseAndUpdateEmployee(IDialogContext context, string profileKey, ExpenseReport expenseReport)
        {
            await DocumentDBRepository.CreateItemAsync <ExpenseReport>(expenseReport);

            Employee employee = context.ConversationData.GetValue <Employee>(profileKey);

            if (employee.ExpenseReportList == null)
            {
                employee.ExpenseReportList = new List <string>()
                {
                    expenseReport.Id
                };
            }
            else
            {
                employee.ExpenseReportList.Add(expenseReport.Id);
            }

            await DocumentDBRepository.UpdateItemAsync <Employee>(employee.EmailId, employee);

            context.ConversationData.SetValue(profileKey, employee);
        }
Пример #2
0
        public override async Task <WopiResponse> GetLock(GetLockRequest getLockRequest)
        {
            WopiResponse wopiResponse = null;
            var          file         = DocumentDBRepository <DetailedFileModel> .GetItem("Files", i => i.id.ToString() == getLockRequest.ResourceId);

            // Check for null file
            if (file != null)
            {
                // Check for valid lock on file
                if (String.IsNullOrEmpty(file.LockValue))
                {
                    // File is not locked...return empty X-WOPI-Lock header
                    // Return success 200
                    wopiResponse = getLockRequest.ResponseFileNotLocked();
                }
                else if (file.LockExpires != null && file.LockExpires < DateTime.Now)
                {
                    // File lock expired, so clear it out
                    file.LockValue   = null;
                    file.LockExpires = null;
                    await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), (FileModel)file);

                    // File is not locked...return empty X-WOPI-Lock header
                    // Return success 200
                    wopiResponse = getLockRequest.ResponseFileNotLocked();
                }
                else
                {
                    // Return success 200
                    wopiResponse = getLockRequest.ResponseFileLocked(file.LockValue);
                }
            }
            else
            {
                wopiResponse = getLockRequest.ResponseNotFound();
            }

            return(wopiResponse);
        }
Пример #3
0
        public async Task <ActionResult> CommonTask4Post(Job item, string NewTask = "-", string NewHandler = "-")
        {
            if (ModelState.IsValid)
            {
                string NewTaskNo = NewTask[0].ToString();

                if (!(NewTask + NewHandler).Contains("-"))
                {
                    Session["SendingFlag"] = NewTaskNo;
                    item.TaskHandler       = NewHandler;
                    item.GetType().GetProperty("Task" + NewTaskNo).SetValue(item, "TASK");
                    await DocumentDBRepository.UpdateItemAsync <Job>(item.Id, item);

                    return(Redirect(Url.Content("~/Job/SendJob/" + item.Id)));
                }
            }

            await DocumentDBRepository.UpdateItemAsync <Job>(item.Id, item);

            await SetViewBags();

            return(Redirect(Url.Content("~/Job/_Index/")));
        }
Пример #4
0
        private static async Task MarkFreeAirCraft(AirCraftDetails aircardInfo, Activity replyActivity)
        {
            var aircraftInfo = await DocumentDBRepository <AirCraftInfo> .GetItemsAsync(d => d.FlightNumber == aircardInfo.FlightNumber && d.AircraftId == aircardInfo.AircraftId);

            if (aircraftInfo.Count() > 0)
            {
                try
                {
                    var list = aircraftInfo.FirstOrDefault();

                    list.Status = Status.Available;
                    var aircraftDetails = await DocumentDBRepository <AirCraftInfo> .UpdateItemAsync(list.Id, list);

                    var replyCard = O365CardHelper.GetO365ConnectorCardResult(aircraftInfo.FirstOrDefault(), aircardInfo.ActionId);
                    replyActivity.Attachments.Add(replyCard.ToAttachment());
                    //replyActivity.Text = $"Aircraft {aircardInfo.AircraftId} is available";
                }
                catch (Exception e)
                {
                    replyActivity.Text = e.Message.ToString();
                }
            }
        }
Пример #5
0
        public async Task <Lesson> UpdateLesson(string id, [FromBody] Lesson Lesson)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Lesson item = await DocumentDBRepository <Lesson> .GetSingleItemAsync(d => d.Id == id);

                    if (item == null)
                    {
                        return(null);
                    }
                    Lesson.Id = item.Id;
                    await DocumentDBRepository <Lesson> .UpdateItemAsync(item.Id, Lesson);

                    return(Lesson);
                }
                return(null);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #6
0
        public async Task <Hero> Put(string uid, [FromBody] Hero hero)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Hero item = await DocumentDBRepository <Hero> .GetSingleItemAsync(d => d.UId == uid);

                    if (item == null)
                    {
                        return(null);
                    }
                    hero.Id = item.Id;
                    await DocumentDBRepository <Hero> .UpdateItemAsync(item.Id, hero);

                    return(hero);
                }
                return(null);;
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #7
0
        public async Task <ActionResult> AddAlternative(QuestionAnswer item)
        {
            if (ModelState.IsValid)
            {
                var question = item.Question;
                var items    = await DocumentDBRepository <QuestionAnswer> .GetItemAsync(item.Id);

                item = items;
                List <string> list = new List <string>();
                list.Add(question);
                if (item.AlternativeQuestion == null)
                {
                    item.AlternativeQuestion = list;
                }
                else
                {
                    item.AlternativeQuestion.Add(question);
                }
                await DocumentDBRepository <QuestionAnswer> .UpdateItemAsync(item.Id, item);

                return(RedirectToAction("Index"));
            }
            return(View(item));
        }
Пример #8
0
        public async Task <CompressorData> Put(string uid, [System.Web.Http.FromBody] CompressorData CompressorData)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    CompressorData item = await DocumentDBRepository <CompressorData> .GetSingleItemAsync(d => d.id == uid);

                    if (item == null)
                    {
                        return(null);
                    }
                    CompressorData.id = item.id;
                    await DocumentDBRepository <CompressorData> .UpdateItemAsync(item.id, CompressorData);

                    return(CompressorData);
                }
                return(null);;
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #9
0
        public async Task <HttpResponseMessage> Add(Movie movie)
        {
            var userName = Request.GetHeaderValue("username");

            if (string.IsNullOrWhiteSpace(userName))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, "Required request header username is missing"));
            }

            var existingUser = await DocumentDBRepository <UserDetails> .GetItemsAsync(d =>
                                                                                       d.UserName == userName);

            if (existingUser == null || existingUser.FirstOrDefault() == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized User"));
            }

            var userId = existingUser.FirstOrDefault().Id;

            existingUser.FirstOrDefault().AddtoMovies(movie);
            await DocumentDBRepository <UserDetails> .UpdateItemAsync(userId, existingUser.FirstOrDefault()).ConfigureAwait(false);

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Пример #10
0
 public async Task Update(string id, Client client)
 {
     await DocumentDBRepository <Client> .UpdateItemAsync(id, client);
 }
        private static async Task WithdrawLeave(IDialogContext context, Activity activity, Employee employee, string leaveCategory)

        {
            var managerId = await GetManagerId(employee);

            if (managerId == null)

            {
                var reply = activity.CreateReply();

                reply.Text = "Unable to fetch your manager details. Please make sure that your manager has installed the Leave App.";

                await context.PostAsync(reply);
            }
            else

            {
                EditLeaveDetails vacationDetails = JsonConvert.DeserializeObject <EditLeaveDetails>(activity.Value.ToString());

                LeaveDetails leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(vacationDetails.LeaveId);

                leaveDetails.Status = LeaveStatus.Withdrawn;

                var attachment = EchoBot.ManagerViewCard(employee, leaveDetails);

                // Manger Updates.

                var conversationId = await SendNotification(context, managerId, null, attachment, leaveDetails.UpdateMessageInfo.Manager, false);

                if (!String.IsNullOrEmpty(conversationId))

                {
                    leaveDetails.UpdateMessageInfo.Manager = conversationId;
                }

                if (!String.IsNullOrEmpty(conversationId))

                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var employeeCardReply = activity.CreateReply();

                    var employeeView = EchoBot.EmployeeViewCard(employee, leaveDetails);

                    employeeCardReply.Attachments.Add(employeeView);

                    if (!string.IsNullOrEmpty(leaveDetails.UpdateMessageInfo.Employee))

                    {
                        await connector.Conversations.UpdateActivityAsync(employeeCardReply.Conversation.Id, leaveDetails.UpdateMessageInfo.Employee, employeeCardReply);
                    }
                    else

                    {
                        var reply = activity.CreateReply();

                        reply.Text = "Your leave request has been successfully withdrawn!";

                        await context.PostAsync(reply);

                        var msgToUpdate = await connector.Conversations.ReplyToActivityAsync(employeeCardReply);
                    }
                }
                else

                {
                    var reply = activity.CreateReply();

                    reply.Text = "Failed to send notification to your manger. Please try again later.";

                    await context.PostAsync(reply);
                }

                // Update DB for all the message Id realted changes

                await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
            }
        }
        public async Task <ActionResult> Create(string Emailid)
        {
            User user1 = new User()
            {
                BotConversationId = "id1", Id = "*****@*****.**", Name = "User 1"
            };
            User user2 = new User()
            {
                BotConversationId = "id2", Id = "*****@*****.**", Name = "User 2"
            };
            User user3 = new User()
            {
                BotConversationId = "id3", Id = "*****@*****.**", Name = "User 3"
            };
            Group group1 = new Group()
            {
                Id    = "GroupId1",
                Name  = "Group 1",
                Users = new List <string>()
                {
                    user1.Id, user2.Id
                }
            };
            Group group2 = new Group()
            {
                Id    = "GroupId2",
                Name  = "Group 2",
                Users = new List <string>()
                {
                    user2.Id, user3.Id
                }
            };

            Team team1 = new Team()
            {
                Id       = "Team1",
                Name     = "Team1",
                Channels = new List <Channel>()
                {
                    new Channel()
                    {
                        Id = "channel1", Name = "Channel 1"
                    },
                    new Channel()
                    {
                        Id = "channel2", Name = "Channel 2"
                    },
                    new Channel()
                    {
                        Id = "channel3", Name = "Channel 3"
                    },
                }
            };

            Team team2 = new Team()
            {
                Id       = "Team2",
                Name     = "Team2",
                Channels = new List <Channel>()
                {
                    new Channel()
                    {
                        Id = "channel1", Name = "Channel 1"
                    },
                    new Channel()
                    {
                        Id = "channel2", Name = "Channel 2"
                    },
                    new Channel()
                    {
                        Id = "channel3", Name = "Channel 3"
                    },
                }
            };

            Tenant tenant = new Tenant()
            {
                Id     = "Tenant1",
                Groups = new List <string>()
                {
                    group1.Id, group2.Id
                },
                Users = new List <string>()
                {
                    user1.Id, user2.Id, user3.Id
                },
                Teams = new List <string>()
                {
                    team1.Id, team2.Id
                }
            };

            Campaign campaignAnnouncement = new Campaign()
            {
                IsAcknowledgementRequested = true,
                IsContactAllowed           = true,
                Title    = "Giving Campaign 2018 is here",
                SubTitle = "Have you contributed to the mission?",
                Author   = new Author()
                {
                    Name = "John Doe",
                    Role = "Director of Corporate Communications",
                },
                Preview     = "The 2018 Employee Giving Campaign is officially underway! Our incredibly generous culture of employee giving is unique to Contoso, and has a long history going back to our founder and his family’s core belief and value in philanthropy. Individually and collectively, we can have an incredible impact no matter how we choose to give. We are all very fortunate and 2018 has been a good year for the company which we are all participating in. Having us live in a community with a strong social safety net benefits us all so lets reflect our participation in this year's success with participation in Give.",
                Body        = "The 2018 Employee Giving Campaign is officially underway! Our incredibly generous culture of employee giving is unique to Contoso, and has a long history going back to our founder and his family’s core belief and value in philanthropy. Individually and collectively, we can have an incredible impact no matter how we choose to give. We are all very fortunate and 2018 has been a good year for the company which we are all participating in. Having us live in a community with a strong social safety net benefits us all so lets reflect our participation in this year's success with participation in Give. I hope you will take advantage of some of the fun and impactful opportunities that our giving team has put together and I’d like to thank our VPALs John Doe and Jason Natie for all the hard work they've put into planning these events for our team. To find out more about these opportunities, look for details in Give 2018",
                ImageUrl    = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSG-vkjeuIlD-up_-VHCKgcREhFGp27lDErFkveBLQBoPZOHwMbjw",
                Sensitivity = MessageSensitivity.Information
            };

            campaignAnnouncement.Id       = "Announcement3";
            campaignAnnouncement.TenantId = tenant.Id;

            var recipients = new RecipientInfo();

            recipients.Channels.Add(new ChannelRecipient()
            {
                TeamId  = team1.Id,
                Channel = new RecipientDetails()
                {
                    Id = "channel1",
                }
            });

            recipients.Channels.Add(new ChannelRecipient()
            {
                TeamId  = team2.Id,
                Channel = new RecipientDetails()
                {
                    Id = "channel2",
                }
            });

            recipients.Groups.Add(new GroupRecipient()
            {
                GroupId = group1.Id,
                Users   = new List <RecipientDetails>()
                {
                    new RecipientDetails()
                    {
                        Id = user1.Id,
                    },
                    new RecipientDetails()
                    {
                        Id = user2.Id,
                    },
                }
            });
            campaignAnnouncement.Recipients = recipients;
            campaignAnnouncement.Status     = Status.Draft;

            // Insert
            //await DocumentDBRepository.CreateItemAsync(user1);
            //await DocumentDBRepository.CreateItemAsync(user2);

            // Udpate
            //user1.Name += "Updated";
            //await DocumentDBRepository.UpdateItemAsync(user1.EmailId, user1);

            //await DocumentDBRepository.CreateItemAsync(group1);
            //await DocumentDBRepository.CreateItemAsync(group2);

            //await DocumentDBRepository.CreateItemAsync(team1);
            //await DocumentDBRepository.CreateItemAsync(team2);

            //await DocumentDBRepository.CreateItemAsync(tenant);

            await DocumentDBRepository.CreateItemAsync(campaignAnnouncement);

            // Update announcements.
            tenant.Announcements.Add(campaignAnnouncement.Id);
            await DocumentDBRepository.UpdateItemAsync(campaignAnnouncement.Id, campaignAnnouncement);

            var allGroups = await DocumentDBRepository.GetItemsAsync <Group>(u => u.Type == nameof(Group));

            var allTeam = await DocumentDBRepository.GetItemsAsync <Team>(u => u.Type == nameof(Team));

            var allTenants = await DocumentDBRepository.GetItemsAsync <Tenant>(u => u.Type == nameof(Tenant));

            var allAnnouncements = await DocumentDBRepository.GetItemsAsync <Campaign>(u => u.Type == nameof(Campaign));

            var myTenantAnnouncements = allAnnouncements.Where(a => a.TenantId == tenant.Id);

            return(View());
        }
Пример #13
0
        /// <summary>
        /// Runs job
        /// </summary>
        /// <param name="state">state information</param>
        private async void RunJob(object state)
        {
            try
            {
                string token = await AuthenticationHelper.GetAccessTokenAsync(_configuration, _httpClientFactory);

                GraphServiceClient graphserviceClient = new GraphServiceClient(
                    new DelegateAuthenticationProvider(
                        (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

                    return(Task.FromResult(0));
                }));
                var callsInformation = await DocumentDBRepository.GetItemsAsync <CallInfo>(c => c.Status == null);

                foreach (var call in callsInformation)
                {
                    try
                    {
                        var participants = await graphserviceClient.Communications.Calls[call.CallId.ToString()].Participants
                                           .Request()
                                           .GetAsync();
                        var attendees = new List <Models.Attendee>();
                        foreach (var participant in participants.CurrentPage)
                        {
                            if (participant.Info.Identity.User != null)
                            {
                                var attendee = new Models.Attendee()
                                {
                                    DisplayName = participant.Info.Identity.User.DisplayName,
                                    AadId       = participant.Info.Identity.User.Id,
                                };
                                attendees.Add(attendee);
                            }
                        }

                        var meetingAttendees = new MeetingAttendees()
                        {
                            LogTime         = DateTime.UtcNow.ToString(),
                            CallId          = call.CallId,
                            EventId         = call.EventId,
                            ListOfAttendees = attendees
                        };
                        if (meetingAttendees.ListOfAttendees.Count > 0)
                        {
                            await DocumentDBRepository.CreateItemAsync <MeetingAttendees>(meetingAttendees);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e.Message + ' ' + e.StackTrace);

                        if (((ServiceException)e).StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            call.Status = (int?)System.Net.HttpStatusCode.NotFound;
                            await DocumentDBRepository.UpdateItemAsync(call.Id, call);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message + ' ' + e.StackTrace);
            }
        }
Пример #14
0
        /// <summary>
        /// Runs job
        /// </summary>
        /// <param name="state">state information</param>
        private async void RunJob(object state)
        {
            try
            {
                DateTime utcTimeNow = DateTime.UtcNow;
                utcTimeNow = utcTimeNow.AddSeconds(-utcTimeNow.Second);
                utcTimeNow = utcTimeNow.AddTicks(-(utcTimeNow.Ticks % TimeSpan.TicksPerSecond));

                var schedules = await DocumentDBRepository.GetItemsAsync <VirtualEvent>(e => e.IsActive == true);

                schedules.ToList();
                var currentSchedules = schedules.Where(s => s.StartTime != null && DateTime.Equals(utcTimeNow, Convert.ToDateTime(s.StartTime).AddSeconds(-Convert.ToDateTime(s.StartTime).Second).AddTicks(-(Convert.ToDateTime(s.StartTime).Ticks % TimeSpan.TicksPerSecond)))).ToList();
                foreach (var currentSchedule in currentSchedules)
                {
                    var currentEvent = await DocumentDBRepository.GetItemAsync <VirtualEvent>(currentSchedule.Id);

                    var encodedChatId = currentEvent.JoinWebUrl.Split('/')[5];
                    var chatId        = Uri.UnescapeDataString(encodedChatId);
                    var sectionName   = currentEvent.Subject + " Section ";
                    var pageName      = currentEvent.Subject + " Page " + DateTime.Now.ToShortDateString();

                    var notebookId = await _graph.CreateNoteBook(_configuration["GroupId"], currentEvent.Subject);

                    var sectionId = await _graph.CreateSection(_configuration["GroupId"], notebookId, sectionName);

                    var pageId = await _graph.CreatePage(_configuration["GroupId"], sectionId, pageName);

                    var newNotebookSectionPage = new OneNoteInfo
                    {
                        ChatId       = chatId,
                        CreatedDate  = DateTime.UtcNow.ToString(),
                        NotebookName = currentEvent.Subject,
                        NoteBookId   = notebookId,
                        SectionName  = sectionName,
                        SectionId    = sectionId,
                        PageName     = pageName,
                        PageId       = pageId,
                        EventId      = currentEvent.Id
                    };

                    await DocumentDBRepository.CreateItemAsync <OneNoteInfo>(newNotebookSectionPage);

                    var callId = await _graph.PostIncidentAsync(currentEvent.ListOfParticipants, currentEvent.JoinWebUrl);

                    if (callId != null)
                    {
                        var callInfo = new CallInfo()
                        {
                            Id          = Guid.NewGuid().ToString(),
                            CallId      = callId,
                            CreatedDate = DateTime.UtcNow.ToString(),
                            EventId     = currentSchedule.Id
                        };
                        await DocumentDBRepository.CreateItemAsync(callInfo);
                    }

                    currentEvent.IsActive = false;
                    await DocumentDBRepository.UpdateItemAsync(currentEvent.Id, currentEvent);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message + ' ' + e.StackTrace);
            }
        }
        public async Task <ActionResult> AuthCode(string userid, string signalrRef)
        {
            //Request should have a code from AAD and an id that represents the user in the data store
            if (Request["code"] == null)
            {
                return(RedirectToAction("Error", "Home", new { error = "Authorization code not passed from the authentication flow" }));
            }
            else if (String.IsNullOrEmpty(userid))
            {
                return(RedirectToAction("Error", "Home", new { error = "User reference code not passed from the authentication flow" }));
            }

            //get access token using the authorization code
            var token = await TokenHelper.GetAccessTokenWithCode(userid.ToLower(), signalrRef, Request["code"], SettingsHelper.O365UnifiedAPIResourceId);

            //get the user from the datastore
            var idString = userid.ToLower();
            var user     = DocumentDBRepository <UserModel> .GetItem("Users", i => i.id == idString);

            if (user == null)
            {
                return(RedirectToAction("Error", "Home", new { error = "User placeholder does not exist" }));
            }

            //get the user's details (name, email)
            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token.access_token);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            using (HttpResponseMessage response = await client.GetAsync(new Uri("https://graph.microsoft.com/beta/me", UriKind.Absolute)))
            {
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();

                    JObject oResponse = JObject.Parse(json);
                    user.display_name  = oResponse.SelectToken("displayName").ToString();
                    user.email_address = oResponse.SelectToken("mail").ToString();
                    user.initials      = UserController.getInititials(user.display_name, user.email_address);
                }
                else
                {
                    return(RedirectToAction("Error", "Home", new { error = "AAD Graph service call failed" }));
                }
            }

            //get the user's profile pic
            var outlookToken = await TokenHelper.GetAccessTokenWithRefreshToken(token.refresh_token, SettingsHelper.OutlookResourceId);

            client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + outlookToken.access_token);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            var url = "https://outlook.office365.com/api/beta/me/userphoto/$value";

            using (HttpResponseMessage response = await client.GetAsync(new Uri(url, UriKind.Absolute)))
            {
                if (response.IsSuccessStatusCode)
                {
                    var stream = await response.Content.ReadAsStreamAsync();

                    byte[] bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, (int)stream.Length);
                    user.picture = "data:image/jpeg;base64, " + Convert.ToBase64String(bytes);
                }
            }

            //update the user with the refresh token and other details we just acquired
            user.refresh_token = token.refresh_token;
            await DocumentDBRepository <UserModel> .UpdateItemAsync("Users", idString, user);

            //notify the client through the hub
            var hubContext = GlobalHost.ConnectionManager.GetHubContext <OAuthHub>();

            hubContext.Clients.Client(signalrRef).oAuthComplete(user);

            //return view successfully
            return(View());
        }
        public async Task SetDiscoverSomethingTwitterAsync(TwitAuthenticateResponse twitAuthResponse, string screenName, long idMax, string idLogin)
        {
            var item = await DocumentDBRepository <Login> .GetItemAsync(idLogin);

            // Busca uma lista de tweets do usuário, neste caso os 100 primeiros. Após isso, é feito por thread, pegando os 100 tweets mais antigos que estes, e assim sucessivamente
            var timelineFormat = "";
            var timelineUrl    = "";

            if (idMax > 0)
            {
                timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&max_id={1}&include_rts=0&exclude_replies=1&count=100";
                timelineUrl    = string.Format(timelineFormat, screenName, idMax);
            }
            else
            {
                timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=0&exclude_replies=1&count=100";
                timelineUrl    = string.Format(timelineFormat, screenName);
            }

            HttpWebRequest timeLineRequest      = (HttpWebRequest)WebRequest.Create(timelineUrl);
            var            timelineHeaderFormat = "{0} {1}";

            timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.TokenType, twitAuthResponse.AccessToken));
            timeLineRequest.Method = "Get";
            WebResponse timeLineResponse = timeLineRequest.GetResponse();
            var         timeLineJson     = string.Empty;

            using (timeLineResponse)
            {
                using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
                {
                    timeLineJson = reader.ReadToEnd();
                }
            }

            dynamic tweets = new JavaScriptSerializer().DeserializeObject(timeLineJson);

            int           count      = 0;
            List <string> textTweets = new List <string>();
            List <string> idTweets   = new List <string>();

            foreach (dynamic tweet in tweets)
            {
                //Joga todos os textos dos tweets dentro de uma lista, e os ids em outra
                textTweets.Add(tweet["text"]);

                long id = tweet["id"];
                idTweets.Add(id.ToString());

                count++;
            }

            //Busca token de acesso para API de Translate
            string authToken = await GetAccessTokenTranslateAsync();

            //Chama API de Tradução, traduzindo o tweet de pt para en
            string[] translates = TranslateArray(authToken, "pt", "en", textTweets.ToArray());
            string[] ids        = idTweets.ToArray();

            //Monta objeto para fazer a chamada da API de análise do texto do tweet
            KeyPhrases KeyPhrases = new KeyPhrases();

            for (int i = 0; i < translates.Length; i++)
            {
                Document document = new Document();
                document.Id       = ids[i];
                document.Language = "en";
                document.Text     = translates[i];

                KeyPhrases.Documents.Add(document);
            }

            //Chama API de Análise de Texto, para buscar as palavras chave da frase tweetada
            dynamic keyPhrasesObj = GetKeyPhrases(KeyPhrases);

            List <string> keyPhrases = new List <string>();

            foreach (var doc in keyPhrasesObj["documents"])
            {
                //Coloca num stringão todas as palavras chaves separadas por ", "
                keyPhrases.Add(string.Join(", ", doc["keyPhrases"]));
            }

            //Busca token de acesso para API de Translate
            authToken = await GetAccessTokenTranslateAsync();

            //Chama API de Tradução, agora traduzindo as palavras chave em en para pt para mostrar corretamente pro usuário
            string[] translateskeyPhrases = TranslateArray(authToken, "en", "pt", keyPhrases.ToArray());

            for (int i = 0; i < translateskeyPhrases.Length; i++)
            {
                References reference = new References();
                reference.IdTweet = ids[i];
                //tweet.TextTweet =

                foreach (string keyPhraseTranslate in translateskeyPhrases[i].Split(new[] { ", " }, StringSplitOptions.None))
                {
                    //Verifica se já tem no objeto uma palavra chave com o mesmo texto
                    if (item.KeyPhrases.Count(k => k.Text == keyPhraseTranslate) > 0)
                    {
                        //Se já existe, somente inclui uma nova referência
                        item.KeyPhrases.FirstOrDefault(k => k.Text == keyPhraseTranslate).References.Add(reference);
                    }
                    else
                    {
                        //Caso não exista, cria uma nova
                        KeyPhrase keyPhrase = new KeyPhrase();
                        keyPhrase.Text = keyPhraseTranslate;
                        keyPhrase.References.Add(reference);

                        item.KeyPhrases.Add(keyPhrase);
                    }
                }
            }

            await DocumentDBRepository <Login> .UpdateItemAsync(idLogin, item);

            //ID do último tweet retornado, para consultar os mais antigos a partir desse, na próxima vez
            var  lastTweet = tweets[count - 1];
            long id_max    = lastTweet["id"];

            //Inicia thread para ir enchendo a base do usuário com mais tweets

            /*new Thread(async () =>
             * {
             *  await SetDiscoverSomethingTwitterAsync(twitAuthResponse, screenName, id_max - 1, idLogin);
             * }).Start();*/
        }
Пример #17
0
        public override async Task <WopiResponse> PutFile(PutFileRequest putFileRequest)
        {
            WopiResponse wopiResponse = null;
            var          file         = DocumentDBRepository <DetailedFileModel> .GetItem("Files", i => i.id.ToString() == putFileRequest.ResourceId);

            // Check for null file
            if (file != null)
            {
                var inputStream = await putFileRequest.Content.ReadAsStreamAsync();

                // Ensure the file has a valid lock
                if (String.IsNullOrEmpty(file.LockValue))
                {
                    // If the file is 0 bytes, this is document creation
                    if (inputStream.Length == 0)
                    {
                        // Update the file in blob storage
                        var bytes = new byte[inputStream.Length];
                        inputStream.Read(bytes, 0, bytes.Length);
                        file.Size = bytes.Length;
                        await AzureStorageUtil.UploadFile(file.id.ToString(), file.Container, bytes);

                        // Update version
                        file.Version++;
                        await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), file);

                        // Return success 200
                        wopiResponse = putFileRequest.ResponseOK();
                    }
                    else
                    {
                        // File isn't locked...pass empty Lock in mismatch response
                        wopiResponse = putFileRequest.ResponseLockConflict(String.Empty, "File isn't locked");
                    }
                }
                else if (file.LockExpires != null && file.LockExpires < DateTime.Now)
                {
                    // File lock expired, so clear it out
                    file.LockValue   = null;
                    file.LockExpires = null;
                    await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), file);

                    // File isn't locked...pass empty Lock in mismatch response
                    wopiResponse = putFileRequest.ResponseLockConflict(String.Empty, "File isn't locked");
                }
                else if (putFileRequest.Lock != file.LockValue)
                {
                    // File lock mismatch...pass Lock in mismatch response
                    wopiResponse = putFileRequest.ResponseLockConflict(file.LockValue, "Lock mismatch");
                }
                else
                {
                    // Update the file in blob storage
                    var bytes = new byte[inputStream.Length];
                    inputStream.Read(bytes, 0, bytes.Length);
                    file.Size = bytes.Length;
                    await AzureStorageUtil.UploadFile(file.id.ToString(), file.Container, bytes);

                    // Update version
                    file.Version++;
                    await DocumentDBRepository <FileModel> .UpdateItemAsync("Files", file.id.ToString(), (FileModel)file);

                    // Return success 200
                    wopiResponse = putFileRequest.ResponseOK();
                }
            }
            else
            {
                wopiResponse = putFileRequest.ResponseNotFound();
            }
            return(wopiResponse);
        }
 public async Task <Document> Put(string productId, string id, [FromBody] Feedback value)
 {
     return(await repository.UpdateItemAsync(productId, id, value));
 }
Пример #19
0
        public static async System.Threading.Tasks.Task <string> GetAddSurveyDetailsAsync(string strFilePath)
        {
            var surveyDetailsList = new List <Question>();

            try
            {
                using (var stream = File.Open(strFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = ExcelReaderFactory.CreateReader(stream))
                    {
                        // 2. Use the AsDataSet extension method
                        var result = reader.AsDataSet();
                        var table  = result.Tables[0]; //get first table from Dataset
                        table.Rows.RemoveAt(0);        // Remvoe Excel Titles
                        int i            = 1;
                        var questionBank = new QuestionBank()
                        {
                            Id     = Guid.NewGuid().ToString(),
                            Type   = Helper.Constants.QuestionBank,
                            Active = true
                        };

                        foreach (DataRow row in table.Rows)
                        {
                            // Skip the first row...
                            Question surveyDetails = new Question();
                            surveyDetails.Id      = Guid.NewGuid().ToString();
                            surveyDetails.Title   = row[0].ToString();
                            surveyDetails.Options = row[1].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(channel => channel.Trim()).ToList();
                            if (questionBank.EmailIds == null)
                            {
                                questionBank.EmailIds = row[2].ToString().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(channel => channel.Trim()).ToList();
                            }
                            i = i + 1;
                            //surveyDetailsList.Add(surveyDetails);
                            questionBank.Questions.Add(surveyDetails);
                        }
                        var updateQuestionBank = await DocumentDBRepository.GetItemsAsync <QuestionBank>(l => l.Type.Contains(Helper.Constants.QuestionBank) && l.Active == true);

                        if (updateQuestionBank != null && updateQuestionBank.Count() > 0)
                        {
                            foreach (var updateq1 in updateQuestionBank)
                            {
                                updateq1.Active = false;
                                var InactiveQuestionBank = await DocumentDBRepository.UpdateItemAsync(updateq1.Id, updateq1);
                            }
                        }
                        var feedbackQuestionBank = await DocumentDBRepository.GetItemsAsync <FeedbackData>(l => l.Type.Contains(Helper.Constants.FeedBack) && l.Active == true);

                        if (feedbackQuestionBank != null && feedbackQuestionBank.Count() > 0)
                        {
                            foreach (var feedback in feedbackQuestionBank)
                            {
                                feedback.Active = false;
                                var InactiveFeedBack = await DocumentDBRepository.UpdateItemAsync(feedback.Id, feedback);
                            }
                        }
                        var InsertQuestionBank = await DocumentDBRepository.CreateItemAsync(questionBank);

                        return(questionBank.Id);
                        // The result of each spreadsheet is in result.Tables
                    }
                }
            }
            catch (Exception)
            {
                // Send null if exception occurred.
                surveyDetailsList = null;
            }
            return(null);
        }
        private static async Task ApproveOrRejectLeaveRequest(IDialogContext context, Activity activity, string type, Employee employee)

        {
            var managerResponse = JsonConvert.DeserializeObject <ManagerResponse>(activity.Value.ToString());

            var leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(managerResponse.LeaveId);

            var appliedByEmployee = await DocumentDBRepository.GetItemAsync <Employee>(leaveDetails.AppliedByEmailId);

            // Check the leave type and reduce in DB.

            leaveDetails.Status = type == Constants.ApproveLeave ? LeaveStatus.Approved : LeaveStatus.Rejected;

            leaveDetails.ManagerComment = managerResponse.ManagerComment;

            await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);

            var conunt = EchoBot.GetDayCount(leaveDetails);

            var employeeView = EchoBot.EmployeeViewCard(appliedByEmployee, leaveDetails);

            UpdateMessageInfo managerMessageIds = leaveDetails.UpdateMessageInfo;

            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

            var managerCardUpdate = activity.CreateReply();

            var managerView = EchoBot.ManagerViewCard(appliedByEmployee, leaveDetails);

            managerCardUpdate.Attachments.Add(managerView);

            if (!string.IsNullOrEmpty(managerMessageIds.Manager))

            {
                await connector.Conversations.UpdateActivityAsync(managerCardUpdate.Conversation.Id, managerMessageIds.Manager, managerCardUpdate);
            }

            bool isGroup = !string.IsNullOrEmpty(leaveDetails.ChannelId);

            if (!isGroup)

            {
                var messageId = await SendNotification(context, isGroup?leaveDetails.ChannelId : appliedByEmployee.UserUniqueId, null, employeeView, managerMessageIds.Employee, isGroup);  // Update card.

                var msg = $"Your {conunt} days leave has been {leaveDetails.Status.ToString()} by your manager.";

                messageId = await SendNotification(context, isGroup?leaveDetails.ChannelId : appliedByEmployee.UserUniqueId, msg, null, null, isGroup);   // Send message.

                if (string.IsNullOrEmpty(messageId))

                {
                    var reply = activity.CreateReply();

                    reply.Text = $"Failed to notify {appliedByEmployee.DisplayName}. Please try again later.";

                    await context.PostAsync(reply);
                }
            }
            else

            {
                var msg = $" - Your {conunt} days leave has been {leaveDetails.Status.ToString()} by your manager.";

                var messageId = await SendChannelNotification(context, leaveDetails.ChannelId, null, employeeView, appliedByEmployee, managerMessageIds.Employee, leaveDetails.ConversationId, false); // Update card.

                messageId = await SendChannelNotification(context, leaveDetails.ChannelId, msg, null, appliedByEmployee, null, leaveDetails.ConversationId, true);                                     // Send message.

                if (string.IsNullOrEmpty(messageId))

                {
                    var reply = activity.CreateReply();

                    reply.Text = $"Failed to notify {appliedByEmployee.DisplayName}. Please try again later.";

                    await context.PostAsync(reply);
                }
            }
        }
Пример #21
0
        public async Task <Document> Update(Skills model)
        {
            var result = await DocumentDBRepository <Skills> .UpdateItemAsync(model.SkillId, model);

            return(result);
        }
        private static async Task ApplyForLeave(IDialogContext context, Activity activity, Employee employee, string leaveCategory)

        {
            if (string.IsNullOrEmpty(employee.ManagerEmailId) && string.IsNullOrEmpty(employee.DemoManagerEmailId))

            {
                var reply = activity.CreateReply();

                reply.Text = "Please set your manager and try again.";

                reply.Attachments.Add(EchoBot.SetManagerCard());

                await context.PostAsync(reply);

                return;
            }

            var managerId = await GetManagerId(employee);

            if (managerId == null)

            {
                var reply = activity.CreateReply();

                reply.Text = "Unable to fetch your manager details. Please make sure that your manager has installed the Leave App.";

                await context.PostAsync(reply);
            }
            else

            {
                VacationDetails vacationDetails = null;

                if (activity.Name == Constants.EditLeave) // Edit request

                {
                    var editRequest = JsonConvert.DeserializeObject <EditRequest>(activity.Value.ToString());

                    vacationDetails = editRequest.data;
                }
                else
                {
                    vacationDetails = JsonConvert.DeserializeObject <VacationDetails>(activity.Value.ToString());
                }

                LeaveDetails leaveDetails;

                if (!string.IsNullOrEmpty(vacationDetails.LeaveId))

                {
                    // Edit request

                    leaveDetails = await DocumentDBRepository.GetItemAsync <LeaveDetails>(vacationDetails.LeaveId);
                }
                else

                {
                    leaveDetails = new LeaveDetails();

                    leaveDetails.LeaveId = Guid.NewGuid().ToString();
                }

                leaveDetails.AppliedByEmailId = employee.EmailId;

                leaveDetails.EmployeeComment = vacationDetails.LeaveReason;

                var channelData = context.Activity.GetChannelData <TeamsChannelData>();

                leaveDetails.ChannelId = channelData.Channel?.Id; // Set channel Data if request is coming from a channel.

                if (!string.IsNullOrEmpty(leaveDetails.ChannelId))
                {
                    leaveDetails.ConversationId = activity.Conversation.Id;
                }

                leaveDetails.StartDate = new LeaveDate()

                {
                    Date = DateTime.Parse(vacationDetails.FromDate),

                    Type = (DayType)Enum.Parse(typeof(DayType), vacationDetails.FromDuration)
                };

                leaveDetails.EndDate = new LeaveDate()

                {
                    Date = DateTime.Parse(vacationDetails.ToDate),

                    Type = (DayType)Enum.Parse(typeof(DayType), vacationDetails.ToDuration)
                };

                leaveDetails.LeaveType = (LeaveType)Enum.Parse(typeof(LeaveType), vacationDetails.LeaveType);

                leaveDetails.Status = LeaveStatus.Pending;

                leaveDetails.ManagerEmailId = employee.ManagerEmailId;// Added for easy reporting.

                switch (leaveCategory)

                {
                case Constants.ApplyForPersonalLeave:

                    leaveDetails.LeaveCategory = LeaveCategory.Personal;

                    break;

                case Constants.ApplyForSickLeave:

                    leaveDetails.LeaveCategory = LeaveCategory.Sickness;

                    break;

                case Constants.ApplyForVacation:

                    leaveDetails.LeaveCategory = LeaveCategory.Vacation;

                    break;

                case Constants.ApplyForOtherLeave:

                default:

                    leaveDetails.LeaveCategory = LeaveCategory.Other;

                    break;
                }

                if (!string.IsNullOrEmpty(vacationDetails.LeaveId))

                {
                    // Edit request

                    await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
                }
                else

                {
                    await DocumentDBRepository.CreateItemAsync(leaveDetails);
                }

                var attachment = EchoBot.ManagerViewCard(employee, leaveDetails);

                UpdateMessageInfo managerMessageIds = leaveDetails.UpdateMessageInfo;

                // Manger Updates.

                var conversationId = await SendNotification(context, managerId, null, attachment, managerMessageIds.Manager, false);

                if (!string.IsNullOrEmpty(conversationId))

                {
                    managerMessageIds.Manager = conversationId;
                }

                if (!string.IsNullOrEmpty(conversationId))

                {
                    ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                    var employeeCardReply = activity.CreateReply();

                    var employeeView = EchoBot.EmployeeViewCard(employee, leaveDetails);

                    employeeCardReply.Attachments.Add(employeeView);

                    if (!string.IsNullOrEmpty(managerMessageIds.Employee))

                    {
                        // Update existing item.

                        await connector.Conversations.UpdateActivityAsync(employeeCardReply.Conversation.Id, managerMessageIds.Employee, employeeCardReply);
                    }
                    else

                    {
                        var reply = activity.CreateReply();

                        reply.Text = "Your leave request has been successfully submitted to your manager! Please review your details below:";

                        await context.PostAsync(reply);

                        var msgToUpdate = await connector.Conversations.ReplyToActivityAsync(employeeCardReply);

                        managerMessageIds.Employee = msgToUpdate.Id;
                    }
                }
                else

                {
                    var reply = activity.CreateReply();

                    reply.Text = "Failed to send notification to your manger. Please try again later.";

                    await context.PostAsync(reply);
                }

                await DocumentDBRepository.UpdateItemAsync(leaveDetails.LeaveId, leaveDetails);
            }
        }
Пример #23
0
        public async Task <Document> Update(Department model)
        {
            var result = await DocumentDBRepository <Department> .UpdateItemAsync(model.DepartmentId, model);

            return(result);
        }
Пример #24
0
        public async Task <ActionResult> CommonTask1(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Job item = await DocumentDBRepository.GetItemAsync <Job>(id);

            if (item == null)
            {
                return(HttpNotFound());
            }

            item.StatusNote      = "";
            item.SendingFlag     = "-";
            Session["DbJobId"]   = item.Id;
            Session["NpsJobId"]  = item.NpsJobId;
            Session["MEDItemNo"] = item.MEDItemNo;
            //Temp. solution. to be fixed
            if (item.BridgeModule == "M3")
            {
                if (!(item.MEDItemNo == "MED/3.16" && item.CertType == "MED"))
                {
                    item.CertType  = "MED";
                    item.MEDItemNo = "MED/3.16";
                    await DocumentDBRepository.UpdateItemAsync <Job>(item.Id, item);
                }

                var lproduct = await DocumentDBRepository.GetItemsAsync <Product>(d => d.Tag == "Product" && d.DbJobId == id);

                if (lproduct.Count() == 0)
                {
                    Product p = new Product()
                    {
                        BridgeModule = item.BridgeModule,
                        ProdName     = item.MEDItemNo,
                        DbJobId      = item.Id,
                        PTPs         = new List <ProdTechPara>(),
                    };
                    await DocumentDBRepository.CreateItemAsync <Product>(p);

                    lproduct = await DocumentDBRepository.GetItemsAsync <Product>(d => d.Tag == "Product" && d.DbJobId == id);
                }

                ViewBag.LProduct = lproduct;

                var LAutoCertText = await DocumentDBRepository.GetItemsAsync <BLSACert>(d => d.Tag == "BLSACert" && d.BridgeModule == item.BridgeModule);

                LAutoCertText         = LAutoCertText.OrderBy(d => d.Description);
                ViewBag.LAutoCertText = LAutoCertText;
            }

            if (item.BridgeModule == "M2" && !string.IsNullOrEmpty(item.CertType) && (item.CertType == "PED" || item.CertType == "TPED"))
            {
                ViewBag.Customer = await AddCustomerInfoIfNoneAsync(item);

                var LCustomer = await DocumentDBRepository.GetItemsAsync <Customer>(d => d.Tag == "Customer" && d.CustomerId == item.CustomerId);

                ViewBag.LCustomerAddr    = LCustomer.GroupBy(x => x.Address).Select(x => x.Last()).ToList();
                ViewBag.LCustomerContact = LCustomer.GroupBy(x => x.Email).Select(x => x.Last()).ToList();

                await AddPEDProductstoJobIfNone(item.Id);
                await SetViewBags();

                return(View((string)Session["BridgeModule"] + "_Task1_PED", item));
            }

            await SetViewBags();

            return(View((string)Session["BridgeModule"] + "_Task1", item));
        }
Пример #25
0
        public async Task <Document> Update(Employee model)
        {
            var result = await DocumentDBRepository <Employee> .UpdateItemAsync(model.EmployeeId, model);

            return(result);
        }
Пример #26
0
        public async Task <ActionResult> IoraDraftPost(Job item)
        {
            await DocumentDBRepository.UpdateItemAsync <Job>(item.Id, item);

            return(Redirect(Url.Content("~/Job/CreateIora/" + item.Id)));
        }
Пример #27
0
        public async Task <Document> Update(Project model)
        {
            var result = await DocumentDBRepository <Project> .UpdateItemAsync(model.Id, model);

            return(result);
        }