Пример #1
0
        public void FunPropertySample(string serverUri, int port, string deviceId, string deviceSecret)
        {
            // 创建设备
            IoTDevice device = new IoTDevice(serverUri, port, deviceId, deviceSecret);

            if (device.Init() != 0)
            {
                return;
            }

            Dictionary <string, object> json = new Dictionary <string, object>();

            // 按照物模型设置属性
            json["alarm"]              = 1;
            json["temperature"]        = 23.45812;
            json["humidity"]           = 56.89013;
            json["smokeConcentration"] = 89.56724;

            ServiceProperty serviceProperty = new ServiceProperty();

            serviceProperty.properties = json;
            serviceProperty.serviceId  = "smokeDetector"; // serviceId要和物模型一致

            List <ServiceProperty> properties = new List <ServiceProperty>();

            properties.Add(serviceProperty);

            device.GetClient().messagePublishListener = this;
            device.GetClient().Report(new PubMessage(properties));
        }
Пример #2
0
        public Message AddOrEdit(ServiceProperty serviceProperty)
        {
            var message = new Message();
            var ID      = serviceProperty.ServiceId;
            int result  = _iServicePropertyRepository.AddOrEdit(serviceProperty);

            try
            {
                if (result > 0)
                {
                    if (Convert.ToInt32(ID) > 0)
                    {
                        message = Message.SetMessages.SetSuccessMessage("Submission Updated Successfully!");
                    }
                    else
                    {
                        message = Message.SetMessages.SetSuccessMessage("Submission Successful!");
                    }
                }
                else
                {
                    message = Message.SetMessages.SetErrorMessage("Could not be submitted!");
                }
            }
            catch (Exception e)
            {
                message = Message.SetMessages.SetWarningMessage(e.Message.ToString());
            }

            return(message);
        }
Пример #3
0
        public TransportServiceType()
        {
            _mServices          = new List <IService>();
            _mServiceProperties = new Dictionary <string, IServiceProperty>();
            Name = "Transport";

            IServiceProperty props = new ServiceProperty {
                Name = "name", Type = "string", ServiceType = this
            };

            ServiceProperties.Add("name", props);
            props = new ServiceProperty {
                Name = "location", Type = "string", ServiceType = this
            };
            ServiceProperties.Add("location", props);
            props = new ServiceProperty {
                Name = "price", Type = "double", ServiceType = this
            };
            ServiceProperties.Add("price", props);
            props = new ServiceProperty {
                Name = "description", Type = "string", ServiceType = this
            };
            ServiceProperties.Add("description", props);
            props = new ServiceProperty {
                Name = "quantity", Type = "double", ServiceType = this
            };
            ServiceProperties.Add("quantity", props);
            DataHolder.GetInstance().ServiceTypes.Add(this);
        }
Пример #4
0
        public ActionResult AddOrEdit(int id = 0)
        {
            ServiceProperty serviceProperty = new ServiceProperty();

            if (id != 0)
            {
                serviceProperty = _iServicePropertyManager.GetAServiceProperty(id);
            }
            return(View(serviceProperty));
        }
Пример #5
0
        private ServiceProperty ValidateServiceProperties(JObject propertyObject)
        {
            bool            isRequired           = true;
            bool            isActive             = true;
            bool            includeInOrderAmount = false;
            byte            inputTypeId          = 0;
            byte            dataTypeId           = 0;
            ServiceProperty serviceProperty      = new ServiceProperty();


            if (propertyObject.SelectToken("DisplayName") == null || propertyObject.SelectToken("DisplayName").ToString().Trim().Length == 0)
            {
                GenerateErrorResponse(400, string.Format("DisplayName is mandatory"));
            }
            if (propertyObject.SelectToken("MetaDataCode") == null || propertyObject.SelectToken("MetaDataCode").ToString().Trim().Length == 0)
            {
                GenerateErrorResponse(400, string.Format("MetaDataCode is mandatory for Property {0}", propertyObject.SelectToken("DisplayName").ToString()));
            }
            if (propertyObject.SelectToken("IsRequired") != null && !bool.TryParse(propertyObject.SelectToken("IsRequired").ToString(), out isRequired))
            {
                GenerateErrorResponse(400, string.Format("Parameter IsRequired should be a boolean value for Property {0}", propertyObject.SelectToken("DisplayName").ToString()));
            }
            if (propertyObject.SelectToken("IncludeInOrderAmount") != null && !bool.TryParse(propertyObject.SelectToken("IncludeInOrderAmount").ToString(), out includeInOrderAmount))
            {
                GenerateErrorResponse(400, string.Format("Parameter IncludeInOrderAmount should be a boolean value for Property {0}", propertyObject.SelectToken("DisplayName").ToString()));
            }
            if (propertyObject.SelectToken("InputTypeId") == null || !byte.TryParse(propertyObject.SelectToken("InputTypeId").ToString(), out inputTypeId))
            {
                GenerateErrorResponse(400, string.Format("Parameter InputTypeId of Property '{0}' is missing or invalid", propertyObject.SelectToken("DisplayName").ToString()));
            }
            if (propertyObject.SelectToken("DataTypeId") == null || !byte.TryParse(propertyObject.SelectToken("DataTypeId").ToString(), out dataTypeId))
            {
                GenerateErrorResponse(400, string.Format("Parameter DataTypeId of Property '{0}' is missing or invalid", propertyObject.SelectToken("DisplayName").ToString()));
            }
            if (propertyObject.SelectToken("IsActive") != null && !bool.TryParse(propertyObject.SelectToken("IsActive").ToString(), out isActive))
            {
                GenerateErrorResponse(400, string.Format("Parameter IsActive of Property '{0}' is missing or invalid", propertyObject.SelectToken("IsActive").ToString()));
            }


            serviceProperty.DisplayName          = propertyObject.SelectToken("DisplayName").ToString();
            serviceProperty.MetaDataCode         = propertyObject.SelectToken("MetaDataCode").ToString();
            serviceProperty.IsRequired           = isRequired;
            serviceProperty.IsActive             = isActive;
            serviceProperty.DefaultValue         = propertyObject.SelectToken("DefaultValue") == null ? string.Empty : propertyObject.SelectToken("DefaultValue").ToString();
            serviceProperty.IncludeInOrderAmount = includeInOrderAmount;
            serviceProperty.InputTypeId          = inputTypeId;
            serviceProperty.DataTypeId           = dataTypeId;
            serviceProperty.InputProperty        = propertyObject.SelectToken("InputProperty") == null ? string.Empty : propertyObject.SelectToken("InputProperty").ToString();

            return(serviceProperty);
        }
