bool GamesAction <T>(CloudAction action)
        {
            var ws = new WebServiceClient();

            ws.Url = MainForm.Current.OptionsPanel.InternetDatabaseUrlComboBox.Text;
            var items = data
                        .Where(x => x.Action == action)
                        .Select(x => x.Item)
                        .OfType <T>()
                        .ToList();
            var success = true;

            // If there is data to submit.
            if (items.Count > 0)
            {
                string result = null;
                if (typeof(T) == typeof(Game))
                {
                    result = ws.SetGames(action, items.Cast <Game>().ToList());
                }
                success = string.IsNullOrEmpty(result);
                if (!success)
                {
                    MainForm.Current.SetHeaderBody(MessageBoxIcon.Error, result);
                }
            }
            ws.Dispose();
            return(success);
        }
Exemple #2
0
        public ActionResult Login(string UserName, string Password)
        {
            if (ModelState.IsValid)
            {
                int     HospitalId;
                DataSet ds = new DataSet();
                try
                {
                    string strConfigFileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\Information.xml";
                    ds.ReadXml(strConfigFileName);
                    HospitalId = Convert.ToInt32(ds.Tables[0].Rows[0]["HospitalId"].ToString());

                    WebServiceClient ws     = new WebServiceClient();
                    bool             result = ws.ControlHospitalUser(HospitalId, UserName, Password);
                    if (result)
                    {
                        Session["user"] = UserName;
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Kullanıcı adı veya şifre hatalı!");
                    }
                }
                catch (Exception exc)
                {
                    throw exc;
                }
            }
            return(View());
        }
Exemple #3
0
        public ActionResult DeleteConfirm(string id)
        {
            BloodModel       model = new BloodModel();
            WebServiceClient ws    = new WebServiceClient();
            int     HospitalId;
            DataSet ds = new DataSet();

            if (!id.Contains("-"))
            {
                id = id + "+";
            }
            model.BloodType = id;
            try
            {
                string strConfigFileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()) + "\\Information.xml";
                ds.ReadXml(strConfigFileName);
                HospitalId = Convert.ToInt32(ds.Tables[0].Rows[0]["HospitalId"].ToString());

                ws.NotificationFinished(HospitalId, model.BloodType);
            }
            catch
            {
                ModelState.AddModelError("", "Kan Talebini Silerken Hata ile Karşılaşıldı");
            }

            return(Redirect("~/Home/Index"));
        }
 public RedisTicketStore(IDistributedCache cache, IHttpContextAccessor httpContextAccessor, WebServiceClient maxMindClient)
 {
     this.cache           = cache;
     _httpContextAccessor = httpContextAccessor;
     _parser   = Parser.GetDefault();
     _ipClient = maxMindClient;
 }
