public static Type GenerateServiceKernelType(Type kernelType, IServiceContract serviceContract)
        {
            var typeName   = GenerateNameFromServiceContract(serviceContract);
            var interfaces = serviceContract.Interfaces
                             .Select(model => model.Interface)
                             .Append(typeof(IHostedService))
                             .ToArray();
            var typeBuilder = _moduleBuilder.DefineType(
                typeName,
                TypeAttributes.Public | TypeAttributes.Sealed,
                typeof(object),
                interfaces);
            var serviceProviderField = typeBuilder.DefineField("_serviceProvider", typeof(IServiceProvider), FieldAttributes.Private);
            var serviceContractField = typeBuilder.DefineField("_serviceContract", typeof(IServiceContract), FieldAttributes.Private);
            var autobusField         = typeBuilder.DefineField("_autobus", typeof(IAutobus), FieldAttributes.Private);

            GenerateConstructor(typeBuilder, serviceContract.GetType(), serviceProviderField, serviceContractField, autobusField);
            GenerateStartAsyncMethod(typeBuilder, serviceContractField, autobusField);
            GenerateStopAsyncMethod(typeBuilder, autobusField);
            foreach (var interfaceModel in serviceContract.Interfaces)
            {
                foreach (var requestModel in interfaceModel.Requests)
                {
                    GenerateRequestMethod(typeBuilder, kernelType, serviceProviderField, requestModel);
                }
                foreach (var commandModel in interfaceModel.Commands)
                {
                    GenerateCommandMethod(typeBuilder, kernelType, serviceProviderField, commandModel);
                }
            }
            return(typeBuilder.CreateType());
        }
Example #2
0
        public TResult <string> CreateComosDeviceByWebUID(CWriteValueCollection values, string projectname, string workinglayer, string language, string owner, string cdev, string user, string desc)
        {
            try
            {
                //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                IServiceContract m_ComosAPIService = GetComosAPI();
                if (string.IsNullOrEmpty(workinglayer))
                {
                    LogHandler.WriteLog("Service.cs: WriteComosValues: Bad request workinglayer argument is empty", EventLogEntryType.Error);
                    return(new TResult <string>()
                    {
                        data = null,
                        Message = "Working Layer is empty",
                        Status = false,
                    });
                }

                return(m_ComosAPIService.CreateComosDeviceByWebUID(values, projectname, workinglayer, language, owner, cdev, user, desc));
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog("Service.cs: CreateComosDeviceByWebUID.  " + ex.Message, EventLogEntryType.Error);
                return(new TResult <string>()
                {
                    Status = false,
                    data = null,
                    Message = ex.Message,
                });
            }
        }
Example #3
0
        /// <summary>
        /// Ejecuta el servicio de negocio.
        /// </summary>
        /// <param name="pData">XML con datos de entrada.</param>
        /// <param name="pServiceConfiguration">configuración del servicio.</param>
        /// <param name="pserviError"></param>
        /// <returns>XML que representa el resultado de la  ejecución del servicio.</returns>
        /// <date>2007-08-07T00:00:00</date>
        /// <author>moviedo</author>
        static string RunService(string pData, ServiceConfiguration pServiceConfiguration, out ServiceError pserviError)
        {
            IServiceContract wRequest  = null;
            IServiceContract wResponse = null;

            // Obtencion del Request.
            wRequest = (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Request);

            if (wRequest == null)
            {
                System.Text.StringBuilder wMessage = new StringBuilder();

                wMessage.Append("Verifique que este assemblie se encuentra en el host del despachador de servicios");
                wMessage.Append("El servicio " + pServiceConfiguration.Handler);
                wMessage.AppendLine(" no se puede ejecutar debido a que esta faltando el assembly ");
                wMessage.Append(pServiceConfiguration.Request);
                wMessage.Append(" en el despachador de servicio");

                throw GetTechnicalException(wMessage.ToString(), "7002", null);
            }

            wRequest.SetXml(pData);
            wRequest.InitializeServerContextInformation();


            wResponse = RunService(wRequest, pServiceConfiguration, out pserviError);


            return(wResponse.GetXml());
        }
Example #4
0
        private long Send(Action <IServiceContract> action)
        {
            long elapsed;

            try
            {
                _timer.Start();
                IServiceContract channel = _channelFactory.CreateChannel();
                ((IClientChannel)channel).Open();
                action(channel);
                ((IClientChannel)channel).Close();
                elapsed = _timer.ElapsedMilliseconds;
                _timer.Stop();
                _timer.Reset();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception caught {ex.Message}: {ex.StackTrace}");
                while (ex != null)
                {
                    ex = ex.InnerException;
                    if (ex != null)
                    {
                        Console.WriteLine($@" ==> {ex.Message}: {ex.StackTrace}");
                    }
                }

                return(-1);
            }

            return(elapsed);
        }
Example #5
0
        public TResult <IBRServiceContracts.CRow> GetTaskDataByUid(string user, string projectname, string workinglayer, string systemuid)
        {
            //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
            //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
            IServiceContract m_ComosAPIService = GetComosAPI();
            int idworkinglayer = 0;

            if (workinglayer != "")
            {
                idworkinglayer = int.Parse(workinglayer);
            }

            IBRServiceContracts.CCell[] result = m_ComosAPIService.GetTaskDataByUid(user, projectname, idworkinglayer, systemuid);

            CRow row = new CRow();

            row.Values = result;

            return(new TResult <IBRServiceContracts.CRow>()
            {
                Status = (result.Length > 0),
                data = row,
                Message = null,
            });
        }
