public static string GenerateContractEventHandlerMethod(CsField sourceField, CsEvent targetEvent, NamespaceManager manager = null)
        {
            if (sourceField == null)
            {
                return(null);
            }
            if (!sourceField.IsLoaded)
            {
                return(null);
            }
            if (targetEvent == null)
            {
                return(null);
            }
            if (!targetEvent.IsLoaded)
            {
                return(null);
            }

            SourceFormatter formatter = new SourceFormatter();

            formatter.AppendCodeLine(0, "/// <summary>");
            formatter.AppendCodeLine(0, $"/// Handles the raised event {targetEvent.Name}");
            formatter.AppendCodeLine(0, "/// </summary>");
            formatter.AppendCodeLine(0, $"protected void {GenerateContractEventHandlerMethodName(sourceField,targetEvent)}{targetEvent.EventHandlerDelegate.Parameters.CSharpFormatParametersSignature(manager,false)}");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, "//TODO: Add Event handler logic");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            return(formatter.ReturnSource());
        }
        /// <summary>
        /// Updates the directives in the page file to use razor syntax.
        /// </summary>
        /// <param name="fileName">The file being processed.</param>
        /// <param name="sourceData">The source data to be updated.</param>
        /// <returns>The updated content.</returns>
        private async Task <String> SetRazorPageDirectives(string fileName, Dictionary <string, string> sourceData)
        {
            //String result = String.Empty;
            SourceFormatter result = new SourceFormatter();

            try
            {
                var    pageData = sourceData["HeaderData"];
                Regex  regex    = new Regex(@"(?<=\bMasterPageFile="")[^""]*");
                Match  match    = regex.Match(pageData);
                string layout   = match.Value;
                layout = layout.Replace(".", ""); //remove the old-style Site.Master layout to read SiteMaster

                result.AppendCode($"@page \"/{fileName}\" ");
                if (layout.Length > 0)
                {
                    //Making sure the ~ gets removed from directives
                    result.AppendCodeLine(0, $"@layout { layout.Replace("~/", "")}");
                }
                //result += $"@inherits {fileName}Base\r\n\r\n {sourceData["alteredSource"]}";

                result.AppendCodeLine(0);
                result.AppendCodeLine(0);
                result.AppendCodeLine(0, $"{sourceData["alteredSource"]}");
            }
            catch (Exception unhandledError)
            {
                await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error,
                                                               $"The following unhandled error occured while setting the razor page directives in the file {fileName}. '{unhandledError.Message}'");
            }

            return(result.ReturnSource());
        }