Пример #6
0
            protected override void ChannelRead0(IChannelHandlerContext ctx, string msg)
            {
                IChannel incoming = ctx.Channel;

                Log.Info("channelRead0" + incoming.RemoteAddress + " msg :" + msg);

                // 如果是首条消息,创建session
                Session session = simpleGateway.GetSessionByChannel(incoming.Id.AsLongText());

                if (session == null)
                {
                    string nodeId = msg;
                    session = simpleGateway.CreateSession(nodeId, incoming);

                    // 创建会话失败,拒绝连接
                    if (session == null)
                    {
                        Log.Info("close channel");
                        ctx.CloseAsync().Wait();
                    }
                    else
                    {
                        Log.Info(session.deviceId + " ready to go online.");
                        simpleGateway.ReportSubDeviceStatus(session.deviceId, "ONLINE");
                    }
                }
                else
                {
                    // 网关收到子设备上行数据时,可以以消息或者属性上报转发到平台。
                    // 实际使用时根据需要选择一种即可,这里为了演示,两种类型都转发一遍

                    // 上报消息用reportSubDeviceMessage
                    DeviceMessage deviceMessage = new DeviceMessage(msg);
                    deviceMessage.deviceId = session.deviceId;
                    simpleGateway.ReportSubDeviceMessage(deviceMessage);

                    // 报属性则调用reportSubDeviceProperties,属性的serviceId和字段名要和子设备的产品模型保持一致
                    ServiceProperty serviceProperty = new ServiceProperty();
                    serviceProperty.serviceId = "smokeDetector";
                    Dictionary <string, object> props = new Dictionary <string, object>();

                    // 属性值暂且写死,实际中应该根据子设备上报的进行组装
                    props.Add("alarm", 1);
                    props.Add("temperature", 2);
                    serviceProperty.properties = props;

                    List <ServiceProperty> services = new List <ServiceProperty>();
                    services.Add(serviceProperty);
                    simpleGateway.ReportSubDeviceProperties(session.deviceId, services);
                }
            }
Пример #7
0
        public DurationDecorator(IServiceType aServiceType) : base(aServiceType)
        {
            //base.Name = "Duration";

            IServiceProperty props = new ServiceProperty {
                Name = "initialdate", Type = "datetime", ServiceType = this
            };

            base.ServiceProperties.Add("initialdate", props);
            props = new ServiceProperty {
                Name = "enddate", Type = "datetime", ServiceType = this
            };
            base.ServiceProperties.Add("enddate", props);
        }
Пример #8
0
        public TimeOffDecorator(IServiceType aServiceType) : base(aServiceType)
        {
            //Name = "Time OFF";

            IServiceProperty props = new ServiceProperty {
                Name = "initialtimeoff", Type = "datetime", ServiceType = this
            };

            base.ServiceProperties.Add("initialtimeoff", props);
            props = new ServiceProperty {
                Name = "endtimeoff", Type = "datetime", ServiceType = this
            };
            base.ServiceProperties.Add("endtimeoff", props);
        }
Пример #9
0
        public ActionResult AddOrEdit(ServiceProperty serviceProperty)
        {
            //if (uploadedFile != null)
            //{
            //    string fileName = Path.GetFileNameWithoutExtension(uploadedFile.FileName);
            //    string extension = Path.GetExtension(uploadedFile.FileName);
            //    fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
            //    socialAccountType.SocialAccountTypeImage = "~/Image/SocialAccountType/" + fileName;
            //    uploadedFile.SaveAs(Path.Combine(Server.MapPath("~/Image/SocialAccountType/"), fileName));

            //}
            var data = _iServicePropertyManager.AddOrEdit(serviceProperty);

            return(Json(new { messageType = data.MessageType, message = data.ReturnMessage, html = GlobalClass.RenderRazorViewToString(this, "ViewAll", _iServicePropertyManager.GetAllServiceProperty()) }, JsonRequestBehavior.AllowGet));
        }
        internal Finder(int interval)
        {
            _interval = interval;
            _clock    = null;
            _active   = false;
            _lock     = new object();
            // propriedade gerada automaticamente
            ServiceProperty autoProp =
                new ServiceProperty("openbus.component.interface",
                                    Repository.GetRepositoryID(typeof(Clock)));
            // propriedade definida pelo serviço independent clock
            ServiceProperty prop = new ServiceProperty("offer.domain",
                                                       "Demo Independent Clock");

            _properties = new[] { prop, autoProp };
        }
Пример #11
0
        protected virtual ServiceProperty ProcessProperty()
        {
            var retval = new ServiceProperty
            {
                Name = this.tokenizer.CurrentIdentifier
            };

            this.ReadNextToken();

            this.Expect(FicklefileToken.Colon);

            this.ReadNextToken();

            retval.TypeName = this.ParseTypeName();

            return(retval);
        }
Пример #12
0
        private void CreateServiceProperties(HttpContext context)
        {
            Int16   serviceId           = 0;
            JObject propertyObject      = null;
            JArray  propertyFieldsArray = null;

            List <ServiceProperty>       servicePropertiesList      = new List <ServiceProperty>();
            List <ServicePropertyFields> servicePropertiesFieldList = new List <ServicePropertyFields>();

            if (context.Request["ServiceId"] == null || !Int16.TryParse(context.Request["ServiceId"].ToString(), out serviceId))
            {
                GenerateErrorResponse(400, string.Format("Parameter ServiceId is missing or not a valid number"));
            }
            try
            {
                propertyObject = JObject.Parse(context.Request["Properties"].ToString());
            }
            catch (Exception e)
            {
                GenerateErrorResponse(400, string.Format("Invalid JSON"));
            }
            //foreach (JObject propertyObject in properiesArray)
            //{
            try
            {
                propertyFieldsArray = JArray.Parse(propertyObject.SelectToken("PropertyFields").ToString());
            }
            catch (Exception ex)
            {
                GenerateErrorResponse(400, string.Format("Invalid JSON"));
            }

            ServiceProperty serviceProperty = ValidateServiceProperties(propertyObject);

            servicePropertiesFieldList = ValidateServicePropertyFields(propertyFieldsArray, serviceProperty);

            //servicePropertiesList.Add(serviceProperty);
            //}


            OrdersManagement.Core.Client client = new OrdersManagement.Core.Client(responseFormat: OrdersManagement.ResponseFormat.JSON);
            context.Response.Write(client.CreateServiceProperties(serviceId, serviceProperty, servicePropertiesFieldList));
        }
        public int AddOrEdit(ServiceProperty serviceProperty)
        {
            if (serviceProperty.ServicePropertyId == 0)
            {
                serviceProperty.CreatedDate = DateTime.Now;
                serviceProperty.UpdatedDate = DateTime.Now;
                serviceProperty.CreatedBy   = 1;
                serviceProperty.UpdatedBy   = 1;
                _dbContext.ServiceProperties.Add(serviceProperty);
            }
            else
            {
                serviceProperty.UpdatedBy               = 1;
                serviceProperty.UpdatedDate             = DateTime.Now;
                _dbContext.Entry(serviceProperty).State = EntityState.Modified;
            }

            return(_dbContext.SaveChanges());
        }
Пример #14
0
        public void BuildServiceType(string name, char dp)
        {
            foreach (var sTypes in DataHolder.GetInstance().ServiceTypes.Where(sTypes => sTypes.Name == name))
            {
                Type = sTypes;
                return;
            }

            Type = new DurationType {
                Name = name
            };
            IServiceProperty props = new ServiceProperty {
                Name = "name", Type = "string", ServiceType = Type
            };

            Type.ServiceProperties.Add("name", props);
            props = new ServiceProperty {
                Name = "location", Type = "string", ServiceType = Type
            };
            Type.ServiceProperties.Add("location", props);
            props = new ServiceProperty {
                Name = "price", Type = "double", ServiceType = Type
            };
            Type.ServiceProperties.Add("price", props);
            props = new ServiceProperty {
                Name = "description", Type = "string", ServiceType = Type
            };
            Type.ServiceProperties.Add("description", props);
            props = new ServiceProperty {
                Name = "date", Type = "date", ServiceType = Type
            };
            Type.ServiceProperties.Add("date", props);
            props = new ServiceProperty {
                Name = "time", Type = "time", ServiceType = Type
            };
            Type.ServiceProperties.Add("time", props);
            props = new ServiceProperty {
                Name = "n_tables", Type = "double", ServiceType = Type
            };
            Type.ServiceProperties.Add("n_tables", props);
            Type.TwoDates = false;
            DataHolder.GetInstance().ServiceTypes.Add(Type);
        }
