public NamespacedResourceWatcherFactory(KubernetesClientConfiguration config, IEnumerable <IWatcherEventHandler <T> > handlers)
 {
     _customResourceDetails = typeof(T).GetTypeInfo().GetCustomAttribute <CustomResourceAttribute>();
     _genericClient         = new GenericClient(config, _customResourceDetails.ApiGroup, _customResourceDetails.Version, _customResourceDetails.Plural);
     _client   = new Kubernetes(config);
     _handlers = handlers;
 }
Exemple #2
0
        public async Task <JsonResult> Post(Models.ApiModel apiModel)
        {
            var customHeadersList = new Dictionary <string, string>();
            var cCodeVal          = !string.IsNullOrEmpty(Request.Headers["CCode"]) ? Request.Headers["CCode"].ToString() : string.Empty;
            var uCodeVal          = !string.IsNullOrEmpty(Request.Headers["UCode"]) ? Request.Headers["UCode"].ToString() : string.Empty;

            customHeadersList.Add("CCode", cCodeVal);
            customHeadersList.Add("UCode", uCodeVal);
            string token = Request.Cookies["MAQTA-LOCAL-TOKEN"].Value;

            //ITokenContainer tokenContainer = new TokenContainer();

            if (token == null)
            {
                return(Json(new
                {
                    redirectUrl = Url.Action("LogOff", "Account"),
                    isRedirect = true
                }, JsonRequestBehavior.AllowGet));
            }
            var data = GetTargetData(apiModel);

            ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpClientInstance.Instance, token);
            GenericClient cb = new GenericClient(client);

            var response = await cb.Post(apiModel.ApiUrl, data, customHeadersList);

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
Exemple #3
0
        static void CallGeneric(GenericClient genericClient, string action, XmlNode messageBody)
        {
            // Build the message
            Message response;
            Message request;

            request = Message.CreateMessage(
                MessageVersion.Default,
                action,
                new XmlNodeReader(messageBody));

            // send request
            response = genericClient.Request(request);

            // dump the result
            if (!response.IsFault)
            {
                XmlReader resultBody = response.GetReaderAtBodyContents();
                resultBody.ReadToDescendant("text", "http://Microsoft.ServiceModel.Samples");
                string responseText = resultBody.ReadElementContentAsString("text", "http://Microsoft.ServiceModel.Samples");
                Console.WriteLine(responseText);
            }
            else
            {
                MessageFault fault = MessageFault.CreateFault(response, 8192);
                throw new FaultException(fault);
            }

            Console.WriteLine();
        }
Exemple #4
0
 public RetrievalTests()
 {
     Credentials            = ConfigHelper.GetCredentials();
     RetrievalConfiguration = ConfigHelper.GetRetrievalConfiguration();
     Mail2DB       = new GenericClient(Credentials);
     Converter     = new MailTypeConverter(Mail2DB);
     DefaultFilter = new ImapFilter().NotSeen(); // younger than two days
 }
Exemple #5
0
        public async Task <JsonResult> Get(string targetUrl, dynamic data)
        {
            try
            {
                string token = Request.Cookies["MAQTA-LOCAL-TOKEN"].Value;
                ViewBag.LoginURL = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["MamarBaseUrl"]);
                var customHeadersList = new Dictionary <string, string>();
                var cCodeVal          = !string.IsNullOrEmpty(Request.Headers["CCode"]) ? Request.Headers["CCode"].ToString() : string.Empty;
                var uCodeVal          = !string.IsNullOrEmpty(Request.Headers["UCode"]) ? Request.Headers["UCode"].ToString() : string.Empty;
                customHeadersList.Add("CCode", cCodeVal);
                customHeadersList.Add("UCode", uCodeVal);

                //ITokenContainer tokenContainer = new TokenContainer();


                if (token == null)
                {
                    return(Json(new
                    {
                        redirectUrl = Url.Action("LogOff", "Account"),
                        isRedirect = true
                    }, JsonRequestBehavior.AllowGet));
                }

                string queryString = string.Empty;
                string dataString  = ((string[])data)[0];
                if (!string.IsNullOrEmpty(dataString))
                {
                    var      dataParams = JObject.Parse(dataString);
                    string[] properties = new string[dataParams.Count];
                    var      i          = 0;
                    foreach (var param in dataParams)
                    {
                        properties[i] = (string.Format("{0}={1}", param.Key, HttpUtility.JavaScriptStringEncode(param.Value.Value <string>())));
                        i++;
                    }
                    queryString = string.Join("&", properties);
                }
                ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpClientInstance.Instance, token);
                GenericClient cb = new GenericClient(client);

                var response = await cb.Get(targetUrl + "?" + queryString, customHeadersList);

                return(new JsonResult()
                {
                    Data = response, ContentType = "application/json", MaxJsonLength = Int32.MaxValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
                //  Json(response, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                CentralELKLogger._errorlog.Error(ex, "MAMAR modul Error: " + ex.Message + " User Name " + User.Identity.GetUserName());
                throw ex;
            }
        }
        public ActionResult Edit(Order model)
        {
            UserSession userSession = new UserSession();
            string      token       = userSession.BearerToken;

            var inputJson = new JavaScriptSerializer().Serialize(model);

            var resultContent = GenericClient.PostEvent("http://localhost:57359/api/orders", inputJson, "PUT", token);

            return(RedirectToAction("Index", "OrderList"));
        }