Пример #3
0
        public static string GeneratePartialClass(CsClass source, NamespaceManager manager = null)
        {
            if (source == null)
            {
                return(null);
            }
            if (!source.IsLoaded)
            {
                return(null);
            }
            SourceFormatter formatter = new SourceFormatter();

            StringBuilder classBuilder = new StringBuilder($"{source.Security.CSharpFormatKeyword()} partial {Keywords.Class} {source.Name}");

            if (source.IsGeneric)
            {
                classBuilder.Append(source.GenericParameters.CSharpFormatGenericParametersSignature(manager));
            }

            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, $"namespace {source.Namespace}");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, classBuilder.ToString());
            formatter.AppendCodeLine(1, "{");
            formatter.AppendCodeLine(1);
            formatter.AppendCodeLine(1, "}");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            return(formatter.ReturnSource());
        }
        /// <summary>
        /// Extension method that will add a using statement to target source code. If the using statement already exists it will simply return the existing source.
        /// </summary>
        /// <param name="source">The source code to update.</param>
        /// <param name="nameSpace">The namespace to be added to the using statement.</param>
        /// <param name="alias">Optional parameter to set if you want an alias assigned to the namespace.</param>
        /// <returns>The updated source code or the original source code if no changes were necessary.</returns>
        public static async Task <CsSource> AddUsingStatementAsync(this CsSource source, string nameSpace, string alias = null)
        {
            // ReSharper disable once ExpressionIsAlwaysNull
            if (source == null)
            {
                return(source);
            }

            if (string.IsNullOrEmpty(nameSpace))
            {
                return(source);
            }

            if (source.HasUsingStatement(nameSpace, alias))
            {
                return(source);
            }

            SourceFormatter usingFormatter = new SourceFormatter();

            usingFormatter.AppendCodeLine(0, alias == null ? $"using {nameSpace};" : $"using {alias} = {nameSpace};");

            string usingStatement = usingFormatter.ReturnSource();

            CsSource result = null;

            if (source.NamespaceReferences.Any())
            {
                var lastUsingStatement = source.NamespaceReferences.Last();

                result = await lastUsingStatement.AddAfterAsync(usingStatement);
            }
            else
            {
                result = await source.AddToBeginningAsync(usingStatement);
            }

            return(result);
        }
        /// <summary>
        /// Generates a method that releases to a target interface contract for the target field.
        /// </summary>
        /// <param name="sourceField">The field for which events to subscribe to.</param>
        /// <param name="contract">The contract to subscribe to.</param>
        /// <returns>Full source code for the subscribe method.</returns>
        public static string GenerateContractReleaseMethod(CsField sourceField, CsInterface contract)
        {
            if (sourceField == null)
            {
                return(null);
            }
            if (!sourceField.IsLoaded)
            {
                return(null);
            }
            if (contract == null)
            {
                return(null);
            }
            if (!contract.IsLoaded)
            {
                return(null);
            }

            SourceFormatter formatter = new SourceFormatter();

            formatter.AppendCodeLine(0, "/// <summary>");
            formatter.AppendCodeLine(0, $"/// Releases the events from the interface contract of {contract.Namespace}.{contract.Name} for the field {sourceField.Name}");
            formatter.AppendCodeLine(0, "/// </summary>");
            formatter.AppendCodeLine(0, $"private void {GenerateContractReleaseMethodName(sourceField)}()");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, $"if({sourceField.Name} == null) return;");
            formatter.AppendCodeLine(0);
            foreach (var contractEvent in contract.Events)
            {
                if (!contractEvent.IsLoaded)
                {
                    continue;
                }
                formatter.AppendCodeLine(1, $"{sourceField.Name}.{contractEvent.Name} -= {sourceField.Name.ConvertToProperCase(new []{'_'})}_{contractEvent.Name}_EventHandler;");
            }
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            return(formatter.ReturnSource());
        }
        public static string GenerateRaiseContractEvent(CsEvent targetEvent, NamespaceManager manager = null)
        {
            if (targetEvent == null)
            {
                return(null);
            }
            if (!targetEvent.IsLoaded)
            {
                return(null);
            }

            SourceFormatter formatter = new SourceFormatter();


            string eventParameters = targetEvent.RaiseMethod.Parameters.CSharpFormatParametersSignature(manager);


            int parameterCount = 0;

            StringBuilder parameterBuilder = new StringBuilder();

            foreach (var raiseMethodParameter in targetEvent.RaiseMethod.Parameters)
            {
                parameterCount++;

                if (parameterCount > 1)
                {
                    parameterBuilder.Append($", {raiseMethodParameter.Name}");
                    continue;
                }

                parameterBuilder.Append(raiseMethodParameter.Name);
            }

            formatter.AppendCodeLine(0, "/// <summary>");
            formatter.AppendCodeLine(0, $"/// Raises the event {targetEvent.Name}");
            formatter.AppendCodeLine(0, "/// </summary>");
            formatter.AppendCodeLine(0, $"protected void On{targetEvent.Name}{targetEvent.RaiseMethod.Parameters.CSharpFormatParametersSignature(manager,false)}");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, $"var raiseHandler = _{targetEvent.Name.ConvertToCamelCase()};");
            formatter.AppendCodeLine(1, $"raiseHandler?.Invoke({parameterBuilder});");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            return(formatter.ReturnSource());
        }