Example #6
0
        /// <summary>
        /// Ejecuta un servicio de negocio.
        /// </summary>
        /// <param name="providerName">Nombre del proveedor de metadata de servicios.-</param>
        /// <param name="serviceName">Nombre del servicio de negocio.</param>
        /// <param name="jsonRequest">JSON con datos de entrada para la  ejecución del servicio.</param>
        /// <param name="hostContext">Info del despachador de servicio</param>
        /// <returns>JSON con el resultado de la  ejecución del servicio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public string ExecuteServiceJson(string providerName, string serviceName, string jsonRequest, HostContext hostContext)
        {
            string wResult;

            if (string.IsNullOrEmpty(serviceName))
            {
                throw get_TechnicalException_error_serviceName_null();
            }
            ServiceConfiguration serviceConfiguration = FacadeHelper.GetServiceConfiguration(providerName, serviceName);
            Type reqType = Try_get_reqType(providerName, serviceConfiguration);


            var wRequest = (IServiceContract)Fwk.HelperFunctions.SerializationFunctions.DeSerializeObjectFromJson(reqType, jsonRequest);

            wRequest.ContextInformation.HostName = hostContext.HostName;
            wRequest.ContextInformation.HostIp   = hostContext.HostIp;

            IServiceContract res     = ExecuteService(providerName, (IServiceContract)wRequest);
            Type             resType = Type.GetType(serviceConfiguration.Response);

            if (resType == null)
            {
                throw new TechnicalException(string.Concat("El servicio ", serviceName, " no se encuentra configurado verifique el Response: ", serviceConfiguration.Response));
            }

            wResult = Fwk.HelperFunctions.SerializationFunctions.SerializeObjectToJson(resType, res);
            return(wResult);
        }
Example #7
0
        /// <summary>
        /// Ejecuta un servicio de negocio dentro de un ámbito transaccional.
        /// </summary>
        /// <param name="pRequest">XML con datos de entrada.</param>
        /// <param name="serviceConfiguration">configuración del servicio.</param>
        /// <returns>XML con datos de salida del servicio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public static IServiceContract RunTransactionalProcess(IServiceContract pRequest, ServiceConfiguration serviceConfiguration)
        {
            IServiceContract        wResult;
            TransactionScopeHandler wTransactionScopeHandler = CreateTransactionScopeHandler(serviceConfiguration);
            ServiceError            wServiceError            = null;

            //  ejecución del servicio.
            wTransactionScopeHandler.InitScope();
            wResult = RunService(pRequest, serviceConfiguration, out wServiceError);

            if (wServiceError == null)
            {
                wTransactionScopeHandler.Complete();
            }
            else
            {
                wTransactionScopeHandler.Abort();
            }


            wTransactionScopeHandler.Dispose();
            wTransactionScopeHandler = null;

            return(wResult);
        }
Example #8
0
        public TResult <List <CProject> > GetProjectsAndLayers(string userinput)
        {
            try
            {
                //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                IServiceContract m_ComosAPIService = GetComosAPI();
                List <CProject>  projects          = m_ComosAPIService.GetProjectsAndLayers(userinput);
                return(new TResult <List <CProject> >()
                {
                    Status = true,
                    data = projects,
                    Message = null,
                });
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog(ex.Message);

                return(new TResult <List <CProject> >()
                {
                    Status = false,
                    data = null,
                    Message = ex.Message,
                });
            }
        }
Example #9
0
        private void joinOverRPC(String fullURL)
        {
            IServiceContract proxy = XmlRpcProxyGen.Create <IServiceContract>();

            proxy.Url = fullURL;
            bool result = proxy.addNode(thisMachineIpnPort.getIPnPort());
        }
Example #10
0
        private void signOffOverRPC(String fullUrl)
        {
            IServiceContract proxy = XmlRpcProxyGen.Create <IServiceContract>();

            proxy.Url = fullUrl;
            bool result = proxy.deleteNode(thisMachineIpnPort.getIPnPort());
        }
Example #11
0
        private void addOverRPC(String fullUrl, String message)
        {
            IServiceContract proxy = XmlRpcProxyGen.Create <IServiceContract>();

            proxy.Url = fullUrl;
            int result = proxy.result_update(message);
        }
Example #12
0
        public TResult <bool> ForceCrash(string ctype)
        {
            if (ctype == "full")
            {
                //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                IServiceContract m_ComosAPIService = GetComosAPI();
                TResult <bool>   result            = m_ComosAPIService.ForceCrash(ctype);
                return(result);
            }

            if (ctype == "internal")
            {
                try {
                    //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                    //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                    IServiceContract m_ComosAPIService = GetComosAPI();
                    TResult <bool>   result            = m_ComosAPIService.ForceCrash(ctype);
                    return(result);
                }
                catch (Exception)
                {
                }
            }
            return(new TResult <bool>()
            {
                data = false,
                Message = "",
                Status = false,
            });
        }
Example #13
0
        /// <summary>
        /// Ejecuta un servicio de negocio.
        /// </summary>
        /// <param name="providerName">Nombre del proveedor de metadata de servicios.-</param>
        /// <param name="serviceName">Nombre del servicio de negocio.</param>
        /// <param name="pXmlRequest">XML con datos de entrada para la  ejecución del servicio.</param>
        /// <returns>XML con el resultado de la  ejecución del servicio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public static string ExecuteService(string providerName, string serviceName, string pXmlRequest)
        {
            string wResult;

            ServiceConfiguration wServiceConfiguration = FacadeHelper.GetServiceConfiguration(providerName, serviceName);

            IServiceContract wRequest = (IServiceContract)ReflectionFunctions.CreateInstance(wServiceConfiguration.Request);

            if (wRequest == null)
            {
                TechnicalException te = new TechnicalException(string.Concat("El despachador de servicio no pudo continuar debido\r\na que no logro construir el requets del servicio: ",
                                                                             serviceName, "\r\nVerifique que se encuentre los componentes necesarios para su ejecucion esten en el servidor de aplicación. "));

                Fwk.Exceptions.ExceptionHelper.SetTechnicalException <StaticFacade>(te);

                if (string.IsNullOrEmpty(ConfigurationsHelper.HostApplicationName))
                {
                    te.Source = "Despachador de servicios en " + Environment.MachineName;
                }
                else
                {
                    te.Source = ConfigurationsHelper.HostApplicationName;
                }

                te.ErrorId = "7003";
                throw te;
            }
            wRequest.SetXml(pXmlRequest);

            wResult = ExecuteService(providerName, wRequest).GetXml();

            return(wResult);
        }
