public MockServicesHost Add(Action<ServiceData> setter)
 {
     var service = new ServiceData();
     setter(service);
     Services.Add(service);
     return this;
 }
Exemplo n.º 2
0
        /// <summary>
        /// Adds the given service to the service container.
        /// </summary>
        /// <param name="serviceType">The type of the service to add.</param>
        /// <param name="serviceInstance">An instance of the service.</param>
        /// <param name="shouldDisposeServiceInstance">true if the Dipose of the service provider is allowed to dispose the sevice instance.</param>
        public void AddService(Type serviceType, object serviceInstance, bool shouldDisposeServiceInstance)
        {
            // Create the description of this service. Note that we don't do any validation
            // of the parameter here because the constructor of ServiceData will do it for us.
            ServiceData service = new ServiceData(serviceType, serviceInstance, null, shouldDisposeServiceInstance);

            // Now add the service desctription to the dictionary.
            AddService(service);
        }
Exemplo n.º 3
0
        public ClientFacade(string login, string password, ServiceData serviceData)
            : base(new InstanceContext(new Response(new Notifier())))
        {
            _serviceData = serviceData;

            ClientCredentials.UserName.UserName = login;
            ClientCredentials.UserName.Password = password;
            InnerChannel.Closed += (o, e) => NeedClose = true;
            InnerChannel.Faulted += (o, e) => NeedClose = true;
        }
        static void Main(string[] args)
        {
            Service1Client client = new Service1Client();
            ServiceData responseData = new ServiceData();

            try
            {
                responseData= client.DivideNumbers(10, 0);
                Console.WriteLine("Result is {0}", responseData.result.ToString());
            }
            catch (FaultException<ServiceData> Fex)
            {
                Console.WriteLine("Error Number is  {0}",Fex.Detail.errorNumber);
                Console.WriteLine("Error Message is {0}",Fex.Detail.errorMessage);
            }

            Console.ReadKey();
        }
        public async Task UpdateServiceData_Should_ReturnWithMatchingServiceData()
        {
            // Arrange
            var sut     = new CustomerVehicleService(repo, new MockVehicleDataService());
            var vehicle = await sut.AddVehicleToCustomer("EF02VCC", Guid.NewGuid(), Guid.NewGuid());

            var serviceData = new ServiceData
            {
                EstAnualMileage         = 8000,
                MaxMileage              = 6000,
                MaxMonths               = 12,
                ServiceDataConfiguredBy = "Customer"
            };
            // Act
            var result = await sut.UpdateServiceData(serviceData, vehicle.Id, vehicle.ClientId);

            // Assert
            Assert.Equal(serviceData.EstAnualMileage, result.ServiceData.EstAnualMileage);
            Assert.Equal(serviceData.MaxMonths, result.ServiceData.MaxMonths);
            Assert.Equal(serviceData.MaxMileage, result.ServiceData.MaxMileage);
            Assert.Equal(serviceData.ServiceDataConfiguredBy, result.ServiceData.ServiceDataConfiguredBy);
        }
Exemplo n.º 6
0
        bool RefreshFile(string filePath)
        {
            var srvFile = filePath.AsFile();

            if (srvFile.LastWriteTime != servicesDirectoryLastWriteTime)
            {
                return(LoadFile(filePath));
            }

            foreach (var srv in ServiceData.ToArray())
            {
                var projFolder     = Path.Combine(ServicesDirectory?.FullName ?? "", srv.SolutionFolder);
                var websiteFolder  = Path.Combine(projFolder, "website");
                var launchSettings = Path.Combine(websiteFolder, "properties", "launchSettings.json");
                if (File.Exists(launchSettings))
                {
                    srv.Port = GetPortNumberFromLaunchSettingsFile(launchSettings);
                }
                else
                {
                    srv.Status        = MicroserviceItem.EnumStatus.NoSourcerLocally;
                    srv.WebsiteFolder = null;
                    srv.ProcId        = -1;
                    srv.VsDTE         = null;
                    srv.Port          = null;
                    srv.VsIsOpen      = false;
                    continue;
                }

                if (srv.WebsiteFolder.IsEmpty())
                {
                    srv.Status = MicroserviceItem.EnumStatus.NoSourcerLocally;
                }
            }

            RestartAutoRefresh();
            RestartAutoRefreshProcess();
            return(true);
        }
Exemplo n.º 7
0
        //Choose the SkillTrade for the services rendered
        public void ChooseSkillTrade(String SkillTrade, int Cnt)
        {
            if (SkillTrade == "Skill-exchange")
            {
                //Click on the SkillExchange radio button
                SkillExchangeButton.Click();

                //Implicit wait
                Wait.wait(1, driver);

                String[] Skills = ServiceData.SkillExchangeData(RowNum);
                //Loop in to read all the tags
                for (int TagCount = 0; TagCount < Cnt; TagCount++)
                {
                    //Read the data for Tags from excel in case the services is edited to add new tags
                    SkillExchngTag.SendKeys(Skills[TagCount]);

                    //Press ENTER key to add the tag
                    SkillExchngTag.SendKeys(Keys.Enter);
                }
            }
            else
            {
                //Delete the Skill Exchange tags if present any
                if (Cnt > 0)
                {
                    for (int TagCount = Cnt; TagCount >= 1; TagCount--)
                    {
                        driver.FindElement(By.XPath("//*[@id='service-listing-section']/div[2]/div/form/div[8]/div[4]/div/div/div/div/span[" + TagCount + "]/a")).Click();
                    }
                    Thread.Sleep(100);
                }
                //Change the Skill Trade option to Credit
                CreditButton.Click();

                //Enter the value for Credit
                Credit.SendKeys(ServiceData.CreditValue(RowNum));
            }
        }
