Exemplo n.º 1
0
 /// <summary>
 /// Creates a new instance of MessageResult
 /// </summary>
 /// <param name="result">Result</param>
 /// <param name="callId">CallId</param>
 /// <returns>returns a new instance of MessageResult</returns>
 public static MessageResult CreateInstance(MethodResult result, string callId)
 {
     MessageResult msg = new MessageResult();
     msg.result = result;
     msg.callId = callId;
     return msg;
 }
 public MethodParamPair(
     MethodParamResult method,
     Interfaces.IEventInput input, int nextMethod)
 {
     _result = MethodResult.None;
     _method = method;
     _params = input;
     _exitPaths = new Dictionary<MethodResult, int>();
     _exitPaths[MethodResult.Success] = nextMethod;
 }
     public MethodParamPair(
 MethodParamResult method,
 Interfaces.IEventInput input,
         Collections.ExitPathGroup _paths)
     {
         _result = MethodResult.None;
         _method = method;
         _params = input;
         _exitPaths = _paths;
     }
Exemplo n.º 4
0
        private async Task <MethodResult <List <FortData> > > GetAllForts()
        {
            MethodResult <List <MapCell> > mapCellResponse = await GetMapObjects();

            if (!mapCellResponse.Success)
            {
                return(new MethodResult <List <FortData> >
                {
                    Data = new List <FortData>(),
                    Message = mapCellResponse.Message,
                    Success = mapCellResponse.Success
                });
            }

            return(new MethodResult <List <FortData> >
            {
                Data = mapCellResponse.Data.SelectMany(x => x.Forts).ToList(),
                Success = mapCellResponse.Success,
                Message = mapCellResponse.Message
            });
        }
Exemplo n.º 5
0
        private async void TransferToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(String.Format("Are you sure you want to transfer {0} pokemon?", fastObjectListViewPokemon.SelectedObjects.Count), "Confirmation", MessageBoxButtons.YesNo);

            if (result != DialogResult.Yes)
            {
                return;
            }

            contextMenuStripPokemonDetails.Enabled = false;

            MethodResult managerResult = await _manager.TransferPokemon(fastObjectListViewPokemon.SelectedObjects.Cast <PokemonData>());

            DisplayDetails();

            contextMenuStripPokemonDetails.Enabled = true;

            fastObjectListViewPokemon.SetObjects(_manager.Pokemon);

            MessageBox.Show("Finished transferring pokemon");
        }
Exemplo n.º 6
0
        public MethodResult <Asset> AddAsset(string serialNumber, string name, string description, int customerId)
        {
            var existingAsset = _assetRepository.GetBySerialNumberForCustomer(serialNumber, customerId);

            if (existingAsset != null)
            {
                return(MethodResult <Asset> .CreateFaultedResult("The asset is already created."));
            }

            var newAsset = new Asset
            {
                SerialNumber = serialNumber,
                Name         = name,
                Description  = description,
                CustomerId   = customerId
            };

            _assetRepository.Add(newAsset);

            return(new MethodResult <Asset>(newAsset));
        }
Exemplo n.º 7
0
        public ActionResult Vacuum()
        {
            Database db = new Database(ConfigurationManager.AppSettings["dbPath"]);

            if (db.IsDataBaseExist())
            {
                MethodResult res = db.Vacuum();
                if (res.isSuccess)
                {
                    return(Content("<div class='text-success'>Выполнено успешно!</div>"));
                }
                else
                {
                    return(Content("<div class='text-danger'>Ошибки:</div> " + res.Message));
                }
            }
            else
            {
                return(Content("База данных не обнаружена " + db.GetFilePath));
            }
        }
Exemplo n.º 8
0
        public static MethodResult sendSMSEventInviteViaTextLocal(string countryCode, string contactNumber, string hostname, string eventName)
        {
            Boolean      smsInviteEnabled = Boolean.Parse(ConfigurationManager.AppSettings["SMSInviteEnabled"].ToString());
            MethodResult mr = new MethodResult();

            if (!smsInviteEnabled)
            {
                mr.Status  = false;
                mr.Message = "Sms Invite is Disabled in Web API.";
                return(mr);
            }
            String textLocalMessage = ConfigurationManager.AppSettings["TextLocalSMSEventInviteTemplate1"].ToString();

            if (hostname.Length > 20)
            {
                hostname = hostname.Substring(0, 20);
            }
            textLocalMessage = textLocalMessage.Replace("$hostName$", hostname);
            textLocalMessage = textLocalMessage.Replace("$eventName$", eventName);
            return(sendSMSViaTextLocalGeneric(countryCode, contactNumber, textLocalMessage));
        }
        public static async Task <MethodResult <T> > TryAsync <T>(
            Func <Task <MethodResult <T> > > function,
            int numOfTry)
        {
            var counter = 0;

            while (true)
            {
                try {
                    return(await function());
                }
                catch (Exception e) {
                    counter++;
                    if (counter >= numOfTry)
                    {
                        return(MethodResult <T> .Fail(new ExceptionError(e,
                                                                         moreDetails : new { numOfTry })));
                    }
                }
            }
        }
        public IActionResult UpdateStatus([FromBody] StatusModel model)
        {
            MethodResult result = new MethodResult()
            {
                IsSuccessful = true
            };

            if (model.Running)
            {
                result = _insepectionService.Inspect();
                if (result.IsSuccessful)
                {
                    _worker.Start();
                }
            }
            else
            {
                _worker.Stop();
            }
            return(Ok(result));
        }
Exemplo n.º 11
0
        public void GetReplicationDataInvalidDateTest()
        {
            //create a new instance of the method input class found in ConnectorApi.Actions
            //Assign the MethodInput name to the Name of the method to be executed
            MethodInput methodInput = new MethodInput {
                Name = "GetReplicationData"
            };

            //set the object name by adding the property to the input
            methodInput.Input.Properties.Add("ObjectName", "SalesOrders");

            //set the Last date of syncronization by adding the property to the input
            methodInput.Input.Properties.Add("LastSyncDate", InvalidPropertyValue);


            //execute the selected method
            MethodResult result = _rsSourceConnector.ExecuteMethod(methodInput);

            Assert.IsFalse(result.Success);
            Assert.IsNotNull(result.ErrorInfo);
        }
Exemplo n.º 12
0
        private List <PokemonData> GetPokemonBelowCPIVAmount(IGrouping <PokemonId, PokemonData> pokemon, int minCp, double percent)
        {
            List <PokemonData> toTransfer = new List <PokemonData>();

            foreach (PokemonData pData in pokemon)
            {
                MethodResult <double> perfectResult = CalculateIVPerfection(pData);

                if (!perfectResult.Success)
                {
                    continue;
                }

                if (perfectResult.Data >= 0 && perfectResult.Data < percent && pData.Cp < minCp)
                {
                    toTransfer.Add(pData);
                }
            }

            return(toTransfer);
        }
