private void PhotoPostCompleted(RestRequest request, RestResponse response, object userstate)
 {
     // We want to ensure we are running on our thread UI
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         if (response.StatusCode == HttpStatusCode.Created)
         {
             Deployment.Current.Dispatcher.BeginInvoke(
                 () =>
                 {
                     ToastPrompt toast = new ToastPrompt
                     {
                         Title = "ajapaik",
                         Message = "your photo was uploaded",
                     };
                     toast.Show();
                 });
         }
         else
         {
             MessageBox.Show("Error while uploading to server. Please try again later. " +
                     "If this error persists please let the program author know.");
         }
     });
 }
        /**
         * ASync callback for posting a new photo
         **/
        public void PostCompleted(RestRequest request, RestResponse response, object target)
        {
            Dispatcher.BeginInvoke(() => this.postProgress.Visibility = System.Windows.Visibility.Collapsed);
            this.isPosting = false;
            // HACK: This is kind of hacky...
            Dispatcher.BeginInvoke(() => ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show("Photo Posted Successfully!");
                    this.captionTextbox.IsEnabled = true;

                    // Reset photo and caption
                    this.hasDefaultText = true;
                    this.captionTextbox.Text = "Enter a Caption...";
                    this.captionTextbox.TextAlignment = TextAlignment.Center;
                    this.captionTextbox.Foreground = this.Resources["InactiveTextBrush"] as Brush;

                    this.photo = null;
                    this.photoPreview.Source = new BitmapImage(new Uri("/Images/photo_icon.png", UriKind.Relative));
                    this.photoPreview.Stretch = Stretch.None;
                    this.photoPreview.SetValue(Canvas.MarginProperty, new Thickness(9, 69, 6, 0));
                });
            }
            else
            {
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show("Error Posting Photo: " + response.Content);
                    this.captionTextbox.IsEnabled = true; // Re-enable the text box
                });
            }
        }
        private void searchCallback(RestRequest request, RestResponse response, object sender)
        {
            XmlReader rdr = XmlReader.Create(response.ContentStream);
            while (!rdr.EOF)
            {
                if (rdr.ReadToFollowing("exercise"))
                {
                    SearchedExercise exercise = new SearchedExercise();
                    rdr.ReadToFollowing("id");
                    exercise.id = rdr.ReadElementContentAsInt();
                    rdr.ReadToFollowing("name");
                    exercise.Name = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-description");
                    exercise.Description = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-type");
                    exercise.exercise_type = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-video-url");
                    exercise.exercise_video_url = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-picture-url");
                    exercise.PictureUrl = rdr.ReadElementContentAsString();
                    rdr.ReadToFollowing("exercise-order");
                    if (!rdr.MoveToAttribute("nil"))
                        exercise.exercise_order = rdr.ReadElementContentAsInt();
                    else
                        exercise.exercise_order = 0;

                    exercises.Add(exercise);
                }
            }

            OnSearchComplete();
        }
示例#4
0
 private void postFinished(RestRequest request, Hammock.RestResponse response, object obj)
 {
     Dispatcher.BeginInvoke(() =>
     {
         //MessageBox.Show(AppResources.offer_ThankYou);
         NavigationService.GoBack();
     });
 }
        private void EndGetRequestUrl(RestRequest request, RestResponse response, object userState)
        {
            var r = new Regex("oauth_token=([^&.]*)&oauth_token_secret=([^&.]*)");
            Match match = r.Match(response.Content);
            ((OAuthCredentials)Credentials).Token = match.Groups[1].Value;
            ((OAuthCredentials)Credentials).TokenSecret = match.Groups[2].Value;

            RequestUrlCallback(request, response, String.Format("{0}{1}?{2}", OAuthBase, TokenAuthUrl, response.Content));
        }
        /**
         * Called when we finally need the access token!
         **/
        public void AccessTokenCallback(RestRequest request, RestResponse response, object target)
        {
            string queryString = response.Content;

            // Get the FINAL tokens
            userCredentials.OAuthToken = Common.GetValueFromQueryString(queryString, "oauth_token");
            userCredentials.OAuthTokenSecret = Common.GetValueFromQueryString(queryString, "oauth_token_secret");

            Dispatcher.BeginInvoke(() => this.oAuthClearButton.Visibility = System.Windows.Visibility.Visible);
        }