Exemplo n.º 8
0
        //Choose the radio button based on the Skill Trade
        public void ChooseSkillTrade(String SkillTrade, int Cnt)
        {
            if (SkillTrade == "Skill-exchange")
            {
                SkillExchangeButton.Click();
                Thread.Sleep(200);

                String[] Skills = ServiceData.SkillExchangeData(RowNum);
                for (int TagCount = 0; TagCount < Cnt; TagCount++)
                {
                    //Read the data for Tags from excel and enter the data into the Tags field for Skill-Exchange
                    SkillExchngTag.SendKeys(Skills[TagCount]);

                    //Press ENTER key to add the tag
                    SkillExchngTag.SendKeys(Keys.Enter);
                }
            }
            else
            {
                CreditButton.Click();
                Credit.SendKeys(ServiceData.CreditValue(RowNum));
            }
        }
Exemplo n.º 9
0
        private void PublishToPubNub(string name, ServiceData sd, bool isRemove)
        {
            Message msg = sd.Result as Message;

            if (msg != null)
            {
                List <dynamic> pubnubMessage           = new List <dynamic>();
                Dictionary <string, string> actionDict = new Dictionary <string, string>();
                if (isRemove)
                {
                    actionDict.Add("Action", "del");
                }
                else
                {
                    actionDict.Add("Action", "add");
                }
                actionDict.Add("Channel", name);
                pubnubMessage.Add(actionDict);
                msg.PrivateData = null;
                pubnubMessage.Add(msg);
                List <object> publishResult = pubnub.Publish("NewMsgIn" + name, pubnubMessage);
            }
        }
Exemplo n.º 10
0
        private bool ProcessLine(string line, string user, UserDataService userDataService, out string comanda)
        {
            bool result = false;

            comanda = string.Empty;
            List <MenuItem> _data = userDataService.GetMenuItems();

            ServiceData _sd = new ServiceData();

            _sd.Nume = user;
            _sd.Ziua = DateTime.Now;
            _sd.Masa = new List <string>();

            foreach (var _s in foodslist)
            {
                int count = Regex.Matches(line, _s).Count;
                for (int i = 0; i < count; i++)
                {
                    _sd.Masa.Add(_s);
                }

                //if (line.Contains(_s))
                //{
                //    _sd.Masa.Add(_s);
                //}
            }

            if (_sd.Masa.Count >= 1)
            {
                _sd.Total = Total(_sd.Masa, _data);
                userDataService.AddNew(_sd);
                result = true;

                comanda = string.Join(",", _sd.Masa.ToArray());
            }
            return(result);
        }
Exemplo n.º 11
0
        public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) {
            ppvObject = (IntPtr)0;
            int hr = VSConstants.S_OK;

            ServiceData serviceInstance = null;

            if (services != null && services.ContainsKey(guidService)) {
                serviceInstance = services[guidService];
            }

            if (serviceInstance == null) {
                return VSConstants.E_NOINTERFACE;
            }

            // Now check to see if the user asked for an IID other than
            // IUnknown.  If so, we must do another QI.
            //
            if (riid.Equals(NativeMethods.IID_IUnknown)) {
                object inst = serviceInstance.ServiceInstance;
                if (inst == null) {
                    return VSConstants.E_NOINTERFACE;
                }
                ppvObject = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance);
            } else {
                IntPtr pUnk = IntPtr.Zero;
                try {
                    pUnk = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance);
                    hr = Marshal.QueryInterface(pUnk, ref riid, out ppvObject);
                } finally {
                    if (pUnk != IntPtr.Zero) {
                        Marshal.Release(pUnk);
                    }
                }
            }

            return hr;
        }
