public override bool IsAuthorized(ServiceInterface.Auth.IAuthSession session, ServiceInterface.Auth.IOAuthTokens tokens, ServiceInterface.Auth.Auth request = null)
        {
            if (request != null)
            {
                if (!LoginMatchesSession(session, request.UserName)) return false;
            }

            // For GoogleOpenId, AccessTokenSecret is null/empty, but UserId is populated w/ authenticated url from Google
            return tokens != null && !string.IsNullOrEmpty(tokens.UserId);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 安装一个服务
        /// </summary>
        /// <param name="service">需要安装的服务</param>
        /// <param name="SerivceName">需要安装的服务的名字</param>
        public static void InstallService(ServiceInterface service, string ServiceName)
        {
            Dictionary<string, ServiceInterface> sv = services;
            if (sv.ContainsKey(ServiceName))
            {
                UnInstallSerive(ServiceName);
            }

            //启动服务
            service.OnServiceStart();
            sv.Add(ServiceName, service);
        }
Exemplo n.º 3
0
        public static void GenerateCode(List <HotchnerTable> tableList)
        {
            Backend_Code.PreProcessFolder(ArchorsFolder,
                                          out var entityFolderPath,
                                          out var daoFolderPath,
                                          out var mapperFolderPath,
                                          out var controllerFolderPath,
                                          out var serviceImplFolderPath,
                                          out var serviceInterfaceFolderPath);

            Entity.Generate(entityFolderPath);
            Dao.Generate(daoFolderPath, tableList);
            Mapper.Generate(mapperFolderPath, tableList);
            Controller.Generate(controllerFolderPath, tableList);
            ServiceImpl.Generate(serviceImplFolderPath, tableList);
            ServiceInterface.Generate(serviceInterfaceFolderPath, tableList);
        }
Exemplo n.º 4
0
        public virtual void Start(Ruleset ruleset, ServiceInterface serviceInterface, EventLog eventLog)
        {
            if (ruleset == null)
            {
                throw new ArgumentNullException("ruleset", "ruleset must be non null.");
            }
            if (serviceInterface == null)
            {
                throw new ArgumentNullException("serviceInterface", "serviceInterface must be non null.");
            }
            if (_IsStarted)
            {
                throw new InvalidOperationException("Core is already started.");
            }

            _EventLog = eventLog;

            _ServiceInterface = serviceInterface;
            Ruleset           = ruleset;

            //if (_Driver.IsRunning == false)// TODO: This is not covered by tests.
            _Driver.Start();

            // Subscribe to ruleset's events.
            Ruleset.Paths.RowChanged    += Paths_RowChanged;
            Ruleset.Paths.ColumnChanged += Paths_ColumnChanged;
            Ruleset.Paths.RowDeleted    += Paths_RowDeleted;
            // Populate driver with all paths.
            foreach (Ruleset.PathsRow row in Ruleset.Paths)
            {
                foreach (var path in row.ExpandedPaths)
                {
                    try
                    {
                        _Driver.SendCommand(COMMAND_TYPE.ADD, path, row.ID);
                    }
                    catch (PathAlreadyAddedException e)
                    {
                        EventLog.WriteEntry("APService", e.Message, EventLogEntryType.Warning);
                    }
                }
            }


            _IsStarted = true;
        }
Exemplo n.º 5
0
        public ComputeConnector(string uuid, string name, ServerConfiguration computeInfo)
        {
            UUID = uuid;
            Name = name;
            this.computeNodeInfo = computeInfo;
            serviceInterface = new ServiceInterface(computeNodeInfo.IpAddress, computeNodeInfo.Port);

            workers = new List<WorkerAdapter>();
            for (int i = 0; i < computeInfo.PoolSize; i++)
            {
                var workerInfo = new WorkerAdapter();
                workerInfo.Id = string.Format("Worker_{0}", i);
                workerInfo.Status = RunnerStatus.Idle;
                workerInfo.Connector = this;
                workers.Add(workerInfo);
            }
        }
Exemplo n.º 6
0
        public void TestInitialize()
        {
            ruleset          = new Ruleset();
            serviceInterface = new ServiceInterface(ruleset);

            // Creating instance of driver class.
            driverSC = new AdvSCStub();
            fltLib   = new FltLibStub();
            var ci = typeof(Driver).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
                                                   null,
                                                   new[] { typeof(AdvSC), typeof(FltLib) },
                                                   null);

            Assert.IsNotNull(ci);
            driver = (Driver)ci.Invoke(new object[] { driverSC, fltLib });

            // Creating the core instance
            core = new Core(driver);
        }