Example #14
0
 /// <summary>
 /// Run a qeury and return the results as a CQueryResult.
 /// </summary>
 /// <param name="user">Usario registro no COMOS.</param>
 /// <param name="projectname">Nome da projeto</param>
 /// <param name="workinglayer">ID da camada</param>
 /// <param name="query_fullname">System Full Name da Query object.</param>
 /// <param name="startobject_fullname"></param>
 /// <returns></returns>
 public TResult <CQueryResult> ExecuteQuery(string user, string projectname, string workinglayer, string query_fullname, string startobject_fullname)
 {
     try
     {
         int wo_id = 0;
         if (!int.TryParse(workinglayer, out wo_id))
         {
             return(null);
         }
         //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
         //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
         IServiceContract       m_ComosAPIService = GetComosAPI();
         TResult <CQueryResult> result            = m_ComosAPIService.ExecuteQuery(user, projectname, wo_id, query_fullname, startobject_fullname);
         return(result);
     }
     catch (Exception ex)
     {
         LogHandler.WriteLog(ex.Message);
         return(new TResult <CQueryResult>()
         {
             Status = false,
             data = null,
             Message = ex.Message,
         });
     }
 }
Example #15
0
        private void button2_Click(object sender, RibbonControlEventArgs e)
        {
            var priv = ThisAddIn.Wallets.FirstOrDefault(x => x.Address == ThisAddIn.Menu.WalletCombo.Text);

            if (priv == null)
            {
                return;
            }

            var actdoc = this.application.ActiveDocument.FullName;

            var plainFile = $"{this.application.ActiveDocument.FullName}";

            this.application.ActiveDocument.Close();

            string address = "net.pipe://localhost/ShareFileService";

            NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
            EndpointAddress     ep      = new EndpointAddress(address);
            IServiceContract    channel = ChannelFactory <IServiceContract> .CreateChannel(binding, ep);

            channel.ShareFile(plainFile, "pepito", "Marianico");

            this.application.Documents.Open(plainFile);

            var w = new AskInfo()
            {
                Title = "Paste your private key"
            };

            w.BtOk.Click += (o, args) =>
            {
                w.Close();
            };
        }
Example #16
0
        /// <summary>
        /// Solo chequea si existe el proveedor. Si no, lanza una excepción.-
        /// </summary>
        /// <param name="providerName"></param>
        static void CheckWrapperExist(string providerName, IServiceContract res)
        {
            //Dado que el proveedor por defecto es agregado como String.Empty
            if (String.IsNullOrEmpty(providerName))
            {
                providerName = _DefaultProviderName;
            }

            if (!_WraperPepository.ContainsKey(providerName))
            {
                TechnicalException te;
                if (providerName.Equals(_DefaultProviderName))
                {
                    te = new TechnicalException(string.Concat("El proveedor de configuración del wrapper por defecto del lado del cliente, no existe, verifique en el archivo de configuracion si existe la seccion FwkWrapper y el proveedor por defecto"));
                }
                else
                {
                    te = new TechnicalException(string.Concat("El proveedor de configuración del wrapper ", providerName, " del lado del cliente, no existe, verifique en el archivo de configuracion si existe la seccion FwkWrapper y el proveedor mencionado"));
                }

                te.ErrorId = "6000";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(WrapperFactory));
                res.Error = ProcessConnectionsException.Process(te);
            }
        }
Example #17
0
 public TResult <string> GetObjectDetails(string user, string projectname, string workinglayer, string object_sysuid)
 {
     try
     {
         int wo_id = 0;
         if (!int.TryParse(workinglayer, out wo_id))
         {
             return(null);
         }
         //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
         //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
         IServiceContract m_ComosAPIService = GetComosAPI();
         string           result            = m_ComosAPIService.GetObjectDetails(user, projectname, wo_id, object_sysuid);
         return(new TResult <string>()
         {
             Status = true,
             data = result,
             Message = null,
         });
     }
     catch (Exception ex)
     {
         LogHandler.WriteLog(ex.Message);
         return(new TResult <string>()
         {
             Status = false,
             data = null,
             Message = ex.Message,
         });
     }
 }
Example #18
0
        //init tcpBinding
        public static IServiceContract init_tcpBinding()
        {
            EndpointAddress  epAdd = new EndpointAddress("net.tcp://localhost/SERVICES");
            IServiceContract proxy = ChannelFactory <IServiceContract> .CreateChannel(new NetTcpBinding(), epAdd);

            return(proxy);
        }
Example #19
0
        /// <summary>
        /// Ejecuta un servicio 
        /// </summary>
        /// <param name="providerName">Proveedor de metadata</param>
        /// <param name="pReq">Interfaz de contrato de servicio.- interfaz que implementan todos los request y responsees</param>
        /// <returns><see cref="IServiceContract"/></returns>
        public IServiceContract ExecuteService(string providerName, IServiceContract pReq)
        {

            SimpleFacade wSimpleFacade = CreateSimpleFacade();
            IServiceContract wRsponse = wSimpleFacade.ExecuteService(providerName, pReq);
            return wRsponse;

        }