示例#7
0
 public static void GetFriendsCallback(RestRequest request, RestResponse<List<Friend>> response, object userState)
 {
     if (response.StatusCode == HttpStatusCode.OK)
     {
         List<Friend> list = response.ContentEntity;
         friendscallback.Invoke(null, new FriendsListEventArgs() { Friends = list });
     }
     else
     {
         friendscallback.Invoke(null, new FriendsListEventArgs() { Friends = null, Error = new WebException("Communication Error!") });
     }
 }
示例#8
0
        protected void DoRequestCallback(RestRequest rrqRequest, RestResponse rrsResponse, object objUserState)
        {
            try
            {
                //StreamWriter swWriter = new StreamWriter("C:/Users/le grand fromage/Desktop/tweets.json", true, Encoding.UTF8);
                //StreamReader srReader = new StreamReader(rrsResponse.ContentStream, Encoding.UTF8);
                //swWriter.WriteLine(srReader.ReadToEnd());
                //swWriter.Close();
                //return;

                JsonDocument jsDoc = JsonParser.GetParser().ParseStream(new StreamReader(rrsResponse.ContentStream, Encoding.UTF8));
                APIReturn aprReturn = (APIReturn)objUserState;
                object objToReturn = null;
                string sErrorMessage = "";
                APICallbackArgs acArgs;

                if (jsDoc.Root.IsNode() && jsDoc.Root.ToNode().ContainsKey("error"))
                    sErrorMessage = jsDoc.Root.ToNode()["error"].ToString();
                else if (rrsResponse.InnerException != null)
                    sErrorMessage = rrsResponse.InnerException.Message;

                if (aprReturn.ReturnType != null)
                {
                    if (jsDoc.Root.IsList())
                    {
                        //if the return type is a generic list...
                        if (aprReturn.ReturnType.Name == "List`1")
                        {
                            //get an instance of the list<generic> that will have generics added to it and eventually be returned via the callback
                            //get the type of the generic (because we'll need to make specific instances of him later)
                            objToReturn = System.Activator.CreateInstance(aprReturn.ReturnType);
                            Type tListObjType = aprReturn.ReturnType.GetGenericArguments()[0];

                            //dynamically invoke the Add() method of the list
                            //what's being added: a newly minted instance of the generic class plus data via the constructor
                            foreach (JsonObject joCur in jsDoc.Root.ToList())
                                aprReturn.ReturnType.GetMethod("Add").Invoke(objToReturn, new Object[] { System.Activator.CreateInstance(tListObjType, joCur.ToNode()) });
                        }
                        else
                            objToReturn = System.Activator.CreateInstance(aprReturn.ReturnType, jsDoc.Root.ToList());
                    }
                    else if (jsDoc.Root.IsNode())
                        objToReturn = System.Activator.CreateInstance(aprReturn.ReturnType, jsDoc.Root.ToNode());
                }

                acArgs = new APICallbackArgs(rrsResponse.StatusCode == HttpStatusCode.OK, sErrorMessage, objToReturn);
                aprReturn.SynchronizeInvoke(new object[] { acArgs });  //synchronously invoke the return callback
            }
            catch(Exception e)
            {
                MessageBox.Show("An unknown Twitter API error has occurred (basic).", "API Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
示例#9
0
        private void DoRequestCallback(RestRequest rrqRequest, RestResponse rrsResponse, object objUserState)
        {
            RestResponseHash rrhResponse = new RestResponseHash(rrsResponse);
            APIReturn aprReturn = (APIReturn)objUserState;
            OAuthCredentials oaCredentials = (OAuthCredentials)aprReturn.CallbackArg;
            string sErrorMessage = "";

            if (rrsResponse.InnerException != null)
                sErrorMessage = rrsResponse.InnerException.Message;

            APICallbackArgs acArgs = new APICallbackArgs(rrsResponse.StatusCode == HttpStatusCode.OK, sErrorMessage, new OAuthResponseObject(rrhResponse, oaCredentials));
            aprReturn.SynchronizeInvoke(new object[] { acArgs });
        }
示例#10
0
        void uploadCompleted(RestRequest request, RestResponse response, object userstate)
        {
            Action<RestResponse, string> callback = (Action<RestResponse, string>)userstate;
            string url = "";

            if (response.StatusCode == HttpStatusCode.OK)
            {
                XDocument doc = XDocument.Parse(response.Content);
                XElement node = doc.Descendants("url").FirstOrDefault();
                url = node.Value;
            }

            if (callback != null)
                callback(response, url);
        }
        private void TwitterRequestTokenCompleted(RestRequest request, RestResponse response, object userstate)
        {
            _oAuthToken = GetQueryParameter(response.Content, "oauth_token");
            _oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");

            var authorizeUrl = Constants.AuthorizeUri + "?oauth_token=" + _oAuthToken;
            if (String.IsNullOrEmpty(_oAuthToken) || String.IsNullOrEmpty(_oAuthTokenSecret))
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show("error calling twitter"));
                return;
            }
            Dispatcher.BeginInvoke(() => 
            {
                BrowserControl.Navigate(new Uri(authorizeUrl));
            });
        }
示例#12
0
        public BitlyLogin EndGetAccessToken(RestResponse response)
        {
            try
            {
                var parameters = ParameterHelper.ExtractQueryParameters(response.Content);

                return new BitlyLogin
                           {
                               access_token = parameters["access_token"],
                               apiKey = parameters["apiKey"],
                               login = parameters["login"]
                           };
            }
            catch(Exception ex)
            {
                return new MissingBitlyLogin();
            }
        }
示例#13
0
 protected ReadLaterResult GetResult(RestResponse response)
 {
     switch ((int)response.StatusCode)
     {
         case 200:
         case 201:
             return ReadLaterResult.Accepted;
         case 400:
             return ReadLaterResult.BadRequest;
         case 401:
             return ReadLaterResult.AuthenticationFail;
         case 403:
             return ReadLaterResult.RateLimitExceeded;
         case 503:
             return ReadLaterResult.InternalError;
         default:
             return ReadLaterResult.Unknown;
     }
 }
示例#14
0
 protected void CredentialsCallback(RestRequest request, RestResponse response, object userState)
 {
     Action<bool, ReadLaterResponse> action = userState as Action<bool, ReadLaterResponse>;
     if (action != null)
         action.Invoke(response.StatusCode == HttpStatusCode.OK, new ReadLaterResponse { ResponseBase = response, Result = GetResult(response) });
 }
示例#15
0
        private void StreamCallback(RestRequest request, RestResponse response, object userState)
        {
            try
            {
                var deserialisedResponse = StatusProcessor.Process(response.Content);
                if (deserialisedResponse == null)
                    return;

                if (Callback != null)
                    Callback(request, response, deserialisedResponse);
                else if (CallbackNoRequest != null)
                    CallbackNoRequest(response, deserialisedResponse);
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error streaming: " + ex.Message + " with content '" + response.Content.Trim() + "' END");
            }
        }
示例#16
0
        protected void AddUrlCallback(RestRequest request, RestResponse response, object userState)
        {
            Action<ReadLaterResponse> action = userState as Action<ReadLaterResponse>;

            if (action != null)
                action.Invoke(new ReadLaterResponse { ResponseBase = response, Result = GetResult(response) });
        }
 public void ExecuteWith(RestClient client)
 {
     this.response = client.Request(this.request);
     StatusCode = response.StatusCode;
     if (response.InnerException != null) throw response.InnerException;
     if (response.StatusCode != System.Net.HttpStatusCode.OK)
         throw new InvalidOperationException(String.Format("Server returned {0}: {1}, {2}", response.StatusCode, response.StatusDescription, response.Content));
 }
示例#18
0
        private void SyncTasklistAfterResponse(string tasklistId, ResultCode resultCode, RestResponse response)
        {
            string result = response.Content;
            List<Dictionary<string, string>> responseArray = (List<Dictionary<string, string>>)result.ToJSONObject();

            string newTasklistId = null;
            for (int i = 0; i < responseArray.Count; i++)
            {
                Dictionary<string, string> dict = responseArray[i];
                string oldId = dict["OldId"];
                string newId = dict["NewId"];

                this._console.log(string.Format("任务列表旧值ID:{0}, 变为新值ID:{1}", oldId, newId));

                this._tasklistRepository.UpdateTasklistByNewId(oldId, newId);

                if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
                {
                    string username = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];

                    if (!string.IsNullOrEmpty(username))
                    {
                        this._taskRepository.UpdateTasklistIdByNewId(oldId, newId);
                        this._taskIdxRepository.UpdateTasklistIdByNewId(oldId, newId);
                        this._changeLogRepository.UpdateTasklistIdByNewId(oldId, newId);

                        newTasklistId = newId;
                    }
                }
            }

            if (string.IsNullOrEmpty(tasklistId))
            {
                this._tasklistService.GetTasklists((response1, userState1) =>
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            result = response1.Content;
                            Dictionary<string, string> tasklistsDict = (Dictionary<string, string>)result.ToJSONObject();

                            //删除当前账户所有列表
                            this._tasklistRepository.DeleteAll();

                            List<Tasklist> tasklists = new List<Tasklist>();
                            foreach (string key in tasklistsDict.Keys)
                            {
                                string value = tasklistsDict[key];

                                Tasklist tasklist = new Tasklist();
                                tasklist.TasklistId = key;
                                tasklist.Name = value;
                                tasklist.ListType = "personal";
                                tasklist.Editable = true;
                                if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
                                {
                                    string username = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];
                                    tasklist.AccountId = username;
                                }
                                else
                                {
                                    tasklist.AccountId = "";
                                }
                                tasklists.Add(tasklist);
                            }
                            Tasklist defaultTasklist = new Tasklist();
                            defaultTasklist.TasklistId = "0";
                            defaultTasklist.Name = "默认列表";
                            defaultTasklist.ListType = "personal";
                            defaultTasklist.Editable = true;
                            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
                            {
                                string username = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];
                                defaultTasklist.AccountId = username;
                            }
                            else
                            {
                                defaultTasklist.AccountId = "";
                            }
                            tasklists.Add(defaultTasklist);

                            this._tasklistRepository.AddTasklists(tasklists);

                            if (tasklists.Count == 0)
                            {
                                resultCode.Status = true;
                            }
                            else
                            {
                                foreach (var tasklist in tasklists)
                                {
                                    //HACK:Fetch模式不支持同步变更
                                    if (tasklist.TasklistId.Equals("github")
                                        || tasklist.TasklistId.Equals("ifree")
                                        || tasklist.TasklistId.Equals("wf"))
                                    {
                                        Dictionary<string, object> userState = new Dictionary<string, object>();
                                        userState.Add("tasklistId", tasklist.TasklistId);
                                        this._taskService.GetTasks(tasklist.TasklistId
                                            , (response2, userState2) =>
                                                {
                                                    if (response2.StatusCode == HttpStatusCode.OK)
                                                    {
                                                        Dictionary<string, object> dict = (Dictionary<string, object>)userState2;
                                                        this.GetTasksAfterResponse(dict["tasklistId"].ToString(), resultCode, response2);
                                                    }
                                                    else
                                                    {
                                                        this.DispatchCommandResult(response2);
                                                    }
                                                }
                                            , exception =>
                                                {
                                                    this.DispatchCommandResult(exception);
                                                }
                                            , userState);
                                    }
                                    else
                                    {
                                        Dictionary<string, object> userState = new Dictionary<string, object>();
                                        userState.Add("tasklistId", tasklist.TasklistId);
                                        this._taskService.SyncTasks(tasklist.TasklistId
                                            , (response2, userState2) =>
                                                {
                                                    if (response2.StatusCode == HttpStatusCode.OK)
                                                    {
                                                        Dictionary<string, object> dict = (Dictionary<string, object>)userState2;
                                                        this.SyncTasksAfterResponse(dict["tasklistId"].ToString(), resultCode, response2);
                                                    }
                                                    else
                                                    {
                                                        this.DispatchCommandResult(response2);
                                                    }
                                                }
                                            , exception =>
                                                {
                                                    this.DispatchCommandResult(exception);
                                                }
                                            , userState);
                                    }
                                    resultCode.Status = true;
                                }
                            }
                        }
                        else
                        {
                            this.DispatchCommandResult(response1);
                        }
                    }
                , exception =>
                    {
                        this.DispatchCommandResult(exception);
                    }
                , new Dictionary<string, object>());
            }
        }
