}         // func GetDatasetResourceFile

        /// <summary>Process webrequest, return schema.xml and resource files (client scripts).</summary>
        /// <param name="r"></param>
        /// <returns></returns>
        protected override async Task <bool> OnProcessRequestAsync(IDEWebRequestScope r)
        {
            if (r.RelativeSubPath == "schema.xml")
            {
                await Task.Run(() => DataSetDefinition.WriteToDEContext(r, ConfigPath + "/schema.xml"));

                return(true);
            }
            else if (GetDatasetResourceFile(r.RelativeSubPath, out var fi))
            {
                if (MimeTypeMapping.TryGetMimeTypeFromExtension(fi.Extension, out var mimeType))
                {
                    if (mimeType == MimeTypes.Text.Lua || mimeType == MimeTypes.Text.Html)                     // map lua,html to plain text, do not change content
                    {
                        mimeType = MimeTypes.Text.Plain;
                    }
                }
                else
                {
                    mimeType = MimeTypes.Application.OctetStream;
                }

                await Task.Run(() => r.WriteFile(fi.FullName, mimeType));

                return(true);
            }
            return(await base.OnProcessRequestAsync(r));
        }         // proc OnProcessRequest
Exemplo n.º 2
0
        private void HttpRunReport(IDEWebRequestScope r)
        {
            var reportName = r.GetProperty("name", null);

            if (reportName == null)
            {
                throw new ArgumentNullException("name", "Report name is missing.");
            }
            // enforce user context
            var user = r.GetUser <IPpsPrivateDataContext>();

            try
            {
                // collection arguments
                var properties = new List <KeyValuePair <string, object> >();
                foreach (var p in r.ParameterNames)
                {
                    var v = r.GetProperty(p, (object)null);
                    if (v != null)
                    {
                        properties.Add(new KeyValuePair <string, object>(p, v));
                    }
                }

                // execute report
                var resultInfo = reporting.RunReportAsync(reportName, properties.ToArray()).AwaitTask();
                r.OutputHeaders["x-ppsn-reportname"] = reportName;
                r.WriteFile(resultInfo, MimeTypes.Application.Pdf);
            }
            catch (Exception e)
            {
                Log.Except(e);
                throw;
            }
        }         // proc HttpRunReport
Exemplo n.º 3
0
        }         // proc ImportAccountKey

        #endregion

        #region -- OnProcessRequestAsync ----------------------------------------------

        /// <summary>Return token</summary>
        /// <param name="r"></param>
        /// <returns></returns>
        protected override Task <bool> OnProcessRequestAsync(IDEWebRequestScope r)
        {
            if (TryGetState(LogMsgType.Information, out var state) &&
                state.State == AcmeState.Pending &&
                r.RelativeSubPath == state.Token)
            {
                return(r.WriteTextAsync(state.KeyAuthz).ContinueWith(t => true));
            }

            return(base.OnProcessRequestAsync(r));
        }         // func OnProcessRequestAsync
Exemplo n.º 4
0
        }         // proc ProxyRequestAsync

        async Task <bool> IHttpWorker.RequestAsync(IDEWebRequestScope r)
        {
            var cl = client;

            if (cl != null && r is DEWebRequestScope ir)
            {
                return(await ProxyRequestAsync(cl, ir));
            }
            else
            {
                return(false);
            }
        }         // func RequestAsync
