Exemple #1
0
        public void OrderedRegistry_GetOrRegister()
        {
            var reg = new OrderedRegistry <OrderedClazz>();

            bool wasAdded;
            var  obj1 = reg.GetOrRegister <object>("Apple", (_) => new OrderedClazz("Apple", 8, 1), null, out wasAdded);

            Assert.AreEqual(8, obj1.Order);
            Assert.IsTrue(wasAdded);

            var obj2 = reg.GetOrRegister <object>("Yabloko", (_) => new OrderedClazz("Yabloko", 3, 2), null, out wasAdded);

            Assert.AreEqual(3, obj2.Order);
            Assert.IsTrue(wasAdded);

            Assert.IsFalse(object.ReferenceEquals(obj1, obj2));

            var obj3 = reg.GetOrRegister <object>("Apple", (_) => new OrderedClazz("Apple", 123, 111), null, out wasAdded);

            Assert.AreEqual(8, obj3.Order);
            Assert.IsFalse(wasAdded);

            Assert.IsTrue(object.ReferenceEquals(obj1, obj3));


            var ordered = reg.OrderedValues.ToArray();

            Assert.AreEqual(2, ordered.Length);
            Assert.AreEqual("Yabloko", ordered[0].Name);
            Assert.AreEqual("Apple", ordered[1].Name);
        }
Exemple #2
0
        public Schema(string name, bool readOnly, IEnumerable <FieldDef> fieldDefs, IEnumerable <TableAttribute> tableAttributes = null)
        {
            if (name.IsNullOrWhiteSpace())
            {
                throw new DataException(StringConsts.ARGUMENT_ERROR + "CRUD.Schema.ctor(name==null|empty)");
            }

            if (fieldDefs == null || !fieldDefs.Any())
            {
                throw new DataException(StringConsts.ARGUMENT_ERROR + "CRUD.Schema.ctor(fieldDefs==null|empty)");
            }

            m_Name     = name;
            m_ReadOnly = readOnly;
            if (tableAttributes == null)
            {
                m_TableAttrs = new List <TableAttribute>();
            }
            else
            {
                m_TableAttrs = new List <TableAttribute>(tableAttributes);
            }

            m_FieldDefs = new OrderedRegistry <FieldDef>();
            int order = 0;

            foreach (var fd in fieldDefs)
            {
                fd.m_Order = order;
                m_FieldDefs.Register(fd);
                order++;
            }
        }
Exemple #3
0
 internal State(NetGate gate)
 {
     Gate     = gate;
     Rules    = new OrderedRegistry <Rule>();
     Groups   = new OrderedRegistry <Group>();
     VarDefs  = new Registry <VarDef>();
     NetState = new ConcurrentDictionary <string, NetSiteState>(System.Environment.ProcessorCount * 8, 1024);
 }
Exemple #4
0
 internal State(NetGate gate) 
 {
   Gate = gate; 
   Rules     = new OrderedRegistry<Rule>();
   Groups    = new OrderedRegistry<Group>();
   VarDefs   = new Registry<VarDef>();
   NetState  = new ConcurrentDictionary<string,NetSiteState>(System.Environment.ProcessorCount * 8, 1024);
 }
Exemple #5
0
 private void RegisterMergeDecorator()
 {
     foreach (var orderAware in OrderedRegistry.GetRegisteredOrderedAware <IResultProcessEngine>())
     {
         var processEngine = CreateProcessEngine(orderAware.GetType());
         var ruleType      = orderAware.GetGenericType();
         rules.Where(o => ruleType.IsInstanceOfType(o)).ToList().ForEach(rule => merger.RegisterProcessEngine(rule, processEngine));
     }
 }
Exemple #6
0
        /// <summary>
        /// 注册路由装饰器
        /// </summary>
        private void RegisterRouteDecorator()
        {
            var registeredOrderedAware = OrderedRegistry.GetRegisteredOrderedAware <IRouteDecorator>();

            foreach (var routeDecorator in registeredOrderedAware)
            {
                // var decorator = CreateRouteDecorator(routeDecorator.GetType());
                var ruleType = routeDecorator.GetGenericType();
                foreach (var rule in _rules.Where(rule => !rule.GetType().IsAbstract&& ruleType.IsInstanceOfType(rule)))
                {
                    _router.RegisterDecorator(rule, routeDecorator);
                }
            }
        }
Exemple #7
0
        // //创建路由装饰器
        //  private IRouteDecorator CreateRouteDecorator(Type routeDecoratorType)
        //  {
        //      try
        //      {
        //          return (IRouteDecorator)Activator.CreateInstance(routeDecoratorType);
        //      }
        //      catch (Exception e)
        //      {
        //          throw new ShardingException($"Can not find public default constructor for route decorator {routeDecoratorType}", e);
        //      }
        //  }
        private void RegisterRewriteDecorator()
        {
            var rewriteContextDecorators = OrderedRegistry.GetRegisteredOrderedAware <ISqlRewriteContextDecorator>();

            foreach (var rewriteContextDecorator in rewriteContextDecorators)
            {
                // var decorator = CreateRewriteDecorator(orderAware.GetType());
                var ruleType = rewriteContextDecorator.GetGenericType();
                foreach (var rule in _rules.Where(rule => !rule.GetType().IsAbstract&& ruleType.IsInstanceOfType(rule)))
                {
                    _rewriter.RegisterDecorator(rule, rewriteContextDecorator);
                }
            }
        }