Example #20
0
        /// <summary>
        /// Ejecuta un servicio
        /// </summary>
        /// <param name="providerName">Proveedor de metadata</param>
        /// <param name="pReq">Interfaz de contrato de servicio.- interfaz que implementan todos los request y responsees</param>
        /// <returns><see cref="IServiceContract"/></returns>
        public IServiceContract ExecuteService(string providerName, IServiceContract pReq)
        {
            Console.WriteLine("Executing " + pReq.ServiceName + " " + DateTime.Now.ToString());
            Console.WriteLine("--------Client IP  " + pReq.ContextInformation.HostIp + " Client Name" + pReq.ContextInformation.HostName);
            SimpleFacade     wSimpleFacade = CreateSimpleFacade();
            IServiceContract wRsponse      = wSimpleFacade.ExecuteService(providerName, pReq);

            return(wRsponse);
        }
Example #21
0
        public TResult <CQueryResult> SearchDevicesByNameAndDescriptionWithFilter(string projectname, string workinglayer, string language, string tosearch, string filter)
        {
            //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
            //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
            IServiceContract m_ComosAPIService = GetComosAPI();
            var result = m_ComosAPIService.SearchDevicesByNameAndDescription(projectname, workinglayer, language, tosearch, filter);

            return(result);
        }
Example #22
0
        /// <summary>
        /// Ejecuta un servicio de negocio.
        /// </summary>
        /// <param name="providerName">Nombre del proveedor de metadata de servicios.-</param>
        /// <param name="pRequest">Request con datos de entrada para la  ejecución del servicio.</param>
        /// <returns>XML con el resultado de la  ejecución del servicio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public IServiceContract ExecuteService(string providerName, IServiceContract pRequest)
        {
            IServiceContract wResult = null;

            if (string.IsNullOrEmpty(pRequest.ServiceName))
            {
                throw get_TechnicalException_error_serviceName_null();
            }
            Boolean wExecuteOndispatcher = true;

            IRequest             req = (IRequest)pRequest;
            ServiceConfiguration wServiceConfiguration = FacadeHelper.GetServiceConfiguration(providerName, pRequest.ServiceName);

            //establezco el nombre del proveedor de seguridad al request
            req.SecurityProviderName = FacadeHelper.GetProviderInfo(providerName).SecurityProviderName;


            req.ContextInformation.SetProviderName(providerName);
            //if (String.IsNullOrEmpty(req.ContextInformation.DefaultCulture))
            //    req.ContextInformation.DefaultCulture = FacadeHelper.GetProviderInfo(providerName).DefaultCulture;

            // Validación de disponibilidad del servicio.
            FacadeHelper.ValidateAvailability(wServiceConfiguration, out wResult);
            if (wResult != null)
            {
                if (wResult.Error != null)
                {
                    return(wResult);
                }
            }

            // Caching del servicio.
            if (req.CacheSettings != null && req.CacheSettings.CacheOnServerSide) //--------->>> Implement the cache factory
            {
                wResult = GetCaheDataById(req, wServiceConfiguration);
                if (wResult != null)
                {
                    wExecuteOndispatcher = false;
                }
            }
            // Realiza la ejecucion del servicio
            if (wExecuteOndispatcher)
            {
                //  ejecución del servicio.
                if (wServiceConfiguration.TransactionalBehaviour == Fwk.Transaction.TransactionalBehaviour.Suppres)
                {
                    wResult = FacadeHelper.RunNonTransactionalProcess(pRequest, wServiceConfiguration);
                }
                else
                {
                    wResult = FacadeHelper.RunTransactionalProcess(pRequest, wServiceConfiguration);
                }
            }

            return(wResult);
        }
Example #23
0
        public TResult <bool> UploadFile(string filename, System.IO.Stream reader)
        {
            System.Diagnostics.Debug.Assert(false);
            try
            {
                LogHandler.WriteLog("Service.cs: UploadFile.  " + filename, EventLogEntryType.Information);

                string user    = System.Web.HttpContext.Current.Request.Headers["user"];
                string project = System.Web.HttpContext.Current.Request.Headers["projectname"];
                string layer   = System.Web.HttpContext.Current.Request.Headers["layer"];
                string uid     = System.Web.HttpContext.Current.Request.Headers["owner"];

                //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                IServiceContract m_ComosAPIService = GetComosAPI();

                RemoteFileInfo fileInfo = new RemoteFileInfo()
                {
                    FileByteStream = reader,
                    Project        = project,
                    FullFileName   = "",
                    Owner          = uid,
                    Workinglayer   = layer,
                    FileName       = filename,
                    Description    = "",
                };

                m_ComosAPIService.UploadFileToComosDevice(fileInfo);

                //using (var write = File.OpenWrite("c:\\temp\\"+filename))
                //{
                //    byte[] buffer = new byte[1024];
                //    int size = 0;
                //    //var reader = System.Web.HttpContext.Current.Request.GetBufferedInputStream();
                //    while ((size = reader.Read(buffer, 0, 1024)) != 0)
                //    {
                //        write.Write(buffer, 0, size);
                //    }
                //}
            }
            catch (Exception ex)
            {
                return(new TResult <bool>()
                {
                    Status = false,
                    Message = ex.Message,
                    data = false
                });
            }
            //return null;
            return(new TResult <bool>()
            {
                data = true,
                Status = true,
            });
        }