示例#19
0
 private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
 {
     ;
 }
示例#20
0
        private void GetTasksAfterResponse(string tasklistId, ResultCode resultCode, RestResponse response)
        {
            string result = response.Content;

            JObject dict = (JObject)result.ToJSONObject();
            string tasklist_editableString = dict["Editable"].Value<string>();

            this._tasklistRepository.UpdateEditable(tasklist_editableString.ToLower().Equals("true") ? 1 : 0, tasklistId);
            this._taskRepository.DeleteAll(tasklistId);
            this._taskIdxRepository.DeleteAll(tasklistId);

            JArray tasksArray = (JArray)dict["List"];
            JArray taskIdxsArray = (JArray)dict["Sorts"];

            List<Task> tasks = new List<Task>();
            for (int i = 0; i < tasksArray.Count; i++)
            {
                JToken taskDict = tasksArray[i];
                string taskId = taskDict["ID"].Value<string>();
                string subject = taskDict["Subject"].Value<string>();
                string body = taskDict["Body"].Value<string>();
                bool isCompleted = taskDict["IsCompleted"].Value<bool>();
                string priority = taskDict["Priority"].Value<string>();
                bool editable = taskDict["Editable"].Value<bool>();
                string dueTimeString = taskDict["DueTime"].Value<string>();

                Task task = new Task();
                task.Subject = subject;
                DateTime currentDate = DateTime.Now;
                task.CreateDate = currentDate;
                task.LastUpdateDate = currentDate;
                task.Body = body;
                task.IsPublic = true;
                task.Status = isCompleted ? 1 : 0;
                task.Priority = priority;
                task.TaskId = taskId;
                DateTime dueTime;
                if (DateTime.TryParse(dueTimeString, out dueTime))
                {
                    task.DueDate = dueTime;
                }

                task.Editable = editable;
                task.TasklistId = tasklistId;
                if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
                {
                    string username = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];
                    task.AccountId = username;
                }
                else
                {
                    task.AccountId = "";
                }
                tasks.Add(task);
            }
            this._taskRepository.AddTasks(tasks);

            List<TaskIdx> taskIdxs = new List<TaskIdx>();
            for (int i = 0; i < taskIdxsArray.Count; i++)
            {
                JToken taskIdxDict = taskIdxsArray[i];
                string by = taskIdxDict["By"].Value<string>();
                string taskIdxKey = taskIdxDict["Key"].Value<string>();
                string name = taskIdxDict["Name"].Value<string>();

                JArray indexsArray = (JArray)taskIdxDict["Indexs"];
                string indexes = indexsArray.ToJSONString();

                TaskIdx taskIdx = new TaskIdx();
                taskIdx.By = by;
                taskIdx.Key = taskIdxKey;
                taskIdx.Name = name;
                taskIdx.Indexes = indexes;
                taskIdx.TasklistId = tasklistId;
                if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
                {
                    string username = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];
                    taskIdx.AccountId = username;
                }
                else
                {
                    taskIdx.AccountId = "";
                }
                taskIdxs.Add(taskIdx);
            }
            this._taskIdxRepository.AddTaskIdxs(taskIdxs);

            resultCode.Status = true;

            this.DispatchCommandResult(resultCode);
        }
