internal VlvResponseControl(int targetPosition, int count, byte[] context, ResultCode result, bool criticality, byte[] value) : base("2.16.840.1.113730.3.4.10", value, criticality, true)
 {
     this.position = targetPosition;
     this.count = count;
     this.context = context;
     this.result = result;
 }
 /// <summary>
 ///     Constructor
 /// </summary>
 /// <param name="result">the result code</param>
 /// <param name="exception">the error exception</param>
 public OAuthResult(ResultCode result, Exception exception)
 {
     AuthResponse = null;
     SessionToken = null;
     Result = result;
     Error = exception;
 }
 internal static bool IsResultCode(ResultCode code)
 {
     if ((code < ResultCode.Success) || (code > ResultCode.SaslBindInProgress))
     {
         if ((code >= ResultCode.NoSuchAttribute) && (code <= ResultCode.InvalidAttributeSyntax))
         {
             return true;
         }
         if ((code >= ResultCode.NoSuchObject) && (code <= ResultCode.InvalidDNSyntax))
         {
             return true;
         }
         if ((code >= ResultCode.InsufficientAccessRights) && (code <= ResultCode.LoopDetect))
         {
             return true;
         }
         if ((code >= ResultCode.NamingViolation) && (code <= ResultCode.AffectsMultipleDsas))
         {
             return true;
         }
         if ((((code != ResultCode.AliasDereferencingProblem) && (code != ResultCode.InappropriateAuthentication)) && ((code != ResultCode.SortControlMissing) && (code != ResultCode.OffsetRangeError))) && ((code != ResultCode.VirtualListViewError) && (code != ResultCode.Other)))
         {
             return false;
         }
     }
     return true;
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="result">the result code</param>
 public OAuthResult(ResultCode result)
 {
     Error = null;
     AuthResponse = null;
     SessionToken = null;
     Result = result;
 }
 /// <summary>
 /// Creates a BindResponse for normal bindings and SASL bindings.
 /// </summary>
 /// <param name="context">The user context which contains message ID.</param>
 /// <param name="resultCode">Result code of previous request, as specified in RFC 2251.</param>
 /// <param name="matchedDn">Matched DN. Required, but can be an empty string.</param>
 /// <param name="errorMessage">Error message for result code. Required.</param>
 /// <param name="referral">Referral. Optional and for LDAP v3 only.</param>
 /// <param name="serverCredentials">Server credentials, optional for normal bind.</param>
 /// <returns>The packet that contains the response.</returns>
 internal abstract AdtsBindResponsePacket CreateBindResponse(
     AdtsLdapContext context,
     ResultCode resultCode,
     string matchedDn,
     string errorMessage,
     string[] referral,
     byte[] serverCredentials);
		static string GetMsg (ResultCode code)
		{
			switch (code) {
			case ResultCode.Ok:
				return "Success";
			case ResultCode.Denied:
				return "Access denied";
			case ResultCode.NoKeyringDaemon:
				return "The keyring daemon is not available";
			case ResultCode.AlreadyUnlocked:
				return "Keyring was already unlocked";
			case ResultCode.NoSuchKeyring:
				return "No such keyring";
			case ResultCode.BadArguments:
				return "Bad arguments";
			case ResultCode.IOError:
				return "I/O error";
			case ResultCode.Cancelled:
				return "Operation canceled";
			case ResultCode.AlreadyExists:
				return "Item already exists";
			default:
				return "Unknown error";
			}
		}
Пример #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RiakResult"/> class.
 /// </summary>
 /// <param name="resultCode">The <see cref="ResultCode"/>.</param>
 /// <param name="exception">The <see cref="System.Exception"/>. Required.</param>
 public RiakResult(ResultCode resultCode, Exception exception)
     : this(false, resultCode, exception, null, false)
 {
     if (exception == null)
     {
         throw new ArgumentNullException("exception");
     }
 }
 /// <summary>
 /// Datatype formatter graph result
 /// </summary>
 internal DatatypeR2FormatterGraphResult(ResultCode code, IResultDetail[] details, bool validateConformance) : this(validateConformance)
 {
     this.Code = code;
     if (details != null)
         this.m_details = new List<IResultDetail>(details);
     else
         this.m_details = new List<IResultDetail>(10);
 }
Пример #9
0
 internal DirectoryResponse(string dn, DirectoryControl[] controls, ResultCode result, string message, Uri[] referral)
 {
     this.dn = dn;
     this.directoryControls = controls;
     this.result = result;
     this.directoryMessage = message;
     this.directoryReferral = referral;
 }
Пример #10
0
 /// <summary>
 /// Datatype formatter graph result
 /// </summary>
 internal XmlIts1FormatterGraphResult(ResultCode code, IResultDetail[] details)
 {
     this.Code = code;
     if (details == null)
         this.m_details = new List<IResultDetail>(10);
     else
         this.m_details = new List<IResultDetail>(details);
 }
Пример #11
0
 public static RiakResult Error(ResultCode code, string message = null)
 {
     return new RiakResult
     {
         IsSuccess = false,
         ResultCode = code,
         ErrorMessage = message
     };
 }
Пример #12
0
		internal VlvResponseControl (int contentCount, byte [] contextId, ResultCode result, int targetPosition)
			: base (null, null, false, true)
		{
			throw new NotImplementedException ("ctor-chain");

			ContentCount = contentCount;
			ContextId = contextId;
			Result = result;
			TargetPosition = targetPosition;
		}
Пример #13
0
 internal static RiakResult Error(ResultCode code, string message, bool nodeOffline)
 {
     return new RiakResult
     {
         IsSuccess = false,
         ResultCode = code,
         ErrorMessage = message,
         NodeOffline = nodeOffline
     };
 }
Пример #14
0
		public ADResponse(string dn, DirectoryControl[] controls, ResultCode result, string message, Uri[] referral)
		{
			this._result = ResultCode.OperationsError | ResultCode.ProtocolError | ResultCode.TimeLimitExceeded | ResultCode.SizeLimitExceeded | ResultCode.CompareFalse | ResultCode.CompareTrue | ResultCode.AuthMethodNotSupported | ResultCode.StrongAuthRequired | ResultCode.ReferralV2 | ResultCode.Referral | ResultCode.AdminLimitExceeded | ResultCode.UnavailableCriticalExtension | ResultCode.ConfidentialityRequired | ResultCode.SaslBindInProgress | ResultCode.NoSuchAttribute | ResultCode.UndefinedAttributeType | ResultCode.InappropriateMatching | ResultCode.ConstraintViolation | ResultCode.AttributeOrValueExists | ResultCode.InvalidAttributeSyntax | ResultCode.NoSuchObject | ResultCode.AliasProblem | ResultCode.InvalidDNSyntax | ResultCode.AliasDereferencingProblem | ResultCode.InappropriateAuthentication | ResultCode.InsufficientAccessRights | ResultCode.Busy | ResultCode.Unavailable | ResultCode.UnwillingToPerform | ResultCode.LoopDetect | ResultCode.SortControlMissing | ResultCode.OffsetRangeError | ResultCode.NamingViolation | ResultCode.ObjectClassViolation | ResultCode.NotAllowedOnNonLeaf | ResultCode.NotAllowedOnRdn | ResultCode.EntryAlreadyExists | ResultCode.ObjectClassModificationsProhibited | ResultCode.ResultsTooLarge | ResultCode.AffectsMultipleDsas | ResultCode.VirtualListViewError | ResultCode.Other;
			this._dn = dn;
			this._controls = controls;
			ADResponse.TransformControls(this._controls);
			this._result = result;
			this._message = message;
			this._referral = referral;
		}
        protected RiakResult(bool isSuccess, ResultCode resultCode, Exception exception, string errorMessage)
        {
            this.isSuccess = isSuccess;
            this.resultCode = resultCode;
            this.exception = exception;
            this.errorMessage = errorMessage;

            if (string.IsNullOrWhiteSpace(this.errorMessage) &&
                exception != null &&
                !string.IsNullOrWhiteSpace(exception.Message))
            {
                this.errorMessage = exception.Message;
            }
        }
Пример #16
0
    protected override void OnClicked(int controlId, GUIControl control, Action.ActionType actionType)
    {
      base.OnClicked(controlId, control, actionType);
      if (control == btnOk)
      {
        PageDestroy();
        resultCode = ResultCode.Close;
        return;
      }
      if (control == btnNextItem)
      {
        PageDestroy();
        resultCode = ResultCode.Next;
        return;
      }
      if (control == btnPreviousItem)
      {
        PageDestroy();
        resultCode = ResultCode.Previous;
        return;
      }
      if (control == btnPlay)
      {
        Log.Info("DialogSetRating:Play:{0}", FileName);
        g_Player.Play(FileName);
      }

      if (control == btnMin)
      {
        if (rating >= 1)
        {
          rating--;
        }
        UpdateRating();
        return;
      }
      if (control == btnPlus)
      {
        if (rating < 5)
        {
          rating++;
        }
        UpdateRating();
        return;
      }
    }
 /// <summary>
 /// 获取命令返回结果的文字描述
 /// </summary>
 /// <param name="result"></param>
 /// <returns></returns>
 public static string GetDescription(ResultCode result)
 {
     switch (result)
     {
         case ResultCode.CannotConnectServer:
             return Resource1.ResultCode_CannotConnectServer;
         case ResultCode.Fail:
             return Resource1.ResultCode_Fail;
         case ResultCode.NoRecord:
             return Resource1.ResultCode_NoRecord;
         case ResultCode.SaveDataError:
             return Resource1.ResultCode_SaveDataError;
         case ResultCode.Successful:
             return Resource1.ResultCode_Successfull;
         default:
             return Resource1.ResultCode_Fail;
     }
 }
    // YOUR CANCEL CODE HERE
    private void Cancel(string strId, ref ResultCode iCode, ref string strDescription)
    {
        MySqlCommand					oCommand;

        // Code example

        // Canceling payment
        oCommand = new MySqlCommand("UPDATE `" + m_Config.m_dbPaymentsTable + "` SET `canceled` = \"1\", `date_cancel` = NOW() WHERE `invoice` = @Id", m_Connect);
        oCommand.Prepare();
        oCommand.Parameters.AddWithValue("@Id", strId);
        // performing query
        if(oCommand.ExecuteNonQuery() > 0)
        {
            iCode = ResultCode.SUCCESS;
            strDescription = "OK";
        }
        else
        {
            iCode = ResultCode.CANCEL_NOT_FOUND;
            strDescription = "Payment with given ID does not exist";
        }
    }
Пример #19
0
 protected Result(bool isSuccess, string error, ResultCode code = ResultCode.Unknown)
 {
     IsSuccess = isSuccess;
     Error     = error;
     Code      = code;
 }
Пример #20
0
 public QueryResultList(ResultCode code, List <T> list)
 {
     this._result      = code;
     this._msg         = ResultCodeDecription.GetDescription(code);
     this.QueryObjects = list;
 }
Пример #21
0
 public Result(object value = default(object), bool isSuccess = true, string error = null, ResultCode code = ResultCode.Ok)
 {
     Value     = value;
     IsSuccess = isSuccess;
     Error     = error;
     Code      = code;
 }
Пример #22
0
 /// <summary>
 /// Creates a SearchResultDone packet.
 /// </summary>
 /// <param name="context">The user context which contains message ID.</param>
 /// <param name="resultCode">Result code of previous request, as specified in RFC 2251.</param>
 /// <param name="matchedDn">Matched DN.</param>
 /// <param name="errorMessage">Error message for result code. Required.</param>
 /// <param name="referral">Referral. Optional.</param>
 /// <returns>The packet that contains the response.</returns>
 internal abstract AdtsSearchResultDonePacket CreateSearchResultDone(
     AdtsLdapContext context,
     ResultCode resultCode,
     string matchedDn,
     string errorMessage,
     string[] referral);
Пример #23
0
        public void TestForcePasswordChange(AccessState accessState, HttpStatusCode httpStatusCode, ResultCode resultCode)
        {
            AccessEndpointManager accessEndpointHandler = new AccessEndpointManager();
            var response = accessEndpointHandler.AccessEndpoint <object>(accessState, "/auth/api/identity", new Dictionary <string, object>(), HttpMethod.Post);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(httpStatusCode), "Still able to access identity api.");
        }
