Пример #1
0
        InitializeAllInterfaces(
            Module module,
            bool emptyFirst,
            bool useDefaults)
        {
            this.Module = module;
            var settingsType = this.GetType();

            lock (Cache)
            {
                if (!Cache.ContainsKey(settingsType))
                {
                    var attributeType = typeof(SettingsExtensionsAttribute);
                    var interfaces    = new SettingsInterfaces();
                    foreach (var i in this.Interfaces())
                    {
                        var attributeArray = i.GetCustomAttributes(attributeType, false);
                        if (0 == attributeArray.Length)
                        {
                            throw new Exception("Settings interface {0} is missing attribute {1}", i.ToString(), attributeType.ToString());
                        }

                        var newData = new InterfaceData();
                        newData.InterfaceType = i;

                        var attribute = attributeArray[0] as SettingsExtensionsAttribute;
                        // TODO: the Empty function could be replaced by the auto-property initializers in C#6.0 (when Mono catches up)
                        // although it won't then be a centralized definition, so the extension method as-is is probably better
                        newData.emptyMethod   = attribute.GetMethod("Empty", new[] { i });
                        newData.defaultMethod = attribute.GetMethod("Defaults", new[] { i, typeof(Module) });
                        interfaces.Data.Add(newData);
                    }
                    Cache.Add(settingsType, interfaces);
                }
            }

            var data = Cache[settingsType];

            foreach (var i in data.Data)
            {
                if (emptyFirst)
                {
                    if (null != i.emptyMethod)
                    {
                        i.emptyMethod.Invoke(null, new[] { this });
                    }
                }
                if (useDefaults)
                {
                    if (null != i.defaultMethod)
                    {
                        i.defaultMethod.Invoke(null, new object[] { this, module });
                    }
                }
            }
            if (useDefaults && (null != LocalPolicy))
            {
                LocalPolicy.DefineLocalSettings(this, module);
            }
        }