示例#21
0
        private string SyncTasklistAfterResponse(string tasklistId, Tasklist tasklist, ResultCode resultCode, RestResponse response)
        {
            string result = response.Content;

            this._tasklistRepository.AdjustWithNewId(tasklist.TasklistId, result);

            this._console.log(string.Format("任务列表旧值ID:{0} 变为新值ID:{1}", tasklist.TasklistId, result));

            string newTasklistId = null;
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
            {
                string username = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];

                if (!string.IsNullOrEmpty(username))
                {
                    this._taskRepository.UpdateTasklistIdByNewId(tasklist.TasklistId, result);
                    this._taskIdxRepository.UpdateTasklistIdByNewId(tasklist.TasklistId, result);
                    this._changeLogRepository.UpdateTasklistIdByNewId(tasklist.TasklistId, result);

                    newTasklistId = result;
                }
            }

            return newTasklistId;
        }
示例#22
0
 private void DispatchCommandResult(RestResponse response)
 {
     ResultCode resultCode = new ResultCode();
     resultCode.Status = false;
     resultCode.Message = string.Format("错误验证码:{0},错误消息:{1}"
         , response.StatusCode
         , response.StatusDescription);
     DispatchCommandResult(new PluginResult(PluginResult.Status.OK, resultCode));
 }