Exemple #8
0
        public void OrderedRegistry_Parallel()
        {
            var reg = new OrderedRegistry <OrderedClazz>();

            var CNT = 250000;

            Parallel.For(0, CNT, (i) =>
            {
                reg.Register(new OrderedClazz("Name_{0}".Args(i % 128), i % 789, i));
                var item = reg["Name_{0}".Args(i % 128)];//it may be null
                reg.Unregister("Name_{0}".Args((i - 2) % 128));
            });

            Assert.Pass("No exceptions thrown during multithreaded parallel work");
        }
Exemple #9
0
        public void OrderedRegistry_Clear()
        {
            var reg = new OrderedRegistry <OrderedClazz>();

            Assert.IsTrue(reg.Register(new OrderedClazz("Apple", 8, 1)));
            Assert.IsTrue(reg.Register(new OrderedClazz("Banana", -2, 2)));
            Assert.IsFalse(reg.Register(new OrderedClazz("Apple", 22, 3)));

            var ordered = reg.OrderedValues.ToArray();

            Assert.AreEqual(2, ordered.Length);
            Assert.AreEqual("Banana", ordered[0].Name);
            Assert.AreEqual("Apple", ordered[1].Name);

            reg.Clear();
            Assert.AreEqual(0, reg.Count);
            Assert.AreEqual(0, reg.OrderedValues.Count());
        }
Exemple #10
0
        public void OrderedRegistry_RegisterOrReplace()
        {
            var reg = new OrderedRegistry <OrderedClazz>();

            Assert.IsTrue(reg.Register(new OrderedClazz("Apple", 8, 1)));
            Assert.IsTrue(reg.Register(new OrderedClazz("Banana", -2, 2)));
            Assert.IsTrue(reg.Register(new OrderedClazz("Grapes", 0, 3)));
            Assert.IsFalse(reg.Register(new OrderedClazz("Apple", 22, 12345)));

            var ordered = reg.OrderedValues.ToArray();

            Assert.AreEqual(3, ordered.Length);
            Assert.AreEqual("Banana", ordered[0].Name);
            Assert.AreEqual("Grapes", ordered[1].Name);
            Assert.AreEqual("Apple", ordered[2].Name);

            Assert.AreEqual(1, reg["Apple"].Data);

            Assert.IsFalse(reg.RegisterOrReplace(new OrderedClazz("Apple", 22, 12345)));

            ordered = reg.OrderedValues.ToArray();
            Assert.AreEqual(3, ordered.Length);
            Assert.AreEqual("Banana", ordered[0].Name);
            Assert.AreEqual("Grapes", ordered[1].Name);
            Assert.AreEqual("Apple", ordered[2].Name);

            Assert.AreEqual(12345, reg["Apple"].Data);//got replaced


            Assert.IsTrue(reg.RegisterOrReplace(new OrderedClazz("Peach", 99, -234)));

            ordered = reg.OrderedValues.ToArray();
            Assert.AreEqual(4, ordered.Length);
            Assert.AreEqual("Banana", ordered[0].Name);
            Assert.AreEqual("Grapes", ordered[1].Name);
            Assert.AreEqual("Apple", ordered[2].Name);
            Assert.AreEqual("Peach", ordered[3].Name);

            Assert.AreEqual(12345, reg["Apple"].Data);//got replaced before
            Assert.AreEqual(-234, reg["Peach"].Data);
        }
Exemple #11
0
        internal static void ConfigureMatches(IConfigSectionNode confNode,
                                              OrderedRegistry <WorkMatch> showDumpMatches,
                                              OrderedRegistry <WorkMatch> logMatches,
                                              string from)
        {
            foreach (var cn in confNode[CONFIG_SHOW_DUMP_SECTION].Children.Where(cn => cn.IsSameName(WorkMatch.CONFIG_MATCH_SECTION)))
            {
                if (!showDumpMatches.Register(FactoryUtils.Make <WorkMatch>(cn, typeof(WorkMatch), args: new object[] { cn })))
                {
                    throw new WaveException(StringConsts.CONFIG_OTHER_DUPLICATE_MATCH_NAME_ERROR.Args(cn.AttrByName(Configuration.CONFIG_NAME_ATTR).Value, "{0}.ShowDump".Args(from)));
                }
            }

            foreach (var cn in confNode[CONFIG_LOG_SECTION].Children.Where(cn => cn.IsSameName(WorkMatch.CONFIG_MATCH_SECTION)))
            {
                if (!logMatches.Register(FactoryUtils.Make <WorkMatch>(cn, typeof(WorkMatch), args: new object[] { cn })))
                {
                    throw new WaveException(StringConsts.CONFIG_OTHER_DUPLICATE_MATCH_NAME_ERROR.Args(cn.AttrByName(Configuration.CONFIG_NAME_ATTR).Value, "{0}.Log".Args(from)));
                }
            }
        }
Exemple #12
0
        protected override void DoConfigure(IConfigSectionNode node)
        {
            base.DoConfigure(node);

            m_Filters = new OrderedRegistry <WorkFilter>();//clear existing
            foreach (var fNode in node.Children.Where(cn => cn.IsSameName(WorkFilter.CONFIG_FILTER_SECTION)))
            {
                if (!m_Filters.Register(FactoryUtils.Make <WorkFilter>(fNode, args: new object[] { this, fNode })))
                {
                    throw new WaveException(StringConsts.CONFIG_DUPLICATE_FILTER_NAME_ERROR.Args(fNode.AttrByName(Configuration.CONFIG_NAME_ATTR).Value));
                }
            }

            m_Handlers = new OrderedRegistry <WorkHandler>();//clear existing
            foreach (var hNode in node.Children.Where(cn => cn.IsSameName(WorkHandler.CONFIG_HANDLER_SECTION)))
            {
                if (!m_Handlers.Register(FactoryUtils.Make <WorkHandler>(hNode, args: new object[] { this, hNode })))
                {
                    throw new WaveException(StringConsts.CONFIG_DUPLICATE_HANDLER_NAME_ERROR.Args(hNode.AttrByName(Configuration.CONFIG_NAME_ATTR).Value));
                }
            }
        }