Пример #2
0
        ///// <summary>
        ///// 新增设备告警(含有位置信息,区域信息)
        ///// </summary>
        ///// <param name="eventType"></param>
        ///// <param name="device_code"></param>
        ///// <param name="alarm_location"></param>
        ///// <param name="area_id"></param>
        ///// <param name="alarm_level"></param>
        ///// <param name="report_time"></param>
        ///// <param name="content"></param>
        ///// <returns></returns>
        //public bool AddInformAlarm(int eventType, string device_code, string alarm_location, int area_id, int alarm_level, string content)
        //{
        //    try
        //    {
        //        ServInformAlarmModel model = new ServInformAlarmModel();
        //        model.alarm_level = alarm_level;
        //        model.alarm_location = alarm_location;
        //        model.area_id = area_id;
        //        model.content = content;
        //        model.device_code = device_code;
        //        model.event_type = eventType;
        //        model.report_time = DateTime.Now;
        //        model.status = (int)EnumClass.InformAlarmStatus.未处理;
        //        int res = servInformAlarmDal.AddEntity(model);
        //        if (res > 0)
        //        {
        //            return true;
        //        }
        //        else
        //        {
        //            return false;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        /// <summary>
        /// 页面发送模拟报警至转发层
        /// </summary>
        /// <param name="alarmLevel"></param>
        /// <param name="deviceCode"></param>
        /// <param name="content"></param>
        /// <param name="eventCode"></param>
        /// <returns></returns>
        public bool AddDeviceAlarm(string alarmName, int alarmLevel, string deviceCode, string content, string eventCode)
        {
            try
            {
                sendAlarmPageDele = new SendAlarmPageDele(CSM.Utils.HttpHelper.PostJsonData);
                string              url         = System.Configuration.ConfigurationManager.AppSettings["InterfaceUrl"] + "/api/Interface/Forward";
                ServDeviceInfoDAL   deviceDal   = new ServDeviceInfoDAL();
                AlarmInfoModel      alarmModel  = new AlarmInfoModel();
                InterfaceData       data        = new InterfaceData();
                ServDeviceInfoModel deviceModel = deviceDal.GetDeviceByDeviceCode(deviceCode);
                alarmModel.alarm_cache_status = 0;
                alarmModel.alarm_event        = eventCode;
                alarmModel.alarm_level        = alarmLevel;
                alarmModel.alarm_location     = "";
                alarmModel.alarm_name         = alarmName;
                alarmModel.alarm_subsystem    = deviceModel.subsystem_id;
                alarmModel.alarm_text         = content;
                alarmModel.alarm_time         = DateTime.Now;
                alarmModel.alarm_type         = (int)EnumClass.AlarmType.设备报警;
                alarmModel.code = deviceCode;
                data.data       = alarmModel;
                data.dataType   = 1;
                data.subSysType = deviceModel.subsystem_id;
                data.mark       = "pageMoniter";
                string param = CSM.Utils.JsonHelper.ObjectToString(data);
                sendAlarmPageDele.BeginInvoke(url, param, Encoding.UTF8, null, null);
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #3
0
        GetSettingsInterfaces(
            System.Type settingsType,
            System.Collections.Generic.IEnumerable <System.Type> currentInterfaces)
        {
            lock (Cache)
            {
                if (!Cache.ContainsKey(settingsType))
                {
                    var attributeType = typeof(SettingsExtensionsAttribute);
                    var interfaces    = new SettingsInterfaces();
                    foreach (var i in currentInterfaces)
                    {
                        var attributeArray = i.GetCustomAttributes(attributeType, false);
                        if (0 == attributeArray.Length)
                        {
                            throw new Exception("Settings interface {0} is missing attribute {1}", i.ToString(), attributeType.ToString());
                        }

                        var newData = new InterfaceData();
                        newData.InterfaceType = i;

                        var attribute = attributeArray[0] as SettingsExtensionsAttribute;
                        // TODO: the Empty function could be replaced by the auto-property initializers in C#6.0 (when Mono catches up)
                        // although it won't then be a centralized definition, so the extension method as-is is probably better
                        newData.emptyMethod   = attribute.GetMethod("Empty", new[] { i });
                        newData.defaultMethod = attribute.GetMethod("Defaults", new[] { i, typeof(Module) });
                        interfaces.Data.Add(newData);
                    }
                    Cache.Add(settingsType, interfaces);
                }

                return(Cache[settingsType]);
            }
        }
Пример #4
0
        public void TestClassPrintout()
        {
            var protocol = new QuickClassDesigner.ClassData();

            protocol.@namespace     = "TestableClasses";
            protocol.accessmodifier = AccessLevel.@public;
            protocol.name           = "TestableClass";
            var func = new QuickClassDesigner.FunctionData();

            func.accessmodifer = AccessLevel.@public;
            func.returnType    = typeof(void);
            func.name          = "makeMeAFunction";
            protocol.functions.Add(func);
            var src = protocol.generateSourceCode();

            Console.WriteLine(src);
            var func2 = new QuickClassDesigner.FunctionData();

            func2.accessmodifer = AccessLevel.protectedinternal;
            func2.returnType    = typeof(object[]);
            func2.overrides     = true;
            func2.name          = "makeMeAnotherFunction";
            protocol.functions.Add(func2);
            src = protocol.generateSourceCode();
            Console.WriteLine(src);
            var implement = InterfaceData.fromExistingInterface("System.Collections.IEnumerator");

            protocol.implements.Add(implement.name, implement);
            src = protocol.generateSourceCode();
            Console.WriteLine(src);
        }
Пример #5
0
            public void ConvertsEachMember()
            {
                var code          = AutoFaker.Generate <string>();
                var interfaceName = AutoFaker.Generate <string>();
                var interfaceCode = AutoFaker.Generate <string>();
                var interfaceData = new InterfaceData {
                    Name = interfaceName, Code = interfaceCode
                };

                parser.Setup(it => it.ExtractInterface(code)).Returns(interfaceData);
                var members = new[]
                {
                    new Mock <Member>().Object,
                    new Mock <Member>().Object,
                    new Mock <Member>().Object,
                };

                parser.Setup(it => it.ExtractMembers(interfaceCode)).Returns(members);

                sut.Generate(code);

                foreach (var member in members)
                {
                    memberGenerator.Verify(it => it.Generate(member));
                }
            }
Пример #6
0
 public InterfaceFunctionView(InterfaceFunction function, InterfaceData owner)
 {
     this.owner              = owner;
     this.function           = function;
     title                   = $"{function.name}({ string.Join(", ", function.parameters.Select(p => p.type.DisplayName(false, false))) }) : {function.returnType.DisplayName(false, false)}";
     titleIcon.image         = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.MethodIcon));
     expandedElement.visible = false;
 }