Пример #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="targetClass"></param>
        /// <param name="sourceCode"></param>
        /// <param name="members"></param>
        /// <param name="logging"></param>
        /// <param name="cdf"></param>
        /// <param name="cdfAspnet"></param>
        /// <param name="isContract"></param>
        /// <returns></returns>
        private async Task <CsSource> UpdateFileAsync(CsClass targetClass, CsSource sourceCode, IEnumerable <CsMember> members, bool logging, bool cdf, bool cdfAspnet, bool isContract)
        {
            if (targetClass == null)
            {
                throw new CodeFactoryException("Cannot access class data cannot add members");
            }
            if (sourceCode == null)
            {
                throw new CodeFactoryException("Cannot access the classes source code cannot add members.");
            }
            if (members == null)
            {
                return(sourceCode);
            }
            if (!members.Any())
            {
                return(sourceCode);
            }

            CsSource updatedSourceCode = await sourceCode.AddMissingNamespaces(members, targetClass.Namespace);

            CsClass updatedClass = targetClass;



            if (logging)
            {
                updatedSourceCode = await updatedSourceCode.AddUsingStatementAsync(NetConstants.MicrosoftLoggerNamespace);

                updatedClass = sourceCode.GetModel(updatedClass.LookupPath) as CsClass;
                if (updatedClass == null)
                {
                    throw new CodeFactoryException("Cannot get class data to add members.");
                }

                if (!updatedClass.Fields.Any(f => f.Name == NetConstants.DefaultClassLoggerName))
                {
                    var formatter = new SourceFormatter();
                    formatter.AppendCodeLine(0, "///<summary>");
                    formatter.AppendCodeLine(0, "///Logger used to manage logging for this class.");
                    formatter.AppendCodeLine(0, "///</summary>");
                    formatter.AppendCodeLine(0, $"private ILogger {NetConstants.DefaultClassLoggerName};");
                    updatedSourceCode =
                        await updatedClass.AddToBeginningAsync(
                            CsSourceFormatter.IndentCodeBlock(2, formatter.ReturnSource()));
                }
            }

            if (cdf)
            {
                updatedSourceCode = await updatedSourceCode.AddUsingStatementAsync(CommonDeliveryFrameworkConstants
                                                                                   .CommonDeliveryFrameworkNamespace);
            }

            if (cdfAspnet)
            {
                updatedSourceCode = await updatedSourceCode.AddUsingStatementAsync(CommonDeliveryFrameworkConstants
                                                                                   .CommonDeliveryFrameworkNetAspNetNamespace);
            }

            updatedClass = sourceCode.GetModel(updatedClass.LookupPath) as CsClass;
            if (updatedClass == null)
            {
                throw new CodeFactoryException("Cannot get class data to add members.");
            }

            updatedSourceCode = await UpdateMembersAsync(updatedClass, members, logging, cdf, cdfAspnet,
                                                         updatedSourceCode.SourceDocument, isContract, sourceCode.LoadNamespaceManager(updatedClass.Namespace));

            return(updatedSourceCode);
        }
Пример #8
0
        /// <summary>
        /// Generates the source code for a standard raise event method.
        /// </summary>
        /// <param name="eventData">The target event model to generate the raise method for.</param>
        /// <param name="manager">The namespace manager to manage type naming.</param>
        /// <param name="eventName">the name of implemented event to raise.</param>
        /// <param name="security">The target security level to set the event to.</param>
        /// <param name="eventHandler">Optional field, that provides the name of the direct event handler field to raise.</param>
        /// <param name="methodName">Optional parameter of the custom name of the method. If not set will be On[eventName]</param>
        /// <returns></returns>
        public static string GenerateStandardRaiseEventMethod(CsEvent eventData, NamespaceManager manager,
                                                              string eventName, CsSecurity security, string eventHandler = null, string methodName = null)
        {
            //Bounds checking to make sure all data that is needed is provided. If any required data is missing will return null.
            if (eventData == null)
            {
                return(null);
            }
            if (!eventData.IsLoaded)
            {
                return(null);
            }
            if (manager == null)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(eventName))
            {
                return(null);
            }
            if (security == CsSecurity.Unknown)
            {
                return(null);
            }

            var raiseMethod = eventData.EventHandlerDelegate.InvokeMethod;

            if (raiseMethod == null)
            {
                return(null);
            }
            if (!raiseMethod.IsLoaded)
            {
                return(null);
            }

            var parameters = raiseMethod.Parameters.CSharpFormatParametersSignature(manager, false);

            string raiseHandler = string.IsNullOrEmpty(eventHandler) ? eventName : eventHandler;

            StringBuilder parametersBuilder = new StringBuilder();
            int           parameterCount    = 0;

            foreach (var raiseMethodParameter in raiseMethod.Parameters)
            {
                parameterCount++;
                if (parameterCount > 1)
                {
                    parametersBuilder.Append(", ");
                }

                parametersBuilder.Append(raiseMethodParameter.Name);
            }


            //C# helper used to format output syntax.
            var formatter = new SourceFormatter();


            string raiseMethodName = string.IsNullOrEmpty(methodName) ? $"On{eventName}" : methodName;

            formatter.AppendCodeLine(0, "/// <summary>");
            formatter.AppendCodeLine(0, $"/// Raises the event {eventName} when there are subscribers to the event.");
            formatter.AppendCodeLine(0, "/// </summary>");
            formatter.AppendCodeLine(0, $"{security.CSharpFormatKeyword()} {Keywords.Void} {raiseMethodName}{parameters}");
            formatter.AppendCodeLine(0, "{");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(1, $"var raiseEvent = {raiseHandler};");
            formatter.AppendCodeLine(1, $"raiseEvent?.Invoke({parametersBuilder});");
            formatter.AppendCodeLine(0);
            formatter.AppendCodeLine(0, "}");
            formatter.AppendCodeLine(0);

            return(formatter.ReturnSource());
        }