Пример #24
0
 public static Result <T> Fail <T>(string message, ResultCode code = ResultCode.BadRequest)
 {
     return(new Result <T>(default(T), false, message, code));
 }
Пример #25
0
 /// <summary>
 /// Creates a SicilyBindResponse packet.
 /// </summary>
 /// <param name="context">The user context which contains message ID.</param>
 /// <param name="resultCode">Result code of previous request, as specified in RFC 2251.</param>
 /// <param name="serverCredentials">Server credentials, optional for normal and sicily bind.</param>
 /// <param name="errorMessage">Error message for result code. Required.</param>
 /// <returns>The packet that contains the response.</returns>
 internal abstract AdtsSicilyBindResponsePacket CreateSicilyBindResponse(
     AdtsLdapContext context,
     ResultCode resultCode,
     byte[] serverCredentials,
     string errorMessage);
Пример #26
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;
        }
		public GalleryCommandException (string status_text, ResultCode result) : base (status_text) {
			status = result;
		}
Пример #28
0
 public ExtendAccessTokenCommandResponse(bool isSuccess, ResultCode resultCode, ExtendRefreshTokenViewModel data, string message = null) : base(isSuccess, resultCode, data, message)
 {
 }
Пример #29
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);
            }
        }
Пример #30
0
 public static Result <T> Fail <T>(string error, ResultCode code = ResultCode.BadRequest) => new Result <T>(default(T), false, error, code);