Пример #7
0
 public InterfacePropertyView(InterfaceProperty property, InterfaceData owner)
 {
     this.owner              = owner;
     this.property           = property;
     title                   = $"{property.name} : {property.returnType.DisplayName(false, false)}";
     titleIcon.image         = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.PropertyIcon));
     expandedElement.visible = false;
 }
        public Product CreateProduct(InterfaceData data, string filename)
        {
            Product product = new Product();

            product.SetFilename(filename);

            product.Append(CreateHeader(data.GetNamespaces(), filename));
            product.Append(CreateBody(data.GetMethods()));
            product.Append(CreateFooter(data.GetNamespaces(), filename));

            return(product);
        }
        private (Mock <IMetricsProvider>, Mock <IMetricsPolicy>) GetMetricsProvider(InterfaceData metricsCollectorTypeData, string contextName, bool metricEnabled)
        {
            var metricsProviderMock = new Mock <IMetricsProvider>(MockBehavior.Strict);
            var metricsPolicyMock   = new Mock <IMetricsPolicy>(MockBehavior.Strict);

            foreach (var metricsCollectorMethodData in metricsCollectorTypeData.Methods)
            {
                SetupMetricsProviderMember(metricsProviderMock, metricsPolicyMock, contextName, metricsCollectorMethodData, metricEnabled);
            }

            return(metricsProviderMock, metricsPolicyMock);
        }
Пример #10
0
        public static string GenerateInterfaceCode(InterfaceData interfaceData)
        {
            InterfaceTemplate t = new InterfaceTemplate();

            t.Session = new Microsoft.VisualStudio.TextTemplating.TextTemplatingSession();
            t.Session["interfaceParameters"] = interfaceData;
            t.Session["methods"]             = interfaceData.Methods;
            // Add other parameter values to t.Session here.
            t.Initialize(); // Must call this to transfer values.
            string resultText = t.TransformText();

            return(resultText);
        }
        private void Verify(InterfaceData sutMember, Assembly assembly, bool logEnabled)
        {
            var loggerType = assembly.GetType(sutMember.Namespace + "." + sutMember.Name.Replace("<TInterfaceParam1, TInterfaceParam2>", "`2").TrimStart('I'), true);

            if (loggerType == null)
            {
                throw new Exception("Logger type not found in emitted assembly");
            }

            var methodIndex = 0;

            VerifyInterface(sutMember, loggerType, assembly, logEnabled, ref methodIndex);
        }
Пример #12
0
 /// <summary>
 ///     Creates a new job.
 /// </summary>
 /// <param name="data">Data of the file which will be generated.</param>
 public Job(Data data)
 {
     type = data switch
     {
         ClassData _ => JobType.Class,
         FlagData _ => JobType.Flag,
         EnumeratedData _ => JobType.Enumerated,
         InterfaceData _ => JobType.Interface,
                   _ => type
     };
     this.data = data;
     Console.WriteLine($"Created job for {data.Namespace}.{data.Name}.");
 }
Пример #13
0
        private List <FluentInterfaceFile> CreateInterfaceFiles(InterfaceLocation interfaceLocation)
        {
            List <FluentInterfaceFile> interfaces = new List <FluentInterfaceFile>();

            foreach (InterfaceData interfaceData in _project.Interfaces)
            {
                FluentInterfaceFile builder =
                    new FluentInterfaceFile($"{interfaceData.Name}.{_project.OutputLanguage.FileExtension}");

                if (interfaceLocation == InterfaceLocation.IndividualFiles)
                {
                    AddRequiredUsingStatements(builder, interfaceData.NamespacesNeeded());

                    // Start namespace
                    builder.AddLine(0, $"namespace {_project.FactoryClassNamespace}");
                    builder.AddLine(0, "{");
                }

                builder.AddLine(1, $"public interface {interfaceData.Name}");

                builder.AddLine(1, "{");

                foreach (Method callableMethod in
                         interfaceData.CallableMethods.Where(cm => cm.Group.IsChainStartingMethod()))
                {
                    InterfaceData returnInterface =
                        _project.Interfaces
                        .FirstOrDefault(i => i.CalledByMethods.Exists(cm => cm.Name == callableMethod.Name));

                    builder.AddLine(2, $"{returnInterface?.Name} {callableMethod.Signature};");
                }

                foreach (Method callableMethod in
                         interfaceData.CallableMethods
                         .Where(cm => cm.Group == Method.MethodGroup.Executing))
                {
                    builder.AddLine(2, $"{callableMethod.ReturnDatatype.Name} {callableMethod.Signature};");
                }

                builder.AddLine(1, "}");

                if (interfaceLocation == InterfaceLocation.IndividualFiles)
                {
                    builder.AddLine(0, "}");
                }

                interfaces.Add(builder);
            }

            return(interfaces);
        }