Exemple #13
0
        private Schema(Type trow)
        {
            lock (s_TypeLatch)
            {
                if (s_TypeLatch.Contains(trow))
                {
                    throw new CRUDException(StringConsts.CRUD_TYPED_ROW_RECURSIVE_FIELD_DEFINITION_ERROR.Args(trow.FullName));
                }

                s_TypeLatch.Add(trow);
                try
                {
                    m_Name = trow.AssemblyQualifiedName;


                    var tattrs = trow.GetCustomAttributes(typeof(TableAttribute), false).Cast <TableAttribute>();
                    m_TableAttrs = new List <TableAttribute>(tattrs);


                    m_FieldDefs = new OrderedRegistry <FieldDef>();
                    var props = GetFieldMembers(trow);
                    var order = 0;
                    foreach (var prop in props)
                    {
                        var fattrs = prop.GetCustomAttributes(typeof(FieldAttribute), false).Cast <FieldAttribute>();
                        var fdef   = new FieldDef(prop.Name, order, prop.PropertyType, fattrs, prop);
                        m_FieldDefs.Register(fdef);

                        order++;
                    }
                    s_TypedRegistry.Register(this);
                    m_TypedRowType = trow;
                }
                finally
                {
                    s_TypeLatch.Remove(trow);
                }
            }    //lock
        }
Exemple #14
0
        public void OrderedRegistry()
        {
            var reg = new OrderedRegistry <OrderedClazz>();

            Assert.IsTrue(reg.Register(new OrderedClazz("Apple", 8, 1)));
            Assert.IsTrue(reg.Register(new OrderedClazz("Banana", -2, 2)));
            Assert.IsFalse(reg.Register(new OrderedClazz("Apple", 22, 3)));

            Assert.AreEqual(2, reg.Count);

            Assert.AreEqual(1, reg["Apple"].Data);
            Assert.AreEqual(2, reg["Banana"].Data);
            Assert.AreEqual(null, reg["Grapes"]);

            var ordered = reg.OrderedValues.ToArray();

            Assert.AreEqual(2, ordered.Length);
            Assert.AreEqual("Banana", ordered[0].Name);
            Assert.AreEqual("Apple", ordered[1].Name);

            Assert.IsTrue(reg.Register(new OrderedClazz("Zukini", 0, 180)));

            ordered = reg.OrderedValues.ToArray();
            Assert.AreEqual(3, ordered.Length);
            Assert.AreEqual("Banana", ordered[0].Name);
            Assert.AreEqual("Zukini", ordered[1].Name);
            Assert.AreEqual("Apple", ordered[2].Name);


            Assert.IsFalse(reg.Unregister(new OrderedClazz("I was never added before", 1, 1)));
            Assert.AreEqual(3, reg.Count);

            Assert.IsTrue(reg.Unregister(new OrderedClazz("Apple", 2, 1)));
            Assert.AreEqual(2, reg.Count);
            Assert.AreEqual(null, reg["Apple"]);
            Assert.AreEqual(2, reg["Banana"].Data);
            Assert.AreEqual(180, reg["Zukini"].Data);
        }
Exemple #15
0
        public static HostNetInfo ForThisHost()
        {
            var computerProps = IPGlobalProperties.GetIPGlobalProperties();

            var result = new HostNetInfo
            {
                m_Name              = "{0}.{1}".Args(computerProps.HostName, computerProps.DomainName),
                m_HostNameSegment   = computerProps.HostName,
                m_DomainNameSegment = computerProps.DomainName
            };

            var adapters = new OrderedRegistry <NetAdapterInfo>();
            var nics     = NetworkInterface.GetAllNetworkInterfaces();
            var ord      = 0;

            foreach (var nic in nics)
            {
                adapters.Register(new NetAdapterInfo(nic, ord));
                ord++;
            }

            result.m_Adapters = adapters;
            return(result);
        }
Exemple #16
0
        public void OrderedRegistry_GetOrRegister()
        {
            var reg = new OrderedRegistry<OrderedClazz>();

               bool wasAdded;
               var obj1 = reg.GetOrRegister<object>("Apple", (_) => new OrderedClazz("Apple",  8,  1), null, out wasAdded);
               Assert.AreEqual( 8, obj1.Order );
               Assert.IsTrue( wasAdded );

               var obj2 = reg.GetOrRegister<object>("Yabloko", (_) => new OrderedClazz("Yabloko",  3,  2), null, out wasAdded);
               Assert.AreEqual( 3, obj2.Order );
               Assert.IsTrue( wasAdded );

               Assert.IsFalse( object.ReferenceEquals( obj1, obj2 ) );

               var obj3 = reg.GetOrRegister<object>("Apple", (_) => new OrderedClazz("Apple",  123,  111), null, out wasAdded);
               Assert.AreEqual( 8, obj3.Order );
               Assert.IsFalse( wasAdded );

               Assert.IsTrue( object.ReferenceEquals( obj1, obj3 ) );

               var ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(2, ordered.Length);
               Assert.AreEqual("Yabloko", ordered[0].Name);
               Assert.AreEqual("Apple", ordered[1].Name);
        }
Exemple #17
0
        public void OrderedRegistry_Clear()
        {
            var reg = new OrderedRegistry<OrderedClazz>();
               Assert.IsTrue(  reg.Register( new OrderedClazz("Apple",  8,  1) ) );
               Assert.IsTrue(  reg.Register( new OrderedClazz("Banana", -2,  2) ) );
               Assert.IsFalse(  reg.Register( new OrderedClazz("Apple", 22, 3) ) );

               var ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(2, ordered.Length);
               Assert.AreEqual("Banana", ordered[0].Name);
               Assert.AreEqual("Apple", ordered[1].Name);

               reg.Clear();
               Assert.AreEqual(0, reg.Count);
               Assert.AreEqual(0, reg.OrderedValues.Count());
        }