Exemplo n.º 13
0
        public JsonResult CanReceiveProductGifts(int destinationID)
        {
            try
            {
                var source      = SessionHelper.CurrentEntity;
                var destination = entityRepository.GetById(destinationID);

                MethodResult result = giftService.CanReceiveProductGifts(source, destination);

                if (result.IsError)
                {
                    return(JsonData(new { result = false, error = result.Errors[0] }));
                }

                return(JsonData(new { result = true, error = "" }));
            }
            catch (Exception e)
            {
                return(JsonError("Undefined error!"));
            }
        }
Exemplo n.º 14
0
            internal static async Task <MethodResult> VerifyTask(Model account, HttpClient client)
            {
                var methodResult = new MethodResult();

                try
                {
                    var keyValuePairArray = new KeyValuePair <string, string>[3]
                    {
                        new KeyValuePair <string, string>("csrfmiddlewaretoken", account.Csrf),
                        new KeyValuePair <string, string>("username", account.Username),
                        new KeyValuePair <string, string>("password", account.Password)
                    };
                    if (!client.DefaultRequestHeaders.Contains("Referer"))
                    {
                        client.DefaultRequestHeaders.Add("Referer", Activated);
                    }
                    using (
                        var httpResponseMessage =
                            await client.PostAsync(Activated, new FormUrlEncodedContent(keyValuePairArray)))
                    {
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            methodResult.Value = await httpResponseMessage.Content.ReadAsStringAsync();

                            methodResult.Success = true;
                        }
                        else
                        {
                            methodResult.Error = new Exception("Failed to re-verify");
                        }
                    }
                }
                catch (Exception ex)
                {
                    methodResult.Error   = ex;
                    methodResult.Success = false;
                }

                return(methodResult);
            }