Пример #14
0
            public void ExtractsTheMembersFromTheInterface()
            {
                var code          = AutoFaker.Generate <string>();
                var interfaceName = AutoFaker.Generate <string>();
                var interfaceCode = AutoFaker.Generate <string>();
                var interfaceData = new InterfaceData {
                    Name = interfaceName, Code = interfaceCode
                };

                parser.Setup(it => it.ExtractInterface(code)).Returns(interfaceData);

                sut.Generate(code);

                parser.Verify(it => it.ExtractMembers(interfaceCode));
            }
Пример #15
0
            public void ConvertsTheInterfaceNameToAClassName()
            {
                var code          = AutoFaker.Generate <string>();
                var interfaceName = AutoFaker.Generate <string>();
                var interfaceCode = AutoFaker.Generate <string>();
                var interfaceData = new InterfaceData {
                    Name = interfaceName, Code = interfaceCode
                };

                parser.Setup(it => it.ExtractInterface(code)).Returns(interfaceData);

                sut.Generate(code);

                classNameGenerator.Verify(it => it.GenerateClassName(interfaceCode));
            }
Пример #16
0
        /// <summary>
        /// 逻辑层处理报警数据
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public string HandleLogicAlarmData([FromBody] InterfaceData info)
        {
            //Log4NetHelp.Info("业务层接收数据");
            BusinessLogicBLL businessLogicBll = new BusinessLogicBLL();
            bool             bl = businessLogicBll.HandleBusiness(info);

            //Log4NetHelp.Info("业务层数据处理完成");
            if (bl == true)
            {
                return(JsonHelper.ObjectToString(RetMsgHelper.RetMsg(1, "已接收数据")));
            }
            else
            {
                return(JsonHelper.ObjectToString(RetMsgHelper.RetMsg(0, "报警数据处理失败")));
            }
        }
Пример #17
0
        public InterfaceView(InterfaceData interfaceData, uNodeData owner)
        {
            this.owner         = owner;
            this.interfaceData = interfaceData;
            title           = interfaceData.name;
            titleIcon.image = uNodeEditorUtility.GetTypeIcon(typeof(TypeIcons.InterfaceIcon));

            foreach (var p in interfaceData.properties)
            {
                AddChild(new InterfacePropertyView(p, interfaceData));
            }
            foreach (var f in interfaceData.functions)
            {
                AddChild(new InterfaceFunctionView(f, interfaceData));
            }
        }
Пример #18
0
        /// <summary>
        /// 处理转发层数据
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public string HandleSystemData([FromBody] InterfaceData info)
        {
            //Log4NetHelp.Info("过滤层接收数据");
            FilterBLL filterBll = new FilterBLL();
            bool      bl        = filterBll.HandleSystemData(info);

            // Log4NetHelp.Info("过滤层数据处理完成");
            if (bl == true)
            {
                return(JsonHelper.ObjectToString(RetMsgHelper.RetMsg(1, "已接收数据")));
            }
            else
            {
                return(JsonHelper.ObjectToString(RetMsgHelper.RetMsg(0, "数据处理失败")));
            }
        }
Пример #19
0
        private void AddInstantiatingFunctions(FluentInterfaceFile builder)
        {
            builder.AddLine(2, "// Instantiating functions");

            foreach (Method method in _project.InstantiatingMethods)
            {
                InterfaceData returnDataType = ReturnDataTypeForMethod(method);

                if (returnDataType != null)
                {
                    builder.AddLineAfterBlankLine(2, $"public static {returnDataType.Name} {method.Signature}");
                    builder.AddLine(2, "{");
                    builder.AddLine(3, $"return new {_project.FactoryClassName}();");
                    builder.AddLine(2, "}");
                }
            }
        }