Exemple #18
0
        public void OrderedRegistry()
        {
            var reg = new OrderedRegistry<OrderedClazz>();
               Assert.IsTrue(  reg.Register( new OrderedClazz("Apple",  8,  1) ) );
               Assert.IsTrue(  reg.Register( new OrderedClazz("Banana", -2,  2) ) );
               Assert.IsFalse(  reg.Register( new OrderedClazz("Apple", 22, 3) ) );

               Assert.AreEqual(2, reg.Count);

               Assert.AreEqual(1, reg["Apple"].Data);
               Assert.AreEqual(2, reg["Banana"].Data);
               Assert.AreEqual(null, reg["Grapes"]);

               var ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(2, ordered.Length);
               Assert.AreEqual("Banana", ordered[0].Name);
               Assert.AreEqual("Apple", ordered[1].Name);

               Assert.IsTrue( reg.Register( new OrderedClazz("Zukini", 0, 180) )  );

               ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(3, ordered.Length);
               Assert.AreEqual("Banana", ordered[0].Name);
               Assert.AreEqual("Zukini", ordered[1].Name);
               Assert.AreEqual("Apple", ordered[2].Name);

               Assert.IsFalse( reg.Unregister(new OrderedClazz("I was never added before", 1, 1)) );
               Assert.AreEqual(3, reg.Count);

               Assert.IsTrue( reg.Unregister(new OrderedClazz("Apple", 2, 1)) );
               Assert.AreEqual(2, reg.Count);
               Assert.AreEqual(null, reg["Apple"]);
               Assert.AreEqual(2, reg["Banana"].Data);
               Assert.AreEqual(180, reg["Zukini"].Data);
        }
Exemple #19
0
        /// <summary>
        /// Handles the exception by responding appropriately with error page with conditional level of details and logging
        /// </summary>
        public static void HandleException(WorkContext work,
                                           Exception error,
                                           OrderedRegistry <WorkMatch> showDumpMatches,
                                           OrderedRegistry <WorkMatch> logMatches,
                                           string securityRedirectURL    = null,
                                           string securityRedirectTarget = null,
                                           OrderedRegistry <WorkMatch> securityRedirectMatches = null,
                                           Type customPageType = null
                                           )
        {
            if (work == null || error == null)
            {
                return;
            }

            var showDump = showDumpMatches != null?
                           showDumpMatches.OrderedValues.Any(m => m.Make(work) != null) : false;

            if (work.Response.Buffered)
            {
                work.Response.CancelBuffered();
            }

            var json = false;

            if (work.Request != null && work.Request.AcceptTypes != null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null
            {
                json = work.Request.AcceptTypes.Any(at => at.EqualsIgnoreCase(ContentType.JSON));
            }

            var actual = error;

            if (actual is FilterPipelineException fpe)
            {
                actual = fpe.RootException;
            }

            if (actual is MvcException mvce)
            {
                actual = mvce.InnerException;
            }


            var securityError = Security.AuthorizationException.IsDenotedBy(error);

            var hsp = error.SearchThisOrInnerExceptionOf <IHttpStatusProvider>();

            if (hsp != null)
            {
                work.Response.StatusCode        = hsp.HttpStatusCode;
                work.Response.StatusDescription = hsp.HttpStatusDescription;
            }
            else
            {
                if (securityError)
                {
                    work.Response.StatusCode        = WebConsts.STATUS_403;
                    work.Response.StatusDescription = WebConsts.STATUS_403_DESCRIPTION;
                }
                else
                {
                    work.Response.StatusCode        = WebConsts.STATUS_500;
                    work.Response.StatusDescription = WebConsts.STATUS_500_DESCRIPTION;
                }
            }


            if (json)
            {
                work.Response.ContentType = ContentType.JSON;
                work.Response.WriteJSON(error.ToClientResponseJsonMap(showDump), JsonWritingOptions.PrettyPrintRowsAsMap);
            }
            else
            {
                if (securityRedirectMatches != null && securityRedirectMatches.Count > 0)
                {
                    JsonDataMap matched = null;
                    foreach (var match in securityRedirectMatches.OrderedValues)
                    {
                        matched = match.Make(work, actual);
                        if (matched != null)
                        {
                            break;
                        }
                    }
                    if (matched != null)
                    {
                        var url    = matched[VAR_SECURITY_REDIRECT_URL].AsString();
                        var target = matched[VAR_SECURITY_REDIRECT_TARGET].AsString();

                        if (url.IsNotNullOrWhiteSpace())
                        {
                            securityRedirectURL = url;
                        }
                        if (target.IsNotNullOrWhiteSpace())
                        {
                            securityRedirectTarget = target;
                        }
                    }
                }

                if (securityRedirectURL.IsNotNullOrWhiteSpace() && securityError && !work.IsAuthenticated)
                {
                    var url    = securityRedirectURL;
                    var target = securityRedirectTarget;
                    if (target.IsNotNullOrWhiteSpace())
                    {
                        var partsA = url.Split('#');
                        var parts  = partsA[0].Split('?');
                        var query  = parts.Length > 1 ? parts[0] + "&" : string.Empty;
                        url = "{0}?{1}{2}={3}{4}".Args(parts[0], query,
                                                       target, Uri.EscapeDataString(work.Request.Url.PathAndQuery),
                                                       partsA.Length > 1 ? "#" + partsA[1] : string.Empty);
                    }
                    work.Response.RedirectAndAbort(url);
                }
                else
                {
                    WaveTemplate errorPage = null;

                    if (customPageType != null)
                    {
                        try
                        {
                            //20201130 DKh fix #376
                            var simpleCtor = customPageType.GetConstructor(new Type[] { typeof(Exception), typeof(bool) }) == null;
                            errorPage = (simpleCtor ? Activator.CreateInstance(customPageType) :
                                         Activator.CreateInstance(customPageType, error, showDump)
                                         ) as WaveTemplate;//fix #376

                            if (errorPage == null)
                            {
                                throw new WaveException("not a {0}".Args(nameof(WaveTemplate)));
                            }
                        }
                        catch (Exception actErr)
                        {
                            work.Log(Log.MessageType.Error,
                                     StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()),
                                     typeof(ErrorFilter).FullName + ".ctor(customPageType)",
                                     actErr);
                        }
                    }

                    if (errorPage == null)
                    {
                        errorPage = new ErrorPage(error, showDump);
                    }

                    errorPage.Render(work, error);
                }
            }

            if (logMatches != null && logMatches.Count > 0)
            {
                JsonDataMap matched = null;
                foreach (var match in logMatches.OrderedValues)
                {
                    matched = match.Make(work, error);
                    if (matched != null)
                    {
                        break;
                    }
                }
                if (matched != null)
                {
                    matched["$ip"]   = work.EffectiveCallerIPEndPoint.ToString();
                    matched["$ua"]   = work.Request.UserAgent.TakeFirstChars(78, "..");
                    matched["$mtd"]  = work.Request.HttpMethod;
                    matched["$uri"]  = work.Request.Url.ToString().TakeFirstChars(78, "..");
                    matched["$ref"]  = work.Request.UrlReferrer?.ToString().TakeFirstChars(78, "..");
                    matched["$stat"] = "{0}/{1}".Args(work.Response.StatusCode, work.Response.StatusDescription);

                    if (work.Portal != null)
                    {
                        matched["$portal"] = work.Portal.Name;
                    }

                    if (work.GeoEntity != null)
                    {
                        matched["$geo"] = work.GeoEntity.LocalityName;
                    }

                    work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJson(JsonWritingOptions.CompactASCII));
                }
            }
        }