Example #24
0
        public System.IO.Stream DownloadFile(string uidDocument, string project_name, string working_layer, string revision_file)
        {
            string downloadFilePath = "";


            try
            {
                IServiceContract m_ComosAPIService = GetComosAPI();

                int id_working_layer        = int.Parse(working_layer);
                System.IO.FileInfo fileInfo = null;

                bool isrev = false;

                if (revision_file.ToUpper() == "TRUE")
                {
                    isrev = true;
                }

                downloadFilePath = m_ComosAPIService.DownloadFile(uidDocument, project_name, id_working_layer, isrev);

                LogHandler.WriteLog("Service.CS:Download::" + downloadFilePath);

                fileInfo = new System.IO.FileInfo(downloadFilePath);

                if (fileInfo.Exists)
                {
                    string fileName   = fileInfo.Name;
                    String headerInfo = "attachment; filename=" + fileName;
                    WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";

                    /*result.Status = true;
                     * result.data = System.IO.File.OpenRead(downloadFilePath);
                     * return result;
                     */
                    return(System.IO.File.OpenRead(downloadFilePath));
                }
                else
                {
                    LogHandler.WriteLog("Arquivo não encontrado!::" + downloadFilePath);
                    return(null);

                    //    result.Message = "Arquivo não encontrado!";
                    //  return result;
                }
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog(ex.Message + "::" + downloadFilePath);
                //result.Message = "Erro: " + ex.Message;
                //return result;
                return(null);
            }
        }
Example #25
0
        /// <summary>
        /// Almacena informacion de auditoria.-
        /// Llama a StaticLogger y carga el log auditando los datos del Request de entrada
        /// </summary>
        /// <param name="pRequest">Request</param>
        /// <param name="wResult">Response</param>
        /// <param name="logType">Audit default</param>
        public static void LogSuccessfulExecution(IServiceContract pRequest, IServiceContract wResult, Fwk.Logging.EventType logType = Fwk.Logging.EventType.Audit)
        {
            fwk_ServiceAudit audit = new fwk_ServiceAudit();

            audit.LogTime     = System.DateTime.Now;
            audit.ServiceName = pRequest.ServiceName;
            audit.Send_Time   = pRequest.ContextInformation.HostTime;
            if (Fwk.HelperFunctions.DateFunctions.IsSqlDateTimeOutOverflow(wResult.ContextInformation.HostTime) == false)
            {
                audit.Resived_Time = wResult.ContextInformation.HostTime;
            }
            else
            {
                audit.Resived_Time = wResult.ContextInformation.HostTime = DateTime.Now;
            }

            audit.Send_UserId  = pRequest.ContextInformation.UserId;
            audit.Send_Machine = pRequest.ContextInformation.HostName;

            audit.Dispatcher_Instance_Name = FacadeHelper.ServiceDispatcherConfig.InstanseName;
            audit.ApplicationId            = pRequest.ContextInformation.AppId;

            try
            {
                audit.RequetsText  = HelperFunctions.SerializationFunctions.SerializeObjectToJson_Newtonsoft(pRequest);
                audit.ResponseText = HelperFunctions.SerializationFunctions.SerializeObjectToJson_Newtonsoft(wResult.Error);
            }
            catch
            {
                //Si existe error al serializar json almacena el xml
                audit.RequetsText  = pRequest.GetXml();
                audit.ResponseText = wResult.Error.GetXml();
            }

            audit.Logtype = Enum.GetName(typeof(Fwk.Logging.EventType), logType);


            try
            {
                using (FwkDatacontext context = new FwkDatacontext(System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationsHelper.ServiceDispatcherConnection].ConnectionString))
                {
                    context.fwk_ServiceAudit.InsertOnSubmit(audit);
                    context.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                TechnicalException te = new TechnicalException("No se pudo insertar la auditoria de la ejecucion de un servicio.-  " + ex.Message.ToString(), ex);
                te.ErrorId = "7010";
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException(te, typeof(Audit));
                LogDispatcherError(te);

                LogSuccessfulExecution_Old(pRequest, wResult);
            }
        }
Example #26
0
        /// <summary>
        /// Ejecuta un servicio de negocio.
        /// </summary>
        /// <param name="pRequest">Request con datos de entrada para la  ejecución del servicio.</param>
        /// <returns>Dataset con datos de respuesta del servicio.</returns>
        /// <date>2007-08-24T00:00:00</date>
        /// <author>moviedo</author>
        static TResponse ExecuteService <TRequest, TResponse>(TRequest pRequest)
            where TRequest : IServiceContract
            where TResponse : IServiceContract, new()
        {
            TResponse wResponse = new TResponse();

            #region fill data
            SearchRelatedDomainsByUserRes wSearchRelatedDomainsByUserRes = new SearchRelatedDomainsByUserRes();
            wSearchRelatedDomainsByUserRes.BusinessData = new DomainList();
            Domain d = new Domain();
            d.DomainId = 111;
            d.Name     = "Dominio A";
            wSearchRelatedDomainsByUserRes.BusinessData.Add(d);
            #endregion

            Boolean wExecuteOndispatcher = true;
            //Si no ocurrio algun error
            if (wResponse.Error == null)
            {
                IServiceContract res = null;
                IRequest         req = (IRequest)pRequest;
                // Caching del servicio.
                if (req.CacheSettings != null && req.CacheSettings.CacheOnClientSide) //--------------------------------------->>> Implement the cache factory
                {
                    res       = ServiceCacheMannager.Get(req);
                    wResponse = (TResponse)res;
                    //Si estaba en la cache no es necesario llamar al despachador de servicio
                    if (wResponse != null)
                    {
                        wExecuteOndispatcher = false;
                    }
                }


                if (wExecuteOndispatcher)
                {
                    res       = (IServiceContract)wSearchRelatedDomainsByUserRes;
                    wResponse = (TResponse)res;
                    //wResponse = _Wrapper.ExecuteService<TRequest, TResponse>(pRequest);

                    //Si aplica cache y se llamo a la ejecucion se debe almacenar en cache para proxima llamada
                    if (req.CacheSettings != null && req.CacheSettings.CacheOnClientSide)
                    {
                        //Es posible que la ejecucion produzca algun error y por lo tanto no se permitira
                        //su almacen en cache
                        if (wResponse.Error == null)
                        {
                            ServiceCacheMannager.Add(req, wResponse);
                        }
                    }
                }
            }

            return(wResponse);
        }