Exemplo n.º 5
0
        }         // func GetMimeTypesInfo

        private void WriteApplicationInfo(IDEWebRequestScope r, string applicationName, bool returnAll)
        {
            using (clientApplicationInfos.EnterReadLock())
            {
                clientApplicationInfos.OnBeforeList();

                using (var xml = XmlWriter.Create(r.GetOutputTextWriter(MimeTypes.Text.Xml, r.Http.DefaultEncoding, -1L), Procs.XmlWriterSettings))
                {
                    xml.WriteStartElement("ppsn");
                    xml.WriteAttributeString("displayName", DisplayName);
                    xml.WriteAttributeString("loginSecurity", "NTLM,Basic");

                    // add specific application information
                    if (!String.IsNullOrEmpty(applicationName))
                    {
                        var appInfo = GetClientApplicationInfo(applicationName);
                        if (appInfo == null)
                        {
                            xml.WriteAttributeString("version", "1.0.0.0");
                        }
                        else
                        {
                            xml.WriteAttributeString("version", appInfo.Version.ToString());
                            if (appInfo.Source != null)
                            {
                                xml.WriteAttributeString("src", r.GetOrigin(new Uri(appInfo.Source, UriKind.Relative)).ToString());
                            }
                        }
                    }

                    // return all application
                    if (returnAll)
                    {
                        xml.WriteStartElement("appinfos");
                        var itemWriter = new DEListItemWriter(xml);
                        foreach (var cur in clientApplicationInfos.List)
                        {
                            clientApplicationInfos.Descriptor.WriteItem(itemWriter, cur);
                        }
                        xml.WriteEndElement();
                    }

                    // add mime information
                    GetMimeTypesInfo().WriteTo(xml);

                    xml.WriteEndElement();
                }
            }
        }         // func WriteApplicationInfo
Exemplo n.º 6
0
        private void HttpListGetAction(IDEWebRequestScope r, string id, int start = 0, int count = Int32.MaxValue)
        {
            // Suche den passenden Controller
            var controller = FindController(id);

            if (controller == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest, String.Format("Liste '{0}' nicht gefunden.", id));
            }

            // check security token
            r.DemandToken(controller.SecurityToken);

            // write list
            ((IDEListService)Server).WriteList(r, controller, start, count);
        }         // func HttpListGetAction
Exemplo n.º 7
0
        }         // func WriteApplicationInfo

        /// <summary></summary>
        /// <param name="r"></param>
        /// <returns></returns>
        protected override async Task <bool> OnProcessRequestAsync(IDEWebRequestScope r)
        {
            switch (r.RelativeSubPath)
            {
            case "info.xml":
                await Task.Run(() => WriteApplicationInfo(r, r.GetProperty("app", (string)null), r.GetProperty("all", false)));

                return(true);

            case "login.xml":
                r.DemandToken(SecurityUser);

                var ctx = r.GetUser <IPpsPrivateDataContext>();
                await Task.Run(() => r.WriteObject(GetLoginData(ctx)));

                return(true);

            case "geometries.xml":
                await WriteXmlGeometriesAsync(r);

                return(true);

            case "geometries.json":
                await WriteJsonGeometriesAsync(r);

                return(true);

            default:
                if (r.TryEnterSubPath(this, "geometry/"))
                {
                    try
                    {
                        if (await WriteSingleGeometryAsync(r))
                        {
                            return(true);
                        }
                    }
                    finally
                    {
                        r.ExitSubPath(this);
                    }
                }
                return(await base.OnProcessRequestAsync(r));
            }
        } // proc OnProcessRequest
Exemplo n.º 8
0
        }         // ctor

        /// <summary></summary>
        /// <param name="item"></param>
        /// <param name="context"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        public object Invoke(DEConfigItem item, IDEWebRequestScope context, LogMessageScopeProxy log = null)
        {
            if (action != null)
            {
                if (isNativeCall)
                {
                    action(item, context, log);
                    return(DBNull.Value);
                }
                else
                {
                    return(action(item, context, log));
                }
            }
            else
            {
                return(null);
            }
        }         // proc Invoke
Exemplo n.º 9
0
        }         // func WriteSchema

        /// <summary></summary>
        /// <param name="r"></param>
        /// <param name="cacheId"></param>
        public void WriteToDEContext(IDEWebRequestScope r, string cacheId)
        {
            r.SetLastModified(ConfigurationStamp);

            r.WriteContent(() =>
            {
                var xSchema = new XElement("schema");
                WriteSchema(xSchema);

                var dst                 = new MemoryStream();
                var xmlSettings         = Procs.XmlWriterSettings;
                xmlSettings.CloseOutput = false;
                xmlSettings.Encoding    = Encoding.UTF8;
                using (var xml = XmlWriter.Create(dst, xmlSettings))
                    xSchema.WriteTo(xml);

                dst.Position = 0;
                return(dst);
            }, cacheId, MimeTypes.Text.Xml + ";charset=utf-8"
                           );
        }         // proc WriteToDEContext