Exemple #7
0
        static void GenericCallInvalid(GenericClient client, string action)
        {
            XmlDocument xmlFactory = new XmlDocument();
            XmlElement requestBodyElement = xmlFactory.CreateElement("Hello", ns);
            XmlElement requestContentElement = xmlFactory.CreateElement("greeting", ns);
            XmlElement requestParameterElement = xmlFactory.CreateElement("incorrect", ns); // <--
            requestParameterElement.InnerText = "Hello Server!";
            requestContentElement.AppendChild(requestParameterElement);
            requestBodyElement.AppendChild(requestContentElement);

            CallGeneric(client, action, requestBodyElement);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            UserSession userSession = new UserSession();
            string      token       = userSession.BearerToken;

            string url          = "http://localhost:57359/api/orders/";
            var    urlWithParam = string.Format("{0}{1}", url, id);

            var resultContent = GenericClient.PostEvent(urlWithParam, "", "DELETE", token);

            return(RedirectToAction("Index"));
        }
Exemple #9
0
        public async Task <ActionResult> DownloadReport(string targetUrl, string CCode, string UCode, string ReportParameter)
        {
            //	ITokenContainer tokenContainer = new TokenContainer();
            string token = Request.Cookies["MAQTA-LOCAL-TOKEN"].Value;

            if (token == null)
            {
                return(Json(new
                {
                    redirectUrl = Url.Action("LogOff", "Account"),
                    isRedirect = true
                }, JsonRequestBehavior.AllowGet));
            }
            ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpClientInstance.Instance, token);
            GenericClient cb       = new GenericClient(client);
            var           response = await cb.Get(targetUrl);

            JavaScriptSerializer j = new JavaScriptSerializer();

            ADP.MG.Pcs.Models.EntityModels.Report reportModel = default(ADP.MG.Pcs.Models.EntityModels.Report);
            if (!string.IsNullOrEmpty((response.ResponseResult)))
            {
                reportModel = Newtonsoft.Json.JsonConvert.DeserializeObject <ADP.MG.Pcs.Models.EntityModels.Report>(response.ResponseResult);
            }
            //var typeReportSource = new UriReportSource { Uri = string.Format("Reports/{0}", reportModel.ReportFileName) };
            var typeReportSource = new UriReportSource {
                Uri = string.Format("Report/{0}", "CustomReport.trdx")
            };

            string[] parameters;
            parameters = ReportParameter.ToString().Split(';');
            typeReportSource.Parameters.Add("centerCode", parameters[0]);
            typeReportSource.Parameters.Add("jobNumber", parameters[1]);
            typeReportSource.Parameters.Add("searchString", parameters[2]);
            typeReportSource.Parameters.Add("pageNumber", parameters[3]);
            typeReportSource.Parameters.Add("pageSize", parameters[4]);
            typeReportSource.Parameters.Add("CCode", CCode);
            typeReportSource.Parameters.Add("UCode", UCode);
            typeReportSource.Parameters.Add("token", token);


            Telerik.Reporting.Processing.ReportProcessor reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
            //Telerik.Reporting.Processing.RenderingResult result = reportProcessor.RenderReport(reportModel.DownloadType.ToUpper(), typeReportSource, null);
            Telerik.Reporting.Processing.RenderingResult result = reportProcessor.RenderReport("XLS", typeReportSource, null);
            byte[] contents = result.DocumentBytes;
            //string mimeType = reportModel.DownloadType == "xls" ? "vnd.ms-excel" : "vnd.ms-excel";//reportModel.DownloadType;
            string mimeType = "vnd.ms-excel";            //reportModel.DownloadType;

            //return File(contents, string.Format("application/{0}", mimeType), reportModel.DownloadFileName);
            return(File(contents, string.Format("application/{0}", mimeType), "Chassis Details.xls"));
        }