Пример #20
0
        private void AddChainingFunctions(FluentInterfaceFile builder)
        {
            builder.AddLineAfterBlankLine(2, "// Chaining functions");

            foreach (Method method in _project.ChainingMethods)
            {
                InterfaceData returnDataType = ReturnDataTypeForMethod(method);

                if (returnDataType != null)
                {
                    builder.AddLineAfterBlankLine(2, $"public {returnDataType.Name} {method.Signature}");
                    builder.AddLine(2, "{");
                    builder.AddLine(3, "return this;");
                    builder.AddLine(2, "}");
                }
            }
        }
Пример #21
0
        /// <summary>
        /// 页面发送模拟报警至转发层
        /// </summary>
        /// <param name="alarmLevel"></param>
        /// <param name="deviceCode"></param>
        /// <param name="content"></param>
        /// <param name="eventCode"></param>
        /// <returns></returns>
        public RetMsgModel AddMapDeviceAlarm(string alarmName, int alarmLevel, string deviceCode, string content, string eventCode)
        {
            try
            {
                RetMsgModel retModel = new RetMsgModel();
                sendAlarmPageDele = new SendAlarmPageDele(CSM.Utils.HttpHelper.PostJsonData);
                string              url         = System.Configuration.ConfigurationManager.AppSettings["InterfaceUrl"] + "/api/Interface/Forward";
                ServDeviceInfoDAL   deviceDal   = new ServDeviceInfoDAL();
                AlarmInfoModel      alarmModel  = new AlarmInfoModel();
                InterfaceData       data        = new InterfaceData();
                ServDeviceInfoModel deviceModel = deviceDal.GetDeviceByDeviceCode(deviceCode);
                alarmModel.alarm_cache_status = 0;
                alarmModel.alarm_event        = eventCode;
                alarmModel.alarm_level        = alarmLevel;
                alarmModel.alarm_location     = "";
                alarmModel.alarm_name         = alarmName;
                alarmModel.alarm_subsystem    = deviceModel.subsystem_id;
                alarmModel.alarm_text         = content;
                alarmModel.alarm_time         = DateTime.Now;
                alarmModel.alarm_type         = (int)EnumClass.AlarmType.设备报警;
                alarmModel.code = deviceCode;
                data.data       = alarmModel;
                data.dataType   = 1;
                data.subSysType = deviceModel.subsystem_id;
                data.mark       = "pageMoniter";
                string param = CSM.Utils.JsonHelper.ObjectToString(data);
                //sendAlarmPageDele.BeginInvoke(url, param, Encoding.UTF8, null, null);
                string ret = Utils.HttpHelper.PostWebRequestBandError(url, param, "application/json;charset=utf-8", Encoding.UTF8);
                if (string.IsNullOrEmpty(ret))
                {
                    retModel.status  = 1;
                    retModel.message = "调用转发层返回值为空!";
                }
                else
                {
                    retModel = Utils.JsonHelper.StringToObject <RetMsgModel>(ret);
                }

                return(retModel);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #22
0
            public void ReturnsTheNewClass()
            {
                var          code           = AutoFaker.Generate <string>();
                const string INTERFACE_NAME = "ISomething";
                const string INTERFACE_CODE = "interface ISomething {}";
                var          interfaceData  = new InterfaceData {
                    Name = INTERFACE_NAME, Code = INTERFACE_CODE
                };

                parser.Setup(it => it.ExtractInterface(code)).Returns(interfaceData);
                classNameGenerator.Setup(it => it.GenerateClassName(INTERFACE_CODE)).Returns("SomethingDecorator");
                var members = new[]
                {
                    new Mock <Member>().Object,
                    new Mock <Member>().Object,
                    new Mock <Member>().Object,
                };

                parser.Setup(it => it.ExtractMembers(INTERFACE_CODE)).Returns(members);
                memberGenerator.Setup(it => it.Generate(members[0])).Returns("M0");
                memberGenerator.Setup(it => it.Generate(members[1])).Returns("M1");
                memberGenerator.Setup(it => it.Generate(members[2])).Returns("M2");

                var result = sut.Generate(code);

                Assert.AreEqual(
                    @"public class SomethingDecorator : ISomething
{
    public SomethingDecorator(ISomething decorated)
    {
        this.decorated = decorated;
    }

    M0
    M1
    M2

    //

    private readonly ISomething decorated;
}",
                    result);
            }
Пример #23
0
 /// <summary>
 /// 处理预案
 /// </summary>
 /// <param name="info"></param>
 /// <returns></returns>
 public bool HandleBusiness(InterfaceData info)
 {
     try
     {
         //  InterfaceData interfaceData = JsonHelper.StringToObject<InterfaceData>(info);
         if (info != null)
         {
             if (info.dataType == 1)  //报警数据(默认类型1)
             {
                 ServAlarmRecordModel alarmRecord = JsonHelper.StringToObject <ServAlarmRecordModel>(info.data.ToString());
                 if (alarmRecord != null)
                 {
                     //Log4NetHelp.Info("业务层开始处理预案!");
                     HandlePlan(alarmRecord);
                     // Log4NetHelp.Info("业务层预案处理完成!");
                 }
                 else
                 {
                     //log:报警数据转换失败
                     Log4NetHelp.Info("数据类型转换失败!数据:" + info.data.ToString());
                 }
             }
             else
             {
                 //log:非报警数据
                 Log4NetHelp.Info("非报警数据");
             }
         }
         else
         {
             //log:HandleBusiness转换子系统数据失败
             Log4NetHelp.Info("业务层接收数据为空");
         }
         return(true);
     }
     catch (Exception ex)
     {
         //log  数据处理失败+ex.message
         Log4NetHelp.Error("预案处理出现异常!" + ex.Message);
         return(false);
     }
 }
Пример #24
0
 /// <summary>
 /// 转发
 /// </summary>
 /// <param name="info"></param>
 public bool Forward(string info, List <InterfaceRouteModel> routeList)
 {
     try
     {
         InterfaceData data = JsonHelper.StringToObject <InterfaceData>(info);
         foreach (InterfaceRouteModel route in routeList)
         {
             if (route.subsyslist.Contains(data.subSysType))
             {
                 // PostHttpData.PostWebRequest(obj.url, param, Encoding.UTF8);
                 SendData.BeginInvoke(route.url, info, Encoding.UTF8, null, null);   //异步调用委托,防止线程阻塞
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         //log:转发失败+ex.message
         return(false);
     }
 }
Пример #25
0
        static void Main(string[] args)
        {
            InterfaceData interfaceData = new InterfaceData("Pattern", "IBuilder");
            Method        m             = new Method("string", "metoda");
            Parameter     p             = new Parameter("string", "test");

            m.Parameters.Add(p);
            interfaceData.Methods.Add(m);
            string resultText = InterfaceService.GenerateInterfaceCode(interfaceData);

            Console.WriteLine(resultText);
            Console.ReadKey();
            ClassData classData = new ClassData("Pattern", "IBuilder", "baseClass");
            Method    mc        = new Method("string", "metoda", "public");
            Parameter pc        = new Parameter("string", "test", "public");

            mc.Parameters.Add(pc);
            classData.Methods.Add(mc);
            classData.Parameters.Add(pc);
            classData.Parameters.Add(pc);
            string resultTextc = ClassService.GenerateClassCode(classData);
        }
Пример #26
0
        private static void CreateTraceInterfaceJob()
        {
            var interfaceData = new InterfaceData
            {
                Name        = "ITrace",
                Namespace   = $"{Namespace}",
                Description = new[] { "The trace interface." },
                Properties  = new List <Property>
                {
                    new Property
                    {
                        PropertyDescription = new[] { "The type of the trace." },
                        TypeName            = "TraceTypeEnum?",
                        PropertyName        = "Type",
                        DisplayName         = "type",
                        IsReadOnly          = true,
                        IsInherited         = true
                    }
                }
            };

            Jobs.Add($"{interfaceData.Namespace}.{interfaceData.Name}", new Job(interfaceData));
        }
        private void BuildAndVerify(InterfaceData metricsCollectorTypeData, Assembly assembly, bool metricEnabled)
        {
            var metricsCollectorType =
                assembly.GetType(metricsCollectorTypeData.Namespace + "." + metricsCollectorTypeData.Name.TrimStart('I').Replace("<TInterfaceParam1, TInterfaceParam2>", "`2"), true);

            if (metricsCollectorType == null)
            {
                throw new Exception(
                          $"MetricsCollector implementation for '{metricsCollectorTypeData}' not found in emitted assembly");
            }

            var metricsCollectorInterfaceAttributeData = metricsCollectorTypeData.AttributeDataList
                                                         .OfType <MetricsCollectorInterfaceAttributeData>().FirstOrDefault();

            if (metricsCollectorInterfaceAttributeData == null)
            {
                throw new Exception($"{typeof(MetricsCollectorInterfaceAttributeData)} not found");
            }

            var contextName = metricsCollectorInterfaceAttributeData.ContextName;

            VerifyInterface(metricsCollectorTypeData, metricsCollectorType, assembly, contextName, metricEnabled);
        }
        private void VerifyInterface(InterfaceData interfaceData, Type loggerType, Assembly assembly, bool logEnabled, ref int methodIndex)
        {
            _output.WriteLine($"VerifyInterface:'{interfaceData}'");
            var loggerInterfaceType =
                assembly.GetType(interfaceData.Namespace + "." + interfaceData.Name.Replace("<TInterfaceParam1, TInterfaceParam2>", "`2"), true);

            if (loggerInterfaceType == null)
            {
                throw new Exception(
                          "Logger interface for not found in emitted assembly");
            }

            for (var index = 0; index < interfaceData.Methods.Length; index++)
            {
                var interfaceMethod = interfaceData.Methods[index];
                var methodName      = interfaceMethod.Name;
                var loggerInterfaceMethodAttributeData = interfaceMethod.AttributeDataList
                                                         .OfType <LoggerInterfaceMethodAttributeData>().FirstOrDefault();
                string   message;
                LogLevel logLevel;
                if (loggerInterfaceMethodAttributeData == null)
                {
                    message  = methodName.Humanize();
                    logLevel = LogLevel.Information;
                }
                else
                {
                    message = loggerInterfaceMethodAttributeData.MessageIsDefined
                                                ? loggerInterfaceMethodAttributeData.Message
                                                : methodName.Humanize();
                    logLevel = loggerInterfaceMethodAttributeData.LogLevelIsDefined
                                                ? loggerInterfaceMethodAttributeData.Level
                                                : LogLevel.Information;
                }

                methodIndex += 1;
                var internalLogger = new TestLogger(new EventId(methodIndex, methodName), methodName, message, logLevel,
                                                    interfaceMethod.Parameters, logEnabled);
                var loggerFactory = new TestLoggerFactory(internalLogger);
                if (loggerType.IsGenericTypeDefinition)
                {
                    var loggerTypeParams = new[] { typeof(object), typeof(int) };
                    loggerType = loggerType.MakeGenericType(loggerTypeParams);
                }

                if (loggerInterfaceType.IsGenericTypeDefinition)
                {
                    var loggerTypeParams = new[] { typeof(object), typeof(int) };
                    loggerInterfaceType = loggerInterfaceType.MakeGenericType(loggerTypeParams);
                }

                var logger = Activator.CreateInstance(loggerType, loggerFactory);

                var loggerMethod = loggerInterfaceType.GetTypeInfo().GetDeclaredMethod(methodName);
                if (loggerMethod == null)
                {
                    throw new Exception("Logger method not found in emitted assembly");
                }

                loggerMethod = loggerMethod.MakeGenericMethod(typeof(string), typeof(Guid));
                var parameters = interfaceMethod.Parameters.Select(p => p.Value).ToArray();
                loggerMethod.Invoke(logger, parameters);
                internalLogger.Verify();
            }

            foreach (var inheritedInterface in interfaceData.InheritedInterfaces)
            {
                VerifyInterface(inheritedInterface, loggerType, assembly, logEnabled, ref methodIndex);
            }
        }
Пример #29
0
        private void ProcessImplementsStatements(List <Definition> unresolved)
        {
            foreach (var def in unresolved)
            {
                def.Decompose(implements:
                              implements => {
                    string error = null;
                    InterfaceData implementing = null;
                    DataBase d;
                    if (_entities.TryGetValue(implements.ImplementingType, out d))
                    {
                        implementing = d as InterfaceData;
                        if (implementing == null)
                        {
                            error = "The type `" + implements.ImplementingType + "' cannot implement `" + implements.ImplementedType + "' because the type `" + implements.ImplementingType + "' is a " + d.DefinitionType + ", not an interface";
                        }
                    }
                    else
                    {
                        error = "The interface `" + implements.ImplementingType + "', supposed to implement `" + implements.ImplementedType + "', does not exist";
                    }

                    if (error == null)
                    {
                        if (_entities.TryGetValue(implements.ImplementedType, out d))
                        {
                            var id = d as InterfaceData;
                            if (id != null)
                            {
                                id.IsUsed = true;
                            }
                            else
                            {
                                error = "The interface `" + implements.ImplementingType + "' cannot implement `" + implements.ImplementedType + "' because the type `" + implements.ImplementedType + "' is a " + d.DefinitionType + ", not an interface";
                            }
                        }
                        else
                        {
                            error = "The interface `" + implements.ImplementedType + "', supposed to be implemented by `" + implements.ImplementingType + "', does not exist";
                        }
                    }

                    if (error == null)
                    {
                        implementing.Implements.Add(implements.ImplementedType);
                    }
                    else
                    {
                        _errors.Add(error);
                    }
                },
                              @interface: null, callbackInterface: null, partialInterface: null, dictionary: null, partialDictionary: null, callback: null, exception: null, typedef: null, @enum: null, interfaceDeclaration: null
                              );
            }

            // handle transitivity (I1 implements I2; I2 implements I3;)
            var interfaces = _entities.Values.OfType <InterfaceData>().ToList();

            foreach (var component in TopologicalSorter.FindAndTopologicallySortStronglyConnectedComponents(interfaces, interfaces.SelectMany(iface => iface.Implements.Select(imp => Tuple.Create(iface, (InterfaceData)_entities[imp])))))
            {
                if (component.Count > 1)
                {
                    _errors.Add("Circular implementation involving the interfaces " + string.Join(", ", component.Select(c => "`" + c.Name + "'")));
                }
                else
                {
                    var item = component[0];
                    var all  = item.Implements.Concat(item.Implements.SelectMany(imp => ((InterfaceData)_entities[imp]).Implements)).Distinct().ToList();
                    item.Implements.Clear();
                    item.Implements.AddRange(all);
                }
            }
        }
Пример #30
0
        InitializeAllInterfaces(
            Module module,
            bool emptyFirst,
            bool useDefaults)
        {
            this.Module = module;
            var settingsType = this.GetType();
            lock (Cache)
            {
                if (!Cache.ContainsKey(settingsType))
                {
                    var attributeType = typeof(SettingsExtensionsAttribute);
                    var interfaces = new SettingsInterfaces();
                    foreach (var i in this.Interfaces())
                    {
                        var attributeArray = i.GetCustomAttributes(attributeType, false);
                        if (0 == attributeArray.Length)
                        {
                            throw new Exception("Settings interface {0} is missing attribute {1}", i.ToString(), attributeType.ToString());
                        }

                        var newData = new InterfaceData();
                        newData.InterfaceType = i;

                        var attribute = attributeArray[0] as SettingsExtensionsAttribute;
                        // TODO: the Empty function could be replaced by the auto-property initializers in C#6.0 (when Mono catches up)
                        // although it won't then be a centralized definition, so the extension method as-is is probably better
                        newData.emptyMethod = attribute.GetMethod("Empty", new[] { i });
                        newData.defaultMethod = attribute.GetMethod("Defaults", new[] { i, typeof(Module) });
                        interfaces.Data.Add(newData);
                    }
                    Cache.Add(settingsType, interfaces);
                }
            }

            var data = Cache[settingsType];

            foreach (var i in data.Data)
            {
                if (emptyFirst)
                {
                    if (null != i.emptyMethod)
                    {
                        i.emptyMethod.Invoke(null, new[] { this });
                    }
                }
                if (useDefaults)
                {
                    if (null != i.defaultMethod)
                    {
                        i.defaultMethod.Invoke(null, new object[] { this, module });
                    }
                }
            }
            if (useDefaults && (null != LocalPolicy))
            {
                LocalPolicy.DefineLocalSettings(this, module);
            }
        }
Пример #31
0
        private void SelectInterfaceToName_OnClick(object sender, RoutedEventArgs e)
        {
            InterfaceData selectedInterface = ((FrameworkElement)sender).DataContext as InterfaceData;

            _projectEditorViewModel.SelectedInterface = selectedInterface;
        }