示例#23
0
        private void GetTasklistsAfterResponse(string tasklistId, ResultCode resultCode, RestResponse response)
        {
            string result = response.Content;
            Dictionary<string, string> tasklistDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
            //删除当前账户的所有任务列表
            this._tasklistRepository.DeleteAll();

            List<Tasklist> tasklists = new List<Tasklist>();
            foreach (var key in tasklistDict.Keys)
            {
                string value = tasklistDict[key];

                Tasklist tasklist = new Tasklist();
                tasklist.TasklistId = key;
                tasklist.Name = value;
                tasklist.ListType = "personal";
                tasklist.Editable = true;
                if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
                {
                    tasklist.AccountId = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];
                }
                else
                {
                    tasklist.AccountId = "";
                }
                tasklists.Add(tasklist);
            }
            Tasklist defaultTasklist = new Tasklist();
            defaultTasklist.TasklistId = "0";
            defaultTasklist.Name = "默认列表";
            defaultTasklist.ListType = "personal";
            defaultTasklist.Editable = true;
            if (IsolatedStorageSettings.ApplicationSettings.Contains(Constant.USERNAME_KEY))
            {
                defaultTasklist.AccountId = (string)IsolatedStorageSettings.ApplicationSettings[Constant.USERNAME_KEY];
            }
            else
            {
                defaultTasklist.AccountId = "";
            }
            tasklists.Add(defaultTasklist);

            this._tasklistRepository.AddTasklists(tasklists);

            if (tasklists.Count == 0)
            {
                resultCode.Status = true;

                this.DispatchCommandResult(resultCode);
            }
            else
            {
                foreach(Tasklist tempTasklist in tasklists)
                {
                    //HACK:Fetch模式不支持同步变更
                    if(tempTasklist.TasklistId.Equals("github")
                            || tempTasklist.TasklistId.Equals("ifree")
                            || tempTasklist.TasklistId.Equals("wf"))
                    {
                        Dictionary<string, object> userState = new Dictionary<string, object>();
                        userState.Add("tasklistId", tempTasklist.TasklistId);

                        this._taskService.GetTasks(tempTasklist.TasklistId
                            , (response1, userState1) =>
                            {
                                if (response1.StatusCode == HttpStatusCode.OK)
                                {
                                    Dictionary<string, object> dict = (Dictionary<string, object>)userState1;

                                    this.GetTasksAfterResponse(dict["tasklistId"].ToString(), resultCode, response1);
                                }
                                else
                                {
                                    this.DispatchCommandResult(response1);
                                }
                            }
                            , exception =>
                            {
                                this.DispatchCommandResult(exception);
                            }
                            , userState);
                    }
                    else
                    {
                        this._console.log("tasklistId:" + tempTasklist.TasklistId);
                        Dictionary<string, object> userState = new Dictionary<string, object>();
                        userState.Add("tasklistId", tempTasklist.TasklistId);

                        this._taskService.SyncTasks(tempTasklist.TasklistId
                            , (response1, userState1) =>
                            {
                                if (response1.StatusCode == HttpStatusCode.OK)
                                {
                                    Dictionary<string, object> dict = (Dictionary<string, object>)userState1;

                                    this.SyncTasksAfterResponse(dict["tasklistId"].ToString(), resultCode, response1);
                                }
                                else
                                {
                                    this.DispatchCommandResult(response1);
                                }
                            }
                            , exception =>
                            {
                                this.DispatchCommandResult(exception);
                            }
                            , userState);

                    }
                }
                resultCode.Status = true;

                this.DispatchCommandResult(resultCode);
            }
        }
        private void HandleSearchResults(RestRequest request, RestResponse response, object obj)
        {
            var updates = new List<Tweet>();

            if (obj is List<SearchTweet>)
            {
                var results = (List<SearchTweet>) obj;

                foreach (SearchTweet s in results)
                {
                    try
                    {
                        var c = _contactsRepository.GetOrCreate<TwitterContact>(s.ContactName, Parent.Source);
                        c.SetContactImage(new Uri(s.ContactImage), DateTime.Parse(s.CreatedDate.ToString()));

                        var t = new Tweet
                                    {
                                        ID = s.Id.ToString(),
                                        Contact = c,
                                        Microblog = Parent,
                                        Text = WebUtility.HtmlDecode(s.Text),
                                        Time = DateTime.Parse(s.CreatedDate.ToString()).ToLocalTime(),
                                        SourceUri = s.Source.StripHTML().GetSourceURL(),
                                        Source = s.Source.StripHTML().GetSourceText(),
                                        Types = new List<UpdateType> {new SearchUpdate()}
                                    };

                        t.AddParent(Parent);
                        updates.Add(t);
                    }
                    catch (Exception ex)
                    {
                        CompositionManager.Get<IExceptionReporter>().ReportHandledException(ex);
                    }
                }
            }

            if (updates.Any())
                _statusUpdate.Send(updates);
        }