Exemple #20
0
      /// <summary>
      /// Handles the exception by responding appropriately with error page with conditional level of details and logging
      /// </summary>
      public static void HandleException(WorkContext work, 
                                         Exception error,
                                         OrderedRegistry<WorkMatch> showDumpMatches,
                                         OrderedRegistry<WorkMatch> logMatches,
                                         string securityRedirectURL = null,
                                         Type customPageType = null
                                         )
      {
          if (work==null || error==null) return;
          
          var showDump = showDumpMatches != null ? 
                         showDumpMatches.OrderedValues.Any(m => m.Make(work)!=null) : false;

          if (work.Response.Buffered)
            work.Response.CancelBuffered();

          var json = false;
          
          if (work.Request!=null && work.Request.AcceptTypes!=null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null
               json = work.Request.AcceptTypes.Any(at=>at.EqualsIgnoreCase(ContentType.JSON));

          var actual = error;
          if (actual is FilterPipelineException)
            actual = ((FilterPipelineException)actual).RootException;

          if (json)
          {
             work.Response.ContentType = ContentType.JSON;
             work.Response.WriteJSON(error.ToClientResponseJSONMap(showDump));
          }
          else
          {
            if (securityRedirectURL.IsNotNullOrWhiteSpace() && (actual is NFX.Security.AuthorizationException || actual.InnerException is NFX.Security.AuthorizationException))
              work.Response.RedirectAndAbort(securityRedirectURL);
            else
            {
              WaveTemplate errorPage = null;

              if (customPageType!=null)
                try
                {
                  errorPage = Activator.CreateInstance(customPageType) as WaveTemplate;
                  if (errorPage==null) throw new WaveException("not WaveTemplate");
                }
                catch(Exception actErr)
                {
                  work.Log(Log.MessageType.Error, 
                            StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()),
                            typeof(ErrorFilter).FullName+".ctor(customPageType)",
                            actErr);
                }
              
              if (errorPage==null)
                errorPage =  new ErrorPage(work, error, showDump);
                
              errorPage.Render(work, error);
            }
          }

         
          
          if (actual is HTTPStatusException)
          {
            var se = (HTTPStatusException)actual;
            work.Response.StatusCode = se.StatusCode;
            work.Response.StatusDescription = se.StatusDescription;
          }

          if (logMatches!=null && logMatches.Count>0)
          {
            JSONDataMap matched = null;
            foreach(var match in logMatches.OrderedValues)
            {
              matched = match.Make(work);
              if (matched!=null) break;
            }
            if (matched!=null)
              work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJSON(JSONWritingOptions.CompactASCII));
          }  

      }
Exemple #21
0
      internal static void ConfigureMatches(IConfigSectionNode confNode,
                                            OrderedRegistry<WorkMatch> showDumpMatches,
                                            OrderedRegistry<WorkMatch> logMatches,
                                            string from)
      {
        foreach(var cn in confNode[CONFIG_SHOW_DUMP_SECTION].Children.Where(cn=>cn.IsSameName(WorkMatch.CONFIG_MATCH_SECTION)))
          if(!showDumpMatches.Register( FactoryUtils.Make<WorkMatch>(cn, typeof(WorkMatch), args: new object[]{ cn })) )
            throw new WaveException(StringConsts.CONFIG_OTHER_DUPLICATE_MATCH_NAME_ERROR.Args(cn.AttrByName(Configuration.CONFIG_NAME_ATTR).Value, "{0}.ShowDump".Args(from))); 

        foreach(var cn in confNode[CONFIG_LOG_SECTION].Children.Where(cn=>cn.IsSameName(WorkMatch.CONFIG_MATCH_SECTION)))
          if(!logMatches.Register( FactoryUtils.Make<WorkMatch>(cn, typeof(WorkMatch), args: new object[]{ cn })) )
            throw new WaveException(StringConsts.CONFIG_OTHER_DUPLICATE_MATCH_NAME_ERROR.Args(cn.AttrByName(Configuration.CONFIG_NAME_ATTR).Value, "{0}.Log".Args(from))); 
      }