Exemple #10
0
        /// <summary>
        /// Disposable impl. Handles cleanup and marks any uncompleted tasks as failed.
        /// </summary>
        public void Dispose()
        {
            // the consumer did not assert the task was succesfully completed,
            // or something sinister has happened. Add the task to the failed tasks list.
            if (State == RedisQueueState.TaskReserved && !LocalCachingEnabled)
            {
                Fail("RedisClient disposed prior to the task being completed.");
            }

            TypedClient.Dispose();
            GenericClient.Dispose();

            Log.Info("Disconnected from Redis.");
            Log.DebugFormat("Client state on disconnect: {0}", State);
        }
Exemple #11
0
        private static async Task Main(string[] args)
        {
            var config  = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            var generic = new GenericClient(config, "", "v1", "nodes");
            var node    = await generic.ReadAsync <V1Node>("kube0").ConfigureAwait(false);

            Console.WriteLine(node.Metadata.Name);

            var genericPods = new GenericClient(config, "", "v1", "pods");
            var pods        = await genericPods.ListNamespacedAsync <V1PodList>("default").ConfigureAwait(false);

            foreach (var pod in pods.Items)
            {
                Console.WriteLine(pod.Metadata.Name);
            }
        }
Exemple #12
0
        static void SendRequest(string requestBodyXml)
        {
            Message requestMessage;
            Message replyMessage;

            GenericClient genericClient = new GenericClient();
            requestMessage = Message.CreateMessage(
                                    MessageVersion.Default,
                                    nullAction,
                                    XmlReader.Create(new StringReader(requestBodyXml)));
            replyMessage = genericClient.ProcessMessage(requestMessage);
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(Console.Out));
            replyMessage.WriteBodyContents(writer);
            writer.Flush();
            Console.WriteLine();
        }
        // GET: OrderList
        public ActionResult Index()
        {
            UserSession userSession = new UserSession();
            string      token       = userSession.BearerToken;

            List <Order> orderList = new List <Order>();

            var resultContent = GenericClient.GetEvent("http://localhost:57359/api/orders", "", token);

            if (resultContent != "")
            {
                orderList = JsonConvert.DeserializeObject <List <Order> >(resultContent);
            }

            return(View(orderList));
        }
        private void LogErrorInMgApp(string targetUrl, string data, string response)
        {
            ITokenContainer tokenContainer = new TokenContainer();

            ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpClientInstance.Instance, tokenContainer);
            GenericClient cb = new GenericClient(client);

            cb.LogErrorinMgApp("PCSWEBREQUESTURL:" + targetUrl);
            if (data != null)
            {
                cb.LogErrorinMgApp("PCSWEBDATA:" + data);
            }
            if (response != null)
            {
                cb.LogErrorinMgApp("PCSWEBRESPONSE:" + response);
            }
        }
