Exemplo n.º 1
0
        protected override void Execute(CodeActivityContext context)
        {
            string content = Content.Get(context);
            string apiKey  = APIKey.Get(context);
            string seKey   = SecretKey.Get(context);
            string title   = Title.Get(context);
            int    maxlen  = MaxLen.Get(context);

            try
            {
                var client = new Baidu.Aip.Nlp.Nlp(apiKey, seKey);
                // 修改超时时间
                client.Timeout = 60000;
                //设置可选参数
                var options = new Dictionary <string, object>
                {
                    { "title", title }
                };
                //带参数调用新闻摘要接口
                string result = client.NewsSummary(content, maxlen, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
Exemplo n.º 2
0
        public void TestEdit()
        {
            APIKey dummyInsertKey = mKeyMananger.CreateKey(mTestKey.Email, mTestKey.Usage);

            selenium.Open("/Users/Profile.aspx");

            mTestKey.Usage = "This has been edited, part of key UI test";
            mTestKey.Key   = dummyInsertKey.Key;
            mTestKey.State = APIKeyState.ACTIVE;

            driver.FindElement(By.CssSelector("tr:last-child .update-key-request")).Click();
            WaitForElementVisible(By.Id("KeyRequestForm"));

            driver.FindElement(By.CssSelector("#KeyRequestForm textarea")).SendKeys(mTestKey.Usage);
            driver.FindElement(By.Id("KeyRequestSubmit")).Click();

            Thread.Sleep(2000);
            selenium.Click("//input[@value='Ok']");

            //Make sure the UI is updated
            Assert.AreEqual(driver.FindElement(By.CssSelector("tr:last-child .usage")).Text,
                            mTestKey.Usage);

            Assert.True(mTestKey.Equals(mKeyMananger.GetKeyByKey(dummyInsertKey.Key)));
        }
Exemplo n.º 3
0
        public void TestDelete()
        {
            APIKey dummyInsertKey = mKeyMananger.CreateKey(mTestKey.Email, mTestKey.Usage);

            selenium.Open("/Users/Profile.aspx");

            string getNumRowsJs    = "return window.jQuery('#ctl00_ContentPlaceHolder1_KeysControl_APIKeysListView_KeysTable tr').length";
            int    numRowsOriginal = Int32.Parse(((IJavaScriptExecutor)driver).ExecuteScript(getNumRowsJs).ToString());

            driver.FindElement(By.CssSelector("tr:last-child .delete-key-request")).Click();
            driver.FindElement(By.CssSelector(".ui-dialog-buttonset > button:first-child")).Click();

            Thread.Sleep(500);
            driver.FindElement(By.CssSelector(".ui-dialog-buttonset > button:first-child")).Click();

            //Make sure it is gone from the UI
            Thread.Sleep(2000);
            int numRowsFinal = Int32.Parse(((IJavaScriptExecutor)driver).ExecuteScript(getNumRowsJs).ToString());

            try
            {
                Assert.AreEqual(numRowsOriginal - 1, numRowsFinal);
            }
            catch
            {
                Assert.AreEqual(numRowsFinal, 0);
            }

            //Make sure it's not in the database anymore
            Assert.IsNull(mKeyMananger.GetKeyByKey(dummyInsertKey.Key));
        }
        // Performs an INSERT to persist a newly created API Key (salted and hashed key and its Salt value).
        public bool PersistAPIKey(APIKey api_key)
        {
            // Define the insert command with the values to insert.
            string insertCommand = $"INSERT INTO {DatabaseAPIKey.TABLE_NAME} "
                                   + $"({DatabaseAPIKey.API_KEY_LABEL},{DatabaseAPIKey.API_KEY_SALT_LABEL},{DatabaseAPIKey.API_KEY_ISACTIVE_LABEL}) VALUES "
                                   + $"({api_key.API_Key},{api_key.API_KeySalt},{api_key.IsActive})";

            // Open connection and execute the insert command.
            using (MySqlConnection conn = GetConnection())
            {
                conn.Open();

                try
                {
                    MySqlCommand cmd = new MySqlCommand(insertCommand, conn);
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    // Write to Log
                    return(false); // This is probably not going to be executed...
                }
            }
            return(true);
        }
Exemplo n.º 5
0
        private void SwaggerTest()
        {
            // Configure API key authorization: apiKey
            Configuration.Default.ApiKey.Add("api-key", "BITMEX_API_KEY");
            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
            // Configuration.Default.ApiKeyPrefix.Add("api-key", "Bearer");
            // Configure API key authorization: apiNonce
            Configuration.Default.ApiKey.Add("api-nonce", "BITMEX_API_KEY");
            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
            // Configuration.Default.ApiKeyPrefix.Add("api-nonce", "Bearer");
            // Configure API key authorization: apiSignature
            Configuration.Default.ApiKey.Add("api-signature", "BITMEX_API_KEY");
            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
            // Configuration.Default.ApiKeyPrefix.Add("api-signature", "Bearer");

            //Configuration.Default.AccessToken

            var apiInstance = new APIKeyApi();
            var apiKeyID    = "BITMEX_API_KEY"; // string | API Key ID (public component).

            try
            {
                // Disable an API Key.
                APIKey result = apiInstance.APIKeyDisable(apiKeyID);
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling APIKeyApi.APIKeyDisable: " + e.Message);
            }
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            String keyText = txtKey.Text;

            litKeyInfo.Text = "";

            if (keyText.Length == 40)
            {
                lblError.Text = "";

                APIKey searchResults = null;

                String dbConnectionString = ConfigurationManager.ConnectionStrings["DataExplorerDatabase"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(dbConnectionString))
                {
                    searchResults = APIKey.loadThisAPIKey(connection, keyText);
                }

                if (searchResults == null)
                {
                    lblError.Text = "Key not found";
                }
                else
                {
                    litKeyInfo.Text = "<br/><b>Key:</b> " + searchResults.key + "<br><b>Issued for</b> " + searchResults.username + "<br/><b>Description:</b>" + searchResults.description + "<br/><b>Date Issued:</b> " + searchResults.issueDate.ToShortDateString() + "<br/><b>Date Expires: </b>" + searchResults.expires.ToShortDateString();
                }
            }
            else
            {
                lblError.Text = "Invalid key";
            }
        }
        public User GetUserByClientId(string id)
        {
            APIKey apk = dbcontext.APIKeys.SingleOrDefault(a => a.ClientId == id);
            User   usr = dbcontext.Users.SingleOrDefault(u => u.Id == apk.UserId);

            return(usr);
        }
Exemplo n.º 8
0
    public async Task <IActionResult> ExecuteAsync(string apiKey)
    {
        //Validate API Key
        APIKey currentAPIKey = await _apiKeyService.GetAPIKeyByKeyAsync(apiKey);

        if (currentAPIKey == null)
        {
            return(Unauthorized());
        }

        IActionResult result = null;

        try
        {
            result =
                await _hubSpotToConstantContactService.TransferContactsFromHubSpotToConstantContact(
                    GetDataFromRequest(),
                    currentAPIKey
                    );
        }
        catch (Exception ex)
        {
            GetErrorJson(ex.Message);
        }

        return(result);
    }
        private TableRow keyTableRow(APIKey key)
        {
            TableRow newRow = new TableRow();

            newRow.CssClass = "Row";

            TableCell cell_username = new TableCell();

            cell_username.Text = key.username;
            newRow.Cells.Add(cell_username);

            TableCell cell_key = new TableCell();

            cell_key.Text = key.key;
            newRow.Cells.Add(cell_key);

            TableCell cell_issuedate = new TableCell();

            cell_issuedate.Text = key.issueDate.ToShortDateString();
            newRow.Cells.Add(cell_issuedate);

            TableCell cell_expirydate = new TableCell();

            cell_expirydate.Text = key.expires.ToShortDateString();
            newRow.Cells.Add(cell_expirydate);

            TableCell cell_description = new TableCell();

            cell_description.Text = key.description;
            newRow.Cells.Add(cell_description);
            return(newRow);
        }
        //GENERAL FLOW:
        // 1) Receive deal change event from HubSpot
        // 2) Grab corresponding deal along with contacts
        //   a) Need to pass deal name along with contact into 'Project' field in Constant Contact
        // 3) For each contact
        //   a) Pull current info from HubSpot
        //   b) Validate
        //       i) Should have at least one e-mail address
        //       ii) Should have a contact type (custom field in both HubSpot and Constant Contact)
        //       iii) Contact type should have associated lists
        //   c) Compare current HubSpot data to most recent data in database to determine what kind
        //      of operation is needed
        //       i) If the same, do nothing
        //       ii) If e-mail addresses or eligible contact lists have changed, update
        //       iii) If not in the database, add to Constant Contact (verify doesn't exist first)


        public async Task <IActionResult> TransferContactsFromHubSpotToConstantContact(
            string requestJSON,
            APIKey apiKey
            )
        {
            //Verify deal is in proper stage
            dynamic eventData = JsonConvert.DeserializeObject <List <ExpandoObject> >(requestJSON);

            if (eventData[0] == null ||
                !((ExpandoObject)eventData[0]).HasProperty("propertyName"))
            {
                throw new Exception("Unable to parse request body.");
            }

            if (eventData[0].propertyName.ToString() != "dealstage")
            {
                throw new Exception("Ignoring event. Property changed is not dealstage.");
            }

            if (!await DealStageIsValid(eventData[0].propertyValue.ToString()))
            {
                throw new Exception("Invalid dealstage. Ignoring deal.");
            }

            return(await TransferContactsFromHubSpotToConstantContact((int)eventData[0].objectId, apiKey));
        }
        protected override void Execute(CodeActivityContext context)
        {
            string path       = FileName.Get(context);
            string API_KEY    = APIKey.Get(context);
            string SECRET_KEY = SecretKey.Get(context);

            img = image.Get(context);
            try
            {
                if (path != null)
                {
                    by = SaveImage(path);
                }
                else
                {
                    by = ConvertImageToByte(img);
                }
                var client = new Ocr(API_KEY, SECRET_KEY);
                //修改超时时间
                client.Timeout = 60000;
                //参数设置
                var options = new Dictionary <string, object>
                {
                    { "detect_direction", detect_direction.ToString().ToLower() },
                    { "probability", probability.ToString().ToLower() }
                };
                //带参数调用通用文字识别(高精度版)
                string result = client.AccurateBasic(by, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, Localize.LocalizedResources.GetString("msgErrorOccurred"), e.Message);
            }
        }
        public async Task <Deal> FetchDealWithContactsFromHubSpot(int dealID, APIKey apiKey)
        {
            Deal deal = null;

            dynamic responseDeal = await _hubSpotService.FetchDealDataByID(dealID, apiKey);

            if (responseDeal == null)
            {
                throw new Exception("Unable to retrieve HubSpot deal.");
            }

            deal = _dealService.GetDealFromHubSpotDealData(responseDeal, apiKey);

            deal.Contacts = new List <Contact>();

            if (((ExpandoObject)responseDeal).HasProperty("associations.associatedVids"))
            {
                foreach (dynamic i in responseDeal.associations.associatedVids)
                {
                    Contact contact = await _hubSpotService.FetchContactByID((int)i, apiKey);

                    if (contact != null)
                    {
                        deal.Contacts.Add(contact);
                    }
                }
            }

            Console.WriteLine(JsonConvert.SerializeObject(deal));
            return(deal);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Validates the operation and closes the window.
        /// </summary>
        private void Complete()
        {
            if (m_creationArgs == null)
            {
                return;
            }

            m_apiKey = m_creationArgs.CreateOrUpdate();

            // Takes care of the ignore list
            foreach (ListViewItem item in CharactersListView.Items)
            {
                CharacterIdentity id = (CharacterIdentity)item.Tag;
                // If it's a newly created API key, character monitoring has been already been set
                // We only need to deal with those coming out of the ignore list
                if (item.Checked)
                {
                    if (m_apiKey.IdentityIgnoreList.Contains(id))
                    {
                        m_apiKey.IdentityIgnoreList.Remove(id);
                        id.CCPCharacter.Monitored = true;
                    }
                    continue;
                }

                // Add character in ignore list if not already
                if (!m_apiKey.IdentityIgnoreList.Contains(id))
                {
                    m_apiKey.IdentityIgnoreList.Add(id.CCPCharacter);
                }
            }

            // Closes the window
            Close();
        }
        public IActionResult TAC_Map()
        {
            APIKey aPIKey = new APIKey();

            ViewBag.key = aPIKey.googleKey;
            return(View());
        }
Exemplo n.º 15
0
        public void SearchTest()
        {
            APIKey      apiKey  = new APIKey("AIzaSyC3evyffluu_gsQxMJq0ljpCrsFdfldLoM"); //TODO Use using here for efficiency
            CityFinder  finder  = new CityFinder(apiKey);
            ICityResult results = (CityResult)finder.Search("mid");

            ICollection <string> nextLetters = new List <string>();
            ICollection <string> nextCities  = new List <string>();

            nextCities.Add("Midland");
            nextCities.Add("Midrand");
            nextCities.Add("Midlothian");
            nextCities.Add("Middlesbrough");
            nextCities.Add("Middletown");

            nextLetters.Add("l");
            nextLetters.Add("r");
            nextLetters.Add("l");
            nextLetters.Add("d");
            nextLetters.Add("d");

            ICityResult testResults = new CityResult(nextLetters, nextCities);

            for (int i = 0; i > nextCities.Count; i++)
            {
                Assert.AreEqual(testResults.NextCities.ElementAt(i), results.NextCities.ElementAt(i));
            }

            for (int i = 0; i > nextLetters.Count; i++)
            {
                Assert.AreEqual(testResults.NextLetters.ElementAt(i), results.NextLetters.ElementAt(i));
            }
        }
Exemplo n.º 16
0
        public override void BuildDatabase()
        {
            using (var tx = Session.BeginTransaction())
            {
                profiles.Clear();
                workoutPlans.Clear();
                exercises.Clear();
                profiles.Add(CreateProfile(Session, "test1"));
                profiles.Add(CreateProfile(Session, "test2"));
                //creates workout plans for profile 1
                var workoutPlan = CreatePlan(Session, profiles[0], "test1-1", TrainingPlanDifficult.Beginner, TrainingType.HST, true, Language.Languages[0].Shortcut, WorkoutPlanPurpose.FatLost, 3);
                workoutPlans.Add(workoutPlan.Name, workoutPlan);
                workoutPlan = CreatePlan(Session, profiles[1], "test1-2", TrainingPlanDifficult.Advanced, TrainingType.HST, false, Language.Languages[0].Shortcut, WorkoutPlanPurpose.Mass, 3);
                workoutPlans.Add(workoutPlan.Name, workoutPlan);

                var ex = CreateExercise(Session, profiles[0], "Test", "t");
                exercises.Add(ex.Shortcut, ex);
                ex = CreateExercise(Session, null, "Global", "global");
                exercises.Add(ex.Shortcut, ex);

                apiKey                  = new APIKey();
                apiKey.ApiKey           = Guid.NewGuid();
                apiKey.ApplicationName  = "UnitTest";
                apiKey.EMail            = "*****@*****.**";
                apiKey.RegisterDateTime = DateTime.UtcNow;
                insertToDatabase(apiKey);
                tx.Commit();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="apiKey">The API key.</param>
        /// <exception cref="System.ArgumentNullException">apiKey</exception>
        public ApiKeyDeletionWindow(APIKey apiKey)
            : this()
        {
            apiKey.ThrowIfNull(nameof(apiKey), "API key can't be null");

            m_apiKey = apiKey;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Handles the updating of the
        /// </summary>
        /// <param name="key"></param>
        /// <param name="item"></param>
        public void UpdateOrderStatusItem(APIKey key, OrderStatusItem item)
        {
            if (key == null)
            {
                return;
            }

            var existing = _context.Orders.FirstOrDefault(i => i.ItemId == item.ItemId);

            if (existing == null)
            {
                return;
            }

            existing.OrderStatus          = item.OrderStatus;
            existing.OrderTrackingNumber  = item.OrderTransactionNumber;
            existing.ReciptTrackingNumber = item.ReturnTransactionNumber;
            existing.OrderStatusDate      = DateTime.Now;

            // Adding the crud information to the record
            existing.ModifiedBy   = key.Vendor.VendorName;
            existing.ModifiedDate = DateTime.Now;

            _context.SaveChanges();
        }
Exemplo n.º 19
0
        protected virtual SessionData CreateNewSession(ProfileDTO profile, ClientInformation clientInfo, LoginData loginData = null, APIKey apiKey = null)
        {
            if (loginData == null)
            {
                if (apiKey == null)
                {
                    apiKey                 = new APIKey();
                    apiKey.ApiKey          = Guid.NewGuid();
                    apiKey.ApplicationName = "UnitTest";
                    apiKey.EMail           = "*****@*****.**";
                    Session.Save(apiKey);
                }
                loginData        = new LoginData();
                loginData.ApiKey = apiKey;
                loginData.ApplicationLanguage = clientInfo.ApplicationLanguage;
                loginData.ApplicationVersion  = clientInfo.ApplicationVersion;
                loginData.ClientInstanceId    = clientInfo.ClientInstanceId;
                loginData.ProfileId           = profile.GlobalId;
                loginData.LoginDateTime       = DateTime.UtcNow;
                loginData.Platform            = (PlatformType)clientInfo.Platform;
                loginData.PlatformVersion     = clientInfo.PlatformVersion;
                Session.Save(loginData);
                Session.Flush();
            }
            var data = SecurityManager.CreateNewSession(profile, clientInfo, loginData);

            data.Token.Language = "en";
            var securityInfo = SecurityManager.EnsureAuthentication(data.Token);
            var dbProfile    = Session.Get <Profile>(profile.GlobalId);

            securityInfo.Licence = dbProfile.Licence.Map <LicenceInfoDTO>();
            securityInfo.Licence.CurrentAccountType = securityInfo.Licence.AccountType;
            return(data);
        }
Exemplo n.º 20
0
        public GetOrderListResult GetAll(
            APIKey key, DateTime?fromDate, DateTime?toDate, string orderStatus, int page = 0, int itemsPerPage = 300)
        {
            if (key == null)
            {
                return(null);
            }

            IQueryable <Order> query = null;

            if (string.IsNullOrEmpty(orderStatus))
            {
                if (!fromDate.HasValue && !toDate.HasValue)
                {
                    query = _context.Orders
                            .Where(o => o.Vendor == key.Vendor)
                            .OrderBy(o => o.OrderId);
                }

                else if (toDate.HasValue && toDate.Value > fromDate)
                {
                    query = _context.Orders.Where(o =>
                                                  o.Vendor == key.Vendor && (o.OrderDate >= fromDate && o.OrderDate <= toDate));
                }
                else
                {
                    query = _context.Orders.Where(o => o.Vendor == key.Vendor && o.OrderDate >= fromDate);
                }
            }
            else
            {
                if (!fromDate.HasValue && !toDate.HasValue)
                {
                    query = _context.Orders
                            .Where(o => o.Vendor == key.Vendor && o.OrderStatus == orderStatus)
                            .OrderBy(o => o.OrderId);
                }

                else if (toDate.HasValue && toDate.Value > fromDate)
                {
                    query = _context.Orders.Where(o =>
                                                  o.Vendor == key.Vendor && (o.OrderDate >= fromDate && o.OrderDate <= toDate) && o.OrderStatus == orderStatus);
                }
                else
                {
                    query = _context.Orders.Where(o => o.Vendor == key.Vendor && o.OrderDate >= fromDate && o.OrderStatus == orderStatus);
                }
            }

            var count  = query.Count();
            var result = query
                         .OrderBy(o => o.OrderId)
                         .Skip(page * itemsPerPage)
                         .Take(itemsPerPage)
                         .ToList();
            var orderResult = PackageResults(page, count, result);

            orderResult.ItemsPerPage = itemsPerPage;
            return(orderResult);
        }
Exemplo n.º 21
0
        protected override void Execute(CodeActivityContext context)
        {
            string path       = FileName.Get(context);
            string API_KEY    = APIKey.Get(context);
            string SECRET_KEY = SecretKey.Get(context);

            img = image.Get(context);
            try
            {
                if (path != null)
                {
                    by = SaveImage(path);
                }
                else
                {
                    by = ConvertImageToByte(img);
                }
                var client = new Ocr(API_KEY, SECRET_KEY);
                //修改超时时间
                client.Timeout = 60000;
                //参数设置
                var options = new Dictionary <string, object>
                {
                    { "detect_direction", detect_direction.ToString().ToLower() },
                    { "detect_language", detect_language.ToString().ToLower() }
                };
                //带参数调用网络图片文字识别
                string result = client.WebImage(by, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Updates the content.
        /// </summary>
        private void UpdateContent()
        {
            if (!Visible)
            {
                m_pendingUpdate = true;
                return;
            }
            m_pendingUpdate = false;

            int    scrollBarPosition = TopIndex;
            APIKey oldSelection      = SelectedItem as APIKey;

            BeginUpdate();
            try
            {
                Items.Clear();
                foreach (APIKey apiKey in APIKeys)
                {
                    Items.Add(apiKey);
                    if (apiKey == oldSelection)
                    {
                        SelectedIndex = Items.Count - 1;
                    }
                }
            }
            finally
            {
                EndUpdate();
                TopIndex = scrollBarPosition;
            }
        }
Exemplo n.º 23
0
        protected override void Execute(CodeActivityContext context)
        {
            var deviceID = (int)DeviceID.Get(context);
            var dynamicEnergyThreshold = (Boolean)DynamicEnergyThreshold.Get(context);
            var energyThresholdValue   = (Int32)EnergyThresholdValue.Get(context);

            if (energyThresholdValue <= 0)
            {
                energyThresholdValue = 300;
            }
            var pauseThreshold = PauseThreshold.Get(context);

            if (pauseThreshold <= 0)
            {
                pauseThreshold = 0.8;
            }
            double?timeoutSeconds  = TimeoutSeconds.Get(context);
            double?phraseTimeLimit = PhraseTimeLimit.Get(context);
            var    inputLanguage   = InputLanguage.Get(context);

            if (inputLanguage.Length < 2)
            {
                inputLanguage = "en-US";
            }
            var apiKey   = APIKey.Get(context);
            var username = Username.Get(context);
            var password = Password.Get(context);
            var engine   = Engine;
            var filePath = FilePath.Get(context);
            IEnumerable <object> inputParameters = new object [] { deviceID, filePath, inputLanguage, apiKey, username, password, engine, dynamicEnergyThreshold, energyThresholdValue, pauseThreshold, timeoutSeconds, phraseTimeLimit };

            OutputParameters.Set(context, inputParameters);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Creates a CHR format file for character exportation.
        /// </summary>
        /// <param name="character"></param>
        /// <param name="plan"></param>
        private static string ExportAsEFTCHR(Character character, Plan plan)
        {
            StringBuilder builder = new StringBuilder();

            foreach (SerializableCharacterSkill skill in character.Skills
                     .Where(x => x.IsPublic &&
                            x.Group.ID != DBConstants.CorporationManagementSkillsGroupID &&
                            x.Group.ID != DBConstants.SocialSkillsGroupID &&
                            x.Group.ID != DBConstants.TradeSkillsGroupID)
                     .Select(x => GetMergedSkill(plan, x)))
            {
                builder.AppendLine($"{skill.Name}={skill.Level}");
            }

            APIKey apiKey = character.Identity.FindAPIKeyWithAccess(CCPAPICharacterMethods.CharacterSheet);

            if (apiKey == null)
            {
                return(builder.ToString());
            }

            builder
            .AppendLine($"KeyID={apiKey.ID}")
            .AppendLine($"VCode={apiKey.VerificationCode}")
            .Append($"CharID={character.CharacterID}");

            return(builder.ToString());
        }
Exemplo n.º 25
0
        public static object PutResource(
            string controller,
            string subcontroller,
            string action,
            IDictionary <string, string> parameters,
            object postObj,
            Type typeOfPostObj,
            Type responseType,
            APIKey apiKey
            )
        {
            HttpWebRequest request = CreateRequest(
                controller,
                subcontroller,
                action,
                parameters,
                apiKey
                );

            request.Method      = "PUT";
            request.ContentType = "application/json";

            try
            {
                request.UploadData(postObj, typeOfPostObj);
                return(request.DownloadResponse(responseType));
            }
            catch (WebException ex)
            {
                var constructor = responseType.GetConstructor(
                    new Type[] { typeof(WebException) }
                    );
                return(constructor.Invoke(new object[] { ex }));
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            string text   = Text.Get(context);
            string apiKey = APIKey.Get(context);
            string seKey  = SecretKey.Get(context);

            try
            {
                var client = new Baidu.Aip.Nlp.Nlp(apiKey, seKey);
                //修改超时时间
                client.Timeout = 60000;
                //设置可选参数
                var options = new Dictionary <string, object>
                {
                    { "type", type }
                };
                //带参数调用评论观点抽取
                string result = client.CommentTag(text, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, Localize.LocalizedResources.GetString("msgErrorOccurred"), e.Message);
            }
        }
Exemplo n.º 27
0
        public static object GetResource(
            string controller,
            string action,
            IDictionary <string, string> parameters,
            Type type,
            APIKey apiKey
            )
        {
            HttpWebRequest request = CreateRequest(
                controller,
                action,
                parameters,
                apiKey
                );

            try
            {
                return(request.DownloadResponse(type));
            }
            catch (WebException ex)
            {
                var constructor = type.GetConstructor(
                    new Type[] { typeof(WebException) }
                    );
                return(constructor.Invoke(new object[] { ex }));
            }
        }
        public async Task <IActionResult> GetNewAPIKey()
        {
            var entity = new APIKey
            {
                ID    = Guid.NewGuid().ToString(),
                Notes = new List <Note>
                {
                    new Note
                    {
                        NoteTitle      = "Welcome",
                        NoteContent    = "This is a test note",
                        CreateDateTime = DateTime.Now
                    },
                    new Note
                    {
                        NoteTitle      = "Hello",
                        NoteContent    = "This is an another test note",
                        CreateDateTime = DateTime.Now
                    },
                    new Note
                    {
                        NoteTitle      = "And finally",
                        NoteContent    = "We have the third test note",
                        CreateDateTime = DateTime.Now
                    },
                }
            };

            await _repository.AddAPIKey(entity);

            var result = _mapper.Map <APIKeyDTO>(entity);

            return(Ok(result));
        }
Exemplo n.º 29
0
        protected override void Execute(CodeActivityContext context)
        {
            string text1  = Text1.Get(context);
            string text2  = Text2.Get(context);
            string apiKey = APIKey.Get(context);
            string seKey  = SecretKey.Get(context);

            try
            {
                var client = new Baidu.Aip.Nlp.Nlp(apiKey, seKey);
                //修改超时时间
                client.Timeout = 60000;
                //设置可选参数
                var options = new Dictionary <string, object>
                {
                    { "model", model }
                };
                //带参数调用短文本相似度
                string result = client.Simnet(text1, text2, options).ToString();
                Result.Set(context, result);
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "有一个错误产生", e.Message);
            }
        }
Exemplo n.º 30
0
        public override void BuildDatabase()
        {
            profiles.Clear();

            using (var tx = Session.BeginTransaction())
            {
                var profile = CreateProfile(Session, "Profile1");
                profile.Password = CryptographyHelper.ToSHA1Hash(profile.UserName);
                Session.Update(profile);
                profiles.Add(profile);
                profile           = CreateProfile(Session, "Profile2");
                profile.IsDeleted = true;
                profile.Password  = CryptographyHelper.ToSHA1Hash(profile.UserName);
                Session.Update(profile);
                profiles.Add(profile);
                profile          = CreateProfile(Session, "Profile3");
                profile.Password = CryptographyHelper.ToSHA1Hash(profile.UserName);
                Session.Update(profile);
                profiles.Add(profile);

                APIKey apiKey = new APIKey();
                apiKey.ApiKey           = key;
                apiKey.ApplicationName  = "UnitTest";
                apiKey.EMail            = "*****@*****.**";
                apiKey.RegisterDateTime = DateTime.UtcNow;
                insertToDatabase(apiKey);
                tx.Commit();
            }
        }
        public static APIKey BuildAPIKey(ref SQLiteDataReader reader)
        {
            DateTime expires;
            DateTime.TryParse(reader["DateExpires"].ToString(), out expires);

            APIKey key = new APIKey()
            {
                KeyID = Convert.ToInt32(reader["KeyID"]),
                VCode = reader["VCode"].ToString(),
                Type = reader["Type"].ToString(),
                CharacterName = reader["CharacterName"].ToString()
            };
            return key;
        }