Exemple #22
0
      /// <summary>
      /// Handles the exception by responding appropriately with error page with conditional level of details and logging
      /// </summary>
      public static void HandleException(WorkContext work,
                                         Exception error,
                                         OrderedRegistry<WorkMatch> showDumpMatches,
                                         OrderedRegistry<WorkMatch> logMatches,
                                         string securityRedirectURL = null,
                                         string securityRedirectTarget = null,
                                         OrderedRegistry<WorkMatch> securityRedirectMatches = null,
                                         Type customPageType = null
                                         )
      {
          if (work==null || error==null) return;

          var showDump = showDumpMatches != null ?
                         showDumpMatches.OrderedValues.Any(m => m.Make(work)!=null) : false;

          if (work.Response.Buffered)
            work.Response.CancelBuffered();

          var json = false;

          if (work.Request!=null && work.Request.AcceptTypes!=null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null
               json = work.Request.AcceptTypes.Any(at=>at.EqualsIgnoreCase(ContentType.JSON));

          var actual = error;
          if (actual is FilterPipelineException)
            actual = ((FilterPipelineException)actual).RootException;

          if (actual is MVCException)
            actual = ((MVCException)actual).InnerException;


          var securityError = NFX.Security.AuthorizationException.IsDenotedBy(actual);


          if (actual is HTTPStatusException)
          {
            var se = (HTTPStatusException)actual;
            work.Response.StatusCode = se.StatusCode;
            work.Response.StatusDescription = se.StatusDescription;
          }
          else
          {
            if (securityError)
            {
              work.Response.StatusCode = WebConsts.STATUS_403;
              work.Response.StatusDescription = WebConsts.STATUS_403_DESCRIPTION;
            }
            else
            {
              work.Response.StatusCode = WebConsts.STATUS_500;
              work.Response.StatusDescription = WebConsts.STATUS_500_DESCRIPTION;
            }
          }


          if (json)
          {
             work.Response.ContentType = ContentType.JSON;
             work.Response.WriteJSON(error.ToClientResponseJSONMap(showDump));
          }
          else
          {
            if (securityRedirectMatches != null && securityRedirectMatches.Count > 0)
            {
              JSONDataMap matched = null;
              foreach(var match in securityRedirectMatches.OrderedValues)
              {
                matched = match.Make(work, actual);
                if (matched!=null) break;
              }
              if (matched!=null)
              {
                var url = matched[VAR_SECURITY_REDIRECT_URL].AsString();
                var target = matched[VAR_SECURITY_REDIRECT_TARGET].AsString();

                if (url.IsNotNullOrWhiteSpace())
                  securityRedirectURL = url;
                if (target.IsNotNullOrWhiteSpace())
                  securityRedirectTarget = target;
              }
            }

            if (securityRedirectURL.IsNotNullOrWhiteSpace() && securityError && !work.IsAuthenticated)
            {
              var url = securityRedirectURL;
              var target = securityRedirectTarget;
              if (target.IsNotNullOrWhiteSpace())
              {
                var partsA = url.Split('#');
                var parts = partsA[0].Split('?');
                var query = parts.Length > 1 ? parts[0] + "&" : string.Empty;
                url = "{0}?{1}{2}={3}{4}".Args(parts[0], query,
                  target, Uri.EscapeDataString(work.Request.Url.PathAndQuery),
                  partsA.Length > 1 ? "#" + partsA[1] : string.Empty);
              }
              work.Response.RedirectAndAbort(url);
            }
            else
            {
              WaveTemplate errorPage = null;

              if (customPageType!=null)
                try
                {
                  errorPage = Activator.CreateInstance(customPageType) as WaveTemplate;
                  if (errorPage==null) throw new WaveException("not WaveTemplate");
                }
                catch(Exception actErr)
                {
                  work.Log(Log.MessageType.Error,
                            StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()),
                            typeof(ErrorFilter).FullName+".ctor(customPageType)",
                            actErr);
                }

              if (errorPage==null)
                errorPage =  new ErrorPage(work, error, showDump);

              errorPage.Render(work, error);
            }
          }

          if (logMatches!=null && logMatches.Count>0)
          {
            JSONDataMap matched = null;
            foreach(var match in logMatches.OrderedValues)
            {
              matched = match.Make(work, error);
              if (matched!=null) break;
            }
            if (matched!=null)
              work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJSON(JSONWritingOptions.CompactASCII));
          }

      }