Exemplo n.º 7
0
        private CodeTypeDeclaration AddClientInterface(ServiceInterface serviceInterface)
        {
            var interfaceTypeDec = new CodeTypeDeclaration(serviceInterface.Name);

            interfaceTypeDec.IsInterface = true;

            foreach (var serviceMethod in serviceInterface.Methods)
            {
                var mth = new CodeMemberMethod();
                mth.Name       = serviceMethod.Name;
                mth.ReturnType = new CodeTypeReference(serviceMethod.MethodInfo.ReturnType);

                foreach (var parameterInfo in serviceMethod.MethodInfo.GetParameters())
                {
                    mth.Parameters.Add(new CodeParameterDeclarationExpression(parameterInfo.ParameterType, parameterInfo.Name));
                }

                interfaceTypeDec.Members.Add(mth);
            }
            return(interfaceTypeDec);
        }
Exemplo n.º 8
0
        private ACCESS_REQUEST ArrangeForCreateRuleTests(string processPath)
        {
            // User wants to create rule.
            serviceInterface = new ServiceInterface(ruleset);

            serviceInterface.AccessRequested += ((sender, e) =>
            {
                e.CreateRule = true;
                e.Allow = true;
            });
            // Request which will be thrown.
            var Request = new ACCESS_REQUEST {
                Path = "c:\\test.txt", ProcessID = 4, MessageId = 123
            };

            fltLib.SetGetMessageReturn(0, Request);
            // Add "wildcard" rule for which WaitRequest will create "specific" rule.
            AddRule(ruleset, RuleAction.Ask, Request.Path, processPath);
            core.Start(ruleset, serviceInterface, null);
            return(Request);
        }
Exemplo n.º 9
0
        public string FacilityOffLine(string HpiFacilityId)
        {
            string rv = null;

            if (AuthenticateUser(WebOperationContext.Current.IncomingRequest))
            {
                if (this.userID != HpiFacilityId)
                {
                    throw new Exception("Invalid Request Parameter");
                }
                ServiceInterface appSi = new ServiceInterface();
                rv = appSi.PutFacilityOffLine(HpiFacilityId);
            }
            else
            {
                OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                response.StatusCode = HttpStatusCode.Unauthorized;
            }

            return(rv);
        }