Example #27
0
        private void _createDuplexChannelFactory()
        {
            var channelFactory = new DuplexChannelFactory <IServiceContract>(_callbackContractImplementation,
                                                                             _clientPipeBinding, new EndpointAddress("net.pipe://localhost/WCFBasis"));

            channelFactory.Faulted += _onChannelFactoryFailure;

            _serviceCommunicationChannel = channelFactory.CreateChannel();

            _duplexChannelFactory = channelFactory;
        }
Example #28
0
        /// <summary>
        /// Ejecuta un servicio de negocio.
        /// </summary>
        /// <param name="providerName">Nombre del proveedor de metadata de servicios.-</param>
        /// <param name="pRequest">Request con datos de entrada para la  ejecución del servicio.</param>
        /// <returns>XML con el resultado de la  ejecución del servicio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public IServiceContract ExecuteService(string providerName, IServiceContract pRequest)
        {
            IServiceContract wResult = null;
            if (string.IsNullOrEmpty(pRequest.ServiceName))
            {

                TechnicalException te = new TechnicalException("El despachador de servicio no pudo continuar debido\r\n a que el nombre del servicio no fue establecido");
                Fwk.Exceptions.ExceptionHelper.SetTechnicalException<SimpleFacade>(te);

                te.ErrorId = "7005";
                throw te;
            }
            Boolean wExecuteOndispatcher = true;

            IRequest req = (IRequest)pRequest;
            ServiceConfiguration wServiceConfiguration = FacadeHelper.GetServiceConfiguration(providerName, pRequest.ServiceName);


            
            //establezco el nombre del proveedor de seguridad al request
            req.SecurityProviderName = FacadeHelper.GetProviderInfo(providerName).SecurityProviderName;

            
            req.ContextInformation.SetProviderName(providerName);
            //if (String.IsNullOrEmpty(req.ContextInformation.DefaultCulture))
            //    req.ContextInformation.DefaultCulture = FacadeHelper.GetProviderInfo(providerName).DefaultCulture;

            // Validación de disponibilidad del servicio.
            FacadeHelper.ValidateAvailability(wServiceConfiguration, out wResult);
            if (wResult != null)
                if (wResult.Error != null) return wResult;

            // Caching del servicio.
            if (req.CacheSettings != null && req.CacheSettings.CacheOnServerSide) //--------->>> Implement the cache factory
            {

                wResult = GetCaheDataById(req, wServiceConfiguration);
                if (wResult != null) wExecuteOndispatcher = false;

            }
            // Realiza la ejecucion del servicio
            if (wExecuteOndispatcher)
            {
                //  ejecución del servicio.
                if (wServiceConfiguration.TransactionalBehaviour == Fwk.Transaction.TransactionalBehaviour.Suppres)
                    wResult = FacadeHelper.RunNonTransactionalProcess(pRequest, wServiceConfiguration);
                else
                    wResult = FacadeHelper.RunTransactionalProcess(pRequest, wServiceConfiguration);


            }

            return wResult;
        }    
Example #29
0
        static void Main(string[] args)
        {
            ChannelFactory <IServiceContract> cf = new ChannelFactory <IServiceContract>(
                new WebHttpBinding(), "http://www.example.com/xmlrpc");

            cf.Endpoint.Behaviors.Add(new XmlRpcEndpointBehavior());

            IServiceContract client = cf.CreateChannel();

            // you can now call methods from your remote service
            string answer = client.Hello("World");
        }
Example #30
0
        static void Main(string[] args)
        {
            Console.Title = "Client";
            ChannelFactory <IServiceContract> factory = new ChannelFactory <IServiceContract>(new BasicHttpBinding(), new EndpointAddress("http://localhost:8000//ServiceWCF"));
            IServiceContract service = factory.CreateChannel();
            double           num     = service.method("double");

            Console.WriteLine($"Double : {num}");

            Console.WriteLine("Any key");
            Console.ReadKey();
        }
Example #31
0
        /// <summary>
        /// Almacena un response en cahce
        /// </summary>
        /// <param name="pRequest"></param>
        /// <param name="pResult"></param>
        public static void Add(IServiceContract pRequest, IServiceContract pResult)
        {
            IRequest req = (IRequest)pRequest;

            if (string.IsNullOrEmpty(req.CacheSettings.ResponseCacheId))
                req.CacheSettings.ResponseCacheId = pRequest.ServiceName;

            CacheManager.Add(
                req.CacheSettings.ResponseCacheId,
                pResult,
                req.CacheSettings.ExpirationTime, req.CacheSettings.TimeMeasures);
        }
        /// <summary>
        /// Almacena un response en cahce
        /// </summary>
        /// <param name="pRequest"></param>
        /// <param name="pResult"></param>
        public static void Add(IServiceContract pRequest, IServiceContract pResult)
        {
            IRequest req = (IRequest)pRequest;

            if (string.IsNullOrEmpty(req.CacheSettings.ResponseCacheId))
            {
                req.CacheSettings.ResponseCacheId = pRequest.ServiceName;
            }

            CacheManager.Add(
                req.CacheSettings.ResponseCacheId,
                pResult,
                req.CacheSettings.ExpirationTime, req.CacheSettings.TimeMeasures);
        }