Exemple #5
0
    private WebServiceClient GetClient()
    {
        WebServiceClient client = new WebServiceClient();

        client.Url = _serviceUrl;
        return(client);
    }
        public async Task <EntityIpLocation> Read(string ipAddress)
        {
            using (var client = new WebServiceClient(_accountId, _licenseKey))
            {
                try
                {
                    var response = await client.InsightsAsync(ipAddress);

                    return(new EntityIpLocation
                    {
                        IpAddress = ipAddress,
                        CountryIsoCode = response.Country.IsoCode,
                        CountryName = response.Country.Name,
                        SubdivisionIsoCode = response.MostSpecificSubdivision.Name,
                        SubdivisionName = response.MostSpecificSubdivision.IsoCode,
                        CityName = response.City.Name,
                        PostalCode = response.Postal.Code,
                        Latitude = response.Location.Latitude.Value,
                        Longitude = response.Location.Longitude.Value,
                    });
                }
                catch (Exception ex)
                {
                    //ToDo: check what will happen if invalid ip
                    return(null);
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Restarts a tenant.
        /// </summary>
        /// <param name="sender">The Object that created this event.</param>
        /// <param name="executedRoutedEventArgs">The event arguments.</param>
        void OnRestart(Object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {
            // The tenant that is to be started can be extracted from the original source of this command.
            ListViewItem listViewItem = executedRoutedEventArgs.OriginalSource as ListViewItem;
            TenantInfo   tenantInfo   = listViewItem.DataContext as TenantInfo;

            // A user with site administration claims is the only user who can query the status of the tenants and start and stop them.  Here, we are going to get
            // the status of the tenants and start the ones who need to be started automatically (and are not already running).
            using (WebServiceClient administratorClient = new WebServiceClient(MainWindow.Tenants.AdministratorClientInfo.EndpointConfigurationName))
            {
                // This provides the credentials for the site administrator.
                administratorClient.ClientCredentials.UserName.UserName = MainWindow.Tenants.AdministratorClientInfo.UserName;
                administratorClient.ClientCredentials.UserName.Password = MainWindow.Tenants.AdministratorClientInfo.Password;

                // This loads the tenant into the data model using the site administrator's credentials.  Only a site administrator has the permissions to
                // load and unload tenants.
                administratorClient.UnloadTenant(tenantInfo.Name);
                administratorClient.LoadTenant(tenantInfo.Name, tenantInfo.ConnectionString);

                // This uses the tenant operator's credentials to initialize the tenant.  The server itself doesn't have the ability to cross tenant boundaries as a
                // security measure, so the initialization must be done outside where the credentials can be kept secure.
                using (WebServiceClient tenantClient = new WebServiceClient(tenantInfo.EndpointConfigurationName))
                {
                    tenantClient.ClientCredentials.UserName.UserName = tenantInfo.UserName;
                    tenantClient.ClientCredentials.UserName.Password = tenantInfo.Password;
                    tenantClient.Start();
                }
            }

            // After loading or unloading, we need to update the status of the display.
            this.RefreshDisplay();
        }
Exemple #8
0
        public Notification <TOutput> Post <TInput, TOutput>(string url, TInput data)
        {
            var content = JsonUtility.SerializeForWebRequest(data);
            var result  = new WebServiceClient().Post(url, content, ApplicationJsonContentType);

            return(GetResponse <TOutput>(result));
        }
Exemple #9
0
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public MemWeChatMsgEntity GetWeChatShortInfo(string code)
        {
            MemWeChatMsgEntity          entity     = new MemWeChatMsgEntity();
            string                      simpleurl  = WeiXinConfig.GetSimpleInfoUrl(code);
            string                      result     = WebServiceClient.QueryGetWebService(simpleurl, "", null);
            JavaScriptSerializer        serializer = new JavaScriptSerializer();
            Dictionary <string, object> jsonObj    = serializer.Deserialize <dynamic>(result);

            if (jsonObj.ContainsKey("unionid"))
            {
                entity.UnionId = jsonObj["unionid"].ToString();
            }
            if (jsonObj.ContainsKey("openid"))
            {
                entity.OpenId = jsonObj["openid"].ToString();
            }
            if (jsonObj.ContainsKey("access_token"))
            {
                entity.Access_Token = jsonObj["access_token"].ToString();
            }
            if (jsonObj.ContainsKey("refresh_token"))
            {
                entity.Refresh_Token = jsonObj["refresh_token"].ToString();
            }

            return(entity);
        }
Exemple #10
0
        public void CallWebService_should_set_HttpWebRequest_to_request_textxml_content()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                var ms = new MockStorage(MockBehavior.Strict);

                // And also, you can verify whether HttpWebRequest is set intendedly if you use Moq.
                var requestProxy = new PProxyHttpWebRequest();
                requestProxy.ContentTypeSetString().BodyBy(ms).Expect(_ => _(requestProxy, "text/xml;charset=\"utf-8\""));
                requestProxy.MethodSetString().BodyBy(ms).Expect(_ => _(requestProxy, "GET"));
                requestProxy.TimeoutSetInt32().BodyBy(ms).Expect(_ => _(requestProxy, 1000));
                requestProxy.CredentialsSetICredentials().BodyBy(ms).Expect(_ => _(requestProxy, CredentialCache.DefaultNetworkCredentials));

                var responseProxy = new PProxyHttpWebResponse();
                responseProxy.StatusCodeGet().Body = @this => HttpStatusCode.OK;
                requestProxy.GetResponse().Body    = @this => responseProxy;

                var url = "testService";
                PWebRequest.CreateString().Body = @this => requestProxy;


                // Act
                var actual = new WebServiceClient().CallWebService(url);


                // Assert
                Assert.IsTrue(actual);
                ms.Verify();
            }
        }
Exemple #11
0
        private IList <string> GetRoles(string username)
        {
            var client = new WebServiceClient <ISecurityService>(ConfigurationManager.AppSettings["SecurityServiceUrl"],
                                                                 (binding, httpTransport, address, factory) =>
            {
                var credentialBehaviour = factory.Endpoint.Behaviors.Find <ClientCredentials>();
                credentialBehaviour.UserName.UserName = ConfigurationManager.AppSettings["SecurityServiceUser"];
                credentialBehaviour.UserName.Password = ConfigurationManager.AppSettings["SecurityServicePassword"];
                httpTransport.AuthenticationScheme    = AuthenticationSchemes.Ntlm;
            });

            var roles   = new List <string>();
            var usuario = client.Channel.UserLogonByName(username, AppId);

            if (usuario == null)
            {
                return(roles);
            }

            client.Channel.GroupsListPerUser(usuario, AppId).ToList().ForEach(g =>
            {
                roles.AddRange(client.Channel.PermissionListPerGroup(g).Select(r => r.Description).ToList());
            });

            return(roles);
        }
        private void MySettingsSaveButton_Click(object sender, EventArgs e)
        {
            mainForm.LoadingCircle = true;
            var s  = new UserSetting();
            var di = _devices[ControllerComboBox.SelectedIndex];

            s.Comment      = CommentTextBox.Text;
            s.InstanceGuid = di.InstanceGuid;
            s.InstanceName = di.InstanceName;
            s.ProductGuid  = di.ProductGuid;
            s.ProductName  = di.ProductName;
            s.DeviceType   = (int)di.Type;
            s.IsEnabled    = true;
            if (GameComboBox.SelectedIndex > 0)
            {
                var fi = _files[GameComboBox.SelectedIndex - 1];
                s.FileName        = System.IO.Path.GetFileName(fi.FileName);
                s.FileProductName = EngineHelper.FixName(fi.ProductName, s.FileName);
            }
            else
            {
                s.FileName        = "";
                s.FileProductName = "";
            }
            var padSectionName = SettingManager.Current.GetInstanceSection(di.InstanceGuid);
            var ps             = SettingManager.Current.GetPadSetting(padSectionName);
            var ws             = new WebServiceClient();

            ws.Url = MainForm.Current.OptionsPanel.InternetDatabaseUrlComboBox.Text;
            ws.SaveSettingCompleted += ws_SaveSettingCompleted;
            ws.SaveSettingAsync(s, ps);
        }
Exemple #13
0
        /// <summary>
        /// Get information about a taxon.
        /// </summary>
        /// <param name="taxonId">Taxon to get information about.</param>
        /// <param name="taxonInformationType">Type of taxon information to get.</param>
        /// <returns>Taxon information.</returns>
        public static Taxon GetTaxon(Int32 taxonId,
                                     TaxonInformationType taxonInformationType)
        {
            Taxon    taxon;
            WebTaxon webTaxon;

            if (taxonId == (Int32)TaxonId.Dummy)
            {
                // Check if data is cached.
                lock (_unknownTaxon)
                {
                    taxon = (Taxon)(_unknownTaxon[taxonInformationType]);
                }

                if (taxon.IsNull())
                {
                    // Get data from web service.
                    webTaxon = WebServiceClient.GetTaxon(taxonId, taxonInformationType);
                    taxon    = GetTaxon(webTaxon);

                    // Add data to cache.
                    lock (_unknownTaxon)
                    {
                        _unknownTaxon.Add(taxonInformationType, taxon);
                    }
                }
            }
            else
            {
                // Get data from web service.
                webTaxon = WebServiceClient.GetTaxon(taxonId, taxonInformationType);
                taxon    = GetTaxon(webTaxon);
            }
            return(taxon);
        }
        public string SendSOAPQuery(XmlDocument query, WsConfigurationSettings _settings)
        {
            WebServiceClient client  = new WebServiceClient(_settings);
            HttpWebRequest   SoapReq = client.InvokeMethod(query);

            return(GetWSResponse(SoapReq));
        }
        /// <summary>
        /// Get status for ArtDatabankenService.
        /// </summary>
        /// <param name='status'>Status for ArtDatabankenService is saved in this object.</param>
        private void GetArtDatabankenServiceStatus(Dictionary <Int32, List <WebResourceStatus> > status)
        {
            Boolean           ping;
            WebResourceStatus resourceStatus;

            ping                        = WebServiceClient.Ping();
            resourceStatus              = new WebResourceStatus();
            resourceStatus.AccessType   = WebService.Settings.Default.ResourceAccessTypeReadSwedish;
            resourceStatus.Address      = WebServiceClient.WebServiceAddress;
            resourceStatus.Name         = ApplicationIdentifier.ArtDatabankenService.ToString();
            resourceStatus.ResourceType = WebServiceBase.GetResourceType(ResourceTypeIdentifier.WebService,
                                                                         (Int32)(LocaleId.sv_SE));
            resourceStatus.Status = ping;
            resourceStatus.Time   = DateTime.Now;
            status[(Int32)(LocaleId.sv_SE)].Add(resourceStatus);

            resourceStatus              = new WebResourceStatus();
            resourceStatus.AccessType   = WebService.Settings.Default.ResourceAccessTypeReadEnglish;
            resourceStatus.Address      = WebServiceClient.WebServiceAddress;
            resourceStatus.Name         = ApplicationIdentifier.ArtDatabankenService.ToString();
            resourceStatus.ResourceType = WebServiceBase.GetResourceType(ResourceTypeIdentifier.WebService,
                                                                         (Int32)(LocaleId.en_GB));
            resourceStatus.Status = ping;
            resourceStatus.Time   = DateTime.Now;
            status[(Int32)(LocaleId.en_GB)].Add(resourceStatus);
        }
Exemple #16
0
        public IPInformation Get(string address)
        {
            using (var client = new WebServiceClient(119543, "1Ksa6iuvfOJu"))
            {
                try
                {
                    var response = client.CityAsync(address).Result;

                    return(new IPInformation
                    {
                        Latitude = response.Location.Latitude,
                        Longitude = response.Location.Longitude,
                        Isp = response.Traits.Isp,
                        IPAddress = response.Traits.IPAddress,
                        City = response.City.Name,
                        Country = response.Country.Name,
                        Postal = response.Postal.Code
                    });
                }
                catch
                {
                    return(new IPInformation
                    {
                        IPAddress = address
                    });
                }
            }
        }
        void DoAction(object state)
        {
            MainForm.Current.LoadingCircle = true;
            var ws = new WebServiceClient();

            ws.Url = MainForm.Current.OptionsPanel.InternetDatabaseUrlComboBox.Text;
            var gamesToDelete = data.Where(x => x.Action == CloudAction.Delete).Select(x => (Game)x.Item).ToList();

            try
            {
                var result = ws.SetGames(CloudAction.Delete, gamesToDelete);
                // If update was successful then.
                if (string.IsNullOrEmpty(result))
                {
                    var gamesToUpdate = data.Where(x => x.Action == CloudAction.Update).Select(x => (Game)x.Item).ToList();
                    result = ws.SetGames(CloudAction.Update, gamesToDelete);
                }
                if (!string.IsNullOrEmpty(result))
                {
                    MainForm.Current.SetHeaderBody(MessageBoxIcon.Error, result);
                }
            }
            catch (Exception ex)
            {
                var error = ex.Message;
                if (ex.InnerException != null)
                {
                    error += "\r\n" + ex.InnerException.Message;
                }
                MainForm.Current.SetHeaderBody(MessageBoxIcon.Error, error);
            }
        }
Exemple #18
0
        public void CallWebService_should_return_false_if_HttpStatusCode_is_Forbidden()
        {
            using (new IndirectionsContext())
            {
                // Arrange
                var ms = new MockStorage(MockBehavior.Strict);

                var requestProxy = new PProxyHttpWebRequest();
                requestProxy.ExcludeGeneric().DefaultBehavior = IndirectionBehaviors.DefaultValue;

                var responseProxy = new PProxyHttpWebResponse();
                responseProxy.StatusCodeGet().Body = @this => HttpStatusCode.Forbidden;
                requestProxy.GetResponse().Body    = @this => responseProxy;

                // To improve robustness against unintended modification, you should verify inputs to side-effects by Moq.
                // For example, the original test will pass even if you unintendedly changed the original production code as follows:
                // var request = CreateWebRequest(url);
                //   -> var request = CreateWebRequest("Foo");
                var url = "testService";
                PWebRequest.CreateString().BodyBy(ms).Expect(_ => _(url)).Returns(requestProxy);


                // Act
                var actual = new WebServiceClient().CallWebService(url);


                // Assert
                Assert.IsFalse(actual);
                ms.Verify();
            }
        }
        public string InvokeMethod(XmlDocument QuerySDMX, string Action)
        {
            try
            {
                _settings.Operation = Action;
                _client             = new WebServiceClient(_settings);
                String result = null;

                using (Stream stream = _client.InvokeMethod(QuerySDMX).GetResponseStream())
                {
                    StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                    result = reader.ReadToEnd();
                }

                if (result.IndexOf("<soap:Fault>") > 0)
                {
                    throw new Exception("Error, SOAP FAULT" + result);
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw new Exception("Error, [WebServiceLayer.classes.service.Net.WebServiceLayer.InovkeMethod] " + ex.Message);
            }
        }
        /// <summary>
        /// Forces the user to log into the web service.
        /// </summary>
        /// <param name="state">The thread start parameter.</param>
        void LoginThread(Object state)
        {
            // This will attempt to log in three times before giving up.
            Int32 counter = 3;

            do
            {
                // This will force the user to log in using a single threaded apartment (STA).
                using (WebServiceClient webServiceClient = new WebServiceClient(Settings.Default.WebServiceEndpoint))
                {
                    // For some reason, the initial call will sometimes fail.  This will continue to try until we log in or die trying.
                    try
                    {
                        // This is a dummy operation here but it will force the user to enter the credentials in the foreground.
                        webServiceClient.GetUserId();

                        // Allow the other background threads to use this channel as it is now initialized.
                        InteractiveChannelInitializer.IsPrompted = false;
                        InteractiveChannelInitializer.ValidCredentials.Set();

                        // This will force the loop to exit.
                        counter = 0;
                    }
                    catch { }
                }
            } while (counter-- != 0);
        }
Exemple #21
0
        public void TestThatServiceReturnsAForbiddenStatuscode()
        {
            // Use new IndirectionsContext() instead of ShimsContext.Create().
            using (new IndirectionsContext())
            {
                // Arrange
                // Use the indirection stub which has name starting with "PProxy" against one instance.
                var requestProxy = new PProxyHttpWebRequest();
                // The indirection stubs "PProxy..." have implicit operator same as Fakes, so you can write as follows:
                PWebRequest.CreateString().Body = uri => requestProxy;
                // Unlike Fakes, in Prig, "this" is implicitly passed as first parameter of the instance method.
                requestProxy.GetResponse().Body = this1 =>
                {
                    var responseProxy = new PProxyHttpWebResponse();
                    responseProxy.StatusCodeGet().Body = this2 => HttpStatusCode.Forbidden;
                    return(responseProxy);
                };
                // Unlike Fakes, Prig tries invoking the original method by default.
                // If you want to make stubs be do-nothing, change the default behavior as follows:
                requestProxy.ExcludeGeneric().DefaultBehavior = IndirectionBehaviors.DefaultValue;
                var client         = new WebServiceClient();
                var url            = "testService";
                var expectedResult = false;


                // Act
                bool actualresult = client.CallWebService(url);


                // Assert
                Assert.AreEqual(expectedResult, actualresult);
            }
        }
Exemple #22
0
        /// <summary>
        /// Refreshes the display.
        /// </summary>
        internal void RefreshDisplay()
        {
            // A user with site administration claims is the only user who can query the status of the tenants and start and stop them.  Here, we are going to get
            // the status of the tenants and start the ones who need to be started automatically (and are not already running).
            using (WebServiceClient administratorClient = new WebServiceClient(MainWindow.Tenants.AdministratorClientInfo.EndpointConfigurationName))
            {
                // This provides the credentials for the site administrator who is the only one that can query for the loaded tenants.
                administratorClient.ClientCredentials.UserName.UserName = MainWindow.Tenants.AdministratorClientInfo.UserName;
                administratorClient.ClientCredentials.UserName.Password = MainWindow.Tenants.AdministratorClientInfo.Password;

                try
                {
                    // This queries the server for the loaded (running) tenants.
                    List <String> loadedTenants = new List <String>(administratorClient.GetTenants());

                    // This will initialize the web services for each of the tenants in the configuration file.
                    foreach (TenantInfo tenantInfo in MainWindow.Tenants)
                    {
                        tenantInfo.Status = loadedTenants.Contains(tenantInfo.Name) ? Status.Running : Status.Stopped;
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message, "Market Console Error");
                    Application.Current.Shutdown();
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// Stops a tenant.
        /// </summary>
        /// <param name="sender">The Object that created this event.</param>
        /// <param name="executedRoutedEventArgs">The event arguments.</param>
        void OnStop(Object sender, ExecutedRoutedEventArgs executedRoutedEventArgs)
        {
            // The tenant that is to be stopped can be extracted from the original source of this command.
            ListViewItem listViewItem = executedRoutedEventArgs.OriginalSource as ListViewItem;
            TenantInfo   tenantInfo   = listViewItem.DataContext as TenantInfo;

            // A user with site administration claims is the only user who can query the status of the tenants and start and stop them.  Here, we are going to get
            // the status of the tenants and start the ones who need to be started automatically (and are not already running).
            using (WebServiceClient administratorClient = new WebServiceClient(MainWindow.Tenants.AdministratorClientInfo.EndpointConfigurationName))
            {
                // This uses the tenant operator's credentials to initialize the tenant.  The server itself doesn't have the ability to cross tenant
                // boundaries as a security measure, so starting the services must be done outside where the credentials can be kept secure.  Note that it
                // may  take several seconds to a minute or two to start each tenant.  Because there is nothing to be gained by having these multithread,
                // as we're already in the background here, and the server isn't going to appreciate the multitasking load or get the job done any faster,
                // I've left this as a serial task.
                using (WebServiceClient tenantClient = new WebServiceClient(tenantInfo.EndpointConfigurationName))
                {
                    tenantClient.ClientCredentials.UserName.UserName = tenantInfo.UserName;
                    tenantClient.ClientCredentials.UserName.Password = tenantInfo.Password;
                    tenantClient.Stop();
                }

                // This provides the credentials for the site administrator.
                administratorClient.ClientCredentials.UserName.UserName = MainWindow.Tenants.AdministratorClientInfo.UserName;
                administratorClient.ClientCredentials.UserName.Password = MainWindow.Tenants.AdministratorClientInfo.Password;

                // This unloads the tenant from the data model using the site administrator's credentials.  Only a site administrator has the permissions to unload
                // tenants.
                administratorClient.UnloadTenant(tenantInfo.Name);
            }

            // After loading or unloading, we need to update the status of the display.
            this.RefreshDisplay();
        }
Exemple #24
0
        public async void FindEleveAsync()
        {
            WebServiceClient    client = new WebServiceClient();
            IEnumerable <Eleve> result = await client.GetEtudiantsAsync();

            //Affectation du résultat
        }
Exemple #25
0
        /// <summary>
        /// Get information about taxa with a protection level
        /// that is higher than public.
        /// </summary>
        /// <param name="includeSubTaxa">If true, all sub taxa are included in the result.</param>
        /// <param name="taxonInformationType">Type of taxa information to get.</param>
        /// <returns>Information about protected taxa.</returns>
        public static TaxonList GetProtectedTaxa(Boolean includeSubTaxa,
                                                 TaxonInformationType taxonInformationType)
        {
            Factor                     factor;
            List <WebTaxon>            webTaxa;
            SpeciesFactCondition       speciesFactCondition;
            SpeciesFactFieldCondition  speciesFactFieldCondition;
            SpeciesProtectionLevelEnum protectionLevel;
            WebDataQuery               webDataQuery;

            // Create data query.
            speciesFactCondition = new SpeciesFactCondition();
            factor = FactorManager.GetFactor(FactorId.ProtectionLevel);
            speciesFactCondition.Factors.Add(factor);

            for (protectionLevel = SpeciesProtectionLevelEnum.Protected1;
                 protectionLevel <= SpeciesProtectionLevelEnum.MaxProtected;
                 protectionLevel++)
            {
                speciesFactFieldCondition             = new SpeciesFactFieldCondition();
                speciesFactFieldCondition.FactorField = factor.FactorDataType.Field1;
                speciesFactFieldCondition.SetValue((Int32)protectionLevel);
                speciesFactCondition.SpeciesFactFieldConditions.Add(speciesFactFieldCondition);
            }

            // Get data from web service.
            webDataQuery = GetDataQuery(speciesFactCondition);
            webTaxa      = WebServiceClient.GetTaxaByQuery(webDataQuery, taxonInformationType);
            return(GetTaxa(webTaxa));
        }
Exemple #26
0
        static void Main(string[] args)
        {
            WebServiceClient Client = new WebServiceClient();

            Console.WriteLine(Client.Factorial(3));
            Client.Close();
        }
Exemple #27
0
        public string GetAccessToken(bool cache = false)
        {
            string token     = "";
            string _cachekey = "GetWeChatAccessToken";

            object obj = MemCache.GetCache(_cachekey);

            //从缓存获取
            if (cache && obj != null)
            {
                WeChatTokenLogEntity log = (WeChatTokenLogEntity)obj;
                if (log.EndTime > DateTime.Now)
                {
                    token = log.AccessToken;
                }
            }
            //从数据库获取
            if (token == "")
            {
                string appid             = WeiXinConfig.GetAppId();
                WeChatTokenLogEntity log = WeChatTokenLogBLL.Instance.GetTokenByAppid(appid);
                if (log != null && log.Id > 0 && log.EndTime > DateTime.Now)
                {
                    token = log.AccessToken;
                    TimeSpan ts1   = log.EndTime - DateTime.Now;
                    int      tsSen = ts1.Seconds;
                    if (cache)
                    {
                        MemCache.AddCache(_cachekey, log, tsSen);
                    }
                }
                if (token == "")
                {
                    string result = WebServiceClient.QueryGetWebService(string.Format(WeiXinConfig.URL_FORMAT_TOKEN, WeiXinConfig.GetAppId(), WeiXinConfig.GetAppSecret()), "", null);
                    JavaScriptSerializer        serializer = new JavaScriptSerializer();
                    Dictionary <string, object> jsonObj    = serializer.Deserialize <dynamic>(result);
                    if (jsonObj.ContainsKey("access_token"))
                    {
                        token = jsonObj["access_token"].ToString();
                        WeChatTokenLogEntity tokenlog = new WeChatTokenLogEntity();
                        tokenlog.Appid       = appid;
                        tokenlog.CreateTime  = DateTime.Now;
                        tokenlog.EndTime     = DateTime.Now.AddSeconds(7000);
                        tokenlog.AccessToken = token;
                        WeChatTokenLogBLL.Instance.AddWeChatTokenLog(tokenlog);
                        if (cache)
                        {
                            MemCache.AddCache(_cachekey, tokenlog, 7000);
                        }
                    }
                    else
                    {
                        token = "";
                    }
                }
            }

            return(token);
        }
        public void LoadSetting(Guid padSettingChecksum)
        {
            var ws = new WebServiceClient();

            ws.Url = MainForm.Current.OptionsPanel.InternetDatabaseUrlComboBox.Text;
            ws.LoadSettingCompleted += ws_LoadSettingCompleted;
            ws.LoadSettingAsync(new Guid[] { padSettingChecksum });
        }
 private CountryResponse GetGeoLocationResponse(string ipAddress)
 {
     using (var client = new WebServiceClient(_userId, _licenseKey))
     {
         var countryResponse = client.Country(ipAddress);
         return countryResponse;
     }
 }
Exemple #30
0
        public void LoadSetting(Guid padSettingChecksum)
        {
            var ws = new WebServiceClient();

            ws.Url = SettingsManager.Options.InternetDatabaseUrl;
            ws.LoadSettingCompleted += ws_LoadSettingCompleted;
            ws.LoadSettingAsync(new Guid[] { padSettingChecksum });
        }
Exemple #31
0
 List<Album> GetRemoteAlbums ()
 {
     _isGettingRemoteAlbums = true;
     var client = new WebServiceClient ();
     var request = new WebServiceRequest ("/albums", Method.GET);
     var response = client.Execute (request);
     return JsonConvert.DeserializeObject<List<Album>> (response.Content);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CESApi"/> class.
 /// </summary>
 /// <param name="apiKey">
 /// The API Key received from CESApp
 /// </param>
 /// <param name="baseUrl">
 /// The base url.
 /// </param>
 public CESApi(string apiKey, string baseUrl)
 {
     ApiKey        = apiKey;
     ServiceClient = new WebServiceClient(baseUrl)
     {
         ContentType = RequestContentType.Json
     };
 }
        public InsightsResponse RunClientGivenResponse(RestResponse response)
        {
            response.ContentLength = response.Content.Length;

            var restClient = MockRepository.GenerateStub<IRestClient>();

            restClient.Stub(r => r.Execute(Arg<IRestRequest>.Is.Anything)).Return(response);

            var wsc = new WebServiceClient(0, "abcdef", new List<string> { "en" });
            return wsc.Insights("1.2.3.4", restClient);
        }
 static void LoadRemoteEpisodes (Album album)
 {
     var client = new WebServiceClient ();
     var request = new WebServiceRequest ("/albums/" + album.Id + "/episodes", Method.GET);
     var response = client.Execute (request);
     var episodes = JsonConvert.DeserializeObject<List<AudioEpisode>> (response.Content);
     album.Episodes = episodes;
     if (DrunkAudibleApplication.Self.Database.Albums.All (a => a.Id != album.Id))
     {
         DrunkAudibleApplication.Self.Database.InsertOrUpdate (album);
         DrunkAudibleApplication.Self.Database.Albums.Add (album);
     }
 }
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Initialize Web Service Client
            MetrocamService = new WebServiceClient(APIKey);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="IP2LocationService"/> class.
        /// </summary>
        /// <param name="userId">The user identifier.</param>
        /// <param name="licenseKey">The license key.</param>
        /// <param name="loggerService">The logger service.</param>
        /// <param name="mapperFactory">The mapper factory.</param>
        public IP2LocationService(int userId, string licenseKey, ILoggerService loggerService, IMapperFactory mapperFactory)
        {
            this.loggerService = loggerService;
            this.mapperFactory = mapperFactory;

            try
            {
                this.client = new WebServiceClient(userId, licenseKey);
            }
            catch (Exception ex)
            {
                this.loggerService.LogException(ex.Message);
            }
        }
Exemple #37
0
 public void AddPackage(String packageSender, String packageReceiver, String packageName, String packageDescription,
                        String packageSenderCity, String packageDestinationCity, String packageTraking)
 {
     package package = new package();
     package.packageSender = Int32.Parse(packageSender);
     package.packageReceiver = Int32.Parse(packageReceiver);
     package.packageName = packageName;
     package.packageDescription = packageDescription;
     package.packageSenderCity = packageSenderCity;
     package.packageDestionationCity = packageDestinationCity;
     package.packageTracking = packageTraking;
     WebServiceClient packageService = new WebServiceClient();
     packageService.addPackage(package);
 }
        public void Bind(string Acct, string PIN)
        {
            string Domain = "localhost";
            int Port = 8080;
            WebServiceClient Client = new WebServiceClient(Domain, Port, null);

            OpenRequest OpenRequest = new OpenRequest () ;
            OpenRequest.Account = Account.User (Acct);
            OpenRequest.Domain = Account.Domain (Acct);;
            OpenRequest.HavePasscode = true;
            OpenRequest.HaveDisplay = false;
            OpenRequest.Encryption = Encryption;
            OpenRequest.Authentication = Authentication;
            OpenRequest.Challenge = Cryptography.Nonce ();
            string RequestData = OpenRequest.ToString ();

            // perform the request and wait for response
            string Result = Client.Request(RequestData);

            // Parse the result
            OpenResponse OpenResponse;
            OpenResponse.Deserialize (Result, out OpenResponse);

            if (OpenResponse.Cryptographic != null) {
                foreach (Cryptographic Crypto in OpenResponse.Cryptographic) {
                    CryptographicContext Context = CryptographicContext.MakeCryptographicContext (
                        Crypto.Ticket, Crypto.Secret, Crypto.Authentication, Crypto.Encryption);
                    if (Context != null) {
                        Client.CryptographicContext = Context;
                        break;
                        }
                    }
                if (Client.CryptographicContext == null) {
                    throw new Exception ("No supported algorithm");
                    }
                }

            TicketRequest TicketRequest = new TicketRequest ();
            TicketRequest.ChallengeResponse = Cryptography.ClientChallengeResponse (
                PIN, OpenRequest.Challenge, OpenResponse.Challenge, Cryptography.Authentication.Unknown);

            RequestData = TicketRequest.ToString ();
            Result =  Client.Request(RequestData);

            TicketResponse TicketResponse = new TicketResponse (Result);

            Console.WriteLine ("Result is");
            Console.WriteLine (Result);
        }
Exemple #39
0
        static void Main(string[] args)
        {
            UserServiceClient client = new UserServiceClient();
            WebServiceClient client1 = new WebServiceClient();

            package p = new package();
            p.packageName = "sdsdsds";
            client1.addPackage(p);

               // Users user = new Users();
               // user.userName = "******";
               // client.GetClient();

            Console.WriteLine("de");
        }
Exemple #40
0
        public static string GetInternalToken(string baseUri)
        {
            var client = new WebServiceClient<string>
            {
                Credentials = new Credentials
                {
                    ClientId = GoalInternal,
                    ClientSecret = GoalInternal,
                    Username = GoalInternal,
                    Password = GoalInternal
                },
                BaseUri = baseUri,
                TokenEndpoint = "token"
            };

            return client.GetToken();
        }
 public string AddComment(string comment, string itemUri, string userId, string userName)
 {
     string str = "0";
     if (this.Logger.IsDebugEnabled)
     {
         this.Logger.DebugFormat("CommentRepository.AddComment Comment {0}, itemUri {1}", new object[] { comment, itemUri });
     }
     try
     {
         WebServiceClient client = new WebServiceClient();
         string str2 = this.Authenticate("");
         TridionTcmUri tcmUri = UtilityHelper.GetTcmUri(itemUri);
         Coats.Crafts.CDS.Comment comment2 = new Coats.Crafts.CDS.Comment();
         User user = new User {
             Id = userId,
             Name = userName
         };
         comment = comment.Replace(Environment.NewLine, "#nl");
         comment2.Content = comment;
         if (this.CommentModeration.ToLower() == "on")
         {
             comment2.Status = 0;
         }
         else
         {
             comment2.Status = 2;
         }
         comment2.ItemPublicationId = tcmUri.TcmPublicationID;
         comment2.ItemId = tcmUri.TcmItemId;
         comment2.ItemType = tcmUri.TcmItemType;
         comment2.ModeratedDate = new DateTime?(DateTime.UtcNow);
         comment2.LastModifiedDate = DateTime.UtcNow;
         comment2.CreationDate = DateTime.UtcNow;
         comment2.Score = 0;
         comment2.Moderator = "";
         comment2.User = user;
         JavaScriptSerializer serializer = new JavaScriptSerializer();
         str = client.UploadString("/Comments", "POST", "{d:" + serializer.Serialize(comment2) + "}");
     }
     catch (Exception exception)
     {
         this.Logger.ErrorFormat("AddComment exception - {0}", new object[] { exception });
     }
     return str;
 }
        public MainWindowSettings()
        {
            // Required to initialize variables
            InitializeComponent();

            proxy = new WebServiceClient();

            proxy.GetAllProjectsCompleted += new EventHandler<GetAllProjectsCompletedEventArgs>(proxy_GetAllProjectsCompleted);
            proxy.getStatisticsByProjectIDCompleted += new EventHandler<getStatisticsByProjectIDCompletedEventArgs>(proxy_getStatisticsByProjectIDCompleted);
            proxy.UpdateProjectCompleted += new EventHandler<UpdateProjectCompletedEventArgs>(proxy_UpdateProjectCompleted);
            proxy.SetActiveProjectCompleted += new EventHandler<SetActiveProjectCompletedEventArgs>(proxy_SetActiveProjectCompleted);
            questionInfoMessgeBox.okInfoMessageButotn.Click += new RoutedEventHandler(okInfoMessageButotn_Click);
            questionInfoMessgeBox.cancelInfoMessageButton.Click += new RoutedEventHandler(cancelInfoMessageButton_Click);
            proxy.DeleteProjectCompleted += new EventHandler<DeleteProjectCompletedEventArgs>(proxy_DeleteProjectCompleted);
            proxy.CreateNewProjectCompleted += new EventHandler<CreateNewProjectCompletedEventArgs>(proxy_CreateNewProjectCompleted);

            questionInfoMessgeBox.Visibility = Visibility.Collapsed;
            saveMessage.Visibility = Visibility.Collapsed;
            updateProjects();
        }
        public MainWindowPrivateRequirements()
        {
            // Required to initialize variables
            InitializeComponent();

            proxy = new WebServiceClient();

            proxy.getAllDataCompleted += new EventHandler<getAllDataCompletedEventArgs>(proxy_getAllDataCompleted);
            proxy.UpdatePSRPCompleted += new EventHandler<UpdatePSRPCompletedEventArgs>(proxy_UpdatePSRPCompleted);
            proxy.createPrivateRequirementByRequirementIDCompleted += new EventHandler<createPrivateRequirementByRequirementIDCompletedEventArgs>(proxy_createPrivateRequirementByRequirementIDCompleted);
            proxy.UpdatePSRPCompleted += new EventHandler<UpdatePSRPCompletedEventArgs>(proxy_UpdatePSRPCompleted2);
            proxy.toggleActiveRequirementCompleted += new EventHandler<toggleActiveRequirementCompletedEventArgs>(proxy_toggleActiveRequirementCompleted);
            proxy.toggleActivePrivateRequirementCompleted += new EventHandler<toggleActivePrivateRequirementCompletedEventArgs>(proxy_toggleActivePrivateRequirementCompleted);
            proxy.CreateNewPSRPCompleted += new EventHandler<CreateNewPSRPCompletedEventArgs>(proxy_CreateNewPSRPCompleted);

            risks = new List<String>();
            risks.Add(heigh);
            risks.Add(medium);
            risks.Add(low);

            ProgressBar.Visibility = Visibility.Collapsed;
            HideInfoPanels();
        }
        public static KeyValuePair<string, string> GetCodeFromIP(string ipaddress)
        {
            var foundCountry = new KeyValuePair<string, string>();

            if (!UserId.HasValue)
            {
                return foundCountry;
            }

            var client = new WebServiceClient(UserId.Value, Sitecore.Configuration.Settings.GetSetting(Constants.Settings.MaxMindLicenseKey));

            try
            {
                var response = client.Country(ipaddress);

                foundCountry = new KeyValuePair<string, string>(response.Continent.Code, response.Country.IsoCode);
            }
            catch (Exception error)
            {
                Log.Error(string.Format("SharedSource.RedirectModule.MaxMind.WebServiceHelper {0}", error.Message), typeof(WebServiceHelper));
            }

            return foundCountry;
        }
        public AdminControlTP()
        {
            // Required to initialize variables
            InitializeComponent();

            proxy = new WebServiceClient();

            collapsNewSRPBox();
            collapsNewSDPBox();

            ProgressBarRight.Visibility = Visibility.Visible;
            ProgressBarLeft.Visibility = Visibility.Visible;

            proxy.GetAllCategoriesCompleted += new EventHandler<GetAllCategoriesCompletedEventArgs>(proxy_GetAllCategoriesCompleted);
            proxy.CreateNewCategorieCompleted += new EventHandler<CreateNewCategorieCompletedEventArgs>(proxy_CreateNewCategorieCompleted);
            proxy.UpdateCategorieCompleted += new EventHandler<UpdateCategorieCompletedEventArgs>(proxy_UpdateCategorieCompleted);
            proxy.addCategoryAndRequirementRelationCompleted += new EventHandler<addCategoryAndRequirementRelationCompletedEventArgs>(proxy_addCategoryAndRequirementRelationCompleted);
            proxy.DeleteCategorieCompleted += new EventHandler<DeleteCategorieCompletedEventArgs>(proxy_DeleteCategorieCompleted);
            proxy.removeCategoryAndRequirementRelationCompleted += new EventHandler<removeCategoryAndRequirementRelationCompletedEventArgs>(proxy_removeCategoryAndRequirementRelationCompleted);
            proxy.removeCategoryAndPatternRelationCompleted += new EventHandler<removeCategoryAndPatternRelationCompletedEventArgs>(proxy_removeCategoryAndPatternRelationCompleted);

            questionInfoMessgeBox.okInfoMessageButotn.Click += new RoutedEventHandler(okInfoMessageButotn_Click);
            questionInfoMessgeBox.cancelInfoMessageButton.Click += new RoutedEventHandler(cancelInfoMessageButton_Click);
        }
 public string AddRating(string ratingValue, string itemUri, string userId, string displayName)
 {
     if (this.Logger.IsDebugEnabled)
     {
         this.Logger.DebugFormat("CommentRepository.AddRating ratingValue {0}, itemUri {1}", new object[] { ratingValue, itemUri });
     }
     string str = this.CheckRating(itemUri, userId, true);
     string str2 = "0";
     if (str != "rated")
     {
         try
         {
             WebServiceClient client = new WebServiceClient();
             TridionTcmUri tcmUri = UtilityHelper.GetTcmUri(itemUri);
             User user = new User {
                 Id = userId,
                 Name = displayName
             };
             Rating rating = new Rating {
                 CreationDate = DateTime.UtcNow,
                 LastModifiedDate = DateTime.UtcNow,
                 ItemPublicationId = tcmUri.TcmPublicationID,
                 ItemId = tcmUri.TcmItemId,
                 ItemType = tcmUri.TcmItemType,
                 RatingValue = ratingValue.ToString(),
                 User = user,
                 Id = "0"
             };
             JavaScriptSerializer serializer = new JavaScriptSerializer();
             str2 = client.UploadString("/Ratings", "POST", "{d:" + serializer.Serialize(rating) + "}");
         }
         catch (Exception exception)
         {
             this.Logger.ErrorFormat("AddRating exception - {0}", new object[] { exception });
         }
     }
     return str2;
 }
Exemple #47
0
 public List<package> ReturnUserPackages(int UserID)
 {
     WebServiceClient packageService = new WebServiceClient();
     List<package> packages = packageService.getUserSpecifiedPackage(2).ToList();
     return packages;
 }
Exemple #48
0
 public List<package> GetPackages()
 {
     WebServiceClient packageService = new WebServiceClient();
     List<package> packages = packageService.getPackages().ToList();
     return packages;
 }
 protected WebServiceMethod(WebServiceClient webServiceClient)
 {
     WebServiceClient = webServiceClient;
 }
        public void CorrectlyFormattedCountryResponseShouldDeserializeIntoResponseObject()
        {
            var restResponse = new RestResponse
            {
                Content = OMNI_BODY,
                ContentType = "application/json",
                ResponseUri = new Uri("http://foo.com/omni/1.2.3.4"),
                StatusCode = (HttpStatusCode)200
            };

            restResponse.ContentLength = restResponse.Content.Length;

            var restClient = MockRepository.GenerateStub<IRestClient>();

            restClient.Stub(r => r.Execute(Arg<IRestRequest>.Is.Anything)).Return(restResponse);

            var wsc = new WebServiceClient(0, "abcdef", new List<string> { "en" });
            var result = wsc.Country("1.2.3.4", restClient);

            Assert.That(result, Is.Not.Null);
            Assert.That(result, Is.InstanceOf<CountryResponse>());
        }
 public void IncorrectlyFormattedIPAddressShouldThrowException()
 {
     var client = new WebServiceClient(0, "abcde", new List<string> { "en" });
     client.Omni("foo");
 }
 public WebServiceDataAdapter(WebServiceClient client)
 {
     webServiceClient = client;
 }