Exemplo n.º 10
0
        public bool HiMessage(Stream requestStream)
        {
            bool messageSaved = false;

            try
            {
                if (AuthenticateUser(WebOperationContext.Current.IncomingRequest))
                {
                    SaveHiMessageRequest requestData = new SaveHiMessageRequest();
                    UTF8Encoding         enc         = new UTF8Encoding();
                    string xmlString = string.Empty;

                    using (StreamReader reader = new StreamReader(requestStream, enc))
                    {
                        xmlString = reader.ReadToEnd();
                    }

                    XDocument xDoc = XDocument.Parse(xmlString);
                    requestData.fileName         = xDoc.Element("SaveHiMessageRequest").Element("fileName").Value;
                    requestData.messageHeader    = xDoc.Element("SaveHiMessageRequest").Element("messageHeader").Value;
                    requestData.replyToMessageID = xDoc.Element("SaveHiMessageRequest").Element("replyToMessageID").Value;
                    requestData.encryptedMessage = xDoc.Element("SaveHiMessageRequest").Element("encryptedMessage").Value;

                    ServiceInterface appSi = new ServiceInterface();
                    messageSaved = appSi.PostHpiMessage(requestData.fileName, requestData.messageHeader, requestData.replyToMessageID, requestData.encryptedMessage);
                }
                else
                {
                    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                    response.StatusCode = HttpStatusCode.Unauthorized;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Web Service Error: " + ex.Message);
            }

            return(messageSaved);
        }
Exemplo n.º 11
0
        public bool HimLog(Stream requestStream)
        {
            bool logSaved = false;

            try
            {
                if (AuthenticateUser(WebOperationContext.Current.IncomingRequest))
                {
                    SaveHimLogRequest requestData = new SaveHimLogRequest();
                    UTF8Encoding      enc         = new UTF8Encoding();
                    string            xmlString   = string.Empty;

                    using (StreamReader reader = new StreamReader(requestStream, enc))
                    {
                        xmlString = reader.ReadToEnd();
                    }

                    XDocument xDoc = XDocument.Parse(xmlString);
                    requestData.hpiFacilityId = xDoc.Element("SaveHimLogRequest").Element("hpiFacilityId").Value;
                    requestData.himLogData    = xDoc.Element("SaveHimLogRequest").Element("himLogData").Value;

                    ServiceInterface appSi = new ServiceInterface();
                    logSaved = appSi.PostHimLogFile(requestData.hpiFacilityId, requestData.himLogData);
                }
                else
                {
                    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                    response.StatusCode = HttpStatusCode.Unauthorized;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Web Service Error: " + ex.Message);
            }

            return(logSaved);
        }
Exemplo n.º 12
0
        public List <HimAppFile> HimAppUpdate(string HimVersion)
        {
            List <HimAppFile> himAppFiles = new List <HimAppFile>();

            try
            {
                if (AuthenticateUser(WebOperationContext.Current.IncomingRequest))
                {
                    ServiceInterface appSi = new ServiceInterface();
                    himAppFiles = appSi.GetHimAppUpdate(HimVersion, this.userID);
                }
                else
                {
                    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                    response.StatusCode = HttpStatusCode.Unauthorized;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Web Service Error: " + ex.Message);
            }

            return(himAppFiles);
        }
Exemplo n.º 13
0
        protected override void OnStart(string[] args)
        {
            try
            {
                if (File.Exists(_DefaultRulesetPath) == false)
                {
                    throw new FileNotFoundException("Ruleset file not found (" + _DefaultRulesetPath + ")");
                }

                _Ruleset = new Ruleset();
                _Ruleset.ReadXml(_DefaultRulesetPath);
                _Ruleset.AcceptChanges();

                var serviceInterface = ServiceInterface.Marshal(_Ruleset);

                AsyncCore.Instance.Start(_Ruleset, serviceInterface, new EventLog("APAccess", ".", "APLogger"));
            }
            catch (RemotingException ex)
            {
                var registeredChannels = string.Format("\r\n******Registered channels({0})*****\r\n", ChannelServices.RegisteredChannels.Length);
                foreach (var channel in ChannelServices.RegisteredChannels)
                {
                    registeredChannels += channel.ChannelName + "\r\n";
                }

                EventLog.WriteEntry("APService", "On start. " + BugSubmitter.FormatErrorMessage(ex) + registeredChannels, EventLogEntryType.Error);
                throw;
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("APService", "On start. " + BugSubmitter.FormatErrorMessage(ex), EventLogEntryType.Error);
                throw;
            }

            EventLog.WriteEntry("APService", "Service successfully started.", EventLogEntryType.Information);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Index()
        {
            RestMessage <List <StudentModel> > response = new RestMessage <List <StudentModel> >();

            try
            {
                ServiceInterface serviceInterface = ServiceInterface.Instance;

                response = await serviceInterface.GetDataAsync <List <StudentModel> >("student");

                if (!response.Success)
                {
                    response.StatusText = "Error fetching Student data";
                }
            }
            catch (Exception e)
            {
                response.Exception = e;
                response.SetAsBadRequest();
                response.StatusText = "Error fetching Student data";
            }

            return(Json(response));
        }
Exemplo n.º 15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string filename = "";

        List <EncoderConfig> cfgs = Utils.LoadConfig();
        EncoderConfig        cfg  = cfgs[Int32.Parse(Request.QueryString["idProfile"])];

        ServiceInterface server = new ServiceInterface();

        if (Request.QueryString["idChannel"] != null)
        {
            if (server.GetChannel(Int32.Parse(Request.QueryString["idChannel"])).isRadio)
            {
                bufferSize = 2560;
            }
            WebTvResult res = server.StartTimeShifting(Int32.Parse(Request.QueryString["idChannel"]));
            if (res.result != 0)
            {
                Utils.Log("Streamer.aspx: ERROR: StartTimeShifting failed with error: " + res.result.ToString());
                Response.Output.WriteLine("ERROR: StartTimeShifting failed with error: " + res.result.ToString());
                Response.End();
                return;
            }
            usedCard         = res.user.idCard;
            usedChannel      = res.user.idChannel;
            tvServerUsername = res.user.name;
            if (cfg.inputMethod == TransportMethod.Filename)
            {
                filename = res.rtspURL;
            }
            else
            {
                filename = res.timeshiftFile;
            }
        }
        else if (Request.QueryString["idRecording"] != null)
        {
            WebRecording rec = server.GetRecording(Int32.Parse(Request.QueryString["idRecording"]));
            filename = rec.fileName;
        }
        else if (Request.QueryString["idMovie"] != null)
        {
            WebMovie movie = server.GetMovie(Int32.Parse(Request.QueryString["idMovie"]));
            filename = movie.file;
        }
        else if (Request.QueryString["idMusicTrack"] != null)
        {
            WebMusicTrack track = server.GetMusicTrack(Int32.Parse(Request.QueryString["idMusicTrack"]));
            filename = track.file;
        }
        else if (Request.QueryString["idTvSeries"] != null)
        {
            WebSeries series = server.GetTvSeries(Request.QueryString["idTvSeries"]);
            filename = series.filename;
        }
        else if (Request.QueryString["idMovingPicture"] != null)
        {
            WebMovingPicture pic = server.GetMovingPicture(Int32.Parse(Request.QueryString["idMovingPicture"]));
            filename = pic.filename;
        }
        if (!File.Exists(filename) && !filename.StartsWith("rtsp://"))
        {
            Utils.Log("Streamer.aspx: Requested file " + filename + " does not exist.");
            return;
        }
        Response.Clear();
        Response.Buffer       = false;
        Response.BufferOutput = false;
        Response.AppendHeader("Connection", "Keep-Alive");
        Response.ContentType = "video/x-msvideo";
        Response.StatusCode  = 200;

        Stream         mediaStream = null;
        EncoderWrapper encoder     = null;
        Stream         outStream   = null;

        if (cfg.inputMethod != TransportMethod.Filename)
        {
            if (Request.QueryString["idChannel"] != null)
            {
                mediaStream = new TsBuffer(filename);
            }
            else
            {
                mediaStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            encoder = new EncoderWrapper(mediaStream, cfg);
        }
        else
        {
            encoder = new EncoderWrapper(filename, cfg);
        }

        if (cfg.useTranscoding)
        {
            outStream = encoder;
        }
        else
        {
            outStream = mediaStream;
        }

        byte[] buffer = new byte[bufferSize];
        int    read;

        try
        {
            while ((read = outStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                try
                {
                    Response.OutputStream.Write(buffer, 0, read);
                }
                catch (Exception)
                {
                    break; // stream is closed
                }
                if (Request.QueryString["idChannel"] != null)
                {
                    server.SendHeartBeat(usedChannel, usedCard, tvServerUsername);
                }
            }
        }
        catch (Exception ex)
        {
            Utils.Log("Streamer.aspx: Exception raised=" + ex.Message + Environment.NewLine + ex.StackTrace);
        }
        if (mediaStream != null)
        {
            mediaStream.Close();
        }
        if (Request.QueryString["idChannel"] != null)
        {
            server.StopTimeShifting(usedChannel, usedCard, tvServerUsername);
        }
        encoder.StopProcess();
        Response.End();
    }
Exemplo n.º 16
0
 /// <summary>
 /// Mapping for Update album request
 /// </summary>
 /// <param name="request">Album request</param>
 /// <returns>An Album</returns>
 public Core.Domain.Album ToAlbum(ServiceInterface.AlbumModel.UpdateAlbum request)
 {
     LogManager.GetLogger("").Info("Mapping for Update album request");
     return Mapper.Map<Album>(request);
 }
Exemplo n.º 17
0
        public string SpecificationTestInstance(string specification)
        {
            ServiceInterface appSi = new ServiceInterface();

            return(appSi.GetSpecificationTestInstance(specification));
        }
Exemplo n.º 18
0
        public List <string> SpecificationList()
        {
            ServiceInterface appSi = new ServiceInterface();

            return(appSi.GetSpecificationList());
        }
Exemplo n.º 19
0
        public Stream TerminzBatch()
        {
            string rv = string.Empty;

            string responseType = GetResponseType();
            string fhirVersion  = GetFhirVersion();

            // get Bundle from the Request Stream

            string       reqBody   = string.Empty;
            UTF8Encoding enc       = new UTF8Encoding();
            Stream       reqStream = OperationContext.Current.RequestContext.RequestMessage.GetBody <Stream>();

            using (StreamReader reader = new StreamReader(reqStream, enc))
            {
                reqBody = reader.ReadToEnd();
            }

            string reqType = WebOperationContext.Current.IncomingRequest.ContentType.ToLower();

            Resource fhirResource;

            if (reqType.Contains("json"))
            {
                FhirJsonParser fjp = new FhirJsonParser();
                fhirResource = fjp.Parse <Resource>(reqBody);
            }
            else
            {
                FhirXmlParser fxp = new FhirXmlParser();
                fhirResource = fxp.Parse <Resource>(reqBody);
            }

            if (fhirResource.ResourceType == ResourceType.Bundle)
            {
                Bundle fb = (Bundle)fhirResource;
                if (fb.Type == Bundle.BundleType.Batch)
                {
                    Bundle responseBundle = new Bundle();

                    responseBundle.Id   = Guid.NewGuid().ToString();
                    responseBundle.Type = Bundle.BundleType.BatchResponse;

                    foreach (Bundle.EntryComponent comp in fb.Entry)
                    {
                        Bundle.RequestComponent rc = comp.Request;

                        if (rc.Method == Bundle.HTTPVerb.GET)
                        {
                            if (rc.Url.IndexOf("$validate-code") > 0)
                            {
                                // extract and parse query string to get parameters
                                int    qsPos       = rc.Url.IndexOf('?');
                                string querystring = (qsPos < rc.Url.Length - 1) ? rc.Url.Substring(qsPos + 1) : String.Empty;
                                qParam = System.Web.HttpUtility.ParseQueryString(querystring);
                                // extract resource (CodeSystem or ValueSet) ID
                                string resourceID   = string.Empty;
                                string resourceName = resourceID.IndexOf("/ValueSet/") > 0 ? "ValueSet" : "CodeSystem";
                                try
                                {
                                    resourceID = rc.Url.Remove(qsPos);
                                    int resNamePos = resourceID.IndexOf("/" + resourceName + "/");
                                    resourceID = resourceID.Substring(resNamePos + 9).Replace("/", "").Replace("$validate-code", "");
                                }
                                catch { }
                                ServiceInterface appSi = new ServiceInterface();
                                responseBundle.AddResourceEntry(appSi.GetFhirResource(resourceName, resourceID, "$validate-code", qParam, fhirVersion), string.Empty);
                            }
                            else
                            {
                                responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Unrecognised Operation in Request..." + rc.Url, OperationOutcome.IssueType.Unknown), string.Empty);
                            }
                        }
                        else if (rc.Method == Bundle.HTTPVerb.POST)
                        {
                            if (rc.Url.IndexOf("$translate") > 0 && comp.Resource.ResourceType == ResourceType.Parameters)
                            {
                                // extract ConceptMap ID
                                string cmID = string.Empty;
                                try
                                {
                                    cmID = rc.Url.Replace("ConceptMap/", "").Replace("$translate", "").Replace("/", "");
                                }
                                catch { }
                                // get parameters
                                Parameters fParam = (Parameters)comp.Resource;
                                SetQueryParameters(fParam);
                                ServiceInterface appSi = new ServiceInterface();
                                responseBundle.AddResourceEntry(appSi.GetFhirResource("ConceptMap", cmID, "$translate", qParam, fhirVersion), string.Empty);
                            }
                            else
                            {
                                responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Unrecognised Operation in Request..." + rc.Url, OperationOutcome.IssueType.Unknown), string.Empty);
                            }
                        }
                        else
                        {
                            responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Method Not Supported in Batch Mode '" + rc.Method.ToString() + "'", OperationOutcome.IssueType.NotSupported), string.Empty);
                        }
                    }

                    fhirResource = responseBundle;
                }
                else
                {
                    fhirResource = OperationOutcome.ForMessage("No module could be found to handle the bundle type '" + fb.TypeName + "'", OperationOutcome.IssueType.NotFound);
                }
            }
            else
            {
                fhirResource = OperationOutcome.ForMessage("No module could be found to handle the request '" + fhirResource.ResourceType.ToString() + "'", OperationOutcome.IssueType.NotFound);
            }

            if (fhirResource.ResourceType == ResourceType.OperationOutcome)
            {
                AddNarrativeToOperationOutcome(fhirResource);
                OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                response.StatusCode = HttpStatusCode.BadRequest;
                // if wish for more granular response codes, need Issue Type
                //OperationOutcome oo = (OperationOutcome)fhirResource;
                //OperationOutcome.IssueType opOutcome = (OperationOutcome.IssueType)oo.Issue[0].Code;
            }

            // convert to stream to remove leading XML elements and json quotes
            rv = SerializeResponse(fhirResource, responseType, SummaryType.False);
            return(new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(rv)));
        }
Exemplo n.º 20
0
        public Stream TerminzGet(string resource, string id, string operation)
        {
            string rv = string.Empty;

            string summaryQueryStringValue = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["_summary"];

            string responseType = GetResponseType();
            string fhirVersion  = GetFhirVersion();

            // If {id} is empty, {$operation} will be in that URL segment - all terminology operations start with $
            string reqId        = id;
            string reqOperation = operation;

            if (!string.IsNullOrEmpty(id) && id.StartsWith("$"))
            {
                reqId        = string.Empty;
                reqOperation = id;
            }

            // handle pure operation calls - e.g. $versions
            if (resource.StartsWith("$"))
            {
                reqOperation = resource;
                resource     = string.Empty;
            }

            if (this.qParam.Count == 0)  // i.e. hasn't been populated from POST
            {
                qParam = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;
            }

            // remove summary type and format from query parameters as they are only processed at this layer
            qParam.Remove("_format");
            qParam.Remove("_summary");

            ServiceInterface appSi        = new ServiceInterface();
            Resource         fhirResource = appSi.GetFhirResource(resource, reqId, reqOperation, qParam, fhirVersion);

            SummaryType st = SummaryType.False;

            // honour summary type requests
            if (!string.IsNullOrEmpty(summaryQueryStringValue))
            {
                if (summaryQueryStringValue.Equals("count", System.StringComparison.OrdinalIgnoreCase))
                {
                    st = SummaryType.Count;
                }
                if (summaryQueryStringValue.Equals("data", System.StringComparison.OrdinalIgnoreCase))
                {
                    st = SummaryType.Data;
                }
                if (summaryQueryStringValue.Equals("text", System.StringComparison.OrdinalIgnoreCase))
                {
                    st = SummaryType.Text;
                }
                if (summaryQueryStringValue.Equals("true", System.StringComparison.OrdinalIgnoreCase))
                {
                    st = SummaryType.True;
                }
            }

            if (fhirResource.ResourceType == ResourceType.OperationOutcome)
            {
                AddNarrativeToOperationOutcome(fhirResource);
                OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                response.StatusCode = HttpStatusCode.BadRequest;
            }

            // convert to stream to remove leading XML elements and json quotes
            rv = SerializeResponse(fhirResource, responseType, st);
            return(new System.IO.MemoryStream(UTF8Encoding.UTF8.GetBytes(rv)));
        }
Exemplo n.º 21
0
        //
        // Gets web service URL for the given TFS server
        //
        private static void GetMiddleTierUrls(
            string teamSystemName,                  // TFS server name
            out string serverUrl,                   // Server URL
            out string configurationSettingsUrl)    // Configuration Settings URL
        {
            Debug.Assert(teamSystemName != null, "TFS server name cannot be null!");
            Debug.Assert(teamSystemName.Length > 0, "TFS server name cannot be empty!");

            //
            // Get registration info from BIS. If there's an connectivity issue (or similar exception)
            //  with BIS, we shouldn't catch and change the exception, we should let the BIS error
            //  bubble up since there's not much can do to handle that situation.  Their exception
            //  should best describe the situation.
            //
            TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(teamSystemName);

            IRegistration regProxy = (IRegistration)tfs.GetService(typeof(IRegistration));

            RegistrationEntry[] regEntries =
                regProxy.GetRegistrationEntries(BisData.Tool);

            Debug.Assert(regEntries.Length == 1, "Only one registration entry must exist for the tool!");
            RegistrationEntry toolEntry = regEntries[0];

            // Find the right service interface
            ServiceInterface si = null;
            ServiceInterface configurationServiceInterface = null;
            int foundCount = 0;

            for (int i = 0; i < toolEntry.ServiceInterfaces.Length; i++)
            {
                string name = toolEntry.ServiceInterfaces[i].Name;
                if (si == null &&
                    TFStringComparer.ServiceInterface.Equals(name, ServiceInterfaces.WorkItem))
                {
                    si = toolEntry.ServiceInterfaces[i];
                    foundCount++;
                }
                else if (configurationServiceInterface == null &&
                         TFStringComparer.ServiceInterface.Equals(name, BisData.ConfigurationServerUrl))
                {
                    configurationServiceInterface = toolEntry.ServiceInterfaces[i];
                    foundCount++;
                }

                if (foundCount == 2)
                {
                    break;
                }
            }

            //
            // If either of these two situations occur, our middle tier location did not get properly registered
            // and we should call attention to that since the app cannot continue and corrective action should
            // be take by the admin.
            //
            if (si == null)
            {
                Logger.Write(LogSource.WorkItemTracking, TraceLevel.Error, "Could not get service interface for WI");
                throw new ConverterException(VSTSResource.ErrorBisMiddleTierNotRegistered);
            }

            serverUrl = si.Url;
            if (String.IsNullOrEmpty(serverUrl))
            {
                Logger.Write(LogSource.WorkItemTracking, TraceLevel.Error, "Could not get service interface URL for WI");
                throw new ConverterException(VSTSResource.ErrorBisMiddleTierNotRegistered);
            }

            if (configurationServiceInterface == null)
            {
                Logger.Write(LogSource.WorkItemTracking, TraceLevel.Error, "Could not get config service interface for WI");
                throw new ConverterException(VSTSResource.ErrorBisMiddleTierNotRegistered);
            }

            configurationSettingsUrl = configurationServiceInterface.Url;
            if (String.IsNullOrEmpty(configurationSettingsUrl))
            {
                Logger.Write(LogSource.WorkItemTracking, TraceLevel.Error, "Could not get config service interface URL for WI");
                throw new ConverterException(VSTSResource.ErrorBisMiddleTierNotRegistered);
            }
        }
Exemplo n.º 22
0
 private void Form1_Load(object sender, EventArgs e)
 {
     Interface = ServiceInterface.Marshal(new Ruleset());
 }
Exemplo n.º 23
0
 public AuthenticationLogic(IJSRuntime jsRuntime, ServiceInterface userService)
 {
     this.jsRuntime   = jsRuntime;
     this.userService = userService;
 }
Exemplo n.º 24
0
 public ServiceInterfaceManagerStub()
 {
     ServiceInterface = new ServiceInterface(new Ruleset());
 }
Exemplo n.º 25
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="cfg">Configuration</param>
        public TfsCore(TfsMigrationDataSource cfg)
        {
            m_rwLock = new ReaderWriterLock();
            m_cfg    = cfg;
            //m_missingArea = missingArea;
            //m_missingIteration = missingIteration;

            m_srv = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(cfg.ServerName));
            m_srv.EnsureAuthenticated();
            TraceManager.TraceInformation("Authenticated User for Uri {0} is '{1}'", m_srv.Uri, m_srv.AuthorizedIdentity.DisplayName);

            //// Verify whether the user is in the service account group. Throw an exception if it is not.
            //// TODO: move this to proper location
            //IGroupSecurityService gss = (IGroupSecurityService)m_srv.GetService(typeof(IGroupSecurityService));
            //Identity serviceAccountIdentity = gss.ReadIdentity(SearchFactor.ServiceApplicationGroup, null, QueryMembership.None);
            //if (!gss.IsMember(serviceAccountIdentity.Sid, m_srv.AuthenticatedUserIdentity.Sid))
            //{
            //    throw new MigrationException(
            //        string.Format(TfsWITAdapterResources.UserNotInServiceAccountGroup, m_srv.AuthenticatedUserName, m_srv.Name));
            //}

            m_store = CreateWorkItemStore();
            m_name  = string.Format(
                CultureInfo.InvariantCulture,
                "{0} ({1})",
                m_store.TeamProjectCollection.Name,
                m_cfg.Project);

            Project p = m_store.Projects[cfg.Project];

            m_projectUri = p.Uri.ToString();
            m_projectId  = p.Id;

            //// Check existence of default area and iteration, if any
            //if (!string.IsNullOrEmpty(cfg.DefaultArea))
            //{
            //    m_defaultAreaId = GetNode(Node.TreeType.Area, cfg.DefaultArea, false);
            //}
            //else
            //{
            //    m_defaultAreaId = p.Id;
            //}
            //if (!string.IsNullOrEmpty(cfg.DefaultIteration))
            //{
            //    m_defaultIterationId = GetNode(Node.TreeType.Iteration, cfg.DefaultIteration, false);
            //}
            //else
            //{
            //    m_defaultIterationId = p.Id;
            //}
            /// TODO: replace the code below with configuration in consideration
            m_defaultAreaId      = p.Id;
            m_defaultIterationId = p.Id;

            // Obtain registration info
            IRegistration regSvc = (IRegistration)m_store.TeamProjectCollection.GetService(typeof(IRegistration));

            RegistrationEntry[] res = regSvc.GetRegistrationEntries(ToolNames.WorkItemTracking);

            if (res.Length != 1)
            {
                throw new MigrationException(TfsWITAdapterResources.ErrorMalformedRegistrationData, cfg.ServerName);
            }

            RegistrationEntry e = res[0];

            // Extract all data from the registration entry.
            for (int i = 0; i < e.ServiceInterfaces.Length; i++)
            {
                ServiceInterface si = e.ServiceInterfaces[i];

                if (TFStringComparer.ServiceInterface.Equals(si.Name, ServiceInterfaces.WorkItem))
                {
                    m_witUrl = si.Url;
                }
                else if (TFStringComparer.ServiceInterface.Equals(si.Name, "ConfigurationSettingsUrl"))
                {
                    m_configUrl = si.Url;
                }
            }

            for (int i = 0; i < e.RegistrationExtendedAttributes.Length; i++)
            {
                RegistrationExtendedAttribute a = e.RegistrationExtendedAttributes[i];

                if (RegistrationUtilities.Compare(a.Name, "AttachmentServerUrl") == 0)
                {
                    m_attachUrl = a.Value;
                    break;
                }
            }

            if (string.IsNullOrEmpty(m_witUrl) || string.IsNullOrEmpty(m_configUrl) ||
                string.IsNullOrEmpty(m_attachUrl))
            {
                throw new MigrationException(TfsWITAdapterResources.ErrorMalformedRegistrationData,
                                             m_cfg.ServerName);
            }

            m_attachUrl = CombineUrl(m_attachUrl, m_witUrl);
        }
Exemplo n.º 26
0
        private CodeTypeDeclaration AddClientImplementation(ServiceInterface serviceInterface)
        {
            var classTypeDec = new CodeTypeDeclaration(serviceInterface.Name + "Client");

            classTypeDec.IsClass         = true;
            classTypeDec.IsPartial       = true;
            classTypeDec.TypeAttributes |= TypeAttributes.Public;

            classTypeDec.BaseTypes.Add(ClientBaseClassName);
            classTypeDec.BaseTypes.Add(new CodeTypeReference(serviceInterface.Name));

            foreach (var serviceMethod in serviceInterface.Methods)
            {
                var mth = new CodeMemberMethod();
                mth.Attributes = MemberAttributes.Public;
                mth.Name       = serviceMethod.Name;
                mth.ReturnType = new CodeTypeReference(serviceMethod.MethodInfo.ReturnType);

                var  parameterName  = "request";
                var  parameterInfos = serviceMethod.MethodInfo.GetParameters();
                Type sendType       = ContractInfo.GetPropertyType(parameterInfos[0].ParameterType);

                foreach (var parameterInfo in parameterInfos)
                {
                    var bodyMember =
                        parameterInfo.ParameterType.GetMembers(BindingFlags.Instance | BindingFlags.Public)
                        .FirstOrDefault(m => m.GetCustomAttribute <System.ServiceModel.MessageBodyMemberAttribute>() != null);

                    if (bodyMember != null)
                    {
                        parameterName += "." + bodyMember.Name;
                        var fieldInfo = bodyMember as FieldInfo;
                        if (fieldInfo != null)
                        {
                            sendType = ContractInfo.GetPropertyType(fieldInfo.FieldType);
                        }

                        var propertyInfo = bodyMember as PropertyInfo;
                        if (propertyInfo != null)
                        {
                            sendType = ContractInfo.GetPropertyType(propertyInfo.PropertyType);
                        }
                    }

                    mth.Parameters.Add(new CodeParameterDeclarationExpression(parameterInfo.ParameterType, parameterInfo.Name));
                }

                var returnStatement = new CodeMethodReturnStatement();

                var invokeExpression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "CallAsync", new CodePrimitiveExpression(serviceMethod.Action), new CodeVariableReferenceExpression(parameterName));
                invokeExpression.Method.TypeArguments.Add(sendType);
                invokeExpression.Method.TypeArguments.Add(serviceMethod.MethodInfo.ReturnType.GenericTypeArguments[0]);
                returnStatement.Expression = invokeExpression;

                mth.Statements.Add(returnStatement);

                classTypeDec.Members.Add(mth);
            }

            return(classTypeDec);
        }
Exemplo n.º 27
0
        virtual public void ProcessRequest(HttpContext context)
        {
            try
            {
                Workbook  workbook = new Workbook();
                Worksheet worksheet;

                int    counter    = 0;
                string methodName = HttpContext.Current.Request.QueryString["methodName"];
                string fileName   = HttpContext.Current.Request.QueryString["fileName"];
                string parameters = HttpContext.Current.Request.QueryString["params"];
                if (parameters == null)
                {
                    parameters = HttpContext.Current.Request.Form["params"];
                }

                int    workSheetCount = workbook.Worksheets.Count;
                string tableName      = string.Empty;

                if (methodName.Length > 0 && fileName.Length > 0)
                {
                    DataSet dataSet = (DataSet)ServiceInterface.InternalGenericInvoke(methodName, parameters);

                    foreach (DataTable dt in dataSet.Tables)
                    {
                        if (dt.Columns.Count > 0)
                        {
                            tableName = dt.TableName;

                            if (counter >= workSheetCount)
                            {
                                worksheet = workbook.Worksheets.Add(tableName);
                            }
                            else
                            {
                                worksheet      = workbook.Worksheets[counter];
                                worksheet.Name = tableName;
                            }


                            worksheet.InsertDataTable(dt, true, 4, 1, -1, -1);
                            counter++;
                            worksheet.AllocatedRange.AutoFitColumns();
                            worksheet.AllocatedRange.AutoFitRows();
                            worksheet.Pictures.Add(1, 1, SD.Reval.Admin.Services.ResourceFile.logo_reval);

                            //Sets header style
                            CellStyle styleHeader = worksheet.Rows[0].Style;
                            styleHeader.Borders[BordersLineType.EdgeLeft].LineStyle   = LineStyleType.Thin;
                            styleHeader.Borders[BordersLineType.EdgeRight].LineStyle  = LineStyleType.Thin;
                            styleHeader.Borders[BordersLineType.EdgeTop].LineStyle    = LineStyleType.Thin;
                            styleHeader.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
                            styleHeader.VerticalAlignment = VerticalAlignType.Center;
                            styleHeader.KnownColor        = ExcelColors.Green;
                            styleHeader.Font.KnownColor   = ExcelColors.White;
                            styleHeader.Font.IsBold       = true;
                        }
                    }
                    fileName = fileName + ".xls";

                    workbook.SaveToHttpResponse(fileName, context.Response);

                    context.Response.Buffer      = true;
                    context.Response.ContentType = "application/x-msdownload";
                    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex);
                throw new ApplicationException("The epxport process failed", ex);
            }
            finally
            {
            }
        }