Пример #15
0
        public void FunCertificateSample(string serverUri, int port, string deviceId)
        {
            string deviceCertPath = IotUtil.GetRootDirectory() + @"\certificate\deviceCert.pfx";

            if (!File.Exists(deviceCertPath))
            {
                Log.Error("请将设备证书放到根目录!");

                return;
            }

            X509Certificate2 deviceCert = new X509Certificate2(deviceCertPath, "123456");

            // 使用证书创建设备
            IoTDevice device = new IoTDevice(serverUri, port, deviceId, deviceCert);

            if (device.Init() != 0)
            {
                return;
            }

            Dictionary <string, object> json = new Dictionary <string, object>();

            // 按照物模型设置属性
            json["alarm"]              = 1;
            json["temperature"]        = 23.45811;
            json["humidity"]           = 56.89012;
            json["smokeConcentration"] = 89.56723;

            ServiceProperty serviceProperty = new ServiceProperty();

            serviceProperty.properties = json;
            serviceProperty.serviceId  = "smokeDetector"; // serviceId要和物模型一致

            List <ServiceProperty> properties = new List <ServiceProperty>();

            properties.Add(serviceProperty);

            device.GetClient().Report(new PubMessage(properties));
        }
Пример #16
0
        private static Messenger GetMessenger()
        {
            // propriedades geradas automaticamente
            ServiceProperty autoProp = new ServiceProperty(
                "openbus.component.interface",
                Repository.GetRepositoryID(typeof(Messenger)));
            // propriedade definida pelo servidor hello
            ServiceProperty prop = new ServiceProperty("offer.domain",
                                                       "Interoperability Tests");

            ServiceProperty[]       properties = { autoProp, prop };
            List <ServiceOfferDesc> offers     =
                Utils.FindOffer(ORBInitializer.Context.OfferRegistry, properties, 1, 10, 1);

            foreach (ServiceOfferDesc serviceOfferDesc in offers)
            {
                try {
                    MarshalByRefObject messengerObj =
                        serviceOfferDesc.service_ref.getFacet(Repository.GetRepositoryID(typeof(Messenger)));
                    if (messengerObj == null)
                    {
                        Logger.Fatal(
                            "Não foi possível encontrar uma faceta com esse nome.");
                        continue;
                    }
                    Messenger messenger = messengerObj as Messenger;
                    if (messenger == null)
                    {
                        Logger.Fatal("Faceta encontrada não implementa Messenger.");
                        continue;
                    }
                    return(messenger);
                }
                catch (TRANSIENT) {
                    Logger.Fatal(
                        "Uma das ofertas obtidas é de um cliente inativo. Tentando a próxima.");
                }
            }
            return(null);
        }
        /// <summary>
        /// 触发属性变化,SDK会上报变化的属性
        /// </summary>
        /// <param name="serviceId">服务id</param>
        /// <param name="properties">属性列表</param>
        internal void FirePropertiesChanged(string serviceId, string[] properties)
        {
            AbstractService deviceService = GetService(serviceId);

            if (deviceService == null)
            {
                return;
            }

            Dictionary <string, object> props = deviceService.OnRead(properties);

            ServiceProperty serviceProperty = new ServiceProperty();

            serviceProperty.serviceId  = deviceService.ServiceId;
            serviceProperty.properties = props;
            serviceProperty.eventTime  = IotUtil.GetEventTime();

            List <ServiceProperty> listProperties = new List <ServiceProperty>();

            listProperties.Add(serviceProperty);

            client.ReportProperties(listProperties);
        }
Пример #18
0
        public void OnPropertiesGet(string requestId, string serviceId)
        {
            Console.WriteLine("requestId Get:" + requestId);
            Console.WriteLine("serviceId Get:" + serviceId);

            Dictionary <string, object> json = new Dictionary <string, object>();

            // 按照物模型设置属性
            json["alarm"]              = 1;
            json["temperature"]        = 23.45813;
            json["humidity"]           = 56.89012;
            json["smokeConcentration"] = 89.56728;

            ServiceProperty serviceProperty = new ServiceProperty();

            serviceProperty.properties = json;
            serviceProperty.serviceId  = serviceId; // serviceId要和物模型一致

            List <ServiceProperty> properties = new List <ServiceProperty>();

            properties.Add(serviceProperty);

            device.GetClient().Report(new PubMessage(CommonTopic.TOPIC_SYS_PROPERTIES_GET_RESPONSE + "=" + requestId, properties));
        }
        /// <summary>
        /// 属性查询回调,由SDK自动调用
        /// </summary>
        /// <param name="requestId">请求ID</param>
        /// <param name="propsGet">属性查询请求</param>
        public void OnPropertiesGet(string requestId, PropsGet propsGet)
        {
            List <ServiceProperty> serviceProperties = new List <ServiceProperty>();

            // 查询所有
            if (propsGet.serviceId == null)
            {
                foreach (KeyValuePair <string, AbstractService> kv in services)
                {
                    IService deviceService = GetService(kv.Key);
                    if (deviceService != null)
                    {
                        Dictionary <string, object> properties      = deviceService.OnRead();
                        ServiceProperty             serviceProperty = new ServiceProperty();
                        serviceProperty.properties = properties;
                        serviceProperty.serviceId  = kv.Key;
                        serviceProperties.Add(serviceProperty);
                    }
                }
            }
            else
            {
                IService deviceService = GetService(propsGet.serviceId);

                if (deviceService != null)
                {
                    Dictionary <string, object> properties      = deviceService.OnRead();
                    ServiceProperty             serviceProperty = new ServiceProperty();
                    serviceProperty.properties = properties;
                    serviceProperty.serviceId  = propsGet.serviceId;
                    serviceProperties.Add(serviceProperty);
                }
            }

            client.RespondPropsGet(requestId, serviceProperties);
        }
Пример #20
0
 public TronService()
 {
     Props = new ServiceProperty();
 }