Exemplo n.º 10
0
        /// <summary></summary>
        /// <param name="r"></param>
        /// <param name="subPath"></param>
        protected void DemandFile(IDEWebRequestScope r, string subPath)
        {
            var tokens = Config.Elements(xnSecurityDef).Where(x => TestFilter(x, subPath)).Select(x => x.Value?.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).FirstOrDefault();

            if (tokens == null || tokens.Length == 0)
            {
                return;
            }

            var a = false;

            foreach (var c in tokens)
            {
                if (a |= r.TryDemandToken(c))
                {
                    break;
                }
            }
            if (!a)
            {
                throw r.CreateAuthorizationException($"Access denied: {subPath}");
            }
        }         // func DemandFile
Exemplo n.º 11
0
        }         // proc OnBeginReadConfiguration

        /// <summary></summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public override async Task <bool> RequestAsync(IDEWebRequestScope r)
        {
            if (assembly == null || namespaceRoot == null)
            {
                return(false);
            }

            // create the resource name
            var resourceName = namespaceRoot + r.RelativeSubPath.Replace('/', '.');

            var src = (Stream)null;

            try
            {
                DateTime stamp;

                // try to open the resource stream
                var forceAlternativeCheck = nonePresentAlternativeExtensions != null && nonePresentAlternativeExtensions.FirstOrDefault(c => resourceName.EndsWith(c, StringComparison.OrdinalIgnoreCase)) != null;
                src = assembly.GetManifestResourceStream(resourceName);
                if (src == null && !forceAlternativeCheck)                 // nothing...
                {
                    return(false);
                }

                // check if there is a newer file
                if (alternativeRoots != null)
                {
                    var relativeFileName = ProcsDE.GetLocalPath(r.RelativeSubPath);
                    var alternativeFile  = (from c in alternativeRoots
                                            let fi = new FileInfo(Path.Combine(c, relativeFileName))
                                                     where fi.Exists && (forceAlternativeCheck || fi.LastWriteTimeUtc > assemblyStamp)
                                                     orderby fi.LastWriteTimeUtc descending
                                                     select fi).FirstOrDefault();

                    if (alternativeFile != null)
                    {
                        src?.Close();
                        src   = alternativeFile.OpenRead();
                        stamp = alternativeFile.LastWriteTimeUtc;
                    }
                    else
                    {
                        stamp = assemblyStamp;
                        if (forceAlternativeCheck && src == null)
                        {
                            return(false);
                        }
                    }
                }
                else
                {
                    stamp = assemblyStamp;
                    if (forceAlternativeCheck && src == null)
                    {
                        return(false);
                    }
                }

                // security
                DemandFile(r, r.RelativeSubPath);

                // send the file
                await Task.Run(() =>
                               r.SetLastModified(stamp)
                               .WriteContent(
                                   () => src,
                                   assembly.FullName.Replace(" ", "") + "\\[" + assemblyStamp.ToString("R") + "]\\" + resourceName,
                                   GetFileContentType(resourceName) ?? r.Http.GetContentType(Path.GetExtension(resourceName))
                                   )
                               );

                return(true);
            }
            finally
            {
                Procs.FreeAndNil(ref src);
            }
        }         // func Request