Пример #31
0
 public static Result <T> Ok <T>(T value, ResultCode code        = ResultCode.Ok) => new Result <T>(value, code: code);
Пример #32
0
 public static Result Fail(string error, ResultCode code         = ResultCode.BadRequest) => new Result(isSuccess: false, error: error, code: code);
Пример #33
0
 public static Result <T> Ok <T>(T value, ResultCode code = ResultCode.Ok)
 {
     return(new Result <T>(value, true, string.Empty));
 }
Пример #34
0
 public Result(ResultCode code, string description)
 {
     ResultCode = code;
     Description = description;
 }
Пример #35
0
 public static Result Fail(string message, ResultCode code = ResultCode.BadRequest)
 {
     return(new Result(false, message, code));
 }
Пример #36
0
        public List <Image> ParseFetchAlbumImages(HttpWebResponse response, Album album)
        {
            string []    data;
            StreamReader reader      = null;
            ResultCode   status      = ResultCode.UnknownResponse;
            string       status_text = "Error: Unable to parse server response";

            try {
                Image current_image = null;
                reader = findResponse(response);
                while ((data = GetNextLine(reader)) != null)
                {
                    if (data [0] == "status")
                    {
                        status = (ResultCode)int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("status_text"))
                    {
                        status_text = data [1];
                        Log.DebugFormat("StatusText : {0}", data [1]);
                    }
                    else if (data [0].StartsWith("image.name"))
                    {
                        current_image = new Image(album, data [1]);
                        album.Images.Add(current_image);
                    }
                    else if (data [0].StartsWith("image.raw_width"))
                    {
                        current_image.RawWidth = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.raw_height"))
                    {
                        current_image.RawHeight = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.raw_height"))
                    {
                        current_image.RawHeight = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.raw_filesize"))
                    {
                    }
                    else if (data [0].StartsWith("image.capturedate.year"))
                    {
                    }
                    else if (data [0].StartsWith("image.capturedate.mon"))
                    {
                    }
                    else if (data [0].StartsWith("image.capturedate.mday"))
                    {
                    }
                    else if (data [0].StartsWith("image.capturedate.hours"))
                    {
                    }
                    else if (data [0].StartsWith("image.capturedate.minutes"))
                    {
                    }
                    else if (data [0].StartsWith("image.capturedate.seconds"))
                    {
                    }
                    else if (data [0].StartsWith("image.hidden"))
                    {
                    }
                    else if (data [0].StartsWith("image.resizedName"))
                    {
                        current_image.ResizedName = data [1];
                    }
                    else if (data [0].StartsWith("image.resized_width"))
                    {
                        current_image.ResizedWidth = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.resized_height"))
                    {
                        current_image.ResizedHeight = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.thumbName"))
                    {
                        current_image.ThumbName = data [1];
                    }
                    else if (data [0].StartsWith("image.thumb_width"))
                    {
                        current_image.ThumbWidth = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.thumb_height"))
                    {
                        current_image.ThumbHeight = int.Parse(data [1]);
                    }
                    else if (data [0].StartsWith("image.caption"))
                    {
                        current_image.Caption = data [1];
                    }
                    else if (data [0].StartsWith("image.extrafield.Description"))
                    {
                        current_image.Description = data [1];
                    }
                    else if (data [0].StartsWith("image.clicks"))
                    {
                        try {
                            current_image.Clicks = int.Parse(data [1]);
                        } catch (System.FormatException) {
                            current_image.Clicks = 0;
                        }
                    }
                    else if (data [0].StartsWith("baseurl"))
                    {
                        album.BaseURL = data [1];
                    }
                    else if (data [0].StartsWith("image_count"))
                    {
                        if (album.Images.Count != int.Parse(data [1]))
                        {
                            Log.Warning("Parsed image count for " + album.Name + "(" + album.Images.Count + ") does not match image_count (" + data [1] + ").  Something is amiss");
                        }
                        else
                        {
                            Log.DebugFormat("Unparsed Line in ParseFetchAlbumImages(): {0}={1}", data [0], data [1]);
                        }
                    }
                }
                //Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
                if (status != ResultCode.Success)
                {
                    Log.Debug(status_text);
                    throw new GalleryCommandException(status_text, status);
                }


                //Set the Urls for downloading the images.
                string baseUrl = album.BaseURL + "/";
                foreach (Image image in album.Images)
                {
                    image.Url = baseUrl + image.Name;
                }

                return(album.Images);
            } finally {
                if (reader != null)
                {
                    reader.Close();
                }

                response.Close();
            }
        }
Пример #37
0
        public static string ConvertString(this ResultCode code, params string[] @params)
        {
            string description = string.Format(code.GetDescription(), @params);

            return(string.Format("{0} {1}", (int)code, description));
        }
Пример #38
0
 public void HandleResult(ResultCode resultCode, Result result)
 {
 }
Пример #39
0
 /// <summary>
 /// Creates an ExtendedResponse packet.
 /// </summary>
 /// <param name="context">The user context which contains message ID.</param>
 /// <param name="resultCode">Result code of previous request, as specified in RFC 2251.</param>
 /// <param name="matchedDn">Matched DN.</param>
 /// <param name="errorMessage">Error message for result code. Required.</param>
 /// <param name="referral">Referral. Optional. Used for LDAP v3 only.</param>
 /// <returns>The packet that contains the response.</returns>
 internal abstract AdtsExtendedResponsePacket CreateExtendedResponse(
     AdtsLdapContext context,
     ResultCode resultCode,
     string matchedDn,
     string errorMessage,
     string[] referral);
Пример #40
0
 public LogResult(ResultCode code, string msg)
 {
     this.Code = code;
     this.Msg  = msg;
 }
Пример #41
0
        /// <summary>
        /// Invokes a call to a partner API method, retrying if needed.
        /// </summary>
        /// <param name="context">
        /// The context of the operation.
        /// </param>
        /// <param name="invoker">
        /// The function to call to invoke the partner API method.
        /// </param>
        /// <param name="terminalCodes">
        /// Set of terminal result codes on which we should not retry.
        /// For example, if result is invalid card, one should not need to try again.
        /// </param>
        /// <param name="partner">
        /// Optionally, callers can specify their partner.
        /// </param>
        /// <param name="retryOnTransientErrorOnly">
        /// Optionally, settting this as true will retry on transientErrorOnly which in this case mean that if there is an exception
        /// </param>
        internal static async Task <ResultCode> InvokePartner(CommerceContext context,
                                                              Func <Task <ResultCode> > invoker,
                                                              HashSet <ResultCode> terminalCodes = null,
                                                              Partner partner = Partner.None, bool retryOnTransientErrorOnly = false)
        {
            ResultCode result = ResultCode.None;

            // initialize terminal codes if not provided
            if (terminalCodes == null)
            {
                terminalCodes = new HashSet <ResultCode>();
                terminalCodes.Add(ResultCode.Success);
                terminalCodes.Add(ResultCode.Created);
            }

            // Invoke the partner, retrying if needed.
            CommerceConfig config = context.Config ?? CommerceServiceConfig.Instance;

            int tryCount     = 0;
            int maxRetries   = config.MaxPartnerRetries;
            int retryLatency = config.InitialPartnerRetryLatency;

            do
            {
                try
                {
                    tryCount++;
                    result = await invoker().ConfigureAwait(false);

                    //we consider transient error as a runtime exception while calling external API. Since there is no exception and retryOnTransientErrorOnly is set
                    //to true we will break
                    if (retryOnTransientErrorOnly)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    bool   firstDataBadRequest = partner == Partner.FirstData && ex.Message.Contains("(400) Bad Request");
                    string message             = String.Format("{0} call encountered an error.", context.ApiCallDescription);
                    if (tryCount <= maxRetries)
                    {
                        if (firstDataBadRequest == false)
                        {
                            context.Log.Critical(message, ex);
                        }
                        else
                        {
                            context.Log.Warning(String.Format("First Data {0}: (400) Bad Request detected. This is common because of clock skew and should resolve itself when the job is retried.", message));
                        }
                    }
                    else
                    {
                        throw;
                    }
                }

                // If a rety is needed, wait a short but increasingly lengthy time before proceeding.
                if (tryCount <= maxRetries && !terminalCodes.Contains(result))
                {
                    context.Log.Verbose("Waiting {0} milliseconds before retrying partner invocation.", retryLatency);
                    Thread.Sleep(retryLatency);
                    retryLatency *= 2;
                }
            }while (tryCount <= maxRetries && result != ResultCode.Success && result != ResultCode.Created);

            return(result);
        }
 protected override bool IsFinancialOperationSuccessful()
 {
     return(ResultCode?.StartsWith("0") == true);
 }
Пример #43
0
 public QueryResultList(ResultCode code, string msg, List <T> list)
 {
     this._result    = code;
     this._msg       = msg;
     this._queryList = list;
 }
Пример #44
0
        public void CallMethod(ServiceCtx context)
        {
            IIpcService service = this;

            if (_isDomain)
            {
                int domainWord0 = context.RequestData.ReadInt32();
                int domainObjId = context.RequestData.ReadInt32();

                int domainCmd       = (domainWord0 >> 0) & 0xff;
                int inputObjCount   = (domainWord0 >> 8) & 0xff;
                int dataPayloadSize = (domainWord0 >> 16) & 0xffff;

                context.RequestData.BaseStream.Seek(0x10 + dataPayloadSize, SeekOrigin.Begin);

                for (int index = 0; index < inputObjCount; index++)
                {
                    context.Request.ObjectIds.Add(context.RequestData.ReadInt32());
                }

                context.RequestData.BaseStream.Seek(0x10, SeekOrigin.Begin);

                if (domainCmd == 1)
                {
                    service = GetObject(domainObjId);

                    context.ResponseData.Write(0L);
                    context.ResponseData.Write(0L);
                }
                else if (domainCmd == 2)
                {
                    Delete(domainObjId);

                    context.ResponseData.Write(0L);

                    return;
                }
                else
                {
                    throw new NotImplementedException($"Domain command: {domainCmd}");
                }
            }

            long sfciMagic = context.RequestData.ReadInt64();
            int  commandId = (int)context.RequestData.ReadInt64();

            bool serviceExists = service.Commands.TryGetValue(commandId, out MethodInfo processRequest);

            if (ServiceConfiguration.IgnoreMissingServices || serviceExists)
            {
                ResultCode result = ResultCode.Success;

                context.ResponseData.BaseStream.Seek(_isDomain ? 0x20 : 0x10, SeekOrigin.Begin);

                if (serviceExists)
                {
                    Logger.PrintDebug(LogClass.KernelIpc, $"{service.GetType().Name}: {processRequest.Name}");

                    ProfileConfig profile = Profiles.ServiceCall;

                    profile.SessionGroup = service.GetType().Name;
                    profile.SessionItem  = processRequest.Name;

                    Profile.Begin(profile);

                    result = (ResultCode)processRequest.Invoke(service, new object[] { context });

                    Profile.End(profile);
                }
                else
                {
                    string serviceName;

                    DummyService dummyService = service as DummyService;

                    serviceName = (dummyService == null) ? service.GetType().FullName : dummyService.ServiceName;

                    Logger.PrintWarning(LogClass.KernelIpc, $"Missing service {serviceName}: {commandId} ignored");
                }

                if (_isDomain)
                {
                    foreach (int id in context.Response.ObjectIds)
                    {
                        context.ResponseData.Write(id);
                    }

                    context.ResponseData.BaseStream.Seek(0, SeekOrigin.Begin);

                    context.ResponseData.Write(context.Response.ObjectIds.Count);
                }

                context.ResponseData.BaseStream.Seek(_isDomain ? 0x10 : 0, SeekOrigin.Begin);

                context.ResponseData.Write(IpcMagic.Sfco);
                context.ResponseData.Write((long)result);
            }
            else
            {
                string dbgMessage = $"{service.GetType().FullName}: {commandId}";

                throw new ServiceNotImplementedException(context, dbgMessage);
            }
        }
Пример #45
0
 public OperationResult(ResultCode code = ResultCode.OK, string friendlyErrorMessage = "", string logErrorMessage = "")
 {
     ExecutionResult = new ExecutionResult(code, friendlyErrorMessage, logErrorMessage);
 }
Пример #46
0
        public void TestOriginalSearchAccessEndpoint(AccessState accessState, HttpStatusCode httpStatusCode, ResultCode resultCode, ConditionTypes conditionTypes)
        {
            var request = conditionTypes == ConditionTypes.Menu ? GetOriginalSearchConditionsParameters(ResourceId.Job) : GetOriginalSearchConditionParameters(ResourceId.Job, expectedId);
            AccessEndpointManager accessEndpointHandler = new AccessEndpointManager();
            var response = accessEndpointHandler.AccessEndpoint <object>(accessState, conditionTypes == ConditionTypes.Dialog ? ConditionEndpoint : ConditionsEndpoint, request, HttpMethod.Get);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(httpStatusCode).And.ErrorCode((int)resultCode), $"Still able to search option.");
        }
 internal AddResponse(string dn, DirectoryControl[] controls, ResultCode result, string message, Uri[] referral) : base(dn, controls, result, message, referral)
 {
 }
Пример #48
0
		public ADAddResponse(string dn, DirectoryControl[] controls, ResultCode result, string message, Uri[] referral) : base(dn, controls, result, message, referral)
		{
		}
Пример #49
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);
        }
Пример #50
0
        public void TestUpdateAccessEndpoint(AccessState accessState, HttpStatusCode httpStatusCode, ResultCode resultCode)
        {
            var request = TextHelpers.GenerateUpdateRequest(ResourceId.Job, Guid, TextHelpers.RequiredProperties(FieldType.SingleLineText));
            AccessEndpointManager accessEndpointHandler = new AccessEndpointManager();
            var response = accessEndpointHandler.AccessEndpoint <object>(accessState, FieldManager.FieldHandlingRelativeUrl, request, HttpMethod.Put);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(httpStatusCode).And.ErrorCode((int)resultCode), $"Still able to send a update field request.");
        }
Пример #51
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>());
            }
        }