示例#25
0
        private void SyncTasksAfterResponse(string tasklistId, ResultCode resultCode, RestResponse response)
        {
            string result = response.Content;
            JArray array = (JArray)result.ToJSONObject();
            //List<object> array = (List<object>)result.ToJSONObject();
            if (array.Count > 0)
            {
                for (int i = 0; i < array.Count; i++)
                {
                    JToken dict = array[i];
                    string oldId = dict["OldId"].Value<string>();
                    string newId = dict["NewId"].Value<string>();

                    this._console.log(string.Format("任务旧值ID:{0} 变为新值ID:{1}", oldId, newId));

                    this._taskRepository.UpdateTaskIdByNewId(oldId, newId, tasklistId);
                    this._taskIdxRepository.UpdateTaskIdxByNewId(oldId, newId, tasklistId);
                }
            }

            this._changeLogRepository.UpdateAllToSend(tasklistId);

            Dictionary<string, object> userState = new Dictionary<string, object>();
            userState.Add("tasklistId", tasklistId);

            this._taskService.GetTasks(tasklistId
                , (response1, userState1) =>
                    {
                        if (response1.StatusCode == HttpStatusCode.OK)
                        {
                            Dictionary<string, object> dict = (Dictionary<string, object>)userState1;
                            this.GetTasksAfterResponse(dict["tasklistId"].ToString(), resultCode, response1);
                        }
                        else
                        {
                            this.DispatchCommandResult(response1);
                        }
                    }
                , exception =>
                    {
                        this.DispatchCommandResult(exception);
                    }
                , userState);
        }