Exemplo n.º 15
0
            internal static async Task <MethodResult> SubmitTosTask(Model account, HttpClient client)
            {
                var methodResult = new MethodResult();

                try
                {
                    var keyValuePairArray = new KeyValuePair <string, string>[2]
                    {
                        new KeyValuePair <string, string>("csrfmiddlewaretoken", account.Csrf),
                        new KeyValuePair <string, string>("go_terms", "on")
                    };
                    using (
                        var httpResponseMessage =
                            await client.PostAsync(GoSettings, new FormUrlEncodedContent(keyValuePairArray)))
                    {
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            var result = await httpResponseMessage.Content.ReadAsStringAsync();

                            methodResult.Value = result;

                            if (!result.ToLower().Contains("id_go_terms"))
                            {
                                methodResult.Success = true;
                            }
                            else
                            {
                                methodResult.Error = new Exception("Failed to submit terms of service");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    methodResult.Error   = ex;
                    methodResult.Success = false;
                }

                return(methodResult);
            }
Exemplo n.º 16
0
        private void DownloadButton_Click(object sender, EventArgs e)
        {
            Dac       dac           = new Dac();
            DataTable userDataTable = dac.ExecuteDataTable("SELECT * FROM User").Result;
            decimal   progress      = 0;

            foreach (DataRow dr in userDataTable.Rows)
            {
                IUser user = TwitterEngine.User.FindUserFromUserName((string)dr["UserName"]).Result;
                if (user == null)
                {
                    continue;
                }

                progress++;
                ProgressbarDescriptionLabel.Text = user.Name;
                ProgressBar.Value = (int)((progress / userDataTable.Rows.Count) * 100);

                MethodResult <int> result = DbHelper.SaveTweetList(user.GetUserTimeline((int)TweetCountNumericUpDown.Value).ToList <ITweet>());
                if (result.IsSuccessful)
                {
                    //ProgressbarDescriptionLabel.Text = user.Name + " : " + result.Result.ToString() + " Tweets Saved :-)";
                    ResultsTextBox.Text += Environment.NewLine + user.Name + " : " + result.Result.ToString() + " Tweets Saved :-)";
                    //MessageBox.Show(user.Name + " : " + result.Result.ToString() + " Tweets Saved :-)", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    ProgressbarDescriptionLabel.Text = user.Name + " : " + "Save Error :-(";
                    ResultsTextBox.Text += Environment.NewLine + user.Name + " : " + "Save Error :-(";
                    ProgressBar.Value    = 0;
                    MessageBox.Show(user.Name + " : " + "Save Error :-(" + Environment.NewLine + result.Exception.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }
            }

            ProgressbarDescriptionLabel.Text = "Finished";
            ResultsTextBox.Text += Environment.NewLine + "Finished";
            ProgressBar.Value    = 100;
        }
Exemplo n.º 17
0
        private async Task <MethodResult> EvolveFilteredPokemon()
        {
            MethodResult <List <PokemonData> > response = await GetPokemonToEvolve();

            if (response.Data.Count == 0)
            {
                return(new MethodResult());
            }

            LogCaller(new LoggerEventArgs(String.Format("{0} pokemon to evolve", response.Data.Count), LoggerTypes.Info));

            if (response.Data.Count < UserSettings.MinPokemonBeforeEvolve)
            {
                LogCaller(new LoggerEventArgs(String.Format("Not enough pokemon to evolve. {0} of {1} evolvable pokemon", response.Data.Count, UserSettings.MinPokemonBeforeEvolve), LoggerTypes.Info));

                return(new MethodResult
                {
                    Message = "Success",
                    Success = true
                });
            }

            if (UserSettings.UseLuckyEgg)
            {
                MethodResult result = await UseLuckyEgg();

                if (!result.Success)
                {
                    LogCaller(new LoggerEventArgs("Failed to use lucky egg. Possibly already active. Continuing evolving", LoggerTypes.Info));
                }
            }

            await EvolvePokemon(response.Data);

            return(new MethodResult
            {
                Success = true,
                Message = "Success"
            });
        }
Exemplo n.º 18
0
        public async Task <MethodResult> AcLogin()
        {
            LogCaller(new LoggerEventArgs("Attempting to login ...", LoggerTypes.Debug));
            AccountState = AccountState.Conecting;

            MethodResult result = null;

            result = await _client.DoLogin(this);

            LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.Debug));

            if (!result.Success)
            {
                LogCaller(new LoggerEventArgs(result.Message, LoggerTypes.FatalError));
                if (AccountState == AccountState.Conecting || AccountState == AccountState.Good)
                {
                    AccountState = AccountState.Unknown;
                }
                Stop();
            }
            else
            {
                if (AccountState == AccountState.Conecting)
                {
                    AccountState = AccountState.Good;
                }
                // This is part of the login process
                if (UserSettings.ClaimLevelUpRewards)
                {
                    await ClaimLevelUpRewards(Level);
                }
            }

            if (CurrentProxy != null)
            {
                ProxyHandler.ResetFailCounter(CurrentProxy);
            }

            return(result);
        }
Exemplo n.º 19
0
        public async Task <MethodResult> GetPlayer(bool nobuddy = true, bool noinbox = true)
        {
            try
            {
                if (!_client.LoggedIn)
                {
                    MethodResult result = await AcLogin();

                    if (!result.Success)
                    {
                        return(result);
                    }
                }

                var response = await _client.ClientSession.RpcClient.SendRemoteProcedureCallAsync(new Request {
                    RequestType    = RequestType.GetPlayer,
                    RequestMessage = new GetPlayerMessage {
                        PlayerLocale = new GetPlayerMessage.Types.PlayerLocale {
                            Country  = UserSettings.PlayerLocale.Country,
                            Language = UserSettings.PlayerLocale.Language,
                            Timezone = UserSettings.PlayerLocale.Timezone
                        }
                    }.ToByteString()
                }, true, nobuddy, noinbox);


                var parsedResponse = GetPlayerResponse.Parser.ParseFrom(response);


                return(new MethodResult
                {
                    Success = true
                });
            }
            catch (Exception ex)
            {
                LogCaller(new LoggerEventArgs("Failed to get level up rewards", LoggerTypes.Exception, ex));
                return(new MethodResult());
            }
        }
Exemplo n.º 20
0
        /// <returns>Virtual path to the file with extension</returns>
        public MethodResult <string> UploadImage(HttpPostedFileBase file, UploadLocationEnum location, bool enableSizeValidation = true)
        {
            MethodResult <string> result = MethodResult <string> .Success;

            if (file == null || file.ContentLength == 0)
            {
                throw new UserReadableException("File is empty or does not exist");
            }

            var tempPath = Path.GetTempFileName();

            file.SaveAs(tempPath);

            Image img = Image.FromFile(tempPath);

            if (enableSizeValidation)
            {
                result.Merge(checkIfImageIsCorrect(img));
            }

            if (result.IsError)
            {
                return(result);
            }

            var fileName = GetUniqueFilePath(location, ".png");

            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
            var imageFile = File.Create(fileName);


            img.Save(imageFile, ImageFormat.Png);
            img.Dispose();
            File.Delete(tempPath);
            imageFile.Close();


            result.ReturnValue = "\\" + fileName.Replace(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"], string.Empty);
            return(result);
        }
        public static async Task <MethodResult <BaseSettings> > Load(this ISettings settings, string moduleName)
        {
            var methodResult = new MethodResult <BaseSettings> {
                MethodName = "SettingExtension.Load"
            };

            ;
            try
            {
                var content = await GetFileContent($"{settings.PluginSettingsBaseDirectory}/{moduleName}.json");

                var loadedSettings = JsonConvert.DeserializeObject <BaseSettings>(content);
                settings.Enabled = loadedSettings.Enabled;
            }
            catch (Exception e)
            {
                methodResult.Error   = e;
                methodResult.Success = false;
            }

            return(methodResult);
        }
Exemplo n.º 22
0
        public MethodResult <int> NewUser(string username, string email, string password, HashSet <Role> roles)
        {
            using (var context = new SecurityContext())
            {
                var  repo = new UserRepository(context);
                User user = repo.Find(x => x.Username == username, null).FirstOrDefault();

                if (user == null)
                {
                    HashSet <Role> _roles = new HashSet <Role>();

                    foreach (var ro in roles)
                    {
                        var _role = repo.GetRole(ro.RoleTitle);
                        if (_role == null)
                        {
                            _role = new Role()
                            {
                                RoleTitle = ro.RoleTitle
                            };
                        }
                        _roles.Add(_role);
                    }



                    user          = new User(username, email, _roles);
                    user.Password = Infrastructure.Utilites.Security.CalculateHash(password, user.Username);
                    repo.Add(user);
                }
                else
                {
                    throw new ArgumentException("Пользователь с таки именем существует", "User");
                }
                repo.Save();
                var result = new MethodResult <int>(0);
                return(result);
            }
        }
Exemplo n.º 23
0
        public void GetReplicationDataInvalidObjectTest()
        {
            //create a new instance of the method input class found in ConnectorApi.Actions
            //Assign the MethodInput name to the Name of the method to be executed
            MethodInput methodInput = new MethodInput {
                Name = "GetReplicationData"
            };

            //set the object name by adding the property to the input
            methodInput.Input.Properties.Add("ObjectName", InvalidPropertyValue);

            //set the Last date of syncronization by adding the property to the input
            methodInput.Input.Properties.Add("LastSyncDate", DateTime.Now.AddYears(-5));


            //execute the selected method
            MethodResult methodResult = _rsSourceConnector.ExecuteMethod(methodInput);

            //Note: this will show it was not a success and set the error info rather than throwing an exception
            Assert.IsFalse(methodResult.Success);
            Assert.IsNotNull(methodResult.ErrorInfo);
        }
Exemplo n.º 24
0
        private MethodResult mysqldump(string databaseName, string destinationSqlScriptFile)
        {
            var result = new MethodResult();

            var Location = Path.Combine(ImportHelper.GetRegistryKeyValue(MYSQL51_REGISTRY_KEY, "Location"), "bin", "mysqldump.exe");

            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.FileName  = String.Format("\"{0}\"", Location);
            startInfo.Arguments = String.Format("--host={0} --user={1}  --password={2} --routines --triggers --events --add-drop-table --dump-date --opt --no-create-db --set-charset --database {3} -r \"{4}\"",
                                                Settings.Default.mysqlHost,
                                                Settings.Default.mysqlUser,
                                                Settings.Default.mysqlPassword,
                                                databaseName,
                                                destinationSqlScriptFile);

            startInfo.CreateNoWindow         = true;
            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardError  = true;
            startInfo.RedirectStandardOutput = false;
            startInfo.WindowStyle            = ProcessWindowStyle.Hidden;

            using (var execute = Process.Start(startInfo))
            {
                execute.WaitForExit();

                if (execute.ExitCode != 0)
                {
                    result.Status = false;
                    result.Msg    = execute.StandardError.ReadToEnd();
                }
                else
                {
                    result.Status = true;
                }
            }

            return(result);
        }
        /// <summary>
        /// Uninitializes a single test case.
        /// </summary>
        public virtual void TestUninitialize(MethodResult result)
        {
            this.TestUninitialize();

            BundleBuilder.CleanupByUninstalling();
            PackageBuilder.CleanupByUninstalling();
            MSIExec.UninstallAllInstalledProducts();

            MsiVerifier.Reset();

            this.ResetRegistry();
            this.ResetDirectory();

            if (this.cleanArtifacts)
            {
                foreach (FileSystemInfo artifact in this.TestArtifacts)
                {
                    if (artifact.Exists)
                    {
                        try
                        {
                            DirectoryInfo dir = artifact as DirectoryInfo;
                            if (null != dir)
                            {
                                dir.Delete(true);
                            }
                            else
                            {
                                artifact.Delete();
                            }
                        }
                        catch
                        {
                            Debug.WriteLine(String.Format("Failed to delete '{0}'.", artifact.FullName));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Administratively adds a user.
        /// </summary>
        /// <param name="toAdd">The user to add.</param>
        /// <param name="userUnits">The users units.</param>
        /// <returns>MethodResult indicating success.</returns>
        public MethodResult AdministrativelyAddUser(User toAdd, IReadOnlyList <Guid> userUnits)
        {
            var password = PasswordGenerator.GeneratePw();
            var result   = Factory.GetControllerInstance <IClipperDatabase>().AddUser(toAdd.MailAddress, toAdd.UserName,
                                                                                      password, toAdd.Role, toAdd.PrincipalUnitId,
                                                                                      userUnits[0], true, true);
            MethodResult innerResult = result;

            if (result.IsSucceeded())
            {
                if (userUnits.Count > 1)
                {
                    innerResult = DatabaseAdapterFactory.GetControllerInstance <IClipperDatabase>()
                                  .SetUserOrganizationalUnits(result.Result, userUnits.Skip(1));
                }

                QuerySendMailAsync(toAdd, ClipperTexts.AccountCreatedMailSubject,
                                   string.Format(ClipperTexts.AccountCreatedMailBody, toAdd.UserName, password));
            }

            return(innerResult);
        }
Exemplo n.º 27
0
        public static MethodResult <List <TResult> > SelectResults <TSource, TResult>(
            this IEnumerable <TSource> @this,
            Func <TSource, MethodResult <TResult> > function)
        {
            var thisList = @this.ToList();

            var selectedResult = new List <TResult>(thisList.Count);

            foreach (var item in thisList)
            {
                var result = function(item);
                if (!result.IsSuccess)
                {
                    result.Detail.AddDetail(new { thisObj = thisList, targetItem = item });
                    return(MethodResult <List <TResult> > .Fail(result.Detail));
                }

                selectedResult.Add(result.Value);
            }

            return(MethodResult <List <TResult> > .Ok(selectedResult));
        }
        public MethodResult Delete(int organisationPKId)
        {
            var methodResult = new MethodResult();

            try
            {
                var organisation = _context.OrgList.Find(organisationPKId);
                if (organisation != null)
                {
                    _context.OrgList.Remove(organisation);
                    _context.SaveChanges();
                }
                methodResult.SuccessFaliure = Enums.MethodResultOutcome.Success;
                methodResult.Message        = "Organisation deleted successfully";
            }
            catch (Exception e)
            {
                methodResult.SuccessFaliure = Enums.MethodResultOutcome.Failure;
                methodResult.Message        = "Error ocurred while deleting organisation, please retry";
            }
            return(methodResult);
        }
Exemplo n.º 29
0
        public override void After(MethodInfo methodUnderTest, MethodResult result)
        {
            // remove logs when test passed and another favour of test doesn't fail previously (used in case of Theory tests).
            if (PerTestLogger.ShouldEnablePerTestLog() && result is PassedResult && !failedMethods.Contains(methodUnderTest))
            {
                var fileToDelete = Path.Combine(PerTestLogger.TestsDirName, PerTestLogger.GenerateTestFileName(methodUnderTest));
                if (File.Exists(fileToDelete))
                {
                    IOExtensions.DeleteFile(fileToDelete);
                    var parentDir = Directory.GetParent(fileToDelete);
                    if (!parentDir.EnumerateFileSystemInfos().Any())
                    {
                        IOExtensions.DeleteDirectory(parentDir.FullName);
                    }
                }
            }

            if (result is FailedResult)
            {
                failedMethods.Add(methodUnderTest);
            }
        }
Exemplo n.º 30
0
        private async Task <MethodResult> SetPlayerAvatar()
        {
            var avatar = new PlayerAvatar();

            if (!_client.LoggedIn)
            {
                MethodResult result = await AcLogin();

                if (!result.Success)
                {
                    return(result);
                }
            }

            var response = await _client.ClientSession.RpcClient.SendRemoteProcedureCallAsync(new Request
            {
                RequestType    = RequestType.SetAvatar,
                RequestMessage = new SetAvatarMessage
                {
                    PlayerAvatar = avatar
                }.ToByteString()
            }, true, true, true);

            if (response == null)
            {
                return(new MethodResult());
            }

            SetAvatarResponse setAvatarResponse = null;

            setAvatarResponse = SetAvatarResponse.Parser.ParseFrom(response);
            LogCaller(new LoggerEventArgs("Avatar set to defaults", LoggerTypes.Success));


            return(new MethodResult
            {
                Success = true
            });
        }
Exemplo n.º 31
0
        public MethodResult <OrderResult> MakeANewOrder(OrderRequest order)
        {
            RateLimit();
            var request = new RestRequest("/orders", Method.POST);

            request.AddJsonBody(GdaxOrderRequest.ConvertFrom(order, _currencyMapper));
            AddAuthenticationHeader(request);
            var client = new RestClient(baseUrl);
            //client.Proxy = new WebProxy("127.0.0.1", 8888); for fiddler trace
            var response = client.Execute <GdaxOrderResponse>(request);

            if (response.IsSuccessful)
            {
                var result = new OrderResult();
                return(new MethodResult <OrderResult>()
                {
                    IsSuccessful = true,
                    Data = response.Data.Convert()
                });
            }
            return(MethodResult <OrderResult> .Failed(response.ErrorMessage));
        }
Exemplo n.º 32
0
        // This other Percent gives different IV % for the same IVs depending of the pokemon level.
        public MethodResult <double> CalculateIVPerfectionUsingMaxCP(PokemonData pokemon)
        {
            MethodResult <PokemonSettings> settingResult = GetPokemonSetting(pokemon.PokemonId);

            if (!settingResult.Success)
            {
                return(new MethodResult <double>
                {
                    Data = -1,
                    Message = settingResult.Message
                });
            }

            /*
             * if (Math.Abs(pokemon.CpMultiplier + pokemon.AdditionalCpMultiplier) <= 0)
             * {
             *  double perfection = (double)(pokemon.IndividualAttack * 2 + pokemon.IndividualDefense + pokemon.IndividualStamina) / (4.0 * 15.0) * 100.0;
             *
             *  return new MethodResult<double>
             *  {
             *      Data = perfection,
             *      Message = "Success",
             *      Success = true
             *  };
             * }*/

            double maxCp = CalculateMaxCpMultiplier(pokemon);
            double minCp = CalculateMinCpMultiplier(pokemon);
            double curCp = CalculateCpMultiplier(pokemon);

            double perfectPercent = (curCp - minCp) / (maxCp - minCp) * 100.0;

            return(new MethodResult <double>
            {
                Data = perfectPercent,
                Message = "Success",
                Success = true
            });
        }
Exemplo n.º 33
0
        public static async Task <MethodResult <List <TResult> > > SelectResultsAsync <TSource, TResult>(
            this Task <IEnumerable <TSource> > @this,
            Func <TSource, TResult> function)
        {
            var thisList = (await @this).ToList();

            var selectedResult = new List <TResult>(thisList.Count);

            foreach (var item in thisList)
            {
                try {
                    var result = function(item);
                    selectedResult.Add(result);
                }
                catch (Exception e) {
                    return(MethodResult <List <TResult> > .Fail(new ExceptionError(e,
                                                                                   moreDetails : new { thisObj = thisList, targetItem = item })));
                }
            }

            return(MethodResult <List <TResult> > .Ok(selectedResult));
        }
Exemplo n.º 34
0
        public static void WriteDependencies(string signatureName, List<string> dependencies, StreamWriter writer, MethodResult methods, MethodResult members, string currentPath)
        {
            var dependenciesList = dependencies.ToArray().ToList();
            if (members != null)
                dependenciesList.AddRange(members.dependencies);
            if (methods != null)
                dependenciesList.AddRange(methods.dependencies);

            foreach (var dep in dependenciesList.Distinct().Where(d => d != signatureName))
            {
                WriteDependency(writer, currentPath, dep);
            }
        }
Exemplo n.º 35
0
        /// <summary>
        /// This method will execute a Method returning a result. 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public MethodResult ExecuteMethod(MethodInput input)
        {
            MethodResult methodResult;

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point is written during garbage collection.
            using (new LogMethodExecution(Globals.ConnectorName, "Execute Method"))
            {
                //Construct a new instance of the method handler
                //passing along the current instance of the data access object
                MethodHandler methodHandler = new MethodHandler(_dataAccess);

                try
                {
                    //Use the name stored in the method
                    //input to determine the correct method to execute
                    switch (input.Name.ToLower())
                    {
                        case "getobjectdefinition":
                            methodResult = methodHandler.GetObjectDefinition(input);
                            break;
                        case "createorupdateobjectforreplication":
                            methodResult = methodHandler.CreateOrUpdateObjectForReplication(input);
                            break;
                        case "getlastreplicationsyncdate":
                            methodResult = methodHandler.GetLastReplicationSyncDate(input);
                            break;
                        default:
                            string message = string.Format(ErrorCodes.UnknownMethod.Description, input.Name);
                            throw new InvalidExecuteMethodException(ErrorCodes.UnknownMethod.Number, message);
                    }

                    LogMethodResult(methodResult);
                }
                //Here we throw the Fatal Error Exception which is used to notify upper layers that
                //an error has occured in the Connector and will be unable to recover from it
                catch (FatalErrorException)
                {
                    throw;
                }
                catch (Exception exception)
                {
                    //Log any other exceptions that occur during method execution
                    //and store them in the MethodResult.ErrorInfo
                    methodResult = new MethodResult {Success = false};

                    //Create the error info using the exception message
                    methodResult.ErrorInfo = new ErrorResult
                    {
                        Description = exception.Message,
                        Detail = exception.StackTrace,
                        Number = ErrorCodes.MethodError.Number
                    };

                    LogMethodResult(methodResult);
                }

            }
            return methodResult;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Method to correctly log the result of the method 
        /// </summary>
        /// <param name="methodResult">Method Result to log</param>
        private void LogMethodResult(MethodResult methodResult)
        {
            string message;
            //Connector Api severity enumertion to define the level for logging
            Logger.Severity severity;

            //check if the result of the method was a success
            if (methodResult.Success)
            {
                //create a message to log in the event of a success
                message = "Method Executed Successfully";
                severity = Logger.Severity.Debug;
            }
            else
            {
                //create a message to log in the event of an error
                var errorInfo = methodResult.ErrorInfo;
                message = string.Format("An Error has occured in {0}: {2}Error Number:{1}{2}Error Description:{3}{2}Error Detail:{4}", Globals.ConnectorName, errorInfo.Number, Environment.NewLine, errorInfo.Description, errorInfo.Detail);
                severity = Logger.Severity.Error;
            }

            //log the result severity, the name of the connector, and the created message
            Logger.Write(severity, Globals.ConnectorName, message);
        }
Exemplo n.º 37
0
        /// <summary>
        /// Get a specific Object's definition, this includes any attributes and
        /// supporting object properties.
        /// In this case retrieve the table definition along with any columns and
        /// the definition of each.
        /// </summary>
        /// <param name="methodInput">Method Input which includes an 'ObjectName' 
        /// property to determine the object to retrieve the definition.</param>
        /// <returns>Method Result, which will either include error information or the 
        /// Object Definition of the 'ObjectName' specified in the 
        /// MethodInput properties.</returns>
        public MethodResult GetObjectDefinition(MethodInput methodInput)
        {
            //Create a new instance of the method result to fill with
            //meta data information
            MethodResult result = null;

            //Create a new instance of the metadata access class and pass the
            //data access instance along with it
            OleDbMetadataAccess metadataAccess = new OleDbMetadataAccess(_dataAccess);

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point
            // is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "GetObjectDefinition"))
            {
                //Get the name of the object in the input properties.
                string objectName =
                    GetPropertyValueName("ObjectName", methodInput.Input.Properties);

                //Use the metadata access to get the
                //definitions for each of the columns in the table.
                DataTable tableColumnDefinitions =
                    metadataAccess.GetColumnDefinitions(objectName);

                //Using the meta data access get the definition for the
                //table indexes (primary and foreign keys)
                DataTable tableIndexDefinition =
                    metadataAccess.GetTableIndexInformation(objectName);

                //Check that both sets of data have been returned
                //from the meta data access layer
                if ((tableColumnDefinitions != null
                    && tableColumnDefinitions.Rows.Count != 0) &&
                    (tableIndexDefinition != null
                    && tableIndexDefinition.Rows.Count != 0))
                {
                    //Create a new replication service object
                    RSObjectDefinition rsObjectDefinition = new RSObjectDefinition()
                    {
                        Name = objectName,
                        RSPropertyDefinitions = new List<RSPropertyDefinition>()
                    };

                    //If this is the change history table set the hidden attribute.
                    //Note: this is how to prevent an object from being replicated.
                    rsObjectDefinition.Hidden = objectName == Globals.ChangeHistoryTableName;

                    List<string> tablePrimaryKeys =
                        GetTablePrimaryKeys(rsObjectDefinition.Name, metadataAccess);

                    //Parse each column returned from the column definitions.
                    //For each column, add a new replication service property definition
                    //to the newly created replication service object definition.
                    foreach (DataRow columnDefinition in tableColumnDefinitions.Rows)
                    {
                        //Process the column definition and set it to the
                        //resplication service property definition.
                        RSPropertyDefinition rsPropertyDefinition =
                            ProcessColumnDefinition(columnDefinition);

                        //Check if this is the default last modified column and
                        //set the object property.
                        if (rsPropertyDefinition.Name == LastModifiedFieldName)
                        {
                            rsObjectDefinition.ModificationDateFullName =
                                rsPropertyDefinition.Name;
                        }

                        //Check if the property is a primary key value.
                        rsPropertyDefinition.InPrimaryKey =
                            tablePrimaryKeys.Contains(rsPropertyDefinition.Name);

                        //Add the property definition to the object definition.
                        rsObjectDefinition.RSPropertyDefinitions.Add(rsPropertyDefinition);
                    }

                    //Convert the replication service object definition to a Data Entity.
                    //Set the result return value to the
                    //replication service object definition.
                    //Set the result Success to true.
                    result = new MethodResult
                    { Success = true, Return = rsObjectDefinition.ToDataEntity() };
                }
                else
                {
                    //Set the proper error information in the method result in the
                    //event of a null table or column definitions.
                    result = SetErrorMethodResult(
                        ErrorCodes.NoObjectsFound.Number,
                        ErrorCodes.NoObjectsFound.Description);
                }

            }

            //Return the method result.
            return result;
        }
Exemplo n.º 38
0
        /// <summary>
        /// Get a specific Object's definition, this includes any attributes and supporting object properties.
        /// In this case retrieve the table definition along with any columns and the definition of each.
        /// </summary>
        /// <param name="methodInput">Method Input which includes an 'ObjectName' 
        /// property to determine the object to retrieve the definition for.</param>
        /// <returns>Method Result which will either include error information or the 
        /// Object Definition of the 'ObjectName' specified in the MethodInput properties</returns>
        public MethodResult GetObjectDefinition(MethodInput methodInput)
        {
            //Create a new instance of the method result to
            //fill with meta data information
            MethodResult result = new MethodResult();

            //create a new instance of the metadata access class and
            //pass the data access instance allong with it
            OleDbMetadataAccess metadataAccess = new OleDbMetadataAccess(_dataAccess);

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point
            //is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "GetObjectDefinitionMethod"))
            {
                //get the name of the object in the input properties
                string objectName = GetPropertyValue(
                    "ObjectName", methodInput.Input.Properties);

                //using the meta data access get the definitions
                //for each of the columns in the table
                DataTable tableColumnDefinitions =
                    metadataAccess.GetColumnDefinitions(objectName);

                //using the meta data access get the definition for
                //the table indexes (primary and foreign keys)
                DataTable tableIndexDefinition =
                    metadataAccess.GetTableIndexInformation(objectName);

                //check that both sets of data have been
                //returned from the meta data access layer
                if ((tableColumnDefinitions != null
                    && tableColumnDefinitions.Rows.Count != 0)
                    && (tableIndexDefinition != null
                    && tableIndexDefinition.Rows.Count != 0))
                {
                    //create a new replication service object
                    RSObjectDefinition rsObjectDefinition = new RSObjectDefinition()
                    {
                        Name = objectName,
                        RSPropertyDefinitions = new List<RSPropertyDefinition>()
                    };

                    List<string> tablePrimaryKeys =
                        GetTablePrimaryKeys(rsObjectDefinition.Name, metadataAccess);

                    //parse through each column return from the column definitions and
                    //add a new replication service property definition to the newly created
                    //replication service object definition for each column in the table
                    foreach (DataRow columnDefinition in tableColumnDefinitions.Rows)
                    {
                        //process the column definition and set it
                        //to the resplication service property definition
                        RSPropertyDefinition rsPropertyDefinition =
                            ProcessColumnDefinition(columnDefinition);

                        //check if this is the default last
                        //modified column and set the object property
                        if (rsPropertyDefinition.Name == LastModifiedFieldName)
                        {
                            rsObjectDefinition.ModificationDateFullName =
                                rsPropertyDefinition.Name;
                        }

                        //check if the property is a primary key value
                        rsPropertyDefinition.InPrimaryKey =
                            tablePrimaryKeys.Contains(rsPropertyDefinition.Name);

                        //add the property definition to the object definition
                        rsObjectDefinition.RSPropertyDefinitions.Add(rsPropertyDefinition);
                    }

                    //Convert the replication service object definition to a Data Entity
                    //set the result return value to the replication service object defintion
                    //set the result success to true
                    result = new MethodResult { Success = true, Return = rsObjectDefinition.ToDataEntity() };
                }
                else
                {
                    result = new MethodResult { Success = false, ErrorInfo = new ErrorResult { Description = ErrorCodes.ObjectNotFound.Description, Number = ErrorCodes.ObjectNotFound.Number } };
                }
            }

            //return the method result
            return result;
        }
Exemplo n.º 39
0
        /// <summary>
        /// Get the list of 'Object' names or in this case 
        /// table names from the data source 
        /// include the primary key or identifyer in the each of the objects
        /// </summary>
        /// <returns>MethodResult to be return in a readable state</returns>
        public MethodResult GetObjectDefinitionList()
        {
            //Create a new instance of the method result to fill with
            //meta data information
            MethodResult result = new MethodResult();

            // Create a new instance of the metadata access class and pass
            // the data access instance along with it
            OleDbMetadataAccess metadataAccess =
                new OleDbMetadataAccess(_dataAccess);

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point
            // is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "GetObjectDefinitionList"))
            {
                //Get a list of indexes for each table
                DataTable tableList = metadataAccess.GetTableList();

                //check that valid data has been return from the schema
                if (tableList != null && tableList.Rows.Count != 0)
                {
                    //Create a list of generic Data Entities
                    //***This is a Key piece of the replication process***
                    //This is where the table list will be stored in a
                    //generic fashion and return in the result.
                    List<DataEntity> dataEntityList = new List<DataEntity>();

                    //Parse the list of rows that contain the table
                    //information and stuff them into generic data entities.
                    //Add them to the list that will be returned in the result.
                    foreach (DataRow tableRow in tableList.Rows)
                    {
                        var tableName = tableRow["TABLE_NAME"].ToString();

                        var dataEntity = new DataEntity("Object");
                        dataEntity.Properties.Add("Name", tableName);
                        dataEntity.Properties.Add(
                            "PrimaryKeyName", PrimaryKeyFieldName);
                        dataEntity.Properties.Add(
                            "Description", GetTableDescription(tableName));
                        //Check if the table has the ModifiedOn column
                        dataEntity.Properties.Add(
                            "ModificationDateFullName",
                            CheckForLastModifiedColumnName(
                                tableName, metadataAccess)
                                ? LastModifiedFieldName : string.Empty);

                        dataEntity.Properties.Add("Hidden", tableName == Globals.ChangeHistoryTableName);

                        dataEntityList.Add(dataEntity);
                    }

                    //Set the success of the result to true since the
                    //list of entities has been filled.
                    result.Success = true;

                    //Create a new instance of the return result set
                    //with the name of the returned items.
                    result.Return = new DataEntity("ObjectList");

                    //Add the entity list to the result.
                    result.Return.Properties.Add("Result", dataEntityList);
                }
                else
                {
                    //Set the proper error information in the event that
                    //incorrect schema information is returned from the database.
                    result = SetErrorMethodResult(
                        ErrorCodes.GetObjectList.Number, ErrorCodes.GetObjectList.Description);
                }
            }

            //Return the method result containing the object definition list.
            return result;
        }
Exemplo n.º 40
0
        /// <summary>
        /// This is the method to get data for replication 
        /// for an individual object. Rows will be returned as they are read.
        /// </summary>
        /// <param name="methodInput"></param>
        /// <returns></returns>
        public MethodResult GetReplicationData(MethodInput methodInput)
        {
            MethodResult result = null;

            using (new LogMethodExecution(
                Globals.ConnectorName, "GetReplicationData"))
            {
                //Get the name of the object in the input properties.
                string objectName = GetPropertyValueName(
                    "ObjectName",methodInput.Input.Properties);

                //Get the last sychronization date from the input properties
                DateTime lastSyncDate = GetLastSyncDate(methodInput.Input.Properties);

                OleDbMetadataAccess metadataAccess = new OleDbMetadataAccess(_dataAccess);
                bool hasLastModified = CheckForLastModifiedColumnName(objectName, metadataAccess);

                try
                {
                    //Passes control of the lower level method in the data access layer
                    //to the calling method.This passes the IEnumerable object
                    //(filled with data rows) out to the calling methodin conjunction
                    //with the yield statement at the lower level, is looking for the
                    //foreach loop else control is passed out to the calling method.
                    //Here, the attempt to get an entity is performed (by calling the
                    //empty foreach loop) in order to check for errors - else the top
                    //level has control and exceptions get passed directly up.  Here we assume
                    //that no error on retrieving row 1 means we are safe to pass control
                    //back to the calling method and skip the error checking
                    //that is forced on the first entity.

                    IEnumerable<DataEntity> replicationData =
                        _dataAccess.GetReplicationDataRetrieve(
                        objectName, lastSyncDate, hasLastModified);

                    //Force a check for errors. The previous method call
                    //will not be performed until it is requested for use here.
                    foreach (var dataEntity in replicationData)
                    {
                        break;
                    }

                    //Create a new method result
                    result = new MethodResult();
                    //Indicate that the result is a success
                    result.Success = true;
                    //Set the result return to a new data entity
                    //which MUST be named "ReplicationQueryData"
                    result.Return = new DataEntity("ReplicationQueryData");

                    //Add the yielded replication data to the return properties in the result
                    //Note: the property name MUST be labeled as 'EntityData'
                    result.Return.Properties.Add("EntityData", replicationData);
                }
                catch (Exception exception)
                {
                    //Be sure to log any errors and add them to the
                    //error information for the method result
                    Logger.Write(
                        Logger.Severity.Error, Globals.ConnectorName, exception.Message);
                    result = SetErrorMethodResult(
                        ErrorCodes.GetData.Number, ErrorCodes.GetData.Description);
                }

            }
            //Return the method result containing the replication data
            return result;
        }
 private void PostExecute(IAsyncResult syncResult)
 {
     _result = _method.EndInvoke(syncResult);
     if (PostExecuteHandler != null)
         PostExecuteHandler(sender, this, _result);
 }
Exemplo n.º 42
0
        /// <summary>
        /// This method defines the process for tracking changes to data.
        /// This particular example shows one way how this operation may work. 
        /// Note: A seperate method will create triggers for each table that will fill this table with deletions.
        /// Note: If the data-source already has a process for tracking changes, this 
        ///       method will only need to return a positive success in the method result
        /// </summary>
        /// <returns></returns>
        public MethodResult InitReplication()
        {
            MethodResult methodResult = null;

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point
            // is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "InitReplication"))
            {
                //First retrieve the object definition of the
                //default table that is used for replication.
                MethodInput objectDefinitionInput = new MethodInput();
                objectDefinitionInput.Input.Properties.Add(
                    "ObjectName", "ScribeChangeHistory");
                MethodResult objectDefinitionResult =
                    GetObjectDefinition(objectDefinitionInput);

                //If the replication table already exist then our work
                //here is done. No other action is required.
                if (objectDefinitionResult.Success == false)
                {
                    //Use the Sribe-provided local data storage
                    //to retrieve and read the sql scripts contents.
                    LocalDataStorage localDataStorage = new LocalDataStorage();
                    string query =
                        localDataStorage.ReadData(ChangeHistoryFileName);

                    //Throw an error message if the file was not found
                    if (string.IsNullOrWhiteSpace(query))
                    {
                        throw new InvalidExecuteOperationException(string.Format("Unable to locate file: {0}", ChangeHistoryFileName));
                    }

                    //Execute the query to create the change history table.
                    _dataAccess.ExecuteNonQuery(query);
                }

                //If there were no errors in processing, then
                //set the Success for the method result to true.
                methodResult = new MethodResult { Success = true };
            }

            return methodResult;
        }
Exemplo n.º 43
0
        /// <summary>
        /// This method determines whether or not an object from the source has changed.
        /// If the object does not exist it will be created.
        /// If the object has changed it will be deleted and the new one will be created.
        /// If no changes are detected then it will be noted and no further action is needed.
        /// </summary>
        /// <param name="methodInput"></param>
        /// <returns></returns>
        public MethodResult CreateOrUpdateObjectForReplication(MethodInput methodInput)
        {
            MethodResult methodResult = new MethodResult();

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point
            //is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "CreateOrUpdateObjectForReplication"))
            {
                string tableName = GetPropertyValue("Name", methodInput.Input.Properties);
                //get the list of the columns to be created
                List<DataEntity> newColumns =
                    methodInput.Input.Children["RSPropertyDefinitions"];

                //add the default columns to the new ones from the input
                newColumns.AddRange(CreateDefaultColumns());

                //get the definition of the existing table
                MethodResult currentTableDefinition =
                    GetObjectDefinition(new MethodInput
                                            {
                                                Input =
                                                    {
                                                        Properties = new EntityProperties
                                                                             {
                                                                                 {"ObjectName", tableName}
                                                                             }
                                                    }
                                            });

                bool changeDetected = true;

                //check if the table was returned from GetObjectDefinition method
                if (currentTableDefinition != null && currentTableDefinition.Success)
                {
                    //look for any changes in the table schema by
                    //comparing the properties
                    //of the existing object against the those
                    //found in the method input
                    changeDetected = CheckForSchemaChanges(newColumns,
                                                           currentTableDefinition.Return.Children[
                                                               "RSPropertyDefinitions"]);

                    //if a change is decteded drop the table
                    if (changeDetected)
                    {
                        string query = string.Format("DROP TABLE [{0}]", tableName);
                        _dataAccess.ExecuteNonQuery(query);
                    }
                }

                //Ff a change is detected create the table
                if (changeDetected)
                {
                    _dataAccess.CreateTable(tableName, newColumns);
                }

                //Set the method result object
                methodResult = new MethodResult { Success = true, Return = new DataEntity() };

                //add a property called 'SchemaChanged' to the return properties
                //this is how ScribeOnline will determine whether or not a replication
                //is required when this method has completed
                //Note: this MUST be labeled 'SchemaChanged'
                methodResult.Return.Properties.Add("SchemaChanged", changeDetected);
            }

            return methodResult;
        }
Exemplo n.º 44
0
        /// <summary>
        /// In the event of an error we want to package it up nicely within the Method Result Error Infor property,
        /// as well as Log the occurence
        /// </summary>
        /// <param name="errorCode">Int value for the error code</param>
        /// <param name="errorDescription">Text value fo the description of the error</param>
        /// <returns>Method Result object containing with the error information property populated</returns>
        private MethodResult SetErrorMethodResult(int errorCode, string errorDescription)
        {
            //create a new instance of the Method Result object from the Connector Api packaging up the error code and description
            MethodResult result = new MethodResult
                                      {
                                          Success = false,
                                          ErrorInfo =
                                              new ErrorResult { Number = errorCode, Description = errorDescription }
                                      };

            //Use the Connector Api Logger to log the error event, include the severity level, connector name as well as the description
            Logger.Write(Logger.Severity.Error, Globals.ConnectorName, result.ErrorInfo.Description);

            //send back the method result object that was created
            return result;
        }
 public void MethodExecuted(object sender, MethodParamPair method, MethodResult result)
 {
     _next = method.NextMethod;
     Execute(sender);
 }
Exemplo n.º 46
0
        /// <summary>
        /// This method creates an object used to 
        /// track changes for future replications.
        /// In this case, a delete trigger is added to a specified table. 
        /// Note: If the data-source already has a process for tracking changes, this 
        ///       method will only need to return a positive success in the method result
        /// </summary>
        /// <param name="methodInput">Method input used for the replication object.
        /// This is the name of the table that we need to extract.
        /// methodInput.Input.properties["ObjectName"]
        /// </param>
        /// <returns></returns>
        public MethodResult InitReplicationObject(MethodInput methodInput)
        {
            MethodResult methodResult = null;

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point
            // is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "InitReplication"))
            {
                //First ensure the change history table exists
                MethodResult initReplicationResult = InitReplication();

                //If the replication table already exist then
                //our work here is done and no other action is required
                if (initReplicationResult.Success)
                {
                    string tableName =
                         GetPropertyValueName("EntityName", methodInput.Input.Properties);
                    string triggerName =
                        string.Format("{0}_Deleted_TRG", tableName);

                    if (CheckForTrigger(triggerName, tableName) == false)
                    {
                        //Use the ConnectorApi provided local data storage to retrieve
                        //and read the sql scripts contents
                        LocalDataStorage localDataStorage = new LocalDataStorage();
                        string deleteTriggerString =
                            localDataStorage.ReadData(TriggerFileName);

                        if (string.IsNullOrWhiteSpace(deleteTriggerString))
                        {
                            throw new InvalidExecuteOperationException(string.Format("Unable to locate file: {0}", TriggerFileName));
                        }

                        string query = string.Format(deleteTriggerString, tableName);
                        //Execute the query to create the change history table.
                        _dataAccess.ExecuteNonQuery(query);
                    }

                    //If there were no errors in processing then
                    //just set the Success for the method result to true.
                    methodResult = new MethodResult { Success = true };
                }
                else
                {
                    methodResult = SetErrorMethodResult(ErrorCodes.InitReplication.Number,
                                                        ErrorCodes.InitReplication.Description);
                }
            }

            return methodResult;
        }
Exemplo n.º 47
0
        /// <summary>
        /// Retrieve all IDs for entities that have changed since last syncronization.
        /// </summary>
        /// <param name="methodInput"></param>
        /// <returns></returns>
        public MethodResult GetChangeHistoryData(MethodInput methodInput)
        {
            MethodResult result = null;

            using (new LogMethodExecution(Globals.ConnectorName, "GetChangeHistory"))
            {
                //Check for the last sync date property
                if (methodInput.Input.Properties.ContainsKey("LastSyncDate") == false)
                {
                    throw new ArgumentNullException("LastSyncDate", InputPropertyNotFound);
                }

                //Retrieve the last date of syncronization from the method input.
                DateTime lastSyncDate = GetLastSyncDate(methodInput.Input.Properties);

                //Retrieve the name of the table from the method input.
                string tableName = GetPropertyValueName(
                    "ObjectName", methodInput.Input.Properties);

                string query = string.Format(
                "SELECT Id FROM ScribeChangeHistory WHERE ModifiedOn > convert(datetime,'{0}') AND TableName ='{1}'",
                lastSyncDate.ToString("s"), tableName);

                //Execute the query.
                DataTable records = _dataAccess.Execute(query);

                result = new MethodResult();

                if (records != null && records.Rows.Count > 0)
                {
                    List<DataEntity> entityList = new List<DataEntity>();

                    //Parse each row and add the records to the entity properties.
                    foreach (DataRow row in records.Rows)
                    {
                        //Create a new entity for each ID returned.
                        DataEntity entity = new DataEntity {ObjectDefinitionFullName = tableName};
                        //This the key name MUST be 'ChangeHistoryId'.
                        //The value MUST be the primary key value of the row that has been deleted
                        entity.Properties.Add("ChangeHistoryId", row["Id"]);
                        //Add the entity to the list.
                        entityList.Add(entity);
                    }

                    //Set the result return the the created data entity.
                    result.Return = new DataEntity("ChangeHistoryData");
                    result.Return.Properties.Add("EntityData", entityList);
                }
                else
                {
                    //Even if no data is being returned
                    //make sure that the return has a value.
                    result.Return = new DataEntity();
                    result.Return.Properties.Add("EntityData", null);
                }

                result.Success = true;
            }

            return result;
        }
Exemplo n.º 48
0
        /// <summary>
        /// Retrieve the last date the specified table was syncronized
        /// MethodInput.Input.Property.Keys 
        /// "ObjectName": Name of the table
        /// "ModificationDateFullName": Name of the column that stored the last date of syncronization
        /// </summary>
        /// <param name="methodInput">Container for the methods input properties</param>
        /// <returns>MethodResult</returns>
        public MethodResult GetLastReplicationSyncDate(MethodInput methodInput)
        {
            MethodResult methodResult = new MethodResult();

            // Use LogMethodExecution to add entry and exit tracing to a method.
            // When wrapped in a using statement, the exit point is written during garbage collection.
            using (new LogMethodExecution(
                Globals.ConnectorName, "GetLastReplicationSyncDate"))
            {
                //get the name of the table from the method input
                string tableName = GetPropertyValue(
                    "ObjectName", methodInput.Input.Properties);

                string modifiedOnColumn = GetPropertyValue(
                    "ModificationDateFullName",
                    methodInput.Input.Properties);

                DateTime lastSyncDate;

                try
                {
                    //verify that the column name for the lasty sync date is specified
                    if (string.IsNullOrWhiteSpace(modifiedOnColumn) == false)
                    {
                        string query = string.Format(
                            "SELECT TOP 1 [{0}] FROM [{1}] ORDER BY [{0}] DESC", modifiedOnColumn, tableName);
                        //execute the query
                        DataTable lastSyncDateTable = _dataAccess.Execute(query);
                        if (lastSyncDateTable.Rows.Count != 0)
                        {
                            lastSyncDate = Convert.ToDateTime(
                                lastSyncDateTable.Rows[0][modifiedOnColumn]);
                        }
                        //If no records are found in the table then set the last sync date to the min value
                        else
                        {
                            lastSyncDate = DateTime.MinValue;
                        }
                    }
                    //If no last sync date column is specified set the last sync date to the min value
                    else
                    {
                        lastSyncDate = DateTime.MinValue;
                    }
                    //create a new method result
                    methodResult = new MethodResult { Success = true, Return = new DataEntity("ReturnValue") };
                    //add the LastSyncDate to the return properties
                    methodResult.Return.Properties.Add("LastSyncDate", lastSyncDate);
                    //put the last sync date in the debug log
                    Logger.Write(Logger.Severity.Debug, Globals.ConnectorName,
                        "LastSyncDate: " + lastSyncDate + Environment.NewLine);
                }
                //catch an errors comming from the database
                //All other erros will be caught on a higher level and thrown
                //As an InvalidExecuteMethodException from the connector interface
                catch (OleDbException oleDbException)
                {
                    //in the event of a database error create a
                    //new method result and set the succes to false
                    methodResult = new MethodResult { Success = false };
                    //create the new error info and set the number
                    //to the code from the connection
                    methodResult.ErrorInfo = new ErrorResult { Number = oleDbException.ErrorCode };
                    //create the description for the error
                    methodResult.ErrorInfo.Description =
                        oleDbException.Message;
                    methodResult.ErrorInfo.Detail =
                        oleDbException.ToString();
                }
            }

            return methodResult;
        }