Example #33
0
        /// <summary>
        /// Implementa la llamada al backend atravez de la ejecucion de la SimpleFacade.
        /// Al llamar directamente a la SimpleFacade funciona como un despachador de servicios, esto lo hace
        /// debido  a aque se trata de un wrapper local.
        /// </summary>
        /// <param name="pReq">Clase request que implementa IServiceContract. No nececita pasarce el representativo xml de tal
        /// objeto, esto es para evitar serializacion innecesaria</param>
        /// <returns>Response con los resultados del servicio</returns>
        private IServiceContract ExecuteService(IServiceContract pReq)
        {
            if (_SimpleFacade == null)
            {
                _SimpleFacade = CreateSimpleFacade();
            }

            pReq.InitializeHostContextInformation();
            IServiceContract wResponse = _SimpleFacade.ExecuteService(_ServiceMetadataProviderName, pReq);

            //wResponse.InitializeHostContextInformation();

            return(wResponse);
        }
Example #34
0
        /// <summary>
        /// Valida que el servicio está disponible para ser ejecutado.
        /// </summary>
        /// <param name="serviceConfiguration">configuración del servicio.</param>
        /// <param name="result"></param>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public static void ValidateAvailability(ServiceConfiguration serviceConfiguration, out IServiceContract result)
        {
            result = null;
            // Validación de disponibilidad del servicio.
            if (!serviceConfiguration.Available)
            {
                result = TryGetResultInstance(serviceConfiguration);
                ServiceError wServiceError;

                #region < Log >
                Audit.LogNotAvailableExcecution(serviceConfiguration, out wServiceError);

                #endregion

                result.Error = wServiceError;
            }
        }
Example #35
0
 //Mtodo que audita
 static void DoAudit(ServiceConfiguration pServiceConfiguration, IServiceContract pRequest, IServiceContract wResponse)
 {
     if ((AuditMode)FacadeHelper.ServiceDispatcherConfig.AuditMode == AuditMode.Required)
         Audit.LogSuccessfulExecution(pRequest, wResponse);
     else
     {
         if (pServiceConfiguration.Audit == true)
         {
             Audit.LogSuccessfulExecution(pRequest, wResponse);
         }
     }
     //Si ocurre un error cualquiera se loguea el mismo
     if (wResponse.Error != null)
         Audit.LogNonSucessfulExecution(pRequest, wResponse);
 }
Example #36
0
        /// <summary>
        /// Ejecuta el servicio de negocio.
        /// </summary>
        /// <param name="pRequest">Request de entrada que se pasa al servicio</param>
        /// <param name="pServiceConfiguration">configuración del servicio.</param>
        /// <param name="pserviError">serviError</param> 
        /// <returns>XML que representa el resultado de la  ejecución del servicio.</returns>
        /// <date>2007-08-07T00:00:00</date>
        /// <author>moviedo</author>
        static IServiceContract RunService(IServiceContract pRequest, ServiceConfiguration pServiceConfiguration, out ServiceError pserviError)
        {
            IServiceContract wResponse = null;

            try
            {
                pRequest.InitializeServerContextInformation();
                // obtención del Response.
                Type wServiceType = ReflectionFunctions.CreateType(pServiceConfiguration.Handler);

                object wServiceInstance = Activator.CreateInstance(wServiceType);
                wResponse =
                    (wServiceType.GetMethod("Execute").Invoke(wServiceInstance, new object[] { pRequest }) as
                     IServiceContract);

                wResponse.InitializeServerContextInformation();


            }

            #region [manage Exception]
            catch (System.IO.FileNotFoundException ex)
            {

                wResponse = GetResponse(pServiceConfiguration);// (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Response);

                wResponse.Error = new ServiceError();
                System.Text.StringBuilder wMessage = new StringBuilder();

                wResponse.Error.ErrorId = "7003";

                #region Message
                wMessage.Append("El despachador de servicio no pudo encontrar alguna de los siguientes assemblies \r\n");

                wMessage.Append("o alguna de sus dependencias: \r\n");

                wMessage.Append("Servicio: ");
                wMessage.Append(pServiceConfiguration.Handler);
                wMessage.Append(Environment.NewLine);

                wMessage.Append("Request: ");
                wMessage.Append(pServiceConfiguration.Request);
                wMessage.Append(Environment.NewLine);

                wMessage.Append("Response: ");
                wMessage.Append(pServiceConfiguration.Response);
                wMessage.Append(Environment.NewLine);

                wMessage.Append("Mensaje original :");
                wMessage.Append(Environment.NewLine);
                wMessage.Append(ex.Message);
                #endregion

                wResponse.Error.Message = wMessage.ToString();
                FillServiceError(wResponse.Error, ex);

            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                wResponse = GetResponse(pServiceConfiguration);
                wResponse.Error = GetServiceError(ex.InnerException);

            }
            catch (TypeLoadException tl)
            {
                wResponse = GetResponse(pServiceConfiguration);
                System.Text.StringBuilder wMessage = new StringBuilder();
                wResponse.Error = new ServiceError();

                wResponse.Error.ErrorId = "7002";
                wMessage.Append("No se encuentra el o los assemblies para cargar el servicio " + pServiceConfiguration.Name);
                wMessage.AppendLine();
                wMessage.AppendLine(tl.Message);
                wResponse.Error.Message = wMessage.ToString();
                FillServiceError(wResponse.Error, tl);
            }
            catch (Exception ex)
            {
                wResponse = GetResponse(pServiceConfiguration);// (IServiceContract)ReflectionFunctions.CreateInstance(pServiceConfiguration.Response);
                wResponse.Error = GetServiceError(ex);
            }

            #endregion

            pserviError = wResponse.Error;

            #region < Log >
            //Audito ensegundo plano
            Action actionAudit = () => { DoAudit(pServiceConfiguration, pRequest, wResponse); };
            Task.Factory.StartNew(actionAudit);


            #endregion




            return wResponse;

        }