示例#26
0
        private void TwitterGetFavoritesCompleted(RestRequest request, RestResponse response, object userstate)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Helper.ShowMessage(String.Format("Twitter Error: {0}", response.StatusCode));
                return;
            }

            var xmlElement = XElement.Parse(response.Content);
            var list = (from item in xmlElement.Elements("status")
                        select new ItemViewModel
                        {
                            UserName = GetChildElementValue(item, "user", "screen_name"),
                            DisplayUserName = GetChildElementValue(item, "user", "name"),
                            TweetText = (string)item.Element("text"),
                            CreatedDate = GetCreatedDate((string)item.Element("created_at")),
                            Image = GetChildElementValue(item, "user", "profile_image_url"),
                            Id = (long)item.Element("id"),
                            NewTweet = true,
                            Source = (string)item.Element("source"),
                        }).ToList();

            if (list.Count > 0)
            {
                Helper.SaveSetting(Constants.FavoritesFileName, list);
            }

            if (LoadedCompleteEvent != null)
                LoadedCompleteEvent(this, EventArgs.Empty);
        }
示例#27
0
        private void TwitterGetStatusesCompleted(RestRequest request, RestResponse response, object userstate)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                Helper.ShowMessage(String.Format("Twitter Error: {0}", response.StatusCode));
                return;
            }

            var xmlElement = XElement.Parse(response.Content);
            var statusList = (from item in xmlElement.Elements("status")
                              select new ItemViewModel
                              {
                                  UserName = GetChildElementValue(item, "user", "screen_name"),
                                  DisplayUserName = GetChildElementValue(item, "user", "name"),
                                  TweetText = (string)item.Element("text"),
                                  CreatedDate = GetCreatedDate((string)item.Element("created_at")),
                                  Image = GetChildElementValue(item, "user", "profile_image_url"),
                                  Id = (long)item.Element("id"),
                                  NewTweet = true,
                                  Source = (string)item.Element("source"),
                              }).ToList();

            // Load cached file and add them but only up to 200 old items
            var oldItems = Helper.LoadSetting<List<ItemViewModel>>(Constants.StatusesFileName);
            if (oldItems != null)
            {
                var maxCount = (oldItems.Count < 200) ? oldItems.Count : 200;
                for (var i = 0; i < maxCount; i++)
                {
                    oldItems[i].NewTweet = false;
                    statusList.Add(oldItems[i]);
                }
            }

            Helper.SaveSetting(Constants.StatusesFileName, statusList);

            if (LoadedCompleteEvent != null)
                LoadedCompleteEvent(this, EventArgs.Empty);
        }
