/// <summary> /// Executes an SQL statement that returns a single row as an Object of the type of /// the resultObject passed in as a parameter. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="resultObject">The result object.</param> /// <returns>The object</returns> public T ExecuteQueryForObject <T>(ISession session, object parameterObject, T resultObject) { // this doesn't need to be in its own RunQueryForCachedObject method because the class is sealed and can't be called by anyone else RequestRunner <T> requestRunner = delegate(RequestScope requestScope, ISession session2, object parameter, CacheKey cacheKey, out bool cacheHit) { T obj; cacheHit = false; object cacheObjet = Statement.CacheModel[cacheKey]; // check if this query has alreay been run if (cacheObjet is T) { cacheHit = true; obj = (T)cacheObjet; } else if (cacheObjet == CacheModel.NULL_OBJECT) { // convert the marker object back into a null value cacheHit = true; obj = default(T); } else //if ((object)obj == null) { obj = mappedStatement.RunQueryForObject(requestScope, session, parameter, resultObject); Statement.CacheModel[cacheKey] = obj; } return(obj); }; return(CachingStatementExecute(PreSelectEventKey, PostSelectEventKey, session, parameterObject, "ExecuteQueryForObject", requestRunner)); }
public async Task IsolatedRequestsWaitForPrecedingReentrantsToClearOff() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); long callCount = 0; requests.PerformAndForget(async() => { Interlocked.Increment(ref callCount); await Task.Delay(100); Interlocked.Decrement(ref callCount); }, RequestMode.Reentrant); await Task.Delay(15); bool clashed = await requests.Perform(() => { var c = Interlocked.Read(ref callCount); return(Task.FromResult(c > 0)); }, RequestMode.Isolated); await requests.WhenIdle(); exceptions.RethrowAll(); Assert.That(clashed, Is.False); }
/// <summary> /// Loads group's posts /// </summary> /// <param name="options"><see cref="LinkedInGetGroupPostsOptions"/> object representing posts retrieval options</param> /// <returns>Request result</returns> /// <remarks>This is synchronous operation, i.e. the current thread will be suspended until it finishes to load all posts. If you want to load group's posts asynchronously, consider to use <see cref="LinkedInClient.GetGroupPosts"/> function instead</remarks> public LinkedInResponse <bool> LoadPosts(LinkedInGetGroupPostsOptions options) { try { if (_Posts == null) { _Posts = new List <LinkedInGroupPost>(); } else { _Posts.Clear(); } options.GroupId = Id; _Posts.AddRange(RequestRunner.GetGroupPosts(options)); return(new LinkedInResponse <bool>(true, LinkedInResponseStatus.OK, null)); } catch (WebException wex) { return(Utils.GetResponse(false, wex, null)); } catch (Exception ex) { return(new LinkedInResponse <bool>(false, LinkedInResponseStatus.OtherException, null, ex)); } }
/// <summary> /// Sends invitation to current member /// </summary> /// <param name="subject">Invitation subject</param> /// <param name="body">Invitation body</param> /// <returns>Value containing true or false, depending on operation success, and response status</returns> /// <exception cref="LinkedInMissingParameterException">Thrown when some of the following is missing: subject, body, <see cref="ApiStandardProfileRquest"/> property or ApiStandardProfileRquest headers</exception> public LinkedInResponse <bool> SendInvitation(string subject, string body) { if (string.IsNullOrEmpty(subject)) { throw new LinkedInMissingParameterException("Invitation subject cannot be null or empty", "Subject"); } if (string.IsNullOrEmpty(body)) { throw new LinkedInMissingParameterException("Invitation body cannot be null or empty", "Body"); } if (ApiStandardProfileRquest == null) { throw new LinkedInMissingParameterException("ApiStandardProfileRquest field is not set", "ApiStandardProfileRquest"); } if (!ApiStandardProfileRquest.Headers.Any()) { throw new LinkedInMissingParameterException("There are no headers in ApiStandardProfileRquest field", "Headers"); } var header = ApiStandardProfileRquest.Headers.First(); var arr = header.Value.Split(':'); var options = new LinkedInInvitationOptions { Body = body, Subject = subject, RecipientId = Id, AuthorizationName = arr[0], AuthorizationValue = arr[1] }; return(RequestRunner.SendInvitation(options)); }
/// <summary> /// Adds new post to group /// </summary> /// <param name="options">Value containing post's details</param> /// <returns>Request result</returns> /// <exception cref="LinkedInMissingParameterException">Thrown when any of post's required parameters is null or empty string</exception> public LinkedInResponse <bool> AddPost(LinkedInGroupPostOptions options) { options.GroupId = Id; if (string.IsNullOrEmpty(options.Title)) { throw new LinkedInMissingParameterException("Post title cannot be empty", "Title"); } if (string.IsNullOrEmpty(options.Summary)) { throw new LinkedInMissingParameterException("Post summary cannot be empty", "Summary"); } var contentPresented = Utils.IsAnyString(options.ContentTitle, options.ContentText, options.SubmittedUrl, options.SubmittedImageUrl); if (contentPresented && string.IsNullOrEmpty(options.ContentTitle)) { throw new LinkedInMissingParameterException("Post content title cannot be empty", "ContentTitle"); } if (contentPresented && string.IsNullOrEmpty(options.ContentText)) { throw new LinkedInMissingParameterException("Post content text cannot be empty", "ContentText"); } if (contentPresented && string.IsNullOrEmpty(options.SubmittedUrl)) { throw new LinkedInMissingParameterException("Submitted URL cannot be empty", "SubmittedUrl"); } if (contentPresented && string.IsNullOrEmpty(options.SubmittedImageUrl)) { throw new LinkedInMissingParameterException("Submitted image URL cannot be empty", "SubmittedImageUrl"); } return(RequestRunner.AddGroupPost(options)); }
/// <summary> /// Adds comment to current update /// </summary> /// <param name="comment">Comment to add</param> /// <returns>Value containing true or false, depending on operation success, and response status</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when current update is not commentable</exception> public LinkedInResponse <bool> Comment(string comment) { try { if (!IsCommentable) { throw new LinkedInInvalidOperationException("Comments are not allowed for this update"); } if (comment.Length > LinkedInShareOptions.MAX_COMMENT_LENGTH) { comment = comment.Substring(0, LinkedInShareOptions.MAX_COMMENT_LENGTH); } var response = RequestRunner.CommentUpdate(UpdateKey, comment); var liComment = getLastComment(); if (liComment != null) { _Comments.Add(liComment); } NumberOfComments++; return(response); } catch (WebException wex) { return(Utils.GetResponse(false, wex, null)); } catch (Exception ex) { return(new LinkedInResponse <bool>(false, LinkedInResponseStatus.OtherException, null, ex)); } }
/// <summary> /// Executes the SQL and retuns all rows selected in a map that is keyed on the property named /// in the keyProperty parameter. The value at each key will be the value of the property specified /// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered. /// </summary> /// <param name="session">The session used to execute the statement</param> /// <param name="parameterObject">The object used to set the parameters in the SQL. </param> /// <param name="keyProperty">The property of the result object to be used as the key. </param> /// <param name="valueProperty">The property of the result object to be used as the value (or null)</param> /// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns> ///<exception cref="MyBatis.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception> public IDictionary <K, V> ExecuteQueryForDictionary <K, V>(ISession session, object parameterObject, string keyProperty, string valueProperty) { // this doesn't need to be in its own RunQueryForCachedDictionary method because the class is sealed and can't be called by anyone else RequestRunner <IDictionary <K, V> > requestRunner = delegate(RequestScope requestScope, ISession session2, object parameter, CacheKey cacheKey, out bool cacheHit) { if (keyProperty != null) { cacheKey.Update(keyProperty); } if (valueProperty != null) { cacheKey.Update(valueProperty); } cacheHit = true; IDictionary <K, V> map = Statement.CacheModel[cacheKey] as IDictionary <K, V>; if (map == null) { cacheHit = false; map = mappedStatement.RunQueryForDictionary <K, V>(requestScope, session2, parameter, keyProperty, valueProperty, null); Statement.CacheModel[cacheKey] = map; } return(map); }; return(CachingStatementExecute(PreSelectEventKey, PostSelectEventKey, session, parameterObject, "ExecuteQueryForDictionary", requestRunner)); }
/// <summary> /// Loads all update's likes (max 250) /// </summary> /// <returns>Request result</returns> /// <remarks>This is synchronous operation, i.e. the current thread will be suspended until it finishes to load all likes. If you want to load update's likes asynchronously, consider to use <see cref="LinkedInClient.GetUpdateLikes"/> function instead</remarks> public LinkedInResponse <bool> LoadLikes() { try { if (_Likes == null) { _Likes = new List <LinkedInLike>(); } else { _Likes.Clear(); } var response = RequestRunner.GetAllUpdateLikes(UpdateKey); if (response != null && response.Result != null && response.Status == LinkedInResponseStatus.OK) { _Likes.AddRange(response.Result); } return(new LinkedInResponse <bool>(true, LinkedInResponseStatus.OK, null)); } catch (WebException wex) { return(Utils.GetResponse(false, wex, null)); } catch (Exception ex) { return(new LinkedInResponse <bool>(false, LinkedInResponseStatus.OtherException, null, ex)); } }
/// <summary> /// Likes current post /// </summary> /// <returns>Request result</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when user attempts to like the post which is not marked as available for this action</exception> public LinkedInResponse <bool> Like() { if (!AvailableAction[LinkedInGroupPostAction.Like]) { throw new LinkedInInvalidOperationException("Like action is not available for current post"); } return(RequestRunner.LikeUnlikePost(Id, true)); }
/// <summary> /// Sends request to join current group /// </summary> /// <returns>Request result</returns> /// <exception cref="LinkedInAlreadyMemberException">Thrown if user is already member of the group</exception> public LinkedInResponse <bool> Join() { if (MembershipState == LinkedInGroupRelationship.NonMember) { return(RequestRunner.RequestJoinGroup(Id)); } throw new LinkedInAlreadyMemberException("The user is already member of group " + Name); }
/// <summary> /// Sends request to leave current group /// </summary> /// <returns>Request result</returns> /// <exception cref="LinkedInAlreadyMemberException">Thrown if user is not a member of the group</exception> public LinkedInResponse <bool> Leave() { if (MembershipState != LinkedInGroupRelationship.NonMember) { return(RequestRunner.RequestLeaveGroup(Id)); } throw new LinkedInIsNotMemberException("The user is not a member of group " + Name); }
/// <summary> /// Saves group's settings /// </summary> /// <returns>Request result</returns> /// <exception cref="LinkedInAlreadyMemberException">Thrown if user is not a member of the group</exception> public LinkedInResponse <bool> SaveSettings() { if (MembershipState != LinkedInGroupRelationship.NonMember) { return(RequestRunner.ChangeGroupSettings(Id, Settings)); } throw new LinkedInIsNotMemberException("The user is not a member of group " + Name); }
/// <summary> /// Deletes current comment if user is the comments's creator or marks the post as inappropriate /// </summary> /// <returns>Request result</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when user attempts to delete the comment which is not marked as available for this action</exception> public LinkedInResponse <bool> Delete() { if (!AvailableAction[LinkedInGroupCommentAction.Delete] && !AvailableAction[LinkedInGroupCommentAction.FlagAsInappropriate]) { throw new LinkedInInvalidOperationException("Deletion of current post is not available"); } return(RequestRunner.DeletePostComment(Id)); }
/// <summary> /// Adds comment to current post /// </summary> /// <param name="comment">Comment's text</param> /// <returns>Request result</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when user attempts to add comment to the post which is not marked as available for this action</exception> public LinkedInResponse <bool> Comment(string comment) { if (!AvailableAction[LinkedInGroupPostAction.AddComment]) { throw new LinkedInInvalidOperationException("Adding comments is not available for current post"); } return(RequestRunner.CommentPost(Id, comment)); }
/// <summary> /// Follows current post /// </summary> /// <returns>Request result</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when user attempts to unfollow the post which is not marked as available for this action</exception> public LinkedInResponse <bool> Unfollow() { if (!AvailableAction[LinkedInGroupPostAction.Follow]) { throw new LinkedInInvalidOperationException("Unfollow action is not available for current post"); } return(RequestRunner.FollowUnfollowPost(Id, false)); }
public async Task Closing_IsAwaitable() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); bool completed = false; await requests.Close(() => Task.Delay(500).ContinueWith(_ => completed = true)); Assert.That(completed); }
public void Closing_DisallowsFurtherRequests() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); requests.Close(() => Task.Delay(50)); Assert.That( () => requests.Perform(() => Task.CompletedTask), Throws.Exception.InstanceOf <RequestRunnerClosedException>()); }
/// <summary> /// Categorizes current post /// </summary> /// <param name="flag">Value indicating how the current post should be categorized</param> /// <returns>Request result</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when user attempts to categorize the post which is not marked as available for this action</exception> public LinkedInResponse <bool> Categorize(LinkedInGroupPostFlag flag) { if (!AvailableAction[LinkedInGroupPostAction.CategorizeAsPromotion] && flag == LinkedInGroupPostFlag.Promotion) { throw new LinkedInInvalidOperationException("Specifying promotion flag is not available for current post"); } if (!AvailableAction[LinkedInGroupPostAction.CategorizeAsJob] && flag == LinkedInGroupPostFlag.Job) { throw new LinkedInInvalidOperationException("Specifying job flag is not available for current post"); } return(RequestRunner.CategorizePost(Id, flag)); }
public void Run(string arguments, Action <string> onLine) { var process = new Process(); _isRunning = true; var stdinForwarder = new Thread(() => { try { while (_isRunning) { var line = Console.ReadLine(); process.Write(line); } } catch { } }); stdinForwarder.Start(); Logger.Write("Running script {0} with {1}", _file, arguments); arguments = "{global-profile} {local-profile} " + arguments; run( arguments, (m) => { var requestRunner = new RequestRunner(_token); if (requestRunner.IsRequest(m)) { ThreadPool.QueueUserWorkItem((msg) => { var response = requestRunner.Request(msg.ToString()); foreach (var content in response) { process.Write(content); } }, m); } else { onLine(m); } }, new[] { new KeyValuePair <string, string>("{global-profile}", "\"" + _globalProfileName + "\""), new KeyValuePair <string, string>("{local-profile}", "\"" + _localProfileName + "\"") }, process); _isRunning = false; stdinForwarder.Abort(); Logger.Write("Running script completed {0}", _file); }
public Activation_New(Fixture fx, Placement placement) { _fx = fx; _placement = placement; _serializer = fx.Serializer; _scheduler = new GrainTaskScheduler(fx.Scheduler, fx.Exceptions); _runner = new RequestRunner(_scheduler, fx.Exceptions, fx.Requests, true); //default isolation??? _timers = new MockTimerRegistry(_scheduler); _receivers = new StreamReceiverRegistry(_serializer); _storage = fx.Stores.GetStorage(placement); _reminders = fx.Reminders.GetRegistry(placement); Placement = placement; Dispatcher = new ActivationDispatcher(_runner, CreateGrainContext); }
public ResponseDispatcher(string token, bool dispatchErrors, string eventPrefix, Action <string, string> outputDispatcher, Action <string> dispatcher, Action <string> dispatchResponse) { _token = token; _outputDispatcher = outputDispatcher; _dispatchErrors = dispatchErrors; _eventPrefix = eventPrefix; _dispatcher = dispatcher; _dispatchResponse = dispatchResponse; _requestRunner = new RequestRunner(_token); _editorFactory = () => { if (_editor == null) { var locator = new OpenIDE.Core.EditorEngineIntegration.EngineLocator(new OpenIDE.Core.FileSystem.FS()); _editor = locator.GetInstance(_token); } return(_editor); }; }
public async Task Closes_Immediately_WhenNoneWaiting() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); bool closed = false; requests.Close(() => { closed = true; return(Task.CompletedTask); }); await requests.WhenIdle(); exceptions.RethrowAll(); Assert.That(closed, Is.True); }
public async Task WhenIdle_AwaitsCompletionOfDeactivation() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); bool closed = false; requests.Close(async() => { await Task.Delay(100); closed = true; }); await requests.WhenIdle(); exceptions.RethrowAll(); Assert.That(closed, Is.True); }
/// <summary> /// Executes the SQL and retuns all rows selected. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>A List of result objects.</returns> public IList <T> ExecuteQueryForList <T>(ISession session, object parameterObject) { // this doesn't need to be in its own RunQueryForCachedList method because the class is sealed and can't be called by anyone else RequestRunner <IList <T> > requestRunner = delegate(RequestScope requestScope, ISession session2, object parameter, CacheKey cacheKey, out bool cacheHit) { cacheHit = true; IList <T> list = Statement.CacheModel[cacheKey] as IList <T>; if (list == null) { cacheHit = false; list = mappedStatement.RunQueryForList <T>(requestScope, session, parameter, null, null); Statement.CacheModel[cacheKey] = list; } return(list); }; return(CachingStatementExecute(PreSelectEventKey, PostSelectEventKey, session, parameterObject, "ExecuteQueryForList", requestRunner)); }
/// <summary> /// Executes an SQL statement that returns DataTable. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>The object</returns> public DataTable ExecuteQueryForDataTable(ISession session, object parameterObject) { RequestRunner <DataTable> requestRunner = delegate(RequestScope requestscope, ISession session2, object parameter, CacheKey cachekey, out bool cachehit) { cachehit = true; DataTable dataTable = Statement.CacheModel[cachekey] as DataTable; if (dataTable == null) { cachehit = false; dataTable = mappedStatement.RunQueryForDataTable(requestscope, session, parameter); Statement.CacheModel[cachekey] = dataTable; } return(dataTable); }; return(CachingStatementExecute(PreSelectEventKey, PostSelectEventKey, session, parameterObject, "ExecuteQueryForDataTable", requestRunner)); }
public async Task IsolatedRequestsIsolatedFromEachOther() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); List <int> callCounts = new List <int>(); int callCount = 0; await Enumerable.Range(0, 20) .Select(_ => requests.Perform(async() => { int c = Interlocked.Increment(ref callCount); callCounts.Add(c); await Task.Delay(15); Interlocked.Decrement(ref callCount); }, RequestMode.Isolated) ).WhenAll(); Assert.That(callCounts.All(c => c == 1)); }
public async Task Closing_Performed() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); bool closed = false; requests.PerformAndForget(() => Task.Delay(50)); requests.Close(() => { closed = true; return(Task.CompletedTask); }); await requests.WhenIdle(); exceptions.RethrowAll(); Assert.That(closed, Is.True); }
/// <summary> /// Sends message to current member /// </summary> /// <param name="subject">Message subject</param> /// <param name="body">Message body</param> /// <param name="includeSenderInRecipients">Indicates whether sender of message should be included in recipients</param> /// <returns>Value containing true or false, depending on operation success, and response status</returns> /// <exception cref="LinkedInMissingParameterException">Thrown when message's subject or body are null or empty strings</exception> public LinkedInResponse <bool> SendMessage(string subject, string body, bool includeSenderInRecipients) { if (string.IsNullOrEmpty(subject)) { throw new LinkedInMissingParameterException("Message subject cannot be null or empty", "Subject"); } if (string.IsNullOrEmpty(body)) { throw new LinkedInMissingParameterException("Message body cannot be null or empty", "Body"); } var options = new LinkedInMessageOptions { Body = body, Subject = subject, IncludeSenderInRecipients = includeSenderInRecipients }; options.Recipients.Add(Id); return(RequestRunner.SendMessage(options)); }
public async Task IsolatedRequestsRespectedByReentrantFollowers() { var exceptions = new ExceptionSink(); var requests = new RequestRunner(TaskScheduler.Default, exceptions); bool isolatedExecuting = false; var tIsolated = requests.Perform(async() => { isolatedExecuting = true; await Task.Delay(100); isolatedExecuting = false; }, RequestMode.Isolated); var clashed = await requests.Perform(async() => { await Task.Delay(15); return(isolatedExecuting); }, RequestMode.Reentrant); await tIsolated; Assert.That(clashed, Is.False); }
/// <summary> /// Unlikes current update /// </summary> /// <returns>Value containing true or false, depending on operation success, and response status</returns> /// <exception cref="LinkedInInvalidOperationException">Thrown when current update is not likable</exception> public LinkedInResponse <bool> Unlike() { try { if (!IsLikable) { throw new LinkedInInvalidOperationException("Likes are not allowed for this update"); } var response = RequestRunner.LikeUnlikeUpdate(UpdateKey, false); var user = Singleton.Instance.CurrentUser; _Likes.RemoveAll(l => l.Person.Id == user.Id); NumberOfLikes--; return(response); } catch (WebException wex) { return(Utils.GetResponse(false, wex, null)); } catch (Exception ex) { return(new LinkedInResponse <bool>(false, LinkedInResponseStatus.OtherException, null, ex)); } }