Example #37
0
 /// <summary>
 /// Ejecuta un servicio de negocio dentro de un ámbito transaccional.
 /// </summary>
 /// <param name="pRequest">Request con datos de entrada.</param>
 /// <param name="serviceConfiguration">configuración del servicio.</param>
 /// <returns>XML con datos de salida del servicio.</returns>
 /// <date>2008-04-07T00:00:00</date>
 /// <author>moviedo</author>
 public static IServiceContract RunNonTransactionalProcess(IServiceContract pRequest, ServiceConfiguration serviceConfiguration)
 {
     ServiceError wServiceError = null;
     return RunService(pRequest, serviceConfiguration, out wServiceError);
 }
Example #38
0
        /// <summary>
        /// Ejecuta un servicio de negocio dentro de un ámbito transaccional.
        /// </summary>
        /// <param name="pRequest">XML con datos de entrada.</param>
        /// <param name="serviceConfiguration">configuración del servicio.</param>
        /// <returns>XML con datos de salida del servicio.</returns>
        /// <date>2008-04-07T00:00:00</date>
        /// <author>moviedo</author>
        public static IServiceContract RunTransactionalProcess(IServiceContract pRequest, ServiceConfiguration serviceConfiguration)
        {
            IServiceContract wResult;
            TransactionScopeHandler wTransactionScopeHandler = CreateTransactionScopeHandler(serviceConfiguration);
            ServiceError wServiceError = null;

            //  ejecución del servicio.
            wTransactionScopeHandler.InitScope();
            wResult = RunService(pRequest, serviceConfiguration, out wServiceError);

            if (wServiceError == null)
                wTransactionScopeHandler.Complete();
            else
                wTransactionScopeHandler.Abort();


            wTransactionScopeHandler.Dispose();
            wTransactionScopeHandler = null;

            return wResult;
        }
Example #39
0
 /// <summary>
 /// Ejecuta un servicio 
 /// </summary>
 /// <param name="providerName">Proveedor de metadata</param>
 /// <param name="pServiceName">Nombre del servicio</param>
 /// <param name="pReq">Interfaz de contrato de servicio.- interfaz que implementan todos los request y responsees</param>
 /// <returns><see cref="IServiceContract"/></returns>
 public IServiceContract ExecuteService(string providerName, string pServiceName, IServiceContract pReq)
 {
     pReq.ServiceName = pServiceName;
     return this.ExecuteService(providerName, pReq);
 }
Example #40
0
        /// <summary>
        /// Almacena informacion de auditoria.- 
        /// Llama a StaticLogger y carga el log auditando los datos del Request de entrada
        /// </summary>
        /// <param name="pRequest">Request</param>
        /// <param name="wResult">Response</param>
        internal static void LogSuccessfulExecution(IServiceContract pRequest, IServiceContract wResult)
        {
            fwk_ServiceAudit audit = new fwk_ServiceAudit();

            audit.LogTime = System.DateTime.Now;
            audit.ServiceName = pRequest.ServiceName;
            audit.Send_Time = pRequest.ContextInformation.HostTime;
            if(Fwk.HelperFunctions.DateFunctions.IsSqlDateTimeOutOverflow(wResult.ContextInformation.HostTime)==false)
                audit.Resived_Time = wResult.ContextInformation.HostTime;
            else
            {
                audit.Resived_Time = wResult.ContextInformation.HostTime = DateTime.Now;
                
            }
            
            audit.Send_UserId = pRequest.ContextInformation.UserId;
            audit.Send_Machine = pRequest.ContextInformation.HostName;

            audit.Dispatcher_Instance_Name = FacadeHelper.ServiceDispatcherConfig.InstanseName;
            audit.ApplicationId = pRequest.ContextInformation.AppId;

            audit.Requets = TypeFunctions.ConvertStringToByteArray(pRequest.GetXml());
            audit.Response = TypeFunctions.ConvertStringToByteArray(wResult.GetXml());

           

            try
            {
                using (FwkDatacontext context = new FwkDatacontext(System.Configuration.ConfigurationManager.ConnectionStrings[ConfigurationsHelper.ServiceDispatcherConnection].ConnectionString))
                {
                    context.fwk_ServiceAudits.InsertOnSubmit(audit);
                    context.SubmitChanges();
                }
    

            }
            catch(Exception)
            {
                
                LogSuccessfulExecution_Old(pRequest, wResult);
            }
            

        }
Example #41
0
        /// <summary>
        /// Almacena informacion de auditoria.- 
        /// Llama a StaticLogger y carga el log auditando los datos del Request de entrada
        /// </summary>
        /// <param name="pRequest">Request</param>
        /// <param name="pResult">Response</param>
        internal static void LogSuccessfulExecution_Old(IServiceContract pRequest, IServiceContract pResult)
        {
            StringBuilder s = new StringBuilder();
            s.AppendLine("<Request>");
            s.AppendLine(pRequest.GetXml());
            s.AppendLine("</Request>");
            s.AppendLine("<Response>");
            s.AppendLine(pResult.GetXml());
            s.AppendLine("</Response>");

            try
            {
                ///TODO: Ver prefijos de logs
                Event ev = new Event(EventType.Audit, Fwk.Bases.ConfigurationsHelper.HostApplicationName, s.ToString(), pRequest.ContextInformation.HostName, pRequest.ContextInformation.UserId);
                Fwk.Logging.StaticLogger.Log(ev);
                    
            }
            catch { }
            finally
            { s = null; }

        }