示例#28
0
 private void NewTweetCompleted(RestRequest request, RestResponse response, object userstate)
 {
     // We want to ensure we are running on our thread UI
     Deployment.Current.Dispatcher.BeginInvoke(() =>
     {
         if (response.StatusCode == HttpStatusCode.OK)
         {
             if (TweetCompletedEvent != null)
                 TweetCompletedEvent(this, EventArgs.Empty);
         }
         else
         {
             if (ErrorEvent != null)
                 ErrorEvent(this, EventArgs.Empty);
         }
     });
 }
示例#29
0
        private void FavoriteItemCompleted(RestRequest request, RestResponse response, object userstate)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Helper.ShowMessage(String.Format("Error calling Twitter : {0}", response.StatusCode));
                    if (ErrorEvent != null)
                        ErrorEvent(this, EventArgs.Empty);
                    return;
                }

                if (FavoriteCompletedEvent != null)
                    FavoriteCompletedEvent(this, EventArgs.Empty);
            });
        }
        private void RequestAccessTokenCompleted(RestRequest request, RestResponse response, object userstate)
        {
            var twitteruser = new TwitterAccess
            {
                AccessToken = GetQueryParameter(response.Content, "oauth_token"),
                AccessTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"),
                UserId = GetQueryParameter(response.Content, "user_id"),
                ScreenName = GetQueryParameter(response.Content, "screen_name")
            };

            uca = new UserConnectedAccount();
            uca.AccountName  = "Twitter";
            uca.ClientSecret = twitteruser.AccessTokenSecret;
            uca.ClientToken  = twitteruser.AccessToken;

            MainPage.TwitterSecret = uca.ClientSecret;
            MainPage.TwitterToken = uca.ClientToken;

            if (String.IsNullOrEmpty(twitteruser.AccessToken) || String.IsNullOrEmpty(twitteruser.AccessTokenSecret))
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
                return;
            }

            // authenticate with user's credentials
            App.MetrocamService.AuthenticateCompleted += new RequestCompletedEventHandler(client_AuthenticateCompleted);
            App.MetrocamService.Authenticate(Settings.username.Value, Settings.password.Value);
        }
        private void RequestAccessTokenCompleted(RestRequest request, RestResponse response, object userstate)
        {
            var twitteruser = new TwitterAccess
            {
                AccessToken = GetQueryParameter(response.Content, "oauth_token"),
                AccessTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"),
                UserId = GetQueryParameter(response.Content, "user_id"),
                ScreenName = GetQueryParameter(response.Content, "screen_name")
            };

            if (String.IsNullOrEmpty(twitteruser.AccessToken) || String.IsNullOrEmpty(twitteruser.AccessTokenSecret))
            {
                Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
                return;
            }

            Helper.SaveSetting(Constants.TwitterAccess, twitteruser);

            Dispatcher.BeginInvoke(() =>
            {
                if (NavigationService.CanGoBack)
                {
                    NavigationService.GoBack();
                }
                else
                {
                    NavigationService.Navigate(new Uri("/Pages/MainPage.xaml", UriKind.Relative));
                }
            });
        }
示例#32
-1
 private void PostTweetRequestCallback(RestRequest request, RestResponse response, object obj)
 {
     if (response.StatusCode == System.Net.HttpStatusCode.OK)
     {
         //Success code
     }
 }