Пример #21
0
        private static void Main(String[] args)
        {
            // Obtém dados através dos argumentos
            string host   = args[0];
            ushort port   = Convert.ToUInt16(args[1]);
            string domain = args[2];
            string entity = args[3];

            byte[] password = new ASCIIEncoding().GetBytes(args.Length > 4 ? args[4] : entity);

            // Cria conexão e a define como conexão padrão tanto para entrada como saída.
            // O uso exclusivo da conexão padrão (sem uso de current e callback de despacho) só é recomendado para aplicações que criem apenas uma conexão e desejem utilizá-la em todos os casos. Para situações diferentes, consulte o manual do SDK OpenBus e/ou outras demos.
            ORBInitializer.InitORB();
            OpenBusContext context = ORBInitializer.Context;
            Connection     conn    = context.ConnectByAddress(host, port);

            context.SetDefaultConnection(conn);

            string helloIDLType = Repository.GetRepositoryID(typeof(Hello));

            ServiceOfferDesc[] offers = null;
            try {
                // Faz o login
                conn.LoginByPassword(entity, password, domain);
                // Faz busca utilizando propriedades geradas automaticamente e propriedades definidas pelo serviço específico
                // propriedade gerada automaticamente
                ServiceProperty autoProp =
                    new ServiceProperty("openbus.component.interface", helloIDLType);
                // propriedade definida pelo serviço hello
                ServiceProperty   prop       = new ServiceProperty("offer.domain", "Demo Hello");
                ServiceProperty[] properties = { prop, autoProp };
                offers = context.OfferRegistry.findServices(properties);
            }
            catch (AccessDenied) {
                Console.WriteLine(Resources.ClientAccessDenied + entity + ".");
            }
            catch (ServiceFailure e) {
                Console.WriteLine(Resources.BusServiceFailureErrorMsg);
                Console.WriteLine(e);
            }
            catch (TRANSIENT) {
                Console.WriteLine(Resources.BusTransientErrorMsg);
            }
            catch (COMM_FAILURE) {
                Console.WriteLine(Resources.BusCommFailureErrorMsg);
            }
            catch (Exception e) {
                NO_PERMISSION npe = null;
                if (e is TargetInvocationException)
                {
                    // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION
                    npe = e.InnerException as NO_PERMISSION;
                }
                if ((npe == null) && (!(e is NO_PERMISSION)))
                {
                    // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar.
                    throw;
                }
                npe = npe ?? (NO_PERMISSION)e;
                if (npe.Minor == NoLoginCode.ConstVal)
                {
                    Console.WriteLine(Resources.NoLoginCodeErrorMsg);
                }
                else
                {
                    throw;
                }
            }

            // analiza as ofertas encontradas
            bool failed = true;

            if (offers != null)
            {
                if (offers.Length < 1)
                {
                    Console.WriteLine(Resources.ServiceNotFound);
                }
                else
                {
                    if (offers.Length > 1)
                    {
                        Console.WriteLine(Resources.ServiceFoundMoreThanExpected);
                    }
                    foreach (ServiceOfferDesc serviceOfferDesc in offers)
                    {
                        Console.WriteLine(Resources.ServiceFoundTesting);
                        try {
                            MarshalByRefObject helloObj =
                                serviceOfferDesc.service_ref.getFacet(helloIDLType);
                            if (helloObj == null)
                            {
                                Console.WriteLine(Resources.FacetNotFoundInOffer);
                                continue;
                            }
                            Hello hello = helloObj as Hello;
                            if (hello == null)
                            {
                                Console.WriteLine(Resources.FacetFoundWrongType);
                                continue;
                            }
                            Console.WriteLine(Resources.OfferFound);
                            // utiliza o serviço
                            hello.sayHello();
                            failed = false;
                            break;
                        }
                        catch (TRANSIENT) {
                            Console.WriteLine(Resources.ServiceTransientErrorMsg);
                        }
                        catch (COMM_FAILURE) {
                            Console.WriteLine(Resources.ServiceCommFailureErrorMsg);
                        }
                        catch (Exception e) {
                            NO_PERMISSION npe = null;
                            if (e is TargetInvocationException)
                            {
                                // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION
                                npe = e.InnerException as NO_PERMISSION;
                            }
                            if ((npe == null) && (!(e is NO_PERMISSION)))
                            {
                                // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar.
                                throw;
                            }
                            npe = npe ?? (NO_PERMISSION)e;
                            bool   found   = false;
                            string message = String.Empty;
                            switch (npe.Minor)
                            {
                            case NoLoginCode.ConstVal:
                                message = Resources.NoLoginCodeErrorMsg;
                                found   = true;
                                break;

                            case UnknownBusCode.ConstVal:
                                message = Resources.UnknownBusCodeErrorMsg;
                                found   = true;
                                break;

                            case UnverifiedLoginCode.ConstVal:
                                message = Resources.UnverifiedLoginCodeErrorMsg;
                                found   = true;
                                break;

                            case InvalidRemoteCode.ConstVal:
                                message = Resources.InvalidRemoteCodeErrorMsg;
                                found   = true;
                                break;
                            }
                            if (found)
                            {
                                Console.WriteLine(message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    if (failed)
                    {
                        Console.WriteLine(Resources.OfferFunctionalNotFound);
                    }
                }
            }

            try {
                conn.Logout();
            }
            catch (ServiceFailure e) {
                Console.WriteLine(Resources.BusServiceFailureErrorMsg);
                Console.WriteLine(e);
            }
            catch (TRANSIENT) {
                Console.WriteLine(Resources.BusTransientErrorMsg);
            }
            catch (COMM_FAILURE) {
                Console.WriteLine(Resources.BusCommFailureErrorMsg);
            }
            if (!failed)
            {
                Console.WriteLine(Resources.ClientOK);
            }
            Console.ReadKey();
        }
Пример #22
0
        private static void Main()
        {
            string        hostName  = DemoConfig.Default.busHostName;
            ushort        hostPort  = DemoConfig.Default.busHostPort;
            ushort        hostPort2 = DemoConfig.Default.bus2HostPort;
            ASCIIEncoding encoding  = new ASCIIEncoding();

            object[] buses;
            bool     useSSL           = DemoConfig.Default.useSSL;
            string   clientUser       = DemoConfig.Default.clientUser;
            string   clientThumbprint = DemoConfig.Default.clientThumbprint;
            string   serverUser       = DemoConfig.Default.serverUser;
            string   serverThumbprint = DemoConfig.Default.serverThumbprint;
            ushort   serverSSLPort    = DemoConfig.Default.serverSSLPort;
            ushort   serverOpenPort   = DemoConfig.Default.serverOpenPort;
            string   busIORFile       = DemoConfig.Default.busIORFile;
            string   bus2IORFile      = DemoConfig.Default.bus2IORFile;

            if (useSSL)
            {
                Utils.InitSSLORB(clientUser, clientThumbprint, serverUser, serverThumbprint, serverSSLPort, serverOpenPort, true, true, "required", false, false);
                buses = new object[] { busIORFile, bus2IORFile };
            }
            else
            {
                ORBInitializer.InitORB();
                buses = new object[] { hostPort, hostPort2 };
            }

            ConnectionProperties props   = new ConnectionPropertiesImpl();
            OpenBusContext       context = ORBInitializer.Context;

            for (int i = 0; i < buses.Length; i++)
            {
                Connection conn;
                if (useSSL)
                {
                    string ior = File.ReadAllText((string)buses[i]);
                    conn = context.ConnectByReference((MarshalByRefObject)OrbServices.CreateProxy(typeof(MarshalByRefObject), ior), props);
                }
                else
                {
                    conn = context.ConnectByAddress(hostName, (ushort)buses[i], props);
                }
                context.SetDefaultConnection(conn);
                const string login = "******";
                conn.LoginByPassword(login, encoding.GetBytes(login), "testing");

                ServiceProperty[] properties = new ServiceProperty[2];
                properties[0] =
                    new ServiceProperty("openbus.component.interface",
                                        Repository.GetRepositoryID(typeof(Hello)));
                properties[1] = new ServiceProperty("offer.domain",
                                                    "Interoperability Tests");
                List <ServiceOfferDesc> offers =
                    Utils.FindOffer(ORBInitializer.Context.OfferRegistry, properties, 1, 10, 1);

                foreach (ServiceOfferDesc offer in offers)
                {
                    string entity = Utils.GetProperty(offer.properties, "openbus.offer.entity");
                    if (entity != null)
                    {
                        Logger.Info("found offer from " + entity + " on bus " + i);
                    }
                    try {
                        MarshalByRefObject obj =
                            offer.service_ref.getFacet(
                                Repository.GetRepositoryID(typeof(Hello)));
                        if (obj == null)
                        {
                            Logger.Info(
                                "Não foi possível encontrar uma faceta com esse nome.");
                            continue;
                        }
                        Hello hello = obj as Hello;
                        if (hello == null)
                        {
                            Logger.Info("Faceta encontrada não implementa Hello.");
                            continue;
                        }
                        string expected = String.Format("Hello {0}@{1}!", login,
                                                        conn.BusId);
                        string ret = hello.sayHello();
                        Assert.AreEqual(expected, ret);
                    }
                    catch (TRANSIENT) {
                        Logger.Info(
                            "Uma das ofertas obtidas é de um cliente inativo. Tentando a próxima.");
                    }
                }
                conn.Logout();
            }
        }
Пример #23
0
        private static void Main()
        {
            string hostName         = DemoConfig.Default.busHostName;
            ushort hostPort         = DemoConfig.Default.busHostPort;
            bool   useSSL           = DemoConfig.Default.useSSL;
            string clientUser       = DemoConfig.Default.clientUser;
            string clientThumbprint = DemoConfig.Default.clientThumbprint;
            string serverUser       = DemoConfig.Default.serverUser;
            string serverThumbprint = DemoConfig.Default.serverThumbprint;
            ushort serverSSLPort    = DemoConfig.Default.serverSSLPort;
            ushort serverOpenPort   = DemoConfig.Default.serverOpenPort;
            string busIORFile       = DemoConfig.Default.busIORFile;

            if (useSSL)
            {
                Utils.InitSSLORB(clientUser, clientThumbprint, serverUser, serverThumbprint, serverSSLPort, serverOpenPort, true, true, "required", false, false);
            }
            else
            {
                ORBInitializer.InitORB();
            }

/*
 *    ConsoleAppender appender = new ConsoleAppender {
 *      Threshold = Level.Off,
 *      Layout =
 *        new SimpleLayout(),
 *    };
 *    BasicConfigurator.Configure(appender);
 */
            ConnectionProperties props   = new ConnectionPropertiesImpl();
            OpenBusContext       context = ORBInitializer.Context;
            Connection           conn;

            if (useSSL)
            {
                string ior = File.ReadAllText(busIORFile);
                conn = context.ConnectByReference((MarshalByRefObject)OrbServices.CreateProxy(typeof(MarshalByRefObject), ior), props);
            }
            else
            {
                conn = context.ConnectByAddress(hostName, hostPort, props);
            }
            context.SetDefaultConnection(conn);

            const string userLogin = "******";

            byte[] userPassword = new ASCIIEncoding().GetBytes(userLogin);

            conn.LoginByPassword(userLogin, userPassword, "testing");

            // propriedades geradas automaticamente
            ServiceProperty prop1 = new ServiceProperty("reloggedjoin.role", "proxy");
            // propriedade definida pelo servidor hello
            ServiceProperty prop2 = new ServiceProperty("offer.domain",
                                                        "Interoperability Tests");

            ServiceProperty[]       properties = { prop1, prop2 };
            List <ServiceOfferDesc> offers     =
                Utils.FindOffer(ORBInitializer.Context.OfferRegistry, properties, 1, 10, 1);

            bool foundOne = false;

            foreach (ServiceOfferDesc serviceOfferDesc in offers)
            {
                try {
                    string found = Utils.GetProperty(serviceOfferDesc.properties, "openbus.offer.entity");
                    Logger.Info("Entidade encontrada: " + found);
                    MarshalByRefObject helloObj =
                        serviceOfferDesc.service_ref.getFacet(
                            Repository.GetRepositoryID(typeof(Hello)));
                    if (helloObj == null)
                    {
                        Logger.Info(
                            "Não foi possível encontrar uma faceta com esse nome.");
                        continue;
                    }
                    Hello hello = helloObj as Hello;
                    if (hello == null)
                    {
                        Logger.Info("Faceta encontrada não implementa Hello.");
                        continue;
                    }
                    foundOne = true;
                    Assert.AreEqual("" + hello.sayHello(), "Hello " + userLogin + "!");
                }
                catch (TRANSIENT) {
                    Logger.Info(
                        "Uma das ofertas obtidas é de um cliente inativo. Tentando a próxima.");
                }
            }
            conn.Logout();
            Assert.IsTrue(foundOne);
            Logger.Info("Fim.");
        }
        private static void Main(String[] args)
        {
            // Obtém dados através dos argumentos
            string host   = args[0];
            ushort port   = Convert.ToUInt16(args[1]);
            string domain = args[2];
            string entity = args[3];

            byte[] password = new ASCIIEncoding().GetBytes(args.Length > 4 ? args[4] : entity);

            // Cria conexão e a define como conexão padrão tanto para entrada como saída.
            // O uso exclusivo da conexão padrão (sem uso de current e callback de despacho) só é recomendado para aplicações que criem apenas uma conexão e desejem utilizá-la em todos os casos. Para situações diferentes, consulte o manual do SDK OpenBus e/ou outras demos.
            ORBInitializer.InitORB();
            OpenBusContext context = ORBInitializer.Context;
            Connection     conn    = context.ConnectByAddress(host, port);

            context.SetDefaultConnection(conn);

            // Pergunta ao usuário qual língua deseja utilizar
            Console.WriteLine(Resources.GreetingsWhichLanguage);
            string language = Console.ReadLine();

            if (language == null)
            {
                Console.WriteLine(Resources.GreetingsLanguageReadErrorMsg);
                Environment.Exit(1);
            }

            string greetingsIDLType = Repository.GetRepositoryID(typeof(Greetings));

            ServiceOfferDesc[] offers = null;
            try {
                // Faz o login
                conn.LoginByPassword(entity, password, domain);
                // Faz busca utilizando propriedades geradas automaticamente e propriedades definidas pelo serviço específico
                // propriedade gerada automaticamente
                ServiceProperty autoProp1 =
                    new ServiceProperty("openbus.component.interface", greetingsIDLType);
                // propriedade definida pelo serviço greetings
                ServiceProperty prop = new ServiceProperty("offer.domain",
                                                           "Demo Greetings");
                ServiceProperty[] properties;
                if (!language.Equals(""))
                {
                    ServiceProperty autoProp2 = new ServiceProperty(
                        "openbus.component.name", language.ToLower());
                    properties = new[] { prop, autoProp1, autoProp2 };
                }
                else
                {
                    Console.WriteLine(Resources.GreetingsNoLanguageSpecified);
                    properties = new[] { prop, autoProp1 };
                }

                offers = context.OfferRegistry.findServices(properties);
            }
            catch (AccessDenied) {
                Console.WriteLine(Resources.ClientAccessDenied + entity + ".");
            }
            catch (ServiceFailure e) {
                Console.WriteLine(Resources.BusServiceFailureErrorMsg);
                Console.WriteLine(e);
            }
            catch (TRANSIENT) {
                Console.WriteLine(Resources.BusTransientErrorMsg);
            }
            catch (COMM_FAILURE) {
                Console.WriteLine(Resources.BusCommFailureErrorMsg);
            }
            catch (Exception e) {
                NO_PERMISSION npe = null;
                if (e is TargetInvocationException)
                {
                    // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION
                    npe = e.InnerException as NO_PERMISSION;
                }
                if ((npe == null) && (!(e is NO_PERMISSION)))
                {
                    // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar.
                    throw;
                }
                npe = npe ?? (NO_PERMISSION)e;
                if (npe.Minor == NoLoginCode.ConstVal)
                {
                    Console.WriteLine(Resources.NoLoginCodeErrorMsg);
                }
                else
                {
                    throw;
                }
            }

            // analiza as ofertas encontradas
            if (offers != null)
            {
                if (offers.Length < 1)
                {
                    Console.WriteLine(Resources.ServiceNotFound);
                }
                else
                {
                    if (offers.Length > 1)
                    {
                        Console.WriteLine(Resources.ServiceFoundMoreThanExpected);
                    }
                    foreach (ServiceOfferDesc serviceOfferDesc in offers)
                    {
                        Console.WriteLine(Resources.ServiceFoundTesting);
                        try {
                            int hours = DateTime.Now.TimeOfDay.Hours;
                            MarshalByRefObject greetObj = hours < 12
                                              ? serviceOfferDesc.service_ref.
                                                          getFacetByName("GoodMorning")
                                              : serviceOfferDesc.service_ref.
                                                          getFacetByName(hours >= 18
                                                                   ? "GoodNight"
                                                                   : "GoodAfternoon");
                            if (greetObj == null)
                            {
                                Console.WriteLine(Resources.FacetNotFoundInOffer);
                                continue;
                            }
                            Greetings greetings = greetObj as Greetings;
                            if (greetings == null)
                            {
                                Console.WriteLine(Resources.FacetFoundWrongType);
                                continue;
                            }
                            Console.WriteLine(Resources.OfferFound);
                            // utiliza o serviço
                            Console.WriteLine((string)greetings.sayGreetings());
                        }
                        catch (TRANSIENT) {
                            Console.WriteLine(Resources.ServiceTransientErrorMsg);
                        }
                        catch (COMM_FAILURE) {
                            Console.WriteLine(Resources.ServiceCommFailureErrorMsg);
                        }
                        catch (Exception e) {
                            NO_PERMISSION npe = null;
                            if (e is TargetInvocationException)
                            {
                                // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION
                                npe = e.InnerException as NO_PERMISSION;
                            }
                            if ((npe == null) && (!(e is NO_PERMISSION)))
                            {
                                // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar.
                                throw;
                            }
                            npe = npe ?? (NO_PERMISSION)e;
                            bool   found   = false;
                            string message = String.Empty;
                            switch (npe.Minor)
                            {
                            case NoLoginCode.ConstVal:
                                message = Resources.NoLoginCodeErrorMsg;
                                found   = true;
                                break;

                            case UnknownBusCode.ConstVal:
                                message = Resources.UnknownBusCodeErrorMsg;
                                found   = true;
                                break;

                            case UnverifiedLoginCode.ConstVal:
                                message = Resources.UnverifiedLoginCodeErrorMsg;
                                found   = true;
                                break;

                            case InvalidRemoteCode.ConstVal:
                                message = Resources.InvalidRemoteCodeErrorMsg;
                                found   = true;
                                break;
                            }
                            if (found)
                            {
                                Console.WriteLine(message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }
            }

            try {
                conn.Logout();
            }
            catch (ServiceFailure e) {
                Console.WriteLine(Resources.BusServiceFailureErrorMsg);
                Console.WriteLine(e);
            }
            catch (TRANSIENT) {
                Console.WriteLine(Resources.BusTransientErrorMsg);
            }
            catch (COMM_FAILURE) {
                Console.WriteLine(Resources.BusCommFailureErrorMsg);
            }
            Console.WriteLine(Resources.ClientOK);
            Console.ReadKey();
        }
Пример #25
0
 public virtual Expression Build(ServiceProperty property)
 {
     return(new PropertyDefinitionExpression(property.Name, this.GetTypeFromName(property.TypeName)));
 }
Пример #26
0
        private CollaborationRegistry GetCollabs()
        {
            bool find = _collabs == null;

            if (!find)
            {
                try
                {
                    find = !_context.ORB.non_existent(_collabs);
                }
                catch (Exception)
                {
                    find = true;
                }
            }
            if (find)
            {
                ServiceProperty[] serviceProperties = new ServiceProperty[1];
                string            collabsRegType    = Repository.GetRepositoryID(typeof(CollaborationRegistry));
                serviceProperties[0] =
                    new ServiceProperty("openbus.component.interface", collabsRegType);
                ServiceOfferDesc[] services = _context.OfferRegistry.findServices(serviceProperties);

                foreach (ServiceOfferDesc offerDesc in services)
                {
                    try
                    {
                        MarshalByRefObject obj =
                            offerDesc.service_ref.getFacet(collabsRegType);
                        if (obj == null)
                        {
                            continue;
                        }
                        _collabs = obj as CollaborationRegistry;
                        if (_collabs != null)
                        {
                            break; // found one
                        }
                    }
                    catch (Exception e)
                    {
                        NO_PERMISSION npe = null;
                        if (e is TargetInvocationException)
                        {
                            npe = e.InnerException as NO_PERMISSION;
                        }
                        // caso não seja uma NO_PERMISSION{NoLogin} descarta essa oferta.
                        if ((npe == null) && (!(e is NO_PERMISSION)))
                        {
                            continue;
                        }
                        npe = npe ?? e as NO_PERMISSION;
                        switch (npe.Minor)
                        {
                        case NoLoginCode.ConstVal:
                            throw;
                        }
                    }
                }
            }
            return(_collabs);
        }
        private static void Main(String[] args)
        {
            // Obtém dados através dos argumentos
            _host     = args[0];
            _port     = Convert.ToUInt16(args[1]);
            _domain   = args[2];
            _entity   = args[3];
            _password =
                new ASCIIEncoding().GetBytes(args.Length > 4 ? args[4] : _entity);

            // Cria conexão e a define como conexão padrão tanto para entrada como saída.
            ORBInitializer.InitORB();
            OpenBusContext context = ORBInitializer.Context;

            context.SetDefaultConnection(NewLogin());

            ServiceOfferDesc[] offers = null;
            try {
                // Faz busca utilizando propriedades geradas automaticamente e propriedades definidas pelo serviço específico
                // propriedade gerada automaticamente
                ServiceProperty autoProp =
                    new ServiceProperty("openbus.component.interface", TimerIDLType);
                // propriedade definida pelo serviço timer
                ServiceProperty prop = new ServiceProperty("offer.domain",
                                                           "Demo Multiplexing");
                ServiceProperty[] properties = { prop, autoProp };
                offers = context.OfferRegistry.findServices(properties);
            }
            catch (ServiceFailure e) {
                Console.WriteLine(Resources.BusServiceFailureErrorMsg);
                Console.WriteLine(e);
            }
            catch (TRANSIENT) {
                Console.WriteLine(Resources.BusTransientErrorMsg);
            }
            catch (COMM_FAILURE) {
                Console.WriteLine(Resources.BusCommFailureErrorMsg);
            }
            catch (Exception e) {
                NO_PERMISSION npe = null;
                if (e is TargetInvocationException)
                {
                    // caso seja uma exceção lançada pelo SDK, será uma NO_PERMISSION
                    npe = e.InnerException as NO_PERMISSION;
                }
                if ((npe == null) && (!(e is NO_PERMISSION)))
                {
                    // caso não seja uma NO_PERMISSION não é uma exceção esperada então deixamos passar.
                    throw;
                }
                npe = npe ?? (NO_PERMISSION)e;
                if (npe.Minor == NoLoginCode.ConstVal)
                {
                    Console.WriteLine(Resources.NoLoginCodeErrorMsg);
                }
                else
                {
                    throw;
                }
            }
            if (offers != null)
            {
                for (int i = 0; i < offers.Length; i++)
                {
                    // garante espera de no mínimo 5s para que dê tempo do cliente executar
                    // todas as chamadas e aumentar o número de notificações esperadas
                    StartTheThread(i + 5, offers[i], Thread.CurrentThread);
                }
            }

            // Mantém a thread ativa para aguardar requisições
            try {
                Thread.Sleep(Timeout.Infinite);
            }
            catch (ThreadInterruptedException) {
                // Se a thread for acordada, é porque não há mais requisições pendentes
                Console.WriteLine(Resources.ClientOK);
            }

            // Faz logout da conexão usada nessa thread
            try {
                context.GetDefaultConnection().Logout();
            }
            catch (ServiceFailure e) {
                Console.WriteLine(Resources.BusServiceFailureErrorMsg);
                Console.WriteLine(e);
            }
            catch (TRANSIENT) {
                Console.WriteLine(Resources.BusTransientErrorMsg);
            }
            catch (COMM_FAILURE) {
                Console.WriteLine(Resources.BusCommFailureErrorMsg);
            }
            Console.ReadKey();
        }
/*
 *  private static void ShowPostsOf(string user, PostDesc[] posts) {
 *    Logger.Fatal(user + " recebeu " + posts.Length + " mensagens:");
 *    for (int i = 0; i < posts.Length; i++) {
 *      Logger.Fatal(i + ") " + posts[i].from + ": " + posts[i].message);
 *    }
 *    Logger.Fatal("\n");
 *  }
 */
        private static void GetService(Type type)
        {
            // propriedades geradas automaticamente
            ServiceProperty autoProp =
                new ServiceProperty("openbus.component.interface",
                                    Repository.GetRepositoryID(type));
            // propriedade definida pelo servidor hello
            ServiceProperty prop = new ServiceProperty("offer.domain",
                                                       "Interoperability Tests");

            ServiceProperty[]       properties = { autoProp, prop };
            List <ServiceOfferDesc> offers     =
                Utils.FindOffer(ORBInitializer.Context.OfferRegistry, properties, 1, 10, 1);

            foreach (ServiceOfferDesc serviceOfferDesc in offers)
            {
                try {
                    MarshalByRefObject obj =
                        serviceOfferDesc.service_ref.getFacet(
                            Repository.GetRepositoryID(type));
                    if (obj == null)
                    {
                        Logger.Fatal(
                            "Não foi possível encontrar uma faceta com esse nome.");
                        continue;
                    }

                    if (type == typeof(Messenger))
                    {
                        Messenger facet = obj as Messenger;
                        if (facet != null)
                        {
                            _messenger = facet;
                            return;
                        }
                    }
                    if (type == typeof(Forwarder))
                    {
                        Forwarder facet = obj as Forwarder;
                        if (facet != null)
                        {
                            _forwarder = facet;
                            return;
                        }
                    }
                    if (type == typeof(Broadcaster))
                    {
                        Broadcaster facet = obj as Broadcaster;
                        if (facet != null)
                        {
                            _broadcaster = facet;
                            return;
                        }
                    }
                }
                catch (TRANSIENT) {
                    Logger.Fatal(
                        "Uma das ofertas obtidas é de um cliente inativo. Tentando a próxima.");
                }
            }
            Assert.Fail("Um servidor do tipo " + type + " não foi encontrado.");
        }
        private static void Main()
        {
            string hostName         = DemoConfig.Default.busHostName;
            ushort hostPort         = DemoConfig.Default.busHostPort;
            bool   useSSL           = DemoConfig.Default.useSSL;
            string clientUser       = DemoConfig.Default.clientUser;
            string clientThumbprint = DemoConfig.Default.clientThumbprint;
            string serverUser       = DemoConfig.Default.serverUser;
            string serverThumbprint = DemoConfig.Default.serverThumbprint;
            ushort serverSSLPort    = DemoConfig.Default.serverSSLPort;
            ushort serverOpenPort   = DemoConfig.Default.serverOpenPort;
            string busIORFile       = DemoConfig.Default.busIORFile;

            if (useSSL)
            {
                Utils.InitSSLORB(clientUser, clientThumbprint, serverUser, serverThumbprint, serverSSLPort, serverOpenPort, true, true, "required", false, false);
            }
            else
            {
                ORBInitializer.InitORB();
            }

            //FileInfo logFileInfo = new FileInfo(DemoConfig.Default.openbusLogFile);
            //XmlConfigurator.ConfigureAndWatch(logFileInfo);

/*
 *    ConsoleAppender appender = new ConsoleAppender {
 *      Threshold = Level.Fatal,
 *      Layout =
 *        new SimpleLayout(),
 *    };
 *    BasicConfigurator.Configure(appender);
 */
            // credential reset tests
            CredentialResetTest[] resetCases = new CredentialResetTest[1];
            CredentialReset       tempReset  = new CredentialReset {
                session = 2 ^ 32 - 1, challenge = CreateSecret(EncryptedBlockSize.ConstVal)
            };

            resetCases[0] = new CredentialResetTest {
                Reset = tempReset, Expected = InvalidRemoteCode.ConstVal
            };

            // no permission tests
            NoPermissionTest[] noPermissionCases = new NoPermissionTest[12];
            noPermissionCases[0] = new NoPermissionTest {
                Raised = 0, Expected = 0
            };
            noPermissionCases[1] = new NoPermissionTest {
                Raised = InvalidCredentialCode.ConstVal, Expected = InvalidRemoteCode.ConstVal
            };
            noPermissionCases[2] = new NoPermissionTest {
                Raised = InvalidChainCode.ConstVal, Expected = InvalidChainCode.ConstVal
            };
            noPermissionCases[3] = new NoPermissionTest {
                Raised = UnverifiedLoginCode.ConstVal, Expected = UnverifiedLoginCode.ConstVal
            };
            noPermissionCases[4] = new NoPermissionTest {
                Raised = UnknownBusCode.ConstVal, Expected = UnknownBusCode.ConstVal
            };
            noPermissionCases[5] = new NoPermissionTest {
                Raised = InvalidPublicKeyCode.ConstVal, Expected = InvalidPublicKeyCode.ConstVal
            };
            noPermissionCases[6] = new NoPermissionTest {
                Raised = NoCredentialCode.ConstVal, Expected = NoCredentialCode.ConstVal
            };
            noPermissionCases[7] = new NoPermissionTest {
                Raised = NoLoginCode.ConstVal, Expected = InvalidRemoteCode.ConstVal
            };
            noPermissionCases[8] = new NoPermissionTest {
                Raised = InvalidRemoteCode.ConstVal, Expected = InvalidRemoteCode.ConstVal
            };
            noPermissionCases[9] = new NoPermissionTest {
                Raised = UnavailableBusCode.ConstVal, Expected = InvalidRemoteCode.ConstVal
            };
            noPermissionCases[10] = new NoPermissionTest {
                Raised = InvalidTargetCode.ConstVal, Expected = InvalidRemoteCode.ConstVal
            };
            noPermissionCases[11] = new NoPermissionTest {
                Raised = InvalidLoginCode.ConstVal, Expected = InvalidRemoteCode.ConstVal
            };

            ORBInitializer.InitORB();
            OpenBusContext       context = ORBInitializer.Context;
            ConnectionProperties props   = new ConnectionPropertiesImpl();
            Connection           conn;

            if (useSSL)
            {
                string ior = File.ReadAllText(busIORFile);
                conn = context.ConnectByReference((MarshalByRefObject)OrbServices.CreateProxy(typeof(MarshalByRefObject), ior), props);
            }
            else
            {
                conn = context.ConnectByAddress(hostName, hostPort, props);
            }
            context.SetDefaultConnection(conn);

            const string userLogin = "******";

            byte[] userPassword = new ASCIIEncoding().GetBytes(userLogin);

            conn.LoginByPassword(userLogin, userPassword, "testing");

            // propriedades geradas automaticamente
            ServiceProperty prop1 = new ServiceProperty("openbus.component.interface", Repository.GetRepositoryID(typeof(Server)));
            // propriedade definida pelo servidor protocol
            ServiceProperty prop2 = new ServiceProperty("offer.domain",
                                                        "Interoperability Tests");

            ServiceProperty[]       properties = { prop1, prop2 };
            List <ServiceOfferDesc> offers     =
                Utils.FindOffer(ORBInitializer.Context.OfferRegistry, properties, 1, 10, 1);

            bool foundOne = false;

            foreach (ServiceOfferDesc serviceOfferDesc in offers)
            {
                try {
                    string found = Utils.GetProperty(serviceOfferDesc.properties, "openbus.offer.entity");
                    Logger.Info("Entidade encontrada: " + found);
                    MarshalByRefObject serverProxyObj =
                        serviceOfferDesc.service_ref.getFacet(
                            Repository.GetRepositoryID(typeof(Server)));
                    if (serverProxyObj == null)
                    {
                        Logger.Info(
                            "Não foi possível encontrar uma faceta com esse nome.");
                        continue;
                    }
                    Server serverProxy = serverProxyObj as Server;
                    if (serverProxy == null)
                    {
                        Logger.Info("Faceta encontrada não implementa Server.");
                        continue;
                    }
                    foundOne = true;
                    // inicio dos testes
                    serverProxy.NonBusCall();
                    foreach (CredentialResetTest test in resetCases)
                    {
                        bool error = false;
                        try {
                            serverProxy.ResetCredentialWithChallenge(test.Reset.session,
                                                                     test.Reset.challenge);
                        }
                        catch (Exception e) {
                            NO_PERMISSION npe = null;
                            if (e is TargetInvocationException)
                            {
                                npe = e.InnerException as NO_PERMISSION;
                            }
                            if ((npe == null) && (!(e is NO_PERMISSION)))
                            {
                                throw;
                            }
                            npe   = npe ?? (NO_PERMISSION)e;
                            error = true;
                            Assert.AreEqual(test.Expected, npe.Minor);
                            Assert.AreEqual(CompletionStatus.Completed_No, npe.Status);
                        }
                        Assert.IsTrue(error);
                    }

                    foreach (NoPermissionTest test in noPermissionCases)
                    {
                        bool error = false;
                        try {
                            serverProxy.RaiseNoPermission(test.Raised);
                        }
                        catch (Exception e) {
                            NO_PERMISSION npe = null;
                            if (e is TargetInvocationException)
                            {
                                npe = e.InnerException as NO_PERMISSION;
                            }
                            if ((npe == null) && (!(e is NO_PERMISSION)))
                            {
                                throw;
                            }
                            npe   = npe ?? (NO_PERMISSION)e;
                            error = true;
                            Assert.AreEqual(test.Expected, npe.Minor);
                            Assert.AreEqual(CompletionStatus.Completed_No, npe.Status);
                        }
                        Assert.IsTrue(error);
                    }
                }
                catch (TRANSIENT) {
                    Logger.Info(
                        "Uma das ofertas obtidas é de um cliente inativo. Tentando a próxima.");
                }
            }
            conn.Logout();
            Assert.IsTrue(foundOne);
            Logger.Info("Fim.");
        }
Пример #30
0
 public PropertyController()
 {
     serviceProperty = new ServiceProperty();
 }
Пример #31
0
        private List <ServicePropertyFields> ValidateServicePropertyFields(JArray propertyFieldsArray, ServiceProperty serviceProperty)
        {
            byte   inputTypeId         = 0;
            byte   minLength           = 0;
            Int16  maxlength           = 0;
            string options             = string.Empty;
            bool   isAllowSpecialChars = false;

            List <ServicePropertyFields> servicePropertiesFieldList = new List <ServicePropertyFields>();

            foreach (JObject propertyFields in propertyFieldsArray)
            {
                ServicePropertyFields servicePropertyFields = new ServicePropertyFields();

                if (serviceProperty.DataTypeId == (int)PropertyDataType.STRING)
                {
                    if (propertyFields.SelectToken("MinLength") == null || !byte.TryParse(propertyFields.SelectToken("MinLength").ToString(), out minLength))
                    {
                        GenerateErrorResponse(400, string.Format("Parameter Minlength of Property '{0}' is missing or invalid", serviceProperty.DisplayName));
                    }
                    if (propertyFields.SelectToken("MaxLength") == null || !byte.TryParse(propertyFields.SelectToken("MaxLength").ToString(), out minLength))
                    {
                        GenerateErrorResponse(400, string.Format("Parameter MaxLength of Property '{0}' is missing or invalid", serviceProperty.DisplayName));
                    }
                }
                if (serviceProperty.InputTypeId == (int)PropertyInputType.TEXT_BOX || inputTypeId == (int)PropertyInputType.TEXT_AREA)
                {
                    if (propertyFields.SelectToken("IsAllowSpecialChars") == null || !bool.TryParse(propertyFields.SelectToken("IsAllowSpecialChars").ToString(), out isAllowSpecialChars))
                    {
                        GenerateErrorResponse(400, string.Format("Parameter IsAllowSpecialCharacters of Property '{0}' is missing or invalid", serviceProperty.DisplayName));
                    }
                }

                if (serviceProperty.InputTypeId != (int)PropertyInputType.TEXT_BOX && inputTypeId == (int)PropertyInputType.TEXT_AREA)
                {
                    if (propertyFields.SelectToken("Options") == null || !byte.TryParse(propertyFields.SelectToken("Options").ToString(), out minLength))
                    {
                        GenerateErrorResponse(400, string.Format("Parameter Options of Property '{0}' is missing or invalid", serviceProperty.DisplayName));
                    }
                }

                servicePropertyFields.FieldId             = serviceProperty.Id;
                servicePropertyFields.MetaDataCode        = serviceProperty.MetaDataCode;
                servicePropertyFields.MinLength           = minLength;
                servicePropertyFields.MaxLength           = maxlength;
                servicePropertyFields.IsAllowSpecialChars = isAllowSpecialChars;
                servicePropertyFields.Options             = options;
                servicePropertiesFieldList.Add(servicePropertyFields);
            }
            return(servicePropertiesFieldList);
        }