Exemple #23
0
        private Schema(Type tdoc)
        {
            lock (s_TypeLatch)
            {
                if (s_TypeLatch.Contains(tdoc))
                {
                    throw new DataException(StringConsts.CRUD_TYPED_DOC_RECURSIVE_FIELD_DEFINITION_ERROR.Args(tdoc.FullName));
                }

                s_TypeLatch.Add(tdoc);
                try
                {
                    m_Name = tdoc.AssemblyQualifiedName;


                    var tattrs = tdoc.GetCustomAttributes(typeof(TableAttribute), false).Cast <TableAttribute>();
                    m_TableAttrs = new List <TableAttribute>(tattrs);


                    m_FieldDefs = new OrderedRegistry <FieldDef>();
                    var props = GetFieldMembers(tdoc);
                    var order = 0;
                    foreach (var prop in props)
                    {
                        var fattrs = prop.GetCustomAttributes(typeof(FieldAttribute), false)
                                     .Cast <FieldAttribute>()
                                     .ToArray();

                        //20160318 DKh. Interpret [Field(CloneFromType)]
                        for (var i = 0; i < fattrs.Length; i++)
                        {
                            var attr = fattrs[i];
                            if (attr.CloneFromDocType == null)
                            {
                                continue;
                            }

                            if (fattrs.Length > 1)
                            {
                                throw new DataException(StringConsts.CRUD_TYPED_DOC_SINGLE_CLONED_FIELD_ERROR.Args(tdoc.FullName, prop.Name));
                            }

                            var clonedSchema = Schema.GetForTypedDoc(attr.CloneFromDocType);
                            var clonedDef    = clonedSchema[prop.Name];
                            if (clonedDef == null)
                            {
                                throw new DataException(StringConsts.CRUD_TYPED_DOC_CLONED_FIELD_NOTEXISTS_ERROR.Args(tdoc.FullName, prop.Name));
                            }

                            fattrs = clonedDef.Attrs.ToArray();//replace these attrs from the cloned target
                            break;
                        }

                        var fdef = new FieldDef(prop.Name, order, prop.PropertyType, fattrs, prop);
                        m_FieldDefs.Register(fdef);

                        order++;
                    }
                    s_TypedRegistry.Register(this);
                    m_TypedDocType = tdoc;
                }
                finally
                {
                    s_TypeLatch.Remove(tdoc);
                }
            }    //lock
        }
Exemple #24
0
        public void OrderedRegistry_Parallel()
        {
            var reg = new OrderedRegistry<OrderedClazz>();

               var CNT = 250000;

               Parallel.For(0, CNT, (i)=>
               {
               reg.Register(new OrderedClazz("Name_{0}".Args(i % 128), i % 789, i));
               var item = reg["Name_{0}".Args(i % 128)];//it may be null
               reg.Unregister("Name_{0}".Args((i-2) %128));
               });

               Assert.Pass("No exceptions thrown during multithreaded parallel work");
        }
Exemple #25
0
        public static HostNetInfo ForThisHost()
        {
            var computerProps = IPGlobalProperties.GetIPGlobalProperties();

              var result = new HostNetInfo
              {
                m_Name = "{0}.{1}".Args(computerProps.HostName, computerProps.DomainName),
                m_HostNameSegment = computerProps.HostName,
                m_DomainNameSegment = computerProps.DomainName
              };

              var adapters = new OrderedRegistry<NetAdapterInfo>();
              var nics = NetworkInterface.GetAllNetworkInterfaces();
              var ord = 0;
              foreach(var nic in nics)
              {
                adapters.Register( new NetAdapterInfo(nic, ord) );
                ord++;
              }

              result.m_Adapters = adapters;
              return result;
        }
Exemple #26
0
        public void OrderedRegistry_RegisterOrReplace()
        {
            var reg = new OrderedRegistry<OrderedClazz>();
               Assert.IsTrue(  reg.Register( new OrderedClazz("Apple",  8,  1) ) );
               Assert.IsTrue(  reg.Register( new OrderedClazz("Banana", -2,  2) ) );
               Assert.IsTrue(  reg.Register( new OrderedClazz("Grapes", 0,  3) ) );
               Assert.IsFalse(  reg.Register( new OrderedClazz("Apple", 22, 12345) ) );

               var ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(3, ordered.Length);
               Assert.AreEqual("Banana", ordered[0].Name);
               Assert.AreEqual("Grapes", ordered[1].Name);
               Assert.AreEqual("Apple", ordered[2].Name);

               Assert.AreEqual( 1, reg["Apple"].Data);

               Assert.IsFalse(  reg.RegisterOrReplace( new OrderedClazz("Apple", 22, 12345) ) );

               ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(3, ordered.Length);
               Assert.AreEqual("Banana", ordered[0].Name);
               Assert.AreEqual("Grapes", ordered[1].Name);
               Assert.AreEqual("Apple", ordered[2].Name);

               Assert.AreEqual( 12345, reg["Apple"].Data);//got replaced

               Assert.IsTrue(  reg.RegisterOrReplace( new OrderedClazz("Peach", 99, -234) ) );

               ordered = reg.OrderedValues.ToArray();
               Assert.AreEqual(4, ordered.Length);
               Assert.AreEqual("Banana", ordered[0].Name);
               Assert.AreEqual("Grapes", ordered[1].Name);
               Assert.AreEqual("Apple", ordered[2].Name);
               Assert.AreEqual("Peach", ordered[3].Name);

               Assert.AreEqual( 12345, reg["Apple"].Data);//got replaced before
               Assert.AreEqual( -234, reg["Peach"].Data);
        }