Exemplo n.º 12
0
        }         // proc CollectActions

        /// <summary>Führt eine Aktion aus.</summary>
        /// <param name="actionName">Name der Aktion</param>
        /// <param name="context">Parameter, die übergeben werden sollen.</param>
        /// <returns>Rückgabe</returns>
        public (bool, object) InvokeAction(string actionName, IDEWebRequestScope context)
        {
            // Lookup action within cache
            DEConfigAction a;

            lock (actions)
            {
                a = actions[actionName];
                if (a == null)                 // No cached action, create execution code
                {
                    a = CompileAction(actionName);
                    if (a == null)
                    {
                        a = DEConfigAction.Empty;
                    }
                    actions[actionName] = a;
                }
            }

            if (a == DEConfigAction.Empty)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest, String.Format("Action {0} not found", actionName));
            }

            // check security
            context.DemandToken(a.SecurityToken);

            // Execute action
            using (var log = a.IsAutoLog ? Log.CreateScope(LogMsgType.Information, false, true) : null)
            {
                try
                {
                    using (context.Use())
                    {
                        log?.AutoFlush();
                        return(true, a.Invoke(this, context, log));                          // support for async actions is missing -> results in a InvokeAcionAsync
                    }
                }
                catch (Exception e)
                {
                    if (!a.IsSafeCall || context.IsOutputStarted || (e is HttpResponseException))                     // Antwort kann nicht mehr gesendet werden
                    {
                        if (log != null)
                        {
                            log.WriteException(e);
                        }
                        throw;
                    }

                    // Write protocol
                    if (e is ILuaUserRuntimeException userMessage)
                    {
                        if (log == null)
                        {
                            Log.Warn(e);
                        }
                        else
                        {
                            log.WriteWarning(e);
                        }
                        return(false, CreateDefaultReturn(context, DEHttpReturnState.User, userMessage.Message));
                    }
                    else
                    {
                        if (log == null)
                        {
                            Log.Except(e);
                        }
                        else
                        {
                            log.WriteException(e);
                        }
                        return(false, CreateDefaultReturn(context, DEHttpReturnState.Error, e.Message));
                    }
                }
            }
        }         // func InvokeAction
Exemplo n.º 13
0
        }         // proc WriteListFetchList

        #endregion

        void IDEListService.WriteList(IDEWebRequestScope r, IDEListController controller, int startAt, int count)
        {
            var sendTypeDefinition = String.Compare(r.GetProperty("desc", Boolean.FalseString), Boolean.TrueString, StringComparison.OrdinalIgnoreCase) == 0;

            // Suche den passenden Descriptor
            var descriptor = controller.Descriptor;

            if (descriptor == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest, String.Format("List '{0}' has no format description.", controller.Id));
            }

            controller.OnBeforeList();

            // Rückgabe
            using (var tw = r.GetOutputTextWriter(MimeTypes.Text.Xml))
                using (var xml = XmlWriter.Create(tw, GetSettings(tw)))
                {
                    xml.WriteStartDocument();
                    xml.WriteStartElement("list");

                    // Sollen die Strukturinformationen übertragen werdem
                    if (sendTypeDefinition)
                    {
                        xml.WriteStartElement("typedef");
                        descriptor.WriteType(new DEListTypeWriter(xml));
                        xml.WriteEndElement();
                    }

                    // Gib die Daten aus
                    using (controller.EnterReadLock())
                    {
                        var list = controller.List;

                        // Prüfe auf Indexierte Listen
                        var  useInterface     = ListEnumeratorType.Enumerable;
                        Type useInterfaceType = null;
                        foreach (var ii in list.GetType().GetTypeInfo().ImplementedInterfaces)
                        {
                            if (ii.IsGenericType)
                            {
                                var genericType = ii.GetGenericTypeDefinition();
                                if (genericType == typeof(IList <>))
                                {
                                    if (useInterface < ListEnumeratorType.ListTyped)
                                    {
                                        useInterface     = ListEnumeratorType.ListTyped;
                                        useInterfaceType = ii;
                                    }
                                }
                                else if (genericType == typeof(IReadOnlyList <>))
                                {
                                    if (useInterface < ListEnumeratorType.ReadOnlyList)
                                    {
                                        useInterface     = ListEnumeratorType.ReadOnlyList;
                                        useInterfaceType = ii;
                                    }
                                }
                                else if (genericType == typeof(IDERangeEnumerable2 <>))
                                {
                                    if (useInterface < ListEnumeratorType.RangeEnumerator)
                                    {
                                        useInterface     = ListEnumeratorType.RangeEnumerator;
                                        useInterfaceType = ii;
                                    }
                                }
                            }
                            else if (ii == typeof(IList))
                            {
                                if (useInterface < ListEnumeratorType.ListUntyped)
                                {
                                    useInterface = ListEnumeratorType.ListUntyped;
                                }
                            }
                        }

                        // Gib die entsprechende Liste aus
                        xml.WriteStartElement("items");
                        switch (useInterface)
                        {
                        case ListEnumeratorType.Enumerable:
                            var enumerator = list.GetEnumerator();
                            try
                            {
                                WriteListFetchEnum(xml, descriptor, enumerator, startAt, count);
                            }
                            finally
                            {
                                if (enumerator is IDisposable tmp)
                                {
                                    tmp.Dispose();
                                }
                            }
                            break;

                        case ListEnumeratorType.ReadOnlyList:
                        case ListEnumeratorType.ListTyped:
                        case ListEnumeratorType.RangeEnumerator:
                            WriteListFetchTyped(useInterfaceType, r, xml, descriptor, list, startAt, count);
                            break;


                        case ListEnumeratorType.ListUntyped:
                            WriteListFetchList(xml, descriptor, (IList)list, startAt, count);
                            break;

                        default:
                            throw new HttpResponseException(HttpStatusCode.InternalServerError, String.Format("Liste '{0}' nicht aufzählbar.", controller.Id));
                        }
                        xml.WriteEndElement();
                    }

                    xml.WriteEndElement();
                    xml.WriteEndDocument();
                }
        }         // proc IDEListService.WriteList