Exemplo n.º 12
0
        public void changeOnwer(String userName, String groupName, ModelObject modl)
        {
            //ModelObject user = findUser(userName);
            ModelObject user = findModel("__WEB_find_user", new string[] { "User ID" }, new string[] { userName });

            if (null == user)
            {
                return;
            }

            //ModelObject userGroup = findGroup(groupName);
            ModelObject userGroup = findModel("__WEB_group", new string[] { "Name" }, new string[] { groupName });

            if (null == userGroup)
            {
                return;
            }

            DataManagementService dmService = DataManagementService.getService(Session.getConnection());

            ObjectOwner[] ownerData = new ObjectOwner[1];

            ObjectOwner ownrObj = new ObjectOwner();

            ownrObj.Object = modl;
            ownrObj.Group  = (Teamcenter.Soa.Client.Model.Strong.Group)userGroup;
            ownrObj.Owner  = (Teamcenter.Soa.Client.Model.Strong.User)user;
            ownerData[0]   = ownrObj;


            ServiceData returnData = dmService.ChangeOwnership(ownerData);

            if (returnData.sizeOfPartialErrors() > 0)
            {
                throw new Exception("Change ownership service: 005" + "Change ownership service - ");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// 出队
        /// </summary>
        /// <returns></returns>
        public ServiceData Dequeue()
        {
            ServiceData command = null;

            try
            {
                if (!IsEmpty())
                {
                    for (int i = 1; i <= 5; i++)
                    {
                        RequestQueue <ServiceData> queue = null;
                        if (m_PriorityQueue.TryGetValue(i, out queue))
                        {
                            if (!queue.IsEmpty())
                            {
                                command = queue.Dequeue();
                            }

                            if (command != null)
                            {
                                m_Logger.Debug(string.Format("服务出队。\r\nGuid:{0}。\r\n服务名称:{1}"
                                                             , command.Command.Guid, command.Command.ServiceFullName));
                                return(command);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                m_Logger.Debug("服务出队异常。");
                m_Logger.Fatal(string.Concat("服务出队: ", ex.Message));
                m_Logger.Fatal(string.Concat("服务出队: ", ex.StackTrace));
            }

            return(command);
        }
Exemplo n.º 14
0
        public ServiceData Register(GuardedServiceDescription description, GuardService service)
        {
            lock (this.guardedServices)
            {
                bool nameConflict = false;
                bool pathConflict = false;
                foreach (var s in this.guardedServices.Values)
                {
                    nameConflict |= s.Description.Name == description.Name;
                    pathConflict |= s.Description.ExecutablePath == description.ExecutablePath && s.Description.Arguments == description.Arguments;
                    if (nameConflict || pathConflict)
                    {
                        break;
                    }
                }
                if (nameConflict)
                {
                    throw new InvalidOperationException("A service that has the same name is already registered.");
                }
                if (pathConflict)
                {
                    throw new InvalidOperationException("A service that has the same path and argument is already registered.");
                }

                Guid        token       = Guid.NewGuid();
                ServiceData serviceData = new ServiceData()
                {
                    Description   = description,
                    Service       = service,
                    SemaphoreName = "NodeServerGuardedService-" + token.ToString(),
                    Token         = token,
                };
                this.guardedServices.Add(token, serviceData);
                service.Callback.Start(serviceData.SemaphoreName);
                return(serviceData);
            }
        }
Exemplo n.º 15
0
        public String deleteItem(String codeNumber)
        {
            String Msg = "执行成功";
            DataManagementService dmService = DataManagementService.getService(Session2.getConnection());

            ////删除前,取消发布
            //ModelObject itemReversion = findModel("", new string[] { "iid" }, new string[] { codeNumber });
            ////取消发布流程
            //workflow_publish("", itemReversion);

            //调用查询构建器,查询ITEM
            ModelObject itemObj = findModel(cfg.get("query_builder_ItemById_name")
                                            , new string[] { cfg.get("query_builder_ItemById_queryKey") }, new string[] { codeNumber });
            ServiceData serviceData = dmService.DeleteObjects(new ModelObject[] { itemObj });

            //if (serviceData.sizeOfPartialErrors() > 0)
            //{
            //    Msg = "删除ITEM失败,已发布的ITEM不能删除或无权限删除:" + serviceData.GetPartialError(0).Messages[0];
            //    throw new Exception("删除ITEM失败,已发布的ITEM不能删除或无权限删除:" + serviceData.GetPartialError(0).Messages[0]);
            //}


            return(Msg);
        }
Exemplo n.º 16
0
        public ServiceData getLogin(string user, string pwd)
        {
            var SD = new ServiceData();

            try
            {
                Console.WriteLine("Requesting login for user " + user);
                var bgWorker = new Update();
                bgWorker.callback = OperationContext.Current.GetCallbackChannel <IBookUpdateCallback>();
                var thread = new Thread(delegate() { SD = bgWorker.Login(user, pwd); });
                thread.IsBackground = true;
                thread.Start();

                return(SD);
            }
            catch (Exception e)
            {
                SD.Result       = false;
                SD.ErrorMessage =
                    "Can't login, please try again with other credentials or check your network connectivity.";
                SD.ErrorDetails = e.ToString();
                throw new FaultException <ServiceData>(SD, e.ToString());
            }
        }
Exemplo n.º 17
0
        //将企业号回复用户的消息加密打包
        // @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
        // @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp
        // @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
        // @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
        //						当return返回0时有效
        // return:成功0,失败返回对应的错误码
        public int EncryptMsg(ServiceData sd, ref Message msg)
        {
            string raw = "";

            try
            {
                raw = Cryptography.MsgEncrypt(Json.Encode <ServiceData>(sd), GetRequestKey(m_sEncodingAESKey, Convert.ToString(msg.timestamp)), m_sPlatID);
            }
            catch (Exception e)
            {
                return((int)TzjMsgCryptErrorCode.TzjMsgCrypt_EncryptAES_Error);
            }
            msg.data = raw;
            string MsgSigature = "";
            int    ret         = 0;

            ret = GenarateSinature(m_sToken, Convert.ToString(msg.timestamp), msg.nonce, raw, ref MsgSigature);
            if (0 != ret)
            {
                return(ret);
            }
            msg.signature = MsgSigature;
            return(0);
        }
Exemplo n.º 18
0
        //start
        void Start()
        {
            //reading info from the json file
            string  myFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "serviceData.json");
            JObject data       = JObject.Parse(File.ReadAllText(myFilePath));

            sd = new ServiceData
            {
                progressName = data["progressName"].ToString(),
                serviceName  = data["serviceName"].ToString()
            };

            Utility util = new Utility();

            //1. kill process
            int  processCheckResult = util.CheckProcess(sd.progressName);
            bool killProcessResult  = true;

            if (processCheckResult > 0)
            {
                util.KillProcess(processCheckResult);
                killProcessResult = util.CheckProcossIsAlive(sd.progressName);
            }


            //2. Start service in Services
            // check if the services status is running if not run Service
            if (!killProcessResult)
            {
                ServiceControlCore scc = new ServiceControlCore();
                if (!scc.GetServices(sd.serviceName))
                {
                    scc.StartService(sd.serviceName, 2000);
                }
            }
        }
Exemplo n.º 19
0
        void HandleServiceInfoRecords(Packet p)
        {
            foreach (var txt in p.Answers.Where(x => x.Record.RecordType == 16))
            {
                var answerData = txt.Data as TXTAnswer;
                var data       = new ServiceData();
                data.TTL   = txt.TTL;
                data.Flags = answerData.Flags;
                data.Data  = answerData.Data;
                _serviceData[txt.Record.Name] = data;
            }

            foreach (var srv in p.Answers.Where(x => x.Record.RecordType == 33))
            {
                var srvData = srv.Data as SRVAnswer;
                var data    = new ServiceConnection();
                data.TTL      = srv.TTL;
                data.Port     = srvData.Port;
                data.Priority = srvData.Priority;
                data.Target   = srvData.Target;
                data.Weight   = srvData.Weight;
                _serviceConnections[srv.Record.Name] = data;
            }
        }
Exemplo n.º 20
0
        public static void GenenateJobs()
        {
            int parallelThread = 10;

            for (int i = 0; i < NumberOfJobs / parallelThread; i++)
            {
                GridService[] gridServiceA = new GridService[parallelThread];
                for (int j = 0; j < parallelThread; j++)
                {
                    GridService gridService = GridAPI.createService(i + "");
                    Dictionary <String, String> parameters = new Dictionary <String, String>();
                    parameters.Add("param1", ((i * 10) + j) + "");
                    Job job = gridService.Submit("Function1", parameters);
                    gridServiceA[j] = gridService;
                }
                Task <ServiceData>[] taskArray =
                {
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[0].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[1].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[2].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[3].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[4].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[5].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[6].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[7].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[8].CollectNext(1000)),
                    Task <ServiceData> .Factory.StartNew(() => gridServiceA[9].CollectNext(1000))
                };
                ServiceData[] serviceDataA = new ServiceData[taskArray.Length];
                for (int k = 0; k < taskArray.Length; k++)
                {
                    serviceDataA[k] = taskArray[k].Result;
                    Console.Write("Result found for k" + k);
                }
            }
        }
Exemplo n.º 21
0
        public string PostLink(string name, string password, string linkUrl, string linkTitle)
        {
            ServiceData sd = new ServiceData()
            {
                ResultType = "postLink"
            };

            try
            {
                string message = linkUrl + "|" + linkTitle;
                sd.Result = PostContent(name, password, message, MessageTypes.Link);
            }
            catch (Exception ex)
            {
                sd.IsError      = true;
                sd.ErrorMessage = ex.Message;
            }
            finally
            {
                SaveSession();
            }
            PublishToPubNub(name, sd, false);
            return(JsonConvert.SerializeObject(sd));
        }
Exemplo n.º 22
0
        private async Task <string> GetCSRFToken(ServiceData authData)
        {
            using (HttpClientHandler handler = new HttpClientHandler())
            {
                handler.CookieContainer = cookieContainer;
                using (HttpClient client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authData.AuthMethod, authData.AuthToken);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("x-csrf-token", "Fetch");

                    string result = null;
                    using (var response = await client.GetAsync(authData.BaseUrl))
                    {
                        var headers = response.Headers;
                        if (headers.Contains("x-csrf-token"))
                        {
                            result = headers.GetValues("x-csrf-token").First();
                        }
                    }
                    return(result);
                }
            }
        }
Exemplo n.º 23
0
        public string GetAllChannels()
        {
            ServiceData sd = new ServiceData()
            {
                ResultType = "getAllChannels"
            };

            try
            {
                GetSession();
                //_sessionState.DeleteMessage();
                //_sessionState.DeleteChannels();
                if (AppCache.ChannelList.Count == 0)
                {
                    AppCache.ChannelList = _sessionState.GetChannels().ToList();
                }
                if (sd.Result == null)
                {
                    sd.Result = new List <string>();
                }
                if (AppCache.ChannelList.Count > 0)
                {
                    sd.Result.AddRange(AppCache.ChannelList.Select(c => c.Name));
                }
            }
            catch (Exception ex)
            {
                sd.IsError      = true;
                sd.ErrorMessage = ex.Message + Environment.NewLine + ex.StackTrace;
            }
            finally
            {
                SaveSession();
            }
            return(JsonConvert.SerializeObject(sd));
        }
Exemplo n.º 24
0
        public List <ServiceData> ListServices()
        {
            List <ServiceData> serviceList = new List <ServiceData>();


            ServiceController[] services = ServiceController.GetServices();
            foreach (var service in services)
            {
                ServiceData serviceData = new ServiceData();

                serviceData.displayName = service.DisplayName;
                serviceData.systemName  = service.ServiceName;

                ManagementObject wmiService;
                wmiService = new ManagementObject("Win32_Service.Name='" + service.ServiceName + "'");
                wmiService.Get();

                if (wmiService["StartName"] != null)
                {
                    serviceData.logon = wmiService["StartName"].ToString();
                }
                else
                {
                    serviceData.logon = "";
                }


                if (wmiService["Description"] != null)
                {
                    serviceData.description = wmiService["Description"].ToString();
                }
                else
                {
                    serviceData.description = "";
                }
                serviceData.type   = service.ServiceType.ToString();
                serviceData.status = service.Status.ToString();


                List <Dependency> dependencies = new List <Dependency>();

                ServiceController[] temp = service.ServicesDependedOn;
                if (temp.Length > 0)
                {
                    foreach (var x in temp)
                    {
                        Dependency dep = new Dependency();
                        dep.name = x.ServiceName;
                        dependencies.Add(dep);
                    }
                }
                else
                {
                    Dependency dep = new Dependency();
                    dep.name = "None";
                    dependencies.Add(dep);
                }

                serviceData.dependencies = dependencies;

                serviceList.Add(serviceData);
            }
            return(serviceList);
        }
Exemplo n.º 25
0
	public static ServiceData CreateServiceData (DiscoveryReference dref)
	{
		ServiceData sd = new ServiceData ();
		
		string name = GetServiceName (dref);
		sd.Name = name;
		int nc = 2;
		while (FindServiceByName (sd.Name) != null)
		{
			sd.Name = name + nc;
			nc++;
		}
		
		sd.Wsdl = dref.Url;
		return sd;
	}
Exemplo n.º 26
0
        // Returns a SerializationData a Serializer can use to save the state
        // of the object to an Xml file
        public SerializationData GetSerializationData(Serializer Serializer, XmlWriter Writer)
        {
            // Create a new SerializationData
            SerializationData data = new SerializationData(Serializer, Writer);

            // Add the basic Component values
            data.AddData("Component.DrawOrder", DrawOrder);
            data.AddData("Component.ParentScreen", Parent.Name);
            data.AddData("Component.Visible", Visible);
            data.AddData("Component.Name", this.Name);

            // Tell serializer that it will need to know the type of component
            data.AddDependency(this.GetType());

            // Construct a ServiceData
            ServiceData sd = new ServiceData();

            // If this object is a service, find out what the provider type is
            // (the type used to look up the services)
            Type serviceType;
            if (Engine.Services.IsService(this, out serviceType))
            {
                // Tell serializer about provider type
                data.AddDependency(serviceType);

                // Set data to ServiceData
                sd.IsService = true;
                sd.Type = serviceType.FullName;
            }

            // Add the ServiceData to the SerializationData
            data.AddData("Component.ServiceData", sd);

            // Call the overridable function that allows components to provide data
            SaveSerializationData(data);

            return data;
        }
Exemplo n.º 27
0
 public async void AddServiceDataAsync(ServiceData data)
 {
     await _context.ServiceData.AddAsync(data);
 }
Exemplo n.º 28
0
        private void AddService(ServiceData data)
        {
            // Make sure that the collection of services is created.
            if (null == services)
            {
                services = new Dictionary<Guid, ServiceData>();
            }

            // Disallow the addition of duplicate services.
            if (services.ContainsKey(data.Guid))
            {
                throw new InvalidOperationException();
            }

            services.Add(data.Guid, data);
        }
Exemplo n.º 29
0
	static string GetProxyFile (ServiceData fd, string protocol)
	{
		string fn = Path.Combine (new Uri (fd.Wsdl).Host, fd.Name + protocol + "Proxy.cs");
		return Path.Combine (GetProxyPath(), fn);
	}
Exemplo n.º 30
0
        /**
         * Create Items
         *
         * @param itemIds        Array of Item and Revision IDs
         * @param itemType       Type of item to create
         *
         * @return Set of Items and ItemRevisions
         *
         * @throws ServiceException  If any partial errors are returned
         */
        public CreateItemsOutput[] createItems(ItemIdsAndInitialRevisionIds[] itemIds, String itemType)
        //       throws ServiceException
        {
            // Get the service stub
            DataManagementService dmService = DataManagementService.getService(MyFormAppSession.getConnection());
            // Populate form type
            GetItemCreationRelatedInfoResponse relatedResponse = dmService.GetItemCreationRelatedInfo(itemType, null);

            String[] formTypes = new String[0];
            if (relatedResponse.ServiceData.sizeOfPartialErrors() > 0)
            {
                throw new ServiceException("DataManagementService.getItemCretionRelatedInfo returned a partial error.");
            }

            formTypes = new String[relatedResponse.FormAttrs.Length];
            for (int i = 0; i < relatedResponse.FormAttrs.Length; i++)
            {
                FormAttributesInfo attrInfo = relatedResponse.FormAttrs[i];
                formTypes[i] = attrInfo.FormType;
            }

            ItemProperties[] itemProps = new ItemProperties[itemIds.Length];
            for (int i = 0; i < itemIds.Length; i++)
            {
                // Create form in cache for form property population
                ModelObject[] forms = createForms(itemIds[i].NewItemId, formTypes[0],
                                                  itemIds[i].NewRevId, formTypes[1],
                                                  null, false);
                ItemProperties itemProperty = new ItemProperties();

                itemProperty.ClientId    = "AppX-Test";
                itemProperty.ItemId      = itemIds[i].NewItemId;
                itemProperty.RevId       = itemIds[i].NewRevId;
                itemProperty.Name        = "AppX-Test";
                itemProperty.Type        = itemType;
                itemProperty.Description = "Test Item for the SOA AppX sample application.";
                itemProperty.Uom         = "";

                // Retrieve one of form attribute value from Item master form.
                ServiceData serviceData = dmService.GetProperties(forms, new String[] { "project_id" });
                if (serviceData.sizeOfPartialErrors() > 0)
                {
                    throw new ServiceException("DataManagementService.getProperties returned a partial error.");
                }
                Property property = null;
                try
                {
                    property = forms[0].GetProperty("project_id");
                }
                catch (NotLoadedException /*ex*/) {}


                // Only if value is null, we set new value
                if (property == null || property.StringValue == null || property.StringValue.Length == 0)
                {
                    itemProperty.ExtendedAttributes = new ExtendedAttributes[1];
                    ExtendedAttributes theExtendedAttr = new ExtendedAttributes();
                    theExtendedAttr.Attributes = new Hashtable();
                    theExtendedAttr.ObjectType = formTypes[0];
                    theExtendedAttr.Attributes["project_id"] = "project_id";
                    itemProperty.ExtendedAttributes[0]       = theExtendedAttr;
                }
                itemProps[i] = itemProperty;
            }


            // *****************************
            // Execute the service operation
            // *****************************
            CreateItemsResponse response = dmService.CreateItems(itemProps, null, "");

            // before control is returned the ChangedHandler will be called with
            // newly created Item and ItemRevisions



            // The AppXPartialErrorListener is logging the partial errors returned
            // In this simple example if any partial errors occur we will throw a
            // ServiceException
            if (response.ServiceData.sizeOfPartialErrors() > 0)
            {
                throw new ServiceException("DataManagementService.createItems returned a partial error.");
            }

            return(response.Output);
        }
Exemplo n.º 31
0
	public static void BuildClient (ServiceData sd)
	{
		string file = GetClientFile (sd);
		
		if (File.Exists (file)) return;

		CreateFolderForFile (file);
		
		StreamWriter sw = new StreamWriter (file);
		sw.WriteLine ("// Web service test for WSDL document:");
		sw.WriteLine ("// " + sd.Wsdl);
		
		sw.WriteLine ();
		sw.WriteLine ("using System;");
		sw.WriteLine ("using NUnit.Framework;");
		
		foreach (string prot in sd.Protocols)
			sw.WriteLine ("using " + sd.Namespace + "." + prot + ";");
		
		sw.WriteLine ();
		sw.WriteLine ("namespace " + sd.Namespace);
		sw.WriteLine ("{");
		sw.WriteLine ("\tpublic class " + sd.Name + ": WebServiceTest");
		sw.WriteLine ("\t{");
		sw.WriteLine ("\t\t[Test]");
		sw.WriteLine ("\t\tpublic void TestService ()");
		sw.WriteLine ("\t\t{");
		sw.WriteLine ("\t\t}");
		sw.WriteLine ("\t}");
		sw.WriteLine ("}");
		sw.Close ();
		
		Console.WriteLine ("Written file '" + file + "'");
	}
Exemplo n.º 32
0
	static void RegisterFailure (ServiceData sd)
	{
		ServiceStatus status = null;
		foreach (ServiceStatus ss in serviceStatus.services)
		{
			if (ss.Name == sd.Name)
			{
				status = ss;
				break;
			}
		}
		
		if (status == null)
		{
			status = new ServiceStatus ();
			status.Name = sd.Name;
			status.Retries = 1;
			status.LastTestDate = DateTime.Now;
			serviceStatus.services.Add (status);
		}
		else
		{
			if ((DateTime.Now - status.LastTestDate).TotalHours >= 24)
				status.Retries++;
		}
	}
Exemplo n.º 33
0
	static void CleanFailures (ServiceData sd)
	{
		ServiceStatus status = null;
		foreach (ServiceStatus ss in serviceStatus.services)
		{
			if (ss.Name == sd.Name)
			{
				serviceStatus.services.Remove (ss);
				break;
			}
		}
	}
        public async Task <ActionResult <CustomerVehicle> > UpdateServiceData([FromRoute] Guid vehicleId, [FromBody] ServiceData serviceData)
        {
            try
            {
                var result = await vehicleService.UpdateServiceData(serviceData, vehicleId, this.ClientId());

                return(new OkObjectResult(result));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw;
            }
        }
Exemplo n.º 35
0
 public void SetServiceData(ulong simDescId, ServiceData data)
 {
     sRequests[simDescId] = data;
 }
Exemplo n.º 36
0
 public void SetServiceData(ulong simDescId, ServiceData data)
 {
     sRequests[simDescId] = data;
 }
Exemplo n.º 37
0
	static string GetClientFile (ServiceData sd)
	{
		return Path.Combine (GetClientPath(), sd.TestFile);
	}
Exemplo n.º 38
0
 private void DrawPie()
 {
     ChartServices.SetChartTitle(this.WebChartControl4, true, "2012年12月第1周收入情况", StringAlignment.Center, ChartTitleDockStyle.Top, true, new Font("宋体", 12f, FontStyle.Bold), Color.Red, 10);
     ChartServices.DrawChart(this.WebChartControl4, ServiceData.GetWeekMoneyAndCost().Rows[0][0].ToString(), ViewType.Pie, ServiceData.GetWeekMoneyAndCost(), "week", "money");
 }
Exemplo n.º 39
0
        public void ViewListings()
        {
            //Implicit wait until the listings are visible
            Wait.wait(2, driver);

            //Validate the Listings in the Manage Listings Page by checking the values displayed for all the fields with the values from excel

            //Read the data for Title from excel into a variable
            var TitleData = ServiceData.TitleData(RowNum);

            //Read the data for Category from excel into a variable
            var CategoryData = ServiceData.CategData(RowNum);

            //Read the data for Description from excel into a variable
            var DescriptionData = ServiceData.DescriptionData(RowNum);

            String DescriptionDataTrunc = "";
            String Description          = "";

            //Truncate the string (only 70 characters of description gets displayed in the Manage listing)
            if (DescriptionData.Length > 70)
            {
                DescriptionDataTrunc = DescriptionData.Substring(0, 70);
                Description          = DescriptionListing.Text.Substring(0, 70);
            }
            else
            {
                DescriptionDataTrunc = DescriptionData;
                Description          = DescriptionListing.Text;
            }

            //Read the data for Service Type from excel into a variable
            var ServiceTypeData = ServiceData.SrvcTypeData(RowNum);

            //Read the data for Service Type from excel into a variable
            var SkillTradeData = ServiceData.SkillTrdeData(RowNum);

            //Read the data for Service Type from excel into a variable
            var ActiveStatusData = ServiceData.ActvStatusData(RowNum);

            //Set a flag as per the status of Active provided by user
            bool ActiveStatusSet = false;

            if (ActiveStatusData == "Active")
            {
                ActiveStatusSet = true;
            }
            else if (ActiveStatusData == "Hidden")
            {
                ActiveStatusSet = false;
            }

            //Assert statements to validate the various fields of the listings
            Assert.Multiple(() =>
            {
                Assert.That(TitleData, Is.EqualTo(TitleListing.Text));
                Assert.That(DescriptionDataTrunc, Is.EqualTo(Description));
                Assert.That(CategoryData, Is.EqualTo(CategoryListing.Text));
                Assert.That(ServiceTypeData, Is.EqualTo(ServiceTypeListing.Text));
                Assert.That(ActiveStatusSet, Is.EqualTo(ActiveStatusListing.Selected));
            });
        }
Exemplo n.º 40
0
 async void UpdateAllNuget_Click(object sender, RoutedEventArgs e)
 {
     ServiceData.SelectMany(x => x.References).Do(x => x.ShouldUpdate = true);
     await Task.WhenAll(ServiceData.Select(x => x.UpdateSelectedPackages()));
 }
Exemplo n.º 41
0
	static void BuildProxy (ServiceData fd, bool rebuild, ArrayList proxies, XmlElement errdoc)
	{
		string wsdl = GetWsdlFile (fd);
		if (!File.Exists (wsdl)) 
			return;
		
		if (fd.Protocols == null)
		{
			ReportError ("Client test '" + fd.Name + "': no protocols declared", "");
			return;
		}
		
		foreach (string prot in fd.Protocols)
		{
			string ns = fd.Namespace;
			ns = CodeIdentifier.MakeValid (ns) + "." + prot;
		
			string pfile = GetProxyFile (fd, prot);
			if (File.Exists (pfile) && !rebuild) { proxies.Add (pfile); continue; }
			
			CreateFolderForFile	(pfile);

			Console.Write (prot + " proxy for " + wsdl + "... ");
			Process proc = new Process ();
			proc.StartInfo.UseShellExecute = false;
			proc.StartInfo.RedirectStandardOutput = true;
			proc.StartInfo.RedirectStandardError = true;
			proc.StartInfo.FileName = "wsdl";
			proc.StartInfo.Arguments = "/out:" + pfile + " /nologo /namespace:" + ns + " /protocol:" + prot + " " + wsdl;
			proc.Start();
			
			if (!proc.WaitForExit (30000))
			{
				try {
					proc.Kill ();
				} catch {}
				
				Console.WriteLine ("FAIL (timeout)");
				if (File.Exists (pfile)) File.Delete (pfile);
				WriteError (errdoc, ns, "Errors found while generating " + prot + " proxy for WSDL: " + wsdl, "wsdl.exe timeout");
			}
			else if (proc.ExitCode != 0)
			{
				Console.WriteLine ("FAIL " + proc.ExitCode);
				
				string err = proc.StandardOutput.ReadToEnd ();
				err += "\n" + proc.StandardError.ReadToEnd ();

				if (File.Exists (pfile))
				{
					if (proc.ExitCode == 1) {
						string fn = fd.Name + prot + "Proxy.cs";
						fn = Path.Combine (GetErrorPath(), fn);
						CreateFolderForFile (fn);
						File.Move (pfile, fn);
						
						StreamWriter sw = new StreamWriter (fn, true);
						sw.WriteLine ();
						sw.WriteLine ("// " + fd.Wsdl);
						sw.WriteLine ();
						sw.Close ();
						
					}
					else
						File.Delete (pfile);
				}
				
				WriteError (errdoc, ns, "Errors found while generating " + prot + " proxy for WSDL: " + wsdl, err);
			}
			else
			{
				if (File.Exists (pfile)) {
					Console.WriteLine ("OK");
					proxies.Add (pfile);
				}
				else {
					Console.WriteLine ("FAIL");
					string err = proc.StandardOutput.ReadToEnd ();
					err += "\n" + proc.StandardError.ReadToEnd ();
					WriteError (errdoc, ns, "Errors found while generating " + prot + " proxy for WSDL: " + wsdl, err);
				}
			}
		}
	}
Exemplo n.º 42
0
	static void Resolve (ServiceData sd)
	{
		Console.Write ("Resolving " + sd.Wsdl + " ");
		try
		{
			DiscoveryClientProtocol contract = new DiscoveryClientProtocol ();
			contract.DiscoverAny (sd.Wsdl);
			
			if (sd.Protocols == null || sd.Protocols.Length==0) 
				RetrieveServiceData (sd, contract);
				
			string wsdlFile = GetWsdlFile (sd);
			CreateFolderForFile (wsdlFile);
			
			ServiceDescription doc = (ServiceDescription) contract.Documents [sd.Wsdl];
			doc.Write (wsdlFile);
			
			Console.WriteLine ("OK");
			CleanFailures (sd);
		}
		catch (Exception ex)
		{
			Console.WriteLine ("FAILED");
			ReportError ("Error resolving: " + sd.Wsdl, ex.ToString ());
			RegisterFailure (sd);
		}
	}
Exemplo n.º 43
0
        public void ValidateServiceDetail()
        {
            //Wait until the page loads and description is visible
            Wait.ElementIsVisible(driver, "XPath", "//*[@id='service-detail-section']/div[2]/div/div[2]/div[1]/div[1]/div[2]/div[2]/div/div/div[1]/div/div/div/div[1]");

            //Read the Skill exchange tag count from the excel
            var SkillExchngCount = ServiceData.TagsCntData(RowNum);

            //Convert the count of the skill exchange tags from String to integer
            int Count = Int32.Parse(SkillExchngCount);

            //Convert the Start Date and End Data format from (dd/mm/yyyy to yyyy-mm-dd)
            String StartDate = (ServiceData.StrtDateData(RowNum).Substring(4, 4)) + "-" + (ServiceData.StrtDateData(RowNum).Substring(2, 2)) + "-" + (ServiceData.StrtDateData(RowNum).Substring(0, 2));
            String EndDate   = (ServiceData.EndDateData(RowNum).Substring(4, 4)) + "-" + (ServiceData.EndDateData(RowNum).Substring(2, 2)) + "-" + (ServiceData.EndDateData(RowNum).Substring(0, 2));

            //Validate the expected and actual values of the different fields in the services
            Assert.Multiple(() =>
            {
                Assert.That(titleServiceDetail.Text, Is.EqualTo(ServiceData.TitleData(RowNum)));
                Assert.That(DescServiceDetail.Text, Is.EqualTo(ServiceData.DescriptionData(RowNum)));
                Assert.That(CategoryServiceDetail.Text, Is.EqualTo(ServiceData.CategData(RowNum)));
                Assert.That(SubCategoryServiceDetail.Text, Is.EqualTo(ServiceData.SubCategData(RowNum)));
                Assert.That(ServTypeServiceDetail.Text, Is.EqualTo(ServiceData.SrvcTypeData(RowNum)));
                Assert.That(StartDateServiceDetail.Text, Is.EqualTo(StartDate));
                Assert.That(EndDateServiceDetail.Text, Is.EqualTo(EndDate));
                Assert.That(LocationTypeServiceDetail.Text, Is.EqualTo(ServiceData.LocatnTypeData(RowNum)));
            });

            //If the skill trade is chosen as "Skill-exchange" then need to validate the Skill exchange tags
            if (ServiceData.SkillTrdeData(RowNum) == "Skill-exchange")
            {
                String[] SkillsTradeData   = new String[Count];
                String[] SkillExchangeData = ServiceData.SkillExchangeData(RowNum);
                for (int Counter = 0; Counter < Count; Counter++)
                {
                    SkillsTradeData[Counter] = driver.FindElement(By.XPath("//*[@id='service-detail-section']/div[2]/div/div[2]/div[1]/div[1]/div[2]/div[2]/div/div/div[4]/div[2]/div/div/div[2]/span[" + (Counter + 1) + "]")).Text;
                    TestContext.WriteLine(SkillsTradeData[Counter]);
                    Assert.That(SkillsTradeData[Counter], Is.EqualTo(SkillExchangeData[Counter]));
                }

                //Click on the Manage Listings
                ManageLstings.Click();

                //Wait until the Listings are available in the Manage Listing page
                Wait.ElementIsVisible(driver, "XPath", "//*[@id='listing-management-section']/div[2]/div[1]/div[1]/table/tbody/tr/td[4]");
            }

            //If the Skill Exchange is chosen as 'Credit' then validate the credit charge value displayed
            else if (ServiceData.SkillTrdeData(RowNum) == "Credit")
            {
                try
                {
                    String SkillsTrade = SkillsTradeDisplay.Text;

                    //Enter the title in the serach Box
                    SearchBox.SendKeys(ServiceData.TitleData(RowNum));

                    //Press enter key to search for the skill
                    SearchBox.SendKeys(Keys.Enter);

                    //Implicit wait for the registeration pop up to be available
                    Wait.wait(2, driver);

                    String CreditCharge    = "Charge is :$" + ServiceData.CreditValue(RowNum);
                    String CreditActualVal = Charge.Text;
                    Assert.Multiple(() =>
                    {
                        Assert.That(CreditActualVal, Is.EqualTo(CreditCharge));
                        Assert.That(SkillsTrade, Is.EqualTo("None Specified"));
                    });

                    //Click on the Manage Listings
                    MngLstngs.Click();

                    //Wait until the Listings are available in the Manage Listing page
                    Wait.ElementIsVisible(driver, "XPath", "//*[@id='listing-management-section']/div[2]/div[1]/div[1]/table/tbody/tr/td[4]");
                }catch (Exception e)
                {
                    Assert.Fail("One or more webelements could not be found", e.Message);
                }
            }
        }
Exemplo n.º 44
0
        public async Task <GenericWriteObject <T> > CallOdataEndpointPostStringReturn <T>(string oDataEndpoint, string filters, T postDataObject,
                                                                                          ServiceData authData, string csrfToken)
        {
            using (HttpClientHandler handler = new HttpClientHandler())
            {
                handler.CookieContainer = this.cookieContainer;
                using (HttpClient client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authData.AuthMethod, authData.AuthToken);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    if (!string.IsNullOrEmpty(csrfToken))
                    {
                        client.DefaultRequestHeaders.Add("x-csrf-token", csrfToken);
                    }
                    client.Timeout = new TimeSpan(0, 3, 0);

                    string endpoint = authData.BaseUrl + authData.OdataUrlPostFix + oDataEndpoint + filters ?? "";
                    var    postData = JsonConvert.SerializeObject(postDataObject);
                    var    content  = new StringContent(postData, Encoding.UTF8, "application/json");
                    var    result   = new GenericWriteObject <T>();
                    try
                    {
                        using (var response = await client.PostAsync(endpoint, content))
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                result.SimpleResult = await response.Content.ReadAsStringAsync();
                            }
                            else
                            {
                                var errorResult = await response.Content.ReadAsStringAsync();

                                result.Exception = new AxBaseException {
                                    ApplicationException = new Exception("Error when sending post request json = " + postData + " " + errorResult)
                                };
                            }
                            return(result);
                        }
                    }
                    catch (Exception e)
                    {
                        if (e is AggregateException)
                        {
                            return(new GenericWriteObject <T> {
                                Exception = new AxBaseException {
                                    ApplicationException = e.InnerException
                                }
                            });
                        }
                        else
                        {
                            return(new GenericWriteObject <T> {
                                Exception = new AxBaseException {
                                    ApplicationException = e
                                }
                            });
                        }
                    }
                }
            }
        }