Пример #52
0
        public void TestDeleteAccessEndpoint(AccessState accessState, HttpStatusCode httpStatusCode, ResultCode resultCode)
        {
            var request = new List <KeyValuePair <string, string> > {
                new KeyValuePair <string, string>(Selects.IdParam, Guid)
            };
            AccessEndpointManager accessEndpointHandler = new AccessEndpointManager();
            var response = accessEndpointHandler.AccessEndpoint <object>(accessState, FieldManager.FieldHandlingRelativeUrl, request, HttpMethod.Delete);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(httpStatusCode).And.ErrorCode((int)resultCode), $"Still able to send a delete field request.");
        }
Пример #53
0
		internal AsqResponseControl(int result, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.1504", controlValue, criticality, true)
		{
			this.result = (ResultCode)result;
		}
Пример #54
0
 public Result(ResultCode code, string message)
 {
     Code    = code;
     Message = message;
 }
Пример #55
0
 public ExecutionResult(ResultCode code = ResultCode.OK, string friendlyErrorMessage = "", string logErrorMessage = "")
 {
     ResultCode = code;
     EndUserErrorMessage = friendlyErrorMessage;
     LogErrorMessage = logErrorMessage;
 }
Пример #56
0
        public static ResultCode DecodeInterleaved(
            this IDecoder decoder,
            bool reset,
            ReadOnlySpan <byte> input,
            out short[] outPcmData,
            ulong outputSize,
            out uint outConsumed,
            out int outSamples)
        {
            outPcmData  = null;
            outConsumed = 0;
            outSamples  = 0;

            int streamSize = input.Length;

            if (streamSize < Unsafe.SizeOf <OpusPacketHeader>())
            {
                return(ResultCode.OpusInvalidInput);
            }

            OpusPacketHeader header = OpusPacketHeader.FromSpan(input);
            int  headerSize         = Unsafe.SizeOf <OpusPacketHeader>();
            uint totalSize          = header.length + (uint)headerSize;

            if (totalSize > streamSize)
            {
                return(ResultCode.OpusInvalidInput);
            }

            byte[] opusData = input.Slice(headerSize, (int)header.length).ToArray();

            ResultCode result = decoder.GetPacketNumSamples(out int numSamples, opusData);

            if (result == ResultCode.Success)
            {
                if ((uint)numSamples * (uint)decoder.ChannelsCount * sizeof(short) > outputSize)
                {
                    return(ResultCode.OpusInvalidInput);
                }

                outPcmData = new short[numSamples * decoder.ChannelsCount];

                if (reset)
                {
                    decoder.ResetState();
                }

                try
                {
                    outSamples  = decoder.Decode(opusData, 0, opusData.Length, outPcmData, 0, outPcmData.Length / decoder.ChannelsCount);
                    outConsumed = totalSize;
                }
                catch (OpusException)
                {
                    // TODO: as OpusException doesn't provide us the exact error code, this is kind of inaccurate in some cases...
                    return(ResultCode.OpusInvalidInput);
                }
            }

            return(ResultCode.Success);
        }
Пример #57
0
		internal AsqResponseControl (ResultCode result)
			: base (null, null, false, false)
		{
			Result = result;
			throw new NotImplementedException ();
		}
Пример #58
0
 public CommandResult(ResultCode code, CommandResponsePacket responsePacket = null)
 {
     Code           = code;
     ResponsePacket = responsePacket;
 }
Пример #59
0
		public ADAddResponse(string dn, DirectoryControl[] controls, ResultCode result, string message) : base(dn, controls, result, message, null)
		{
		}
        public void AccessEndpointTests(AccessState accessState, HttpStatusCode httpStatusCode, ResultCode resultCode)
        {
            AccessEndpointManager accessEndpointHandler = new AccessEndpointManager();
            var request = new Dictionary <string, string>()
            {
                ["_"] = Utils.DateTimeToUnix(null).ToString()
            };

            var response = accessEndpointHandler.AccessEndpoint <object>(accessState, EndPoint, request, HttpMethod.Get);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(httpStatusCode).And.ErrorCode((int)resultCode));
        }