Exemplo n.º 14
0
 public LuaHtmlTable(IDEWebRequestScope context, string contentType)
 {
     this.context     = context;
     this.contentType = contentType;
 }         // ctor
 public void HttpExecuteAction(IDEWebRequestScope ctx, long id)
 {
     throw new NotImplementedException();
 }         // proc HttpExecuteAction
Exemplo n.º 16
0
        }         // func DemandFile

        /// <summary>Does the specific address.</summary>
        /// <param name="r">Request context.</param>
        /// <returns><c>true</c>, if the request is processed.</returns>
        public abstract Task <bool> RequestAsync(IDEWebRequestScope r);
Exemplo n.º 17
0
        /// <summary></summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public override async Task <bool> RequestAsync(IDEWebRequestScope r)
        {
            if (String.IsNullOrEmpty(filterPattern))
            {
                return(false);
            }

            // create the full file name
            var useIndex            = false;
            var fullDirectoryName   = this.directoryBase.FullName;
            var fileName            = Path.GetFullPath(Path.Combine(fullDirectoryName, ProcsDE.GetLocalPath(r.RelativeSubPath)));
            var directoryBaseOffset = fullDirectoryName[fullDirectoryName.Length - 1] == Path.DirectorySeparatorChar ? fullDirectoryName.Length - 1 : fullDirectoryName.Length;

            // Check for a directory escape
            if (!fileName.StartsWith(directoryBase.FullName, StringComparison.OrdinalIgnoreCase) ||
                (fileName.Length > directoryBaseOffset && fileName[directoryBaseOffset] != Path.DirectorySeparatorChar))
            {
                return(false);
            }

            // is the filename a directory, add index.html
            if (Directory.Exists(fileName))
            {
                if (!String.IsNullOrEmpty(r.AbsolutePath) && r.AbsolutePath[r.AbsolutePath.Length - 1] != '/')
                {
                    r.Redirect(r.AbsolutePath + '/');
                    return(true);
                }
                else
                {
                    fileName = Path.Combine(fileName, ConfigNode.GetAttribute <string>("indexPage"));
                    useIndex = true;
                }
            }
            else if (filterPattern != "*")             // check for filter pattern
            {
                if (!Procs.IsFilterEqual(Path.GetFileName(fileName), filterPattern))
                {
                    return(false);                    // pattern does not fit
                }
            }

            if (File.Exists(fileName))
            {
                // security
                DemandFile(r, fileName);
                // Send the file
                await Task.Run(() => r.WriteFile(fileName, GetFileContentType(fileName), defaultReadEncoding));

                return(true);
            }
            else if (useIndex && allowListing)             // write index table
            {
                await Task.Run(() => r.WriteResource(typeof(HttpWorker), "Resources.Listing.html", "text/html"));

                return(true);
            }
            else
            {
                return(false);
            }
        }         // func Request