Exemple #27
0
        /// <summary>
        /// Handles the exception by responding appropriately with error page with conditional level of details and logging
        /// </summary>
        public static void HandleException(WorkContext work,
                                           Exception error,
                                           OrderedRegistry <WorkMatch> showDumpMatches,
                                           OrderedRegistry <WorkMatch> logMatches,
                                           string securityRedirectURL = null,
                                           Type customPageType        = null
                                           )
        {
            if (work == null || error == null)
            {
                return;
            }

            var showDump = showDumpMatches != null?
                           showDumpMatches.OrderedValues.Any(m => m.Make(work) != null) : false;

            if (work.Response.Buffered)
            {
                work.Response.CancelBuffered();
            }

            var json = false;

            if (work.Request != null && work.Request.AcceptTypes != null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null
            {
                json = work.Request.AcceptTypes.Any(at => at.EqualsIgnoreCase(ContentType.JSON));
            }

            var actual = error;

            if (actual is FilterPipelineException)
            {
                actual = ((FilterPipelineException)actual).RootException;
            }

            if (actual is MVCActionException)
            {
                actual = ((MVCActionException)actual).InnerException;
            }


            var securityError = actual is NFX.Security.AuthorizationException || actual.InnerException is NFX.Security.AuthorizationException;

            if (actual is HTTPStatusException)
            {
                var se = (HTTPStatusException)actual;
                work.Response.StatusCode        = se.StatusCode;
                work.Response.StatusDescription = se.StatusDescription;
            }
            else
            {
                if (securityError)
                {
                    work.Response.StatusCode        = WebConsts.STATUS_403;
                    work.Response.StatusDescription = WebConsts.STATUS_403_DESCRIPTION;
                }
                else
                {
                    work.Response.StatusCode        = WebConsts.STATUS_500;
                    work.Response.StatusDescription = WebConsts.STATUS_500_DESCRIPTION;
                }
            }


            if (json)
            {
                work.Response.ContentType = ContentType.JSON;
                work.Response.WriteJSON(error.ToClientResponseJSONMap(showDump));
            }
            else
            {
                if (securityRedirectURL.IsNotNullOrWhiteSpace() && securityError)
                {
                    work.Response.RedirectAndAbort(securityRedirectURL);
                }
                else
                {
                    WaveTemplate errorPage = null;

                    if (customPageType != null)
                    {
                        try
                        {
                            errorPage = Activator.CreateInstance(customPageType) as WaveTemplate;
                            if (errorPage == null)
                            {
                                throw new WaveException("not WaveTemplate");
                            }
                        }
                        catch (Exception actErr)
                        {
                            work.Log(Log.MessageType.Error,
                                     StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()),
                                     typeof(ErrorFilter).FullName + ".ctor(customPageType)",
                                     actErr);
                        }
                    }

                    if (errorPage == null)
                    {
                        errorPage = new ErrorPage(work, error, showDump);
                        errorPage.Render(work, error);
                    }
                    else
                    {
                        errorPage.Render(work, actual);
                    }
                }
            }

            if (logMatches != null && logMatches.Count > 0)
            {
                JSONDataMap matched = null;
                foreach (var match in logMatches.OrderedValues)
                {
                    matched = match.Make(work);
                    if (matched != null)
                    {
                        break;
                    }
                }
                if (matched != null)
                {
                    work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJSON(JSONWritingOptions.CompactASCII));
                }
            }
        }
Exemple #28
0
 public GovernorDaemon(IApplication app) : base(app)
 {
     m_Applications = new OrderedRegistry <App>();
 }
Exemple #29
0
        private Schema(Type tdoc)
        {
            lock (s_TypeLatch)
            {
                if (s_TypeLatch.Contains(tdoc))
                {
                    throw new DataException(StringConsts.CRUD_TYPED_DOC_RECURSIVE_FIELD_DEFINITION_ERROR.Args(tdoc.FullName));
                }

                s_TypeLatch.Add(tdoc);
                try
                {
                    m_Name = tdoc.AssemblyQualifiedName;

                    var tattrs = tdoc.GetCustomAttributes(typeof(SchemaAttribute), false).Cast <SchemaAttribute>();
                    tattrs.ForEach(a => a.StopPropAssignmentTracking());
                    m_SchemaAttrs = new List <SchemaAttribute>(tattrs);

                    //20191026 DKh. Expand resource references in Descriptions
                    m_SchemaAttrs.ForEach(a => { a.ExpandResourceReferencesRelativeTo(tdoc, null); a.Seal(); });

                    m_FieldDefs = new OrderedRegistry <FieldDef>();
                    var props = GetFieldMembers(tdoc);
                    var order = 0;
                    foreach (var prop in props)
                    {
                        var fattrs = prop.GetCustomAttributes(typeof(FieldAttribute), false)
                                     .Cast <FieldAttribute>()
                                     .ToArray();

                        fattrs.ForEach(a => a.StopPropAssignmentTracking());

                        //Interpret [Field(CloneFromType)]
                        for (var i = 0; i < fattrs.Length; i++)
                        {
                            var attr = fattrs[i];

                            if (attr.CloneFromDocType == null)
                            {
                                //20190831 DKh. Expand resource references in Descriptions
                                attr.ExpandResourceReferencesRelativeTo(tdoc, prop.Name);
                                continue;
                            }

                            if (fattrs.Length > 1)
                            {
                                throw new DataException(StringConsts.CRUD_TYPED_DOC_SINGLE_CLONED_FIELD_ERROR.Args(tdoc.FullName, prop.Name));
                            }

                            var clonedSchema = Schema.GetForTypedDoc(attr.CloneFromDocType);
                            var clonedDef    = clonedSchema[prop.Name];
                            if (clonedDef == null)
                            {
                                throw new DataException(StringConsts.CRUD_TYPED_DOC_CLONED_FIELD_NOTEXISTS_ERROR.Args(tdoc.FullName, prop.Name));
                            }

                            fattrs = clonedDef.Attrs.ToArray();//replace these attrs from the cloned target
                            break;
                        }

                        FieldAttribute.FixupInheritedTargets($"{tdoc.Name}.{prop.Name}", fattrs);

                        var fdef = new FieldDef(prop.Name, order, prop.PropertyType, fattrs, prop);
                        m_FieldDefs.Register(fdef);

                        order++;
                    }
                    s_TypedRegistry.Register(this);
                    m_TypedDocType = tdoc;
                }
                finally
                {
                    s_TypeLatch.Remove(tdoc);
                }
            }//lock
        }