Exemple #15
0
        public async Task <ActionResult> DownloadApprovalReport(string targetUrl, string CCode, string UCode, string ReportParameter)
        {
            //ITokenContainer tokenContainer = new TokenContainer();
            string token = Request.Cookies["MAQTA-LOCAL-TOKEN"].Value;//Used this as Per Mudassar on 4-July-2019

            if (token == null)
            {
                return(Json(new
                {
                    redirectUrl = Url.Action("LogOff", "Account"),
                    isRedirect = true
                }, JsonRequestBehavior.AllowGet));
            }

            ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpClientInstance.Instance, token);
            GenericClient cb       = new GenericClient(client);
            var           response = await cb.Get(targetUrl);

            JavaScriptSerializer j = new JavaScriptSerializer();

            ADP.MG.Pcs.Models.EntityModels.Report reportModel = default(ADP.MG.Pcs.Models.EntityModels.Report);
            if (!string.IsNullOrEmpty((response.ResponseResult)))
            {
                reportModel = Newtonsoft.Json.JsonConvert.DeserializeObject <ADP.MG.Pcs.Models.EntityModels.Report>(response.ResponseResult);
            }

            var typeReportSource = new UriReportSource {
                Uri = string.Format("Report/{0}", "Approval.trdx")
            };

            string[] parameters;
            parameters = ReportParameter.ToString().Split(';');
            typeReportSource.Parameters.Add("centerCode", parameters[0]);
            typeReportSource.Parameters.Add("jobNumber", parameters[1]);
            typeReportSource.Parameters.Add("CCode", CCode);
            typeReportSource.Parameters.Add("UCode", UCode);
            typeReportSource.Parameters.Add("token", token);
            Telerik.Reporting.Processing.ReportProcessor reportProcessor = new Telerik.Reporting.Processing.ReportProcessor();
            Telerik.Reporting.Processing.RenderingResult result          = reportProcessor.RenderReport("PDF", typeReportSource, null);
            byte[] contents = result.DocumentBytes;
            string mimeType = "PDF";

            return(File(contents, string.Format("application/{0}", mimeType), "Approval.pdf"));
        }
        public async Task <IEnumerable> GetReplicaSetByNamespace(string resourceNamespace)
        {
            List <ReplicaSetModel> resourceList = new List <ReplicaSetModel>();

            var apiGenericClient = new GenericClient(_config, "apps", "v1", "replicasets");

            var returnedList = await apiGenericClient.ListNamespacedAsync <V1ReplicaSetList>(resourceNamespace).ConfigureAwait(false);

            foreach (var item in returnedList.Items)
            {
                ReplicaSetModel r = new ReplicaSetModel
                {
                    Name = item.Name()
                };
                resourceList.Add(r);
            }

            return(resourceList);
        }
        public async Task <IEnumerable> GetDeploymentsByNamespace(string resourceNamespace)
        {
            List <DeploymentModel> resourceList = new List <DeploymentModel>();

            var apiGenericClient = new GenericClient(_config, "apps", "v1", "deployments");

            var returnedList = await apiGenericClient.ListNamespacedAsync <V1DeploymentList>(resourceNamespace).ConfigureAwait(false);

            foreach (var item in returnedList.Items)
            {
                DeploymentModel d = new DeploymentModel
                {
                    Name = item.Name()
                };
                resourceList.Add(d);
            }

            return(resourceList);
        }
        public async Task <IEnumerable> GetServicesByNamespace(string resourceNamespace)
        {
            List <ServiceModel> resourceList = new List <ServiceModel>();

            var apiGenericClient = new GenericClient(_config, "", "v1", "services");

            var returnedList = await apiGenericClient.ListNamespacedAsync <V1ServiceList>(resourceNamespace).ConfigureAwait(false);

            foreach (var item in returnedList.Items)
            {
                ServiceModel s = new ServiceModel
                {
                    Name = item.Name()
                };
                resourceList.Add(s);
            }

            return(resourceList);
        }
        // GET:
        public ActionResult Delete(int id = 0)
        {
            UserSession userSession = new UserSession();
            string      token       = userSession.BearerToken;

            Order order = null;

            string url          = "http://localhost:57359/api/orders/";
            var    urlWithParam = string.Format("{0}{1}", url, id);

            var resultContent = GenericClient.GetEvent(urlWithParam, "", token);

            if (resultContent != "")
            {
                order = JsonConvert.DeserializeObject <Order>(resultContent);
            }

            return(View("Details", order));
        }
        public async Task <JsonResult> Get(string targetUrl, dynamic data)
        {
            try
            {
                var             customHeadersList = new Dictionary <string, string>();
                var             selectedCompany   = Request.Cookies["_selected_company_"];
                ITokenContainer tokenContainer    = new TokenContainer();
                tokenContainer.ApiSelectedCompany = selectedCompany != null?Server.UrlDecode(selectedCompany.Value) : "";

                var cSelectedCompany = !string.IsNullOrEmpty(Request.Headers["_selected_company_"]) ? Request.Headers["_selected_company_"].ToString() : string.Empty;
                customHeadersList.Add("_selected_company_", cSelectedCompany);

                string queryString = string.Empty;
                if (tokenContainer.ApiToken == null)
                {
                    return(Json(new
                    {
                        redirectUrl = Url.Action("LogOff", "Account", new { area = string.Empty }),
                        isRedirect = true
                    }, JsonRequestBehavior.AllowGet));
                }
                if (!string.IsNullOrEmpty(((string[])data)[0]))
                {
                    var           dataParams = JObject.Parse(((string[])data)[0]);
                    List <string> properties = new List <string>();
                    foreach (var param in dataParams)
                    {
                        properties.Add(string.Format("{0}={1}", param.Key, HttpUtility.JavaScriptStringEncode(param.Value.Value <string>())));
                    }
                    queryString = string.Join("&", properties.ToArray());
                }
                ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpSubscriptionClient.Instance, tokenContainer);
                GenericClient cb       = new GenericClient(client);
                var           response = await cb.Get(targetUrl + "?" + queryString, customHeadersList);

                return(Json(response, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void CopyTestsGenericConnector()
        {
            var connector        = new ContactClient();
            var genericConnector = new GenericClient <StdContact>();
            var tempFolder       = PrepareFolder(false);
            var file1            = Path.Combine(tempFolder, "file1");
            var file2            = Path.Combine(tempFolder, "file2");
            var path1            = Path.Combine(tempFolder, "vCards");

            var originalList = connector.GetAll(file1);

            originalList.Add(new StdContact());
            genericConnector.WriteRange(originalList, path1);
            var copyList = genericConnector.GetAll(path1);

            copyList.Add(new StdContact());
            connector.WriteRange(copyList, file2);

            AssertOriginalAndCopyCompare(originalList, copyList, false);
        }
        public async Task <JsonResult> Post(ADP.MG.Mamar.Web.Models.ApiModel apiModel)
        {
            ITokenContainer tokenContainer = new TokenContainer();

            if (tokenContainer.ApiToken == null)
            {
                return(Json(new
                {
                    redirectUrl = Url.Action("LogOff", "Account", new { area = string.Empty }),
                    isRedirect = true
                }, JsonRequestBehavior.AllowGet));
            }
            var data = GetTargetData(apiModel);

            ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpSubscriptionClient.Instance, tokenContainer);
            GenericClient cb       = new GenericClient(client);
            var           response = await cb.Post(apiModel.ApiUrl, data);

            return(Json(response, JsonRequestBehavior.AllowGet));
        }
        private async Task <GenericRecord> RunGenericClient(GenericClient client, CancellationToken token)
        {
            var parameterType         = client.Protocol.Types.First(r => r.Name == "Greeting") as RecordSchema;
            var parameterRecordSchema = new RecordSchema(
                "hello",
                $"{client.Protocol.Namespace}.messages",
                new RecordSchema.Field[]
            {
                new RecordSchema.Field("greeting", parameterType)
            }
                );
            var parameter = new GenericRecord(parameterType);

            parameter[0] = "Hello!";
            var parameterRecord = new GenericRecord(parameterRecordSchema);

            parameterRecord[0] = parameter;
            var rpcContext = await client.RequestAsync("hello", parameterRecord, token);

            return(rpcContext.Response as GenericRecord);
        }
        public async Task <ActionResult> GetSubscriptionData()
        {
            string EnableSubscriptionFee = ConfigurationManager.AppSettings["EnableMamarSubscriptionFee"];

            if (!string.IsNullOrEmpty(EnableSubscriptionFee) && EnableSubscriptionFee != "__EnableMamarSubscriptionFee__" && Convert.ToBoolean(EnableSubscriptionFee))
            {
                string token = Request.Cookies["MAQTA-LOCAL-TOKEN"].Value;
                if (token == null)
                {
                    return(Json(new
                    {
                        redirectUrl = Url.Action("LogOff", "Account"),
                        isRedirect = true
                    }, JsonRequestBehavior.AllowGet));
                }
                ApiHelper.Client.ApiClient client = new ApiHelper.Client.ApiClient(HttpSubscriptionClient.Instance, token);
                GenericClient cb       = new GenericClient(client);
                var           response = await cb.Get("subscription/SubscriptionStatus");

                var objSubscription = JsonConvert.DeserializeObject <SubscriptionStatusResponse>(response.ResponseResult);
                if (objSubscription.isRestricted)
                {
                    return(Json(new ApiResponse()
                    {
                        StatusIsSuccessful = false, ResponseResult = "Subscription Disabled"
                    }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                return(Json(new ApiResponse()
                {
                    StatusIsSuccessful = false, ResponseResult = "Subscription Disabled"
                }, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #25
0
        /// <summary>
        /// Implements a read of the full list of contacts for the specifies folder.
        /// </summary>
        /// <param name="clientFolderName">
        /// The client folder name for the memory connector.
        /// </param>
        /// <param name="result">
        /// The result list of contacts.
        /// </param>
        /// <returns>
        /// the search results
        /// </returns>
        protected override List <StdElement> ReadFullList(string clientFolderName, List <StdElement> result)
        {
            var connector  = new GenericClient();
            var listToScan = connector.GetAll(clientFolderName);

            this.xingRequester.UiDispatcher = this.UiDispatcher;

            result = new List <StdElement>();

            foreach (StdContact element in listToScan)
            {
                if (!string.IsNullOrEmpty(element.ExternalIdentifier.GetProfileId(ProfileIdentifierType.XingNameProfileId)) ||
                    string.IsNullOrEmpty(element.Name.LastName))
                {
                    continue;
                }

                var guesses = GuessProfileUrls(element.Name);
                foreach (var guess in guesses)
                {
                    for (var i = 0; i < 9; i++)
                    {
                        var profileUrl =
                            "http://www.xing.com/profile/"
                            + guess
                            + ((i > 0) ? i.ToString(CultureInfo.InvariantCulture) : string.Empty);

                        var publicProfile = this.xingRequester.GetContent(profileUrl);

                        if (publicProfile.Contains("Die gesuchte Seite konnte nicht gefunden werden."))
                        {
                            break;
                        }

                        var imageUrl = MapRegexToProperty(
                            publicProfile,
                            @"id=""photo"" src=""(?<info>/img/users/[^""]/[^""]/[^""]*)"" class=""photo profile-photo""");
                        var newContact = new StdContact
                        {
                            Name =
                                MapRegexToProperty(
                                    publicProfile, "\\<meta name=\"author\" content=\"(?<info>[^\"]*)\""),
                            BusinessPosition =
                                MapRegexToProperty(
                                    publicProfile,
                                    "\\<p class=\"profile-work-descr\"\\>(\\<[^>]*>)*(?<info>[^<]*)\\</"),
                            BusinessAddressPrimary =
                                new AddressDetail
                            {
                                PostalCode =
                                    MapRegexToProperty(publicProfile, "zip_code=\\%22(?<info>[^%]*)\\%22"),
                                CityName =
                                    MapRegexToProperty(
                                        publicProfile, "search&amp;city=%22(?<info>[^%]*)%22")
                            },
                            PictureData =
                                string.IsNullOrEmpty(imageUrl)
                                        ? null
                                        : this.xingRequester.GetContentBinary(
                                    MapRegexToProperty(
                                        publicProfile,
                                        @"id=""photo"" src=""(?<info>/img/users/[^""]/[^""]/[^""]*)"" class=""photo profile-photo"""))
                        };

                        if (string.IsNullOrEmpty(newContact.Name.ToString()))
                        {
                            continue;
                        }

                        this.LogProcessingEvent(newContact, "adding new contact candidate");

                        result.Add(newContact);
                    }
                }
            }

            return(result);
        }
Exemple #26
0
 internal UserRepository()
 {
     dal = new GenericClient(AlternateFramework.Data.DatabaseClients.MsSqlServer, ConfigurationManager.ConnectionStrings["ConnectionWCF"].ConnectionString);
 }
Exemple #27
0
        private static async Task Main(string[] args)
        {
            Console.WriteLine("starting main()...");

            // creating the k8s client
            var         k8SClientConfig = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            IKubernetes client          = new Kubernetes(k8SClientConfig);

            // creating a K8s client for the CRD
            var myCRD = Utils.MakeCRD();

            Console.WriteLine("working with CRD: {0}.{1}", myCRD.PluralName, myCRD.Group);
            var generic = new GenericClient(client, myCRD.Group, myCRD.Version, myCRD.PluralName);

            // creating a sample custom resource content
            var myCr = Utils.MakeCResource();

            try
            {
                Console.WriteLine("creating CR {0}", myCr.Metadata.Name);
                var response = await client.CreateNamespacedCustomObjectWithHttpMessagesAsync(
                    myCr,
                    myCRD.Group, myCRD.Version,
                    myCr.Metadata.NamespaceProperty ?? "default",
                    myCRD.PluralName).ConfigureAwait(false);
            }
            catch (HttpOperationException httpOperationException) when(httpOperationException.Message.Contains("422"))
            {
                var phase   = httpOperationException.Response.ReasonPhrase;
                var content = httpOperationException.Response.Content;

                Console.WriteLine("response content: {0}", content);
                Console.WriteLine("response phase: {0}", phase);
            }
            catch (HttpOperationException)
            {
            }

            // listing the cr instances
            Console.WriteLine("CR list:");
            var crs = await generic.ListNamespacedAsync <CustomResourceList <CResource> >(myCr.Metadata.NamespaceProperty ?? "default").ConfigureAwait(false);

            foreach (var cr in crs.Items)
            {
                Console.WriteLine("- CR Item {0} = {1}", crs.Items.IndexOf(cr), cr.Metadata.Name);
            }

            var old = JsonSerializer.SerializeToDocument(myCr);

            myCr.Metadata.Labels.TryAdd("newKey", "newValue");

            var expected = JsonSerializer.SerializeToDocument(myCr);
            var patch    = old.CreatePatch(expected);

            // updating the custom resource
            var crPatch = new V1Patch(patch, V1Patch.PatchType.JsonPatch);

            try
            {
                var patchResponse = await client.PatchNamespacedCustomObjectAsync(
                    crPatch,
                    myCRD.Group,
                    myCRD.Version,
                    myCr.Metadata.NamespaceProperty ?? "default",
                    myCRD.PluralName,
                    myCr.Metadata.Name).ConfigureAwait(false);
            }
            catch (HttpOperationException httpOperationException)
            {
                var phase   = httpOperationException.Response.ReasonPhrase;
                var content = httpOperationException.Response.Content;
                Console.WriteLine("response content: {0}", content);
                Console.WriteLine("response phase: {0}", phase);
            }

            // getting the updated custom resource
            var fetchedCR = await generic.ReadNamespacedAsync <CResource>(
                myCr.Metadata.NamespaceProperty ?? "default",
                myCr.Metadata.Name).ConfigureAwait(false);

            Console.WriteLine("fetchedCR = {0}", fetchedCR.ToString());

            // deleting the custom resource
            try
            {
                myCr = await generic.DeleteNamespacedAsync <CResource>(
                    myCr.Metadata.NamespaceProperty ?? "default",
                    myCr.Metadata.Name).ConfigureAwait(false);

                Console.WriteLine("Deleted the CR");
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception type {0}", exception);
            }
        }
Exemple #28
0
 /// <summary>
 /// Returns an empty channel subscription.
 /// </summary>
 /// <returns></returns>
 public IRedisSubscription GetSubscription()
 {
     return(GenericClient.CreateSubscription());
 }
Exemple #29
0
 /// <summary>
 /// Sends a message to the channel associated with a specific queue.
 /// </summary>
 /// <param name="message"></param>
 /// <param name="queue"></param>
 public void SendMessage(string message, QueueName queue)
 {
     GenericClient.PublishMessage(queue.ChannelName, message);
 }
Exemple #30
0
        internal RepositoryBase()
        {
            var dal = new GenericClient(AlternateFramework.Data.DatabaseClients.MsSqlServer, ConfigurationManager.ConnectionStrings["ConnectionWCF"].ConnectionString);

            SetConnection(dal.Connection);
        }
Exemple #31
0
        public async void GenericTest()
        {
            var namespaceParameter = "default";
            var podName            = "k8scsharp-e2e-generic-pod";

            var client      = CreateClient();
            var genericPods = new GenericClient(client, "", "v1", "pods");

            void Cleanup()
            {
                var pods = client.ListNamespacedPod(namespaceParameter);

                while (pods.Items.Any(p => p.Metadata.Name == podName))
                {
                    try
                    {
                        client.DeleteNamespacedPod(podName, namespaceParameter);
                    }
                    catch (HttpOperationException e)
                    {
                        if (e.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            return;
                        }
                    }
                }
            }

            try
            {
                Cleanup();

                await genericPods.CreateNamespacedAsync(
                    new V1Pod()
                {
                    Metadata = new V1ObjectMeta {
                        Name = podName,
                    },
                    Spec = new V1PodSpec
                    {
                        Containers = new[] { new V1Container()
                                             {
                                                 Name = "k8scsharp-e2e", Image = "nginx",
                                             }, },
                    },
                },
                    namespaceParameter).ConfigureAwait(false);

                var pods = await genericPods.ListNamespacedAsync <V1PodList>(namespaceParameter).ConfigureAwait(false);

                Assert.Contains(pods.Items, p => p.Metadata.Name == podName);

                int retry = 5;
                while (retry-- > 0)
                {
                    try
                    {
                        await genericPods.DeleteNamespacedAsync <V1Pod>(namespaceParameter, podName).ConfigureAwait(false);
                    }
                    catch (HttpOperationException e)
                    {
                        if (e.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
                        {
                            return;
                        }
                    }

                    pods = await genericPods.ListNamespacedAsync <V1PodList>(namespaceParameter).ConfigureAwait(false);

                    if (!pods.Items.Any(p => p.Metadata.Name == podName))
                    {
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(2.5)).ConfigureAwait(false);
                }

                Assert.DoesNotContain(pods.Items, p => p.Metadata.Name == podName);
            }
            finally
            {
                Cleanup();
            }
        }
Exemple #32
0
        static void Main()
        {
            Console.WriteLine("*** Call 'Hello' with svcutil-generated client");
            HelloServiceClient helloClient = new HelloServiceClient();

            Greeting greeting = new Greeting();
            greeting.text = "Hello Server!";
            GreetingResponse response = helloClient.Hello(greeting);
            Console.WriteLine(response.text);
            helloClient.Close();

            try
            {
                Console.WriteLine("*** Call 'Hello' with generic client, no client behavior");
                GenericClient client = new GenericClient();

                Console.WriteLine("--- Sending valid client request:");
                GenericCallValid(client, helloAction);
                Console.WriteLine("--- Sending invalid client request:");
                GenericCallInvalid(client, helloAction);
                client.Close();

            }
            catch (Exception e)
            {
                DumpException(e);
            }

            try
            {
                Console.WriteLine("*** Call 'Hello' with generic client, with client behavior");
                GenericClient client = new GenericClient();

                // Configure client programmatically, adding behavior
                XmlSchema schema = XmlSchema.Read(new StreamReader("messages.xsd"), null);
                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add(schema);
                client.Endpoint.Behaviors.Add(new SchemaValidationBehavior(schemaSet, true, true));

                Console.WriteLine("--- Sending valid client request:");
                GenericCallValid(client, helloAction);
                Console.WriteLine("--- Sending invalid client request:");
                GenericCallInvalid(client, helloAction);

                client.Close();
            }
            catch (Exception e)
            {
                DumpException(e);
            }

            Console.WriteLine("*** Call 'HelloToo' with generic client, no client behavior");
            try
            {
                GenericClient client = new GenericClient();

                Console.WriteLine("--- Sending valid client request, malformed service reply:");
                GenericCallValid(client, helloTooAction);
                client.Close();

            }
            catch (Exception e)
            {
                DumpException(e);
            }

            Console.WriteLine("*** Call 'HelloToo' with generic client, with client behavior, no service behavior");
            try
            {
                GenericClient client = new GenericClient();

                XmlSchema schema = XmlSchema.Read(new StreamReader("messages.xsd"), null);
                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add(schema);

                client.Endpoint.Address = new EndpointAddress(client.Endpoint.Address.Uri.ToString() + "/novalidation");
                client.Endpoint.Behaviors.Add(new SchemaValidationBehavior(schemaSet, true, true));

                Console.WriteLine("--- Sending valid client request, malformed service reply:");
                GenericCallValid(client, helloTooAction);
                client.Close();
            }
            catch (Exception e)
            {
                DumpException(e);
            }

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
        private static async Task Main(string[] args)
        {
            var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();
            //var generic = new GenericClient(config, "", "v1", "nodes");
            // var node = await generic.ReadAsync<V1Node>("kube0").ConfigureAwait(false);
            // Console.WriteLine(node.Metadata.Name);

            var genericPods = new GenericClient(config, "", "v1", "pods");
            var pods        = await genericPods.ListNamespacedAsync <V1PodList>("default").ConfigureAwait(false);

            foreach (var pod in pods.Items)
            {
                Console.WriteLine(pod.Metadata.Name);
            }

            var genericServices = new GenericClient(config, "", "v1", "services");
            var services        = await genericServices.ListNamespacedAsync <V1ServiceList>("default").ConfigureAwait(false);

            foreach (var svc in services.Items)
            {
                Console.WriteLine(svc.Metadata.Name);
            }

            var genericDeployments = new GenericClient(config, "apps", "v1", "deployments");
            var deployments        = await genericDeployments.ListNamespacedAsync <V1DeploymentList>("default").ConfigureAwait(false);

            foreach (var dep in deployments.Items)
            {
                Console.WriteLine(dep.Metadata.Name);
            }

            var genericDaemonSets = new GenericClient(config, "apps", "v1", "daemonsets");
            var daemonsets        = await genericDaemonSets.ListNamespacedAsync <V1DaemonSetList>("kube-system").ConfigureAwait(false);

            foreach (var d in daemonsets.Items)
            {
                Console.WriteLine(d.Metadata.Name);
            }

            // var genericIngress = new GenericClient(config, "apps", "v1", "ingress");
            // var ingresses = await genericIngress.ListNamespacedAsync<V1IngressList>("default").ConfigureAwait(false);
            // foreach (var i in ingresses.Items)
            // {
            //     Console.WriteLine(i.Metadata.Name);
            // }

            var genericReplicaset = new GenericClient(config, "apps", "v1", "replicasets");
            var replicasets       = await genericReplicaset.ListNamespacedAsync <V1ReplicaSetList>("default").ConfigureAwait(false);

            foreach (var r in replicasets.Items)
            {
                Console.WriteLine(r.Metadata.Name);
            }

            // var genericJob = new GenericClient(config, "", "v1", "jobs");
            // var jobs = await genericJob.ListNamespacedAsync<V1JobList>("default").ConfigureAwait(false);
            // foreach (var r in jobs.Items)
            // {
            //     Console.WriteLine(r.Metadata.Name);
            // }
        }