Exemplo n.º 45
0
	public static void RetrieveServiceData (ServiceData sd, DiscoveryClientProtocol contract)
	{
		ServiceDescriptionCollection col = new ServiceDescriptionCollection ();
		foreach (object doc in contract.Documents.Values)
			if (doc is ServiceDescription) col.Add ((ServiceDescription)doc);
		
		string loc = GetLocation (col[0]);
		if (loc != null)
		{
			WebResponse res = null;
			try
			{
				WebRequest req = (WebRequest)WebRequest.Create (loc);
				req.Timeout = 15000;
				res = req.GetResponse ();
			}
			catch (Exception ex)
			{
				WebException wex = ex as WebException;
				if (wex != null) res = wex.Response;
			}
			if (res != null)
			{
				sd.ServerType = res.Headers ["Server"] + " # " + res.Headers ["X-Powered-By"];
			}
		}
		
		ArrayList bins = GetBindingTypes (col);
		sd.Protocols = (string[]) bins.ToArray(typeof(string));
	}
Exemplo n.º 46
0
        static void Main(string[] args)
        {
            var _serviceDataContext = new ServiceData();

            BaseService.Run(_serviceDataContext);
        }
Exemplo n.º 47
0
	static string GetWsdlFile (ServiceData fd)
	{
		string fn = Path.Combine (new Uri (fd.Wsdl).Host, fd.Name + ".wsdl");
		return Path.Combine (GetWsdlPath(), fn);
	}