Exemple #1
0
        private void Write()
        {
            var conflicts = data.ParserAutomata.Conflicts;

            logging.Write(
                new LogEntry
            {
                Severity = Severity.Error,
                Origin   = data.Source.Origin,
                Message  = string.Format(
                    "Found {0} parser conflict{1}.",
                    conflicts.Count,
                    conflicts.Count == 1 ? "" : "s")
            });

            var output = new StringBuilder();

            foreach (var conflict in conflicts)
            {
                WriteConflictEntry(conflict, logging);
            }

            // Write fixing advice
            logging.Write(
                new LogEntry
            {
                Severity = Severity.Warning,
                Origin   = data.Source.Origin,
                Message  = string.Format(
                    "Consider using [{0}({1}.{2})] or changing token and/or rule precedences to fix errors.",
                    typeof(LanguageAttribute).Name,
                    typeof(LanguageFlags).Name,
                    Enum.GetName(typeof(LanguageFlags), LanguageFlags.AllowNonDeterministic))
            });
        }
Exemple #2
0
        public bool SendMessage(string uri, string action, string requestSOAPEnvelope, out string responseSOAPEnvelope)
        {
            bool res = false;

            responseSOAPEnvelope = null;
            if (action == null)
            {
                return(res);
            }
            if (uri == null || uri.Length < 1)
            {
                return(res);
            }
            if (requestSOAPEnvelope == null || requestSOAPEnvelope.Length < 1)
            {
                return(res);
            }

            string soapInfo = string.Format("sending SOAP message to uri: {0} with action: {1}", uri, action);

            _log.Write("Begin " + soapInfo);

            try
            {
                //using (ChannelFactory<IAbstractClientContract> factory = new ChannelFactory<IAbstractClientContract>("ABSTRACT_CLIENT_ENDPOINT"))
                using (ConfigurableChannelFactory <IAbstractClientContract> factory = new ConfigurableChannelFactory <IAbstractClientContract>(_configFile))
                {
                    IAbstractClientContract proxy = factory.CreateChannel(new EndpointAddress(uri));
                    using (proxy as IDisposable)
                    {
                        using (OperationContextScope sc = new OperationContextScope(proxy as IContextChannel))
                        {
                            using (Message wcfRequest = SoapMessageHelper.CreateEmptyWCFMessage(
                                       SoapEnvelopeVersion.Soap11,
                                       WSAddressingVersion.None,
                                       action))
                            {
                                OperationContext.Current.OutgoingMessageProperties.Add(SwaEncoderConstants.SoapEnvelopeProperty, requestSOAPEnvelope);
                                using (Message wcfResponse = proxy.SendMessage(wcfRequest))
                                {
                                    responseSOAPEnvelope = SoapMessageHelper.DumpWCFMessage(wcfResponse);
                                    res = true;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                if (_log != null)
                {
                    _log.Write(err);
                }
                res = false;
            }

            _log.Write(string.Format("End {0}. Result: {1}", soapInfo, res));
            return(res);
        }
Exemple #3
0
 private void NotifyError(Exception e)
 {
     if (_log != null)
     {
         _log.Write(e);
     }
 }
        public CilDocumentSyntax Build(ILogging logging, CilDocumentSyntax context)
        {
            if (data == null)
            {
                logging.Write(
                    new LogEntry
                {
                    Severity = Severity.Error,
                    Message  = string.Format(
                        "Failed to compile '{0}' language definition.",
                        languageName.FullLanguageName),
                    Origin = languageName.Origin
                });

                return(null);
            }

            this.logging = logging;

            this.declaringTypeRef = context.Types.Class_(
                ClassName.Parse(languageName.LanguageTypeName));

            logging.Write(
                new LogEntry
            {
                Severity = Severity.Verbose,
                Message  = string.Format("Started Compiling Derived assembly for {0}", languageName.FullLanguageName)
            });

            var result = context
                         .Class_()
                         .Public
                         .Named(languageName.LanguageTypeName)
                         .Extends(context.Types.Import(typeof(LanguageBase)))
                         .Do(BuildMethod_CreateGrammar)
                         .Do(BuildMethod_GetParserAction)
                         .Do(BuildMethod_CreateTokenIdentities)
                         .Do(BuildMethod_Scan1)
                         .Do(BuildMethod_TermFactory)
                         .Do(BuildMethod_GrammarAction)
                         .Do(BuildMethod_MergeAction)
                         .Do(BuildMethod_CreateStateToSymbol)
                         .Do(BuildMethod_CreateParserActionConflicts)
                         .Do(BuildMethod_CreateTokenComplexityTable)
                         .Do(BuildMethod_CreateDefaultContext)
                         .Do(Build_Ctor)
                         .EndClass()
            ;

            logging.Write(
                new LogEntry
            {
                Severity = Severity.Verbose,
                Message  = string.Format("Done Compiling Derived assembly for {0}", languageName.FullLanguageName)
            });

            implementationGenerator.Generate(context);
            return(result);
        }
Exemple #5
0
 private bool LoadFile()
 {
     try
     {
         this.textBoxMain.Text = File.ReadAllText(FileName, Encoding.UTF8);
         return(true);
     }
     catch (Exception err)
     {
         _log.Write(err);
         MessageBox.Show(this, string.Format("Open file failed from:{0}\r\nReason:{1}",
                                             FileName, err.Message), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
         return(false);
     }
 }
Exemple #6
0
        internal override string Convert(string chinese, ILogging log)
        {
            if (chinese == null || chinese.Length < 1)
            {
                return("");
            }

            try
            {
                StringBuilder strCC = new StringBuilder();
                strCC.Append(chinese);

                StringBuilder strPY = new StringBuilder();
                CC2PY(strPY, strCC, 2);

                return(strPY.ToString());
            }
            catch (Exception err)
            {
                if (log != null)
                {
                    log.Write(LogType.Error, err.ToString());
                }
                return("");
            }
        }
Exemple #7
0
        private void WriteConflictEntry(ParserConflictInfo conflict, ILogging logging)
        {
            using (var writer = new StringWriter())
                using (var message = new IndentedTextWriter(writer, "  "))
                {
                    var symbol = data.Grammar.Symbols[conflict.Token];

                    message.Write("Conflict on token ");
                    message.Write(symbol.Name);
                    message.Write(" between actions in state #");
                    message.Write(conflict.State + "");
                    message.WriteLine(":");

                    ++message.Indent;
                    DescribeState(message, conflict.State);
                    for (int i = 0; i != conflict.Actions.Count; ++i)
                    {
                        message.WriteLine("Action #{0}:", i + 1);
                        DescribeAction(message, conflict.Actions[i]);
                    }

                    --message.Indent;

                    logging.Write(
                        new LogEntry
                    {
                        Severity = Severity.Error,
                        Origin   = data.Source.Origin,
                        Message  = writer.ToString()
                    });
                }
        }
Exemple #8
0
        public static void WriteConfigToFile(string configFileName, string targetFilePath, bool overWrite, ILogging log)
        {
            try
            {
                if (!overWrite)
                {
                    if (File.Exists(targetFilePath))
                    {
                        return;
                    }
                }

                Assembly asm          = Assembly.GetExecutingAssembly();
                string   resourceName = string.Format("HYS.Common.Soap.DefaultConfiguration.{0}", configFileName);
                using (Stream xmlStream = asm.GetManifestResourceStream(resourceName))
                {
                    using (Stream file = File.OpenWrite(targetFilePath))
                    {
                        CopyStream(xmlStream, file);
                    }
                }
            }
            catch (Exception err)
            {
                log.Write(err);
            }
        }
Exemple #9
0
        internal override string Convert(string chinese, ILogging log)
        {
            if (chinese == null || chinese.Length < 1)
            {
                return("");
            }

            try
            {
                StringBuilder strCC = new StringBuilder();
                strCC.Append(chinese);

                StringBuilder strPY = new StringBuilder();
                GetTCPinyin(strCC, strPY, 256, JKTCPYCNVT_NOUPPERCAPITAL);

                return(strPY.ToString());
            }
            catch (Exception err)
            {
                if (log != null)
                {
                    log.Write(LogType.Error, err.ToString());
                }
                return("");
            }
        }
Exemple #10
0
        public bool Save(ILogging log)
        {
            try
            {
                if (_hasSaved)
                {
                    return(true);
                }
                using (StreamWriter sw = File.CreateText(FileName))
                {
                    string str = Config.ToXMLString();
                    str = XMLHeader + str;
                    sw.Write(str);

                    _hasSaved = true;
                    return(true);
                }
            }
            catch (Exception e)
            {
                log.Write(e);
                _lastError = e;
                return(false);
            }
        }
        public bool Load(ILogging logging)
        {
            if (!assemblyProvider.Load(logging))
            {
                return(false);
            }

            var type = assemblyProvider.Resource.GetType(languageName.LanguageTypeName);

            if (type == null)
            {
                logging.Write(
                    new LogEntry
                {
                    Severity = Severity.Error,
                    Message  = string.Format(
                        "Unable to load type '{0}' from the assembly '{1}'",
                        languageName.LanguageTypeName,
                        assemblyProvider.Resource.FullName),
                });
                return(false);
            }

            Resource = (ILanguageRuntime)Activator.CreateInstance(type, languageName);
            return(true);
        }
Exemple #12
0
        public GWLicense LoginGetLicenseLogout(Form frm, ILogging log)
        {
            if (frm != null)
            {
                return(_LoginGetLicenseLogout(frm, log));
            }

            _log     = log;
            _license = null;
            _event   = new ManualResetEvent(false);

            Thread thr = new Thread(new ThreadStart(DoLoginGetLicenseLogout));

            thr.SetApartmentState(ApartmentState.STA);
            thr.Start();

            //bool res = _event.WaitOne(10 * 1000, true);  //10 s
            bool res = _event.WaitOne(3600 * 1000, true);  //60 min

            if (res)
            {
                return(_license);
            }
            else
            {
                if (log != null)
                {
                    log.Write(LogType.Warning, "Get license timeout.");
                }
                return(null);
            }
        }
        public static void WithTimeLogging(
            this ILogging logging,
            string contextName,
            string origin,
            Action action,
            string activityName)
        {
            logging.Verbose(origin, "Started {0} for {1}", activityName, contextName);

            try
            {
                action();
            }
            catch (Exception e)
            {
                logging.Write(
                    new LogEntry
                {
                    Severity = Severity.Error,
                    Origin   = origin,
                    Message  = e.Message
                });
            }
            finally
            {
                logging.Verbose(origin, "Done {0} for {1}", activityName, contextName);
            }
        }
Exemple #14
0
 private void WriteLog(LogType t, string msg)
 {
     if (_log != null)
     {
         _log.Write(t, "[DirectoryMonitor] " + msg);
     }
 }
Exemple #15
0
        public static string Convert(ChineseCodeConvertType type, string strSource, ILogging log)
        {
            try
            {
                switch (type)
                {
                default: return(strSource);

                case ChineseCodeConvertType.BIG52GB: return(BIG52GB(strSource));

                case ChineseCodeConvertType.BIG52GBK: return(BIG52GBK(strSource));

                case ChineseCodeConvertType.GB2BIG5: return(GB2BIG5(strSource));

                case ChineseCodeConvertType.GB2GBK: return(GB2GBK(strSource));

                case ChineseCodeConvertType.GBK2BIG5: return(GBK2BIG5(strSource));

                case ChineseCodeConvertType.GBK2GB: return(GBK2GB(strSource));
                }
            }
            catch (Exception err)
            {
                if (log != null)
                {
                    log.Write(LogType.Error, err.ToString());
                }
                return("");
            }
        }
Exemple #16
0
        private void CheckAllScanRulesDefined(
            IEnumerable <CilSymbol> undefinedTerminals,
            string origin,
            ILogging logging)
        {
            if (undefinedTerminals.Count() == 0)
            {
                return;
            }

            var  message = new StringBuilder("Undefined scan or parse productions for tokens: ");
            bool first   = true;

            foreach (var term in undefinedTerminals)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    message.Append(", ");
                }

                message.Append(term.ToString());
            }

            logging.Write(
                new LogEntry
            {
                Severity = Severity.Warning,
                Message  = message.ToString(),
                Origin   = origin,
            });
        }
Exemple #17
0
        public string Replace(string sourceString, ILogging log)
        {
            try
            {
                if (sourceString == null)
                {
                    return("");
                }

                //log.Write(sourceString);

                //log.Write("Pattern:" + Expression + ";Replacement:" + Replacement);

                string str = Regex.Replace(sourceString, Expression, Replacement);

                //log.Write(str);

                return(str);
            }
            catch (Exception err)
            {
                if (log != null)
                {
                    log.Write(LogType.Error, err.ToString());
                }
                return(sourceString);
            }
        }
Exemple #18
0
 /// <summary>
 /// If your XSLT file need to include/import other XLST file, you cannot use script or call any extension in the XSLT. So set enableExtension as false.
 /// </summary>
 /// <param name="xslFileName"></param>
 /// <param name="log"></param>
 /// <param name="enableExtension"></param>
 /// <returns></returns>
 public static XMLTransformer CreateFromString(string xslString, ILogging log, bool enableExtension)
 {
     try
     {
         using (StringReader sr = new StringReader(xslString))
         {
             using (XmlReader xr = XmlReader.Create(sr))
             {
                 XslCompiledTransform myXslTrans = new XslCompiledTransform();
                 if (enableExtension)
                 {
                     myXslTrans.Load(xr, new XsltSettings(true, true), null);
                 }
                 else
                 {
                     myXslTrans.Load(xr);
                 }
                 return(new XMLTransformer(myXslTrans, log));
             }
         }
     }
     catch (Exception err)
     {
         if (log != null)
         {
             log.Write(err);
         }
         return(null);
     }
 }
Exemple #19
0
        private bool CreateDelegate(ILogging logging)
        {
            if (Resource == null)
            {
                var type = assemblyProvider.Resource.GetType(typeName);
                if (type == null)
                {
                    return(false);
                }

                var method = type.GetMethod(methodName);
                if (method == null)
                {
                    logging.Write(
                        new LogEntry
                    {
                        Severity = Severity.Error,
                        Message  = string.Format(
                            "Type '{0}' does not have method '{1}'",
                            type.FullName,
                            methodName)
                    });
                    return(false);
                }

                Resource = (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), method);
            }

            return(true);
        }
        private bool CheckNonNullablePatterns(AstNode root)
        {
            if (!IsNullable(root))
            {
                return(true);
            }

            foreach (var matcher in Matchers)
            {
                var binding = matcher.Joint.The <CilMatcher>();

                if (matcher.Pattern.Literal != null)
                {
                    if (matcher.Pattern.Literal == "")
                    {
                        logging.Write(
                            new LogEntry
                        {
                            Severity = Severity.Error,
                            Message  = string.Format(
                                "Literal cannot be empty string.",
                                matcher),
                            Origin = ReflectionUtils.ToString(binding.DefiningMethod)
                        });
                    }
                }
                else
                {
                    var ast = GetAst(matcher.Pattern.Pattern);
                    if (IsNullable(ast))
                    {
                        logging.Write(
                            new LogEntry
                        {
                            Severity = Severity.Error,
                            Message  = string.Format(
                                "Scan pattern cannot match empty string.",
                                matcher),
                            Origin = ReflectionUtils.ToString(binding.DefiningMethod)
                        });
                    }
                }
            }

            return(false);
        }
        private ClassSyntax BuildMethod_Scan1(ClassSyntax context)
        {
            logging.Write(
                new LogEntry
            {
                Severity = Severity.Verbose,
                Message  = string.Format("Started compiling Scan1 modes for {0} language", languageName.LanguageName)
            });

            foreach (var condition in data.Grammar.Conditions)
            {
                ITdfaData dfa = condition.Joint.The <ITdfaData>();
                var       dfaSerialization = new DfaSerialization(dfa);
                var       generator        = new ScannerGenerator(dfaSerialization);

                var methodName = ConditionMethods.GetMethodName(condition.Index);
                var args       = context
                                 .Method()
                                 .Static
                                 .Returning(context.Types.Int32)
                                 .Named(methodName)
                                 .BeginArgs();

                var emit = args
                           .Argument(
                    context.Types.Import(typeof(ScanCursor)),
                    args.Args.Generate("cursor"))              // input
                           .EndArgs()
                           .NoInlining
                           .NoOptimization
                           .BeginBody();

                generator.Build(emit);

                context = emit.EndBody();
            }

            logging.Write(
                new LogEntry
            {
                Severity = Severity.Verbose,
                Message  = string.Format("Done compiling Scan1 modes for {0} language", languageName.LanguageName)
            });
            return(context);
        }
Exemple #22
0
        public CrmHelper(ICrmService crmService, ILogging logging, ICrmResourceStrings crmResourceStrings)
        {
            if (crmService == null) throw new ArgumentNullException("crmService");
            if (logging == null) throw new ArgumentNullException("logging");
            _crmService = crmService;
            _logging = logging;
            _crmResourceStrings = crmResourceStrings;

            _logging.Write(GetString("LoggingCrmHelperCreated", "Created CrmHelper"));
        }
 private void ReportError()
 {
     logging.Write(
         new LogEntry
     {
         Severity  = Severity.Error,
         Location  = errorLocation,
         HLocation = errorHLocation,
         Message   = "Unexpected input"
     });
 }
Exemple #24
0
        public void Write_WriteTextToFil_TextIsWrittenToFile(string expected)
        {
            //Act
            _uut.Write(expected);
            using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            using var sr = new StreamReader(fs, Encoding.UTF8);

            string result = sr.ReadToEnd();

            //Assert
            Assert.That(result, Is.EqualTo(expected));
        }
        public void ProcessChangedFrozenFlag(ICrmService service, ILogging logging, CrmObject.Account account, bool forceChanges = false)
        {
            var l = new LocalLogger(logging, this.GetType().Name);

            if (service == null)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (logging == null)
            {
                throw new ArgumentNullException(nameof(logging));
            }
            if (account == null)
            {
                throw new ArgumentNullException(nameof(account));
            }

            var isFrozen = this.IsAccountFrozen(account);

            l.Write($"IsFrozen={isFrozen}");

            var accountQuery = new AccountQueries(service);

            List <CrmObject.Account> childAccounts;

            try
            {
                childAccounts = accountQuery.GetChildAccountsForAnAccount(account.ToEntityReference());
                l.Write($"Retrieved {childAccounts.Count} child records.");
            }
            catch (Exception ex)
            {
                l.Write($"Exception retrieving accounts to update for account id: {account.Id}");
                logging.Write(ex);
                throw;
            }

            var accountsToUpdate = this.UpdateAccountsFrozenFlag(childAccounts, isFrozen, forceChanges);

            l.Write($"Updating {accountsToUpdate.Count} records.");

            try
            {
                accountsToUpdate.ForEach(service.Update);
                l.Write("Completed CRM Updates.");
            }
            catch (Exception ex)
            {
                l.Write("Exception while updating records.");
                l.Write(ex);
                throw;
            }
        }
        protected IEnumerable <File> UpdateFiles()
        {
            ILogging logging = this.Logging ?? new ConsoleLogging();

            var folder = drive.FindFolder(this.GDriveFolder);
            var files  = drive.FindSpreadsheetFiles(folder).Where(file => !(file.ExplicitlyTrashed ?? false));

            var filesGroup = files.GroupBy(file => file.Title);

            var cachedFiles           = System.IO.Directory.GetFiles(CachingDir, "*.xlsx");
            var cachedFilesAccessDate = cachedFiles.ToDictionary(file => System.IO.Path.GetFileNameWithoutExtension(file),
                                                                 file => System.IO.Directory.GetLastWriteTimeUtc(file));

            foreach (var file in files)
            {
                //var modifiedDate = FromRFC3339(file.ModifiedDate ?? file.CreatedDate);
                var modifiedDate = file.ModifiedDate ?? file.CreatedDate;

                if (!cachedFilesAccessDate.ContainsKey(file.Title))
                {
                    //file does'nt exist yet, download it
                    logging.Write("File {0} doesn't exist yet, downloading it...", file.Title);
                    DownloadFile(file);
                    logging.WriteLine(".Done.");
                }
                else if (cachedFilesAccessDate[file.Title] < modifiedDate)
                {
                    //file's been updated, download it
                    logging.Write("File {0} with local date {1} has been updated on {2}, downloading it...", file.Title, cachedFilesAccessDate[file.Title], modifiedDate);
                    DownloadFile(file);
                    logging.WriteLine(".Done.");
                }
                else
                {
                    logging.WriteLine("File {0} with local date {1} is up to date.", file.Title, cachedFilesAccessDate[file.Title]);
                }
            }

            return(files);
        }
Exemple #27
0
        public bool Start(string uri)
        {
            bool res = false;

            if (uri == null || uri.Length < 1)
            {
                return(res);
            }
            _log.Write(string.Format("Begin starting SOAP server on {0}.", uri));

            Stop();

            try
            {
                _host = new ConfigurableServiceHost(_configFile, typeof(AbstractService), new Uri(uri));
                ((ConfigurableServiceHost)_host).Tag = this;
                _host.Open();
                res = true;
            }
            catch (Exception e)
            {
                _log.Write(e);
            }

            _log.Write(string.Format("End starting SOAP server on {0}. Result: {1}", uri, res));
            return(res);
        }
 public static void Verbose(
     this ILogging logging,
     string origin,
     string fmt,
     params object[] args)
 {
     logging.Write(
         new LogEntry
     {
         Severity = Severity.Verbose,
         Origin   = origin,
         Message  = string.Format(fmt, args)
     });
 }
Exemple #29
0
        public SOAPServer(string cfgFile, string soapErrFile, ILogging log)
        {
            _log         = log;
            _configFile  = cfgFile;
            _soapErrFile = soapErrFile;

            try
            {
                _soapErrEnvelope = File.ReadAllText(_soapErrFile);
            }
            catch (Exception err)
            {
                log.Write(err);
            }
        }
Exemple #30
0
        public static string GetValueWithXPath(string xmlString, string xpath, string prefixDef, ILogging log)
        {
            if (xpath == null || xpath.Length < 1)
            {
                return("");
            }
            if (xmlString == null || xmlString.Length < 1)
            {
                return("");
            }

            try
            {
                using (StringReader sr = new StringReader(xmlString))
                {
                    XPathDocument  doc = new XPathDocument(sr);
                    XPathNavigator nvg = doc.CreateNavigator();

                    XmlNamespaceManager nsMgr = null;
                    if (prefixDef != null && prefixDef.Length > 0)
                    {
                        nsMgr = new XmlNamespaceManager(nvg.NameTable);
                        XSLTExtension.FillXmlNamespaceManager(nsMgr, prefixDef);
                    }

                    object o     = (nsMgr == null) ? nvg.Evaluate(xpath) : nvg.Evaluate(xpath, nsMgr);
                    string value = (o != null) ? o.ToString() : "";     //"(null)";

                    XPathNodeIterator i = o as XPathNodeIterator;
                    if (i != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        while (i.MoveNext())
                        {
                            sb.Append(i.Current.Value); //.Append(';');
                        }
                        value = sb.ToString();          //.TrimEnd(';');
                    }

                    return(value);
                }
            }
            catch (Exception e)
            {
                log.Write(e);
                return("");  //"(error)";
            }
        }
        public override bool Validate(ILogging logging)
        {
            if (string.IsNullOrEmpty(LiteralText))
            {
                logging.Write(
                    new LogEntry
                {
                    Severity = Severity.Error,
                    Message  = "Literal cannot be null or empty string.",
                    Origin   = ReflectionUtils.ToString(this.Member)
                });
                return(false);
            }

            return(base.Validate(logging));
        }
        public override bool Validate(ILogging logging)
        {
            if (string.IsNullOrEmpty(LiteralText))
            {
                logging.Write(
                    new LogEntry
                    {
                        Severity = Severity.Error,
                        Message = "Literal cannot be null or empty string.",
                        Origin = ReflectionUtils.ToString(this.Member)
                    });
                return false;
            }

            return base.Validate(logging);
        }
Exemple #33
0
        protected virtual bool ValidatePluginExecution(ICrmContext crmContext, ILogging logging, out string keyName)
        {
            logging.Write("ThinkCrmPlugin: Default ValidatePluginExecution Executed");

            var attrs = System.Attribute.GetCustomAttributes(this.GetType());

            var preImageName = crmContext.PluginExecutionContext.PreEntityImages.Count > 0
                ? crmContext.PluginExecutionContext.PreEntityImages.First().Key : string.Empty;
            var preImage = crmContext.PluginExecutionContext.PreEntityImages.Count > 0
                ? crmContext.PluginExecutionContext.PreEntityImages.First().Value
                : null;

            var postImageName = crmContext.PluginExecutionContext.PostEntityImages.Count > 0
                ? crmContext.PluginExecutionContext.PostEntityImages.First().Key
                : string.Empty;
            var postImage = crmContext.PluginExecutionContext.PostEntityImages.Count > 0
                ? crmContext.PluginExecutionContext.PostEntityImages.First().Value
                : null;

            foreach (var pAtt in attrs.OfType<PluginRegistrationAttribute>().Select(att => att as PluginRegistrationAttribute))
            {
                logging.Write("ThinkCrmPlugin: Validating Key Name: {0}", pAtt.KeyName);
                if (pAtt.MatchesExecutingPlugin(crmContext.Message, crmContext.PluginExecutionContext.PrimaryEntityName,
                    crmContext.PluginExecutionContext.SecondaryEntityName, crmContext.PipelineStage,
                    crmContext.ExecutionMode, crmContext.PluginExecutionContext.IsExecutingOffline, preImageName,
                    preImage, postImageName, postImage))
                {
                    keyName = pAtt.KeyName;
                    logging.WriteAndReturn(true, "ThinkCrmPlugin: Validated Key Name: {0}", keyName);
                }
                else
                {
                    logging.Write("ThinkCrmPlugin: Validation Failed for Key Name: {0}", pAtt.KeyName);
                }

            }

            logging.Write("ThinkCrmPlugin: No PluginRegistrationAttribute was Validated");
            keyName = string.Empty;
            return false;
        }
        protected override bool DoRebuild(ILogging logging, ref Assembly resource)
        {
            CilSyntax context = CecilBackend.Create(null);

            var builder = GetBuilder();

            ((IAssemblyResolverParameters)context).AddSearchDirectory(
                Path.GetDirectoryName(derivedPath));

            if (resourceDirs != null)
            {
                foreach (var resourceDir in resourceDirs)
                {
                    logging.Write(
                        new LogEntry
                        {
                            Severity = Severity.Verbose,
                            Message = "Using additional assembly search directory: " + resourceDir,
                        });
                    ((IAssemblyResolverParameters)context).AddSearchDirectory(
                        resourceDir);
                }
            }

            var cilDocument = context
            .BeginDocument()
                .Assembly(AssemblyName.Name)
                    .CustomAttribute(
                        context.Types.Import(typeof(DerivedAssemblyMarker)))
                .EndAssembly()
                .AssemblyExtern(context.ResolutionScopeNs.DefineReferencedAssemblyName(new Name1("mscorlib")))
                    .Version(4, 0, 0, 0)
                    .PublicKeyToken(new Bytes(new byte[] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 }))
                .EndAssemblyExtern()
                .Module(new QStr(derivedPath))
                ;

            cilDocument = Build(builder, logging, cilDocument);
            if (cilDocument == null)
            {
                logging.Write(
                    new LogEntry
                    {
                        Severity = Severity.Error,
                        Message = string.Format("Failed to compile assembly '{0}'.", derivedPath)
                    });
                return false;
            }

            cilDocument .EndDocument();

            var writer = context as IAssemblyWriter;
            if (writer == null)
            {
                throw new InvalidOperationException("Backend does not support assembly writing");
            }

            writer.Write(derivedPath);

            logging.Write(
                new LogEntry
                {
                    Severity = Severity.Verbose,
                    Message = string.Format("Saved derived assembly {0}", AssemblyName.Name)
                });

            return true;
        }
        private bool ValidateAllGenericArgsAreUsed(
            List<Type> usedTypes,
            Type       compositeType,
            ILogging   logging)
        {
            DeleteUsedGenericArgs(usedTypes, compositeType, logging);
            if (usedTypes.Count != 0)
            {
                logging.Write(
                    new LogEntry
                    {
                        Severity = Severity.Error,
                        Message  = "One or more generic arguments cannot be deduced from the method result type.",
                        Origin   = ReflectionUtils.ToString(Method)
                    });
                return false;
            }

            return true;
        }
Exemple #36
0
 protected virtual ICrmResourceStrings InitializeResourceStrings(IPluginSetup pluginSetup, ILogging logging)
 {
     logging.Write("ThinkCrmPlugin: No Resource Strings Configured");
     return null;
 }
Exemple #37
0
        private bool ExceedsMaxDepth(int pluginDepth, ILogging logging)
        {
            logging.Write("ThinkCrmPlugin: ExceedsMaxDepth Executed");

            var attrs = System.Attribute.GetCustomAttributes(this.GetType());

            if (!attrs.OfType<MaxDepthAttribute>().Any()) return logging.WriteAndReturn(false, "ThinkCrmPlugin: No MaxDepth Attribute Found");

            var maxAllowedDepth = attrs.OfType<MaxDepthAttribute>().First().MaxDepth;

            logging.Write("ThinkCrmPlugin: MaxDepth Attribute Found, MaxDepth Allowed={0} Actual Depth={1}",maxAllowedDepth, pluginDepth);

            return pluginDepth > maxAllowedDepth;
        }
Exemple #38
0
        private ReturnOnErrorAttribute GetErrorRules(ILogging logging)
        {
            logging.Write("ThinkCrmPlugin: GetErrorRules Executed");

            var attrs = System.Attribute.GetCustomAttributes(this.GetType());

            if (!attrs.OfType<ReturnOnErrorAttribute>().Any()) return logging.WriteAndReturn(new ReturnOnErrorAttribute(), "ThinkCrmPlugin: No MaxDepth Attribute Found, Using Defaults");

            var errorRules = (ReturnOnErrorAttribute) attrs.First();

            return logging.WriteAndReturn(errorRules,
                "ThinkCrmPlugin: Found ReturnOnError Attribute ReturnOnPluginError={0} / ReturnOnPluginValiationError={1} / ReturnOnUnhandledError={2} ",
                errorRules.ReturnOnPluginError.ToString(), errorRules.ReturnOnPluginValidationError.ToString(),
                errorRules.ReturnOnUnhandledError.ToString());
        }
Exemple #39
0
        private bool SkipPluginValidation(ICrmContext crmContext, ILogging logging)
        {
            logging.Write("ThinkCrmPlugin: SkipPluginValidation Executed");

            var attrs = System.Attribute.GetCustomAttributes(this.GetType());

            if (!attrs.OfType<SkipValidationAttribute>().Any()) return logging.WriteAndReturn(false, "ThinkCrmPlugin: No SkipValidationAttribute Attribute Found");

            var skipBool = attrs.OfType<SkipValidationAttribute>().First().SkipValidation;

            return logging.WriteAndReturn(skipBool, "ThinkCrmPlugin: SkipPluginValidation Attribute Found, Skip={0}", skipBool.ToString());
        }