Exemplo n.º 1
0
        /// <summary>
        /// Insert header in document
        /// </summary>
        /// <param name="template">Template to be added</param>
        /// <param name="textSelection">Text selection of document</param>
        private void InsertHeader(string template, TextSelection textSelection)
        {
            // Add header
            textSelection.StartOfDocument();
            textSelection.NewLine();
            textSelection.StartOfDocument();

            textSelection.Text = template;
            textSelection.NewLine();
            textSelection.NewLine();
            RemoveSpecialCharacters(textSelection, template);
        }
        public static void AddBlankLineAfterElement(this CodeElement codeElement)
        {
            var           endPoint = codeElement.EndPoint.CreateEditPoint();
            TextSelection txtSel   = (TextSelection)codeElement.DTE.ActiveDocument.Selection;

            endPoint.LineDown();
            endPoint.StartOfLine();
            txtSel.MoveToPoint(endPoint);
            txtSel.NewLine(1);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Adds the header comment.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="headerComment">The header comment.</param>
        public static void AddHeaderComment(
            this ProjectItem instance,
            string headerComment)
        {
            TextSelection selection = (TextSelection)instance.Document.Selection;

            selection.StartOfDocument();
            selection.NewLine();
            selection.LineUp();
            selection.Text = headerComment;
        }
        /// <summary>
        /// Adds the header comment.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="headerComment">The header comment.</param>
        public static void AddHeaderComment(
            this ProjectItem instance,
            string headerComment)
        {
            TraceService.WriteLine("ProjectItemExtensions::AddHeaderComment");

            TextSelection selection = (TextSelection)instance.Document.Selection;

            selection.StartOfDocument();
            selection.NewLine();
            selection.LineUp();
            selection.Text = headerComment;
        }
Exemplo n.º 5
0
        private static void MoveUsingsInsideNameSpace(ProjectItem projectItem, TextSelection txtSel, CodeNamespace nameSpace)
        {
            var usingsOutsideNameSpace = SearchService.FindUsings(projectItem.FileCodeModel.CodeElements);

            if (usingsOutsideNameSpace.Any())
            {
                List <string> linesToMove = new List <string>();
                for (int i = 0; i < usingsOutsideNameSpace.Count(); i++)
                {
                    linesToMove.Add(usingsOutsideNameSpace[i].InnerText());
                    usingsOutsideNameSpace[i].Delete();
                }

                var editPoint = nameSpace.GetStartPoint().CreateEditPoint();
                editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
                txtSel.MoveToPoint(editPoint);
                txtSel.NewLine();
                foreach (var line in linesToMove)
                {
                    txtSel.Insert(line);
                    txtSel.NewLine();
                }
            }
        }
Exemplo n.º 6
0
        private static void AddToExisting(ProjectItem extObject, string code)
        {
            // TODO: Need to handle failure here.
            var window = extObject.Open();

            window.Activate();

            TextSelection selection = (TextSelection)extObject.Document.Selection;

            selection.SelectAll();
            var text = selection.Text;

            selection.EndOfDocument();

            selection.NewLine();
            selection.Insert(code);
        }
Exemplo n.º 7
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Inserts the method header.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        public void InsertMethodHeader()
        {
            TextSelection sel = (TextSelection)m_applicationObject.ActiveDocument.Selection;

            CodeElement codeElement = GetMethodOrProperty(sel);

            if (codeElement == null)
            {
                codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementClass);
                if (codeElement == null)
                {
                    codeElement = sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementInterface);
                }
                if (codeElement == null || codeElement.StartPoint.Line != sel.ActivePoint.Line)
                {
                    // not a function or property, so just insert /// <summary/>
                    sel.LineUp(false, 1);
                    if (!IsXmlCommentLine)
                    {
                        sel.EndOfLine(false);
                        sel.NewLine(1);
                        sel.Text = "///";
                        sel.LineDown(true, 1);
                        sel.Delete(1);
                        sel.LineUp(false, 1);
                        sel.EndOfLine(false);
                        sel.WordRight(true, 2);
                        sel.Delete(1);
                    }
                    else
                    {
                        sel.LineDown(false, 1);
                    }
                    return;
                }
            }

            sel.MoveToPoint(codeElement.StartPoint, false);

            // Figure out indentation and build dashed line
            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);
            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, true);
            string indent = sel.Text;

            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
            string dashedLine = indent + "/// " +
                                new string('-', kLineLen - sel.ActivePoint.VirtualDisplayColumn - 4);

            bool fGhostDoc = true;

            try
            {
                // Use GhostDoc if available
                string addinName = string.Empty;
                foreach (AddIn addin in m_applicationObject.AddIns)
                {
                    if (addin.Name == "GhostDoc")
                    {
                        addinName = (addin.ProgID == "SubMain.GhostDoc.Connect") ?
                                    "Tools.SubMain.GhostDoc.DocumentThis" : "Weigelt.GhostDoc.AddIn.DocumentThis";
                        break;
                    }
                }
                if (addinName != string.Empty)
                {
                    m_applicationObject.ExecuteCommand(addinName, string.Empty);
                }
                else
                {
                    fGhostDoc = false;
                }
            }
            catch
            {
                fGhostDoc = false;
            }

            if (fGhostDoc)
            {
                int nLine       = sel.ActivePoint.Line;
                int nLineOffset = sel.ActivePoint.LineCharOffset;

                // Check to see if we're in the middle of the comment or at the beginning of
                // the method.
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                if (GetMethodOrProperty(sel) == null)
                {
                    // we're in the middle of the comment - move to the end of the comment
                    MoveDownAfterComment(sel);

                    // we're inserting one line (//---) above
                    nLine++;
                }
                else
                {
                    // We are at the beginning of the method.
                    // Check to see if the line above the current line is an attribute. If it is we want to
                    // start there, otherwise we start at the current line.
                    sel.LineUp(false, 1);
                    sel.CharRight(false, 1);
                    if (sel.ActivePoint.get_CodeElement(vsCMElement.vsCMElementAttribute) == null)
                    {
                        sel.MoveToLineAndOffset(nLine, 1, false);
                    }

                    // we're inserting two lines above
                    nLine += 2;
                }
                // In case the line is wrapped, we want to go to the real beginning of the line
                sel.MoveToLineAndOffset(sel.ActivePoint.Line, 1, false);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);

                // Insert a new line and then insert our dashed line.
                sel.Insert(dashedLine + Environment.NewLine, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);

                sel.LineUp(false, 1);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                MoveUpBeforeComment(sel);

                sel.Insert(Environment.NewLine + dashedLine, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);

                // put IP at previous location
                sel.MoveToLineAndOffset(nLine, nLineOffset, false);
            }
            else
            {
                // check if we already have a comment
                sel.LineUp(false, 1);
                if (!IsXmlCommentLine)
                {
                    // Insert comment
                    sel.EndOfLine(false);
                    sel.NewLine(1);
                    sel.Text = "///";
                }

                // Insert line above
                MoveUpBeforeComment(sel);
                sel.EndOfLine(false);
                sel.NewLine(1);
                sel.Text = dashedLine;
                int upperLine = sel.ActivePoint.Line;
                sel.LineDown(false, 1);

                // reformat text
                for (; IsXmlCommentLine;)
                {
                    int curLine = sel.CurrentLine;
                    // go through all words in this line
                    for (; sel.CurrentLine == curLine; sel.WordRight(false, 1))
                    {
                        if (sel.ActivePoint.VirtualDisplayColumn > kLineLen)
                        {
                            // we have to break before this word
                            sel.WordLeft(true, 1);
                            // skip all punctuation characters
                            for (; sel.Text.Length == 1 && char.IsPunctuation(sel.Text[0]);)
                            {
                                sel.CharLeft(false, 1);                                 // removes selection
                                sel.WordLeft(true, 1);
                            }
                            sel.CharLeft(false, 1);                             // removes selection

                            // break the line
                            sel.NewLine(1);

                            // join next line with remainder of current line
                            sel.EndOfLine(false);
                            sel.LineDown(true, 1);
                            sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, true);
                            sel.WordRight(true, 1);
                            sel.Delete(1);

                            // insert a space between the two lines
                            sel.Text = " ";
                        }
                    }
                }

                // Insert line below
                sel.GotoLine(upperLine + 1, false);
                MoveDownAfterComment(sel);
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.NewLine(1);
                sel.LineUp(false, 1);
                sel.Text = dashedLine;
                sel.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, false);
                sel.LineDown(false, 1);
            }
        }
Exemplo n.º 8
0
        private void _Do_0(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace");
                return;
            }

            Func <MBColumn, string> _getType = c =>
            {
                switch (c.Type)
                {
                case _Types.t_bit:
                    if (c.Spec.Contains("(1)"))
                    {
                        return((c.Nullable) ? "Nullable<bool>" : "bool");
                    }
                    return((c.Nullable) ? "Nullable<bool>" : "bool");

                case _Types.t_boolean:
                    return((c.Nullable) ? "Nullable<bool>" : "bool");

                case _Types.t_tinyint:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<byte>" : "byte");
                    }
                    return((c.Nullable) ? "Nullable<sbyte>" : "sbyte");

                case _Types.t_smallint:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<int>" : "int");
                    }
                    return((c.Nullable) ? "Nullable<short>" : "short");

                case _Types.t_year:
                    return((c.Nullable) ? "Nullable<short>" : "short");

                case _Types.t_int:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<long>" : "long");
                    }
                    return((c.Nullable) ? "Nullable<int>" : "int");

                case _Types.t_integer:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<long>" : "long");
                    }
                    return((c.Nullable) ? "Nullable<int>" : "int");

                case _Types.t_mediumint:
                    return((c.Nullable) ? "Nullable<int>" : "int");

                case _Types.t_bigint:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<decimal>" : "decimal");
                    }
                    return((c.Nullable) ? "Nullable<long>" : "long");

                case _Types.t_float:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<decimal>" : "decimal");
                    }
                    return((c.Nullable) ? "Nullable<float>" : "float");

                case _Types.t_double:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<decimal>" : "decimal");
                    }
                    return((c.Nullable) ? "Nullable<double>" : "double");

                case _Types.t_real:
                    return((c.Nullable) ? "Nullable<double>" : "double");

                case _Types.t_rowversion:
                    return("byte[]");

                case _Types.t_numeric:
                case _Types.t_decimal:
                case _Types.t_dec:
                case _Types.t_fixed:
                case _Types.t_serial:
                    return((c.Nullable) ? "Nullable<decimal>" : "decimal");

                case _Types.t_date:
                case _Types.t_datetime:
                case _Types.t_datetime2:
                    return((c.Nullable) ? "Nullable<DateTime>" : "DateTime");

                case _Types.t_timestamp:
                    if (_Context.IsMySql)
                    {
                        return((c.Nullable) ? "Nullable<DateTime>" : "DateTime");
                    }
                    return("byte[]");

                case _Types.t_datetimeoffset:
                    return((c.Nullable) ? "Nullable<System.DateTimeOffset>" : "System.DateTimeOffset");

                case _Types.t_time:
                    return((c.Nullable) ? "Nullable<System.TimeSpan>" : "System.TimeSpan");

                case _Types.t_smalldatetime:
                    return((c.Nullable) ? "Nullable<DateTime>" : "DateTime");

                case _Types.t_image:
                    return("byte[]");

                case _Types.t_money:
                case _Types.t_smallmoney:
                    return((c.Nullable) ? "Nullable<decimal>" : "decimal");

                case _Types.t_uniqueidentifier:
                    return((c.Nullable) ? "Nullable<Guid>" : "Guid");

                case _Types.t_char:
                    if (_Context.IsMySql && c.Spec == "char(36)")
                    {
                        // char(36) 被认为是 MySql 的一个标志性实现
                        return((c.Nullable) ? "Nullable<Guid>" : "Guid");
                    }
                    return("string");

                case _Types.t_varchar:
                case _Types.t_tinytext:
                case _Types.t_text:
                case _Types.t_mediumtext:
                case _Types.t_longtext:
                case _Types.t_set:
                case _Types.t_enum:
                case _Types.t_nchar:
                case _Types.t_nvarchar:
                case _Types.t_ntext:
                case _Types.t_xml:
                    return("string");

                case _Types.t_binary:
                case _Types.t_varbinary:
                case _Types.t_tinyblob:
                case _Types.t_blob:
                case _Types.t_mediumblob:
                case _Types.t_longblob:
                    return("byte[]");

                case _Types.t_spatial_geometry:
                    return((c.Nullable) ? "Nullable<System.Data.Spatial.DbGeometry>" : "System.Data.Spatial.DbGeometry");

                case _Types.t_spatial_geography:
                    return((c.Nullable) ? "Nullable<System.Data.Spatial.DbGeography>" : "System.Data.Spatial.DbGeography");

                case _Types.t_sql_variant:
                    return("object");
                }

                return(string.Empty);
            };

            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("___ENTITIES", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    // _App Configure

                    // Start typing
                    _BatchIndex = -1;
                    ProjectItem   file = null;
                    Window        win  = null;
                    TextSelection ts   = null;

                    var index = 0;
                    var count = -1;
                    for (int i = 0; i < tables.Count; i++)
                    {
                        index = i / _BatchSize;
                        count++;

                        if (index != _BatchIndex)
                        {
                            // New file and insert at the end line
                            file = folder.ProjectItems.AddFromTemplate(
                                DefaultTemplateFile, string.Format("{0}.{1}.cs", _Identifier, index.ToString("D2")));
                            win = file.Open(Constants.vsViewKindCode);
                            win.Activate();
                            win.Document.Activate();

                            ts = _App.ActiveDocument.Selection as TextSelection;
                            ts.EndOfDocument();
                            _BatchIndex = index;

                            // Update timestamp
                            ts.Insert(@"/// <summary>");
                            ts.NewLine();
                            ts.Insert(string.Format(@"{0}", now.ToString()));
                            ts.NewLine();
                            ts.Insert(@"</summary>");
                            ts.NewLine();
                            ts.SelectLine();
                            ts.Insert(" ");

                            // namespace
                            ts.Insert("namespace " + _Namespace);
                            ts.NewLine();
                            ts.Insert("{");
                            ts.NewLine();
                        }

                        MBTable       t    = tables[i];
                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();

                        // summary
                        if (_Context.IsMySql)
                        {
                            if (!string.IsNullOrEmpty(t.Caption))
                            {
                                ts.Insert(@"/// <summary>");
                                ts.NewLine();
                                ts.Insert(string.Format(@"{0}", t.Caption.ToStringEx()));
                                ts.NewLine();
                                ts.Insert(@"</summary>");
                                ts.NewLine();
                                ts.SelectLine();
                                ts.Insert(" ");
                            }
                        }
                        else
                        {
                            properties.SingleOrDefault(d => d.TableId == t.TableId &&
                                                       d.Field == string.Empty && d.Name == FIELD_SUMMARY &&
                                                       !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                            {
                                ts.Insert(@"/// <summary>");
                                ts.NewLine();
                                ts.Insert(string.Format(@"{0}", d.Value));
                                ts.NewLine();
                                ts.Insert(@"</summary>");
                                ts.NewLine();
                                ts.SelectLine();
                                ts.Insert(" ");
                            });
                        }

                        // tableName
                        ts.Insert("[Serializable]");
                        ts.NewLine();
                        ts.Insert(string.Format("[Table(\"{0}\")]", t.Name));
                        ts.NewLine();
                        ts.Insert(string.Format("public partial class TB_{0}:TBObject<TB_{0}>{{", t.Name));
                        ts.NewLine();
                        //ts.Insert(string.Format("public partial class ET_{0} {{", t.Name));
                        //ts.NewLine();
                        columns.ForEach(c =>
                        {
                            if (_Context.IsMySql)
                            {
                                if (!string.IsNullOrEmpty(c.Caption))
                                {
                                    ts.Insert(@"/// <summary>");
                                    ts.NewLine();
                                    ts.Insert(string.Format(@"{0}", c.Caption));
                                    ts.NewLine();
                                    ts.Insert(@"</summary>");
                                    ts.NewLine();
                                    ts.SelectLine();
                                    ts.Insert(" ");
                                }
                            }
                            else
                            {
                                // 说明
                                properties.SingleOrDefault(d =>
                                                           d.TableId == t.TableId &&
                                                           d.Field == c.Name && d.Name == FIELD_SUMMARY &&
                                                           !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                                {
                                    ts.Insert(@"/// <summary>");
                                    ts.NewLine();
                                    ts.Insert(string.Format(@"{0}", d.Value));
                                    ts.NewLine();
                                    ts.Insert(@"</summary>");
                                    ts.NewLine();
                                    ts.SelectLine();
                                    ts.Insert(" ");
                                });
                            }

                            if (t.KeyInfo.ToStringEx(string.Empty).Contains(c.Name))
                            {
                                //var singleKey = !t.KeyInfo.ToStringEx(string.Empty).Contains(",");
                                //if (singleKey && c.Type.Contains("int"))
                                //{
                                //    ts.Insert(@"[Key*]"); // 人为编译不成功,mySql 的问题
                                //}
                                //else
                                //{
                                //    ts.Insert(@"[Key]");
                                //}

                                ts.Insert(@"[Key]");
                                ts.NewLine();
                            }

                            ts.Insert(string.Format(@"[Column(Order = {0})]", c.Ordinal));
                            ts.NewLine();

                            if (c.CharMaxLength.HasValue &&
                                !c.Type.Contains("blob") &&
                                !c.Type.Contains("long") &&
                                !c.Type.Contains("text")
                                //!c.Spec.Contains("char(36)") // guid
                                )
                            {
                                ts.Insert(string.Format(@"[MaxLength({0})]", c.CharMaxLength));
                                ts.NewLine();
                            }

                            var s = "public ";
                            s    += _getType(c) + " ";
                            s    += c.Name;
                            s    += " { get; set; }";

                            ts.Insert(s);
                            ts.NewLine();
                        });

                        ts.Insert("}");
                        ts.NewLine();

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }

                        if (count == _BatchSize - 1)
                        {
                            ts.Insert("}");
                            ts.NewLine();
                            ts.SelectAll();
                            _App.ExecuteCommand("Edit.FormatDocument");
                            win.Close(vsSaveChanges.vsSaveChangesYes);
                            count = -1;
                        }
                    }

                    // closing
                    if (count != -1)
                    {
                        ts.Insert("}");
                        ts.NewLine();
                        ts.SelectAll();
                        _App.ExecuteCommand("Edit.FormatDocument");
                        win.Close(vsSaveChanges.vsSaveChangesYes);
                        count = -1;
                    }
                }
            }
        }
Exemplo n.º 9
0
        private void _Do_3(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace");
                return;
            }

            var template = GetTemplatePath("ABP.DTO");
            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            // 准备插入代码
            ProjectItem   file = null;
            Window        win  = null;
            TextSelection ts   = null;
            StringBuilder sb   = null;

            var batchIndex = -1;
            var batchSize  = 50;
            var saved      = true;

            Action <ProjectItem> _newFile = f =>
            {
                batchIndex++;
                file = f.ProjectItems.AddFromTemplate(template, $"DTO.{batchIndex.ToString("D4")}.cs");
                win  = file.Open(Constants.vsViewKindCode);
                sb   = new StringBuilder();

                ts = win.Document.Selection as TextSelection;
                // ts.EndOfDocument();

                // 插入生成日期
                sb.AppendLine(@"/// <summary>");
                sb.AppendLine($"/// {now}");
                sb.AppendLine(@"/// </summary>");

                // 插入 namespace 行
                sb.AppendLine("namespace " + _Namespace);
                sb.AppendLine("{");

                saved = false;
            };

            Action _saveAndClose = () =>
            {
                ts.EndOfDocument();
                ts.Insert(sb.ToString());
                ts.Insert("}");
                ts.NewLine();
                ts.SelectAll();

                win.Activate();
                win.Document.Activate();

                _App.ExecuteCommand("Edit.FormatDocument");

                win.Close(vsSaveChanges.vsSaveChangesYes);
                saved = true;
            };

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("_DTOs", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    for (int i = 0; i < tables.Count; i++)
                    {
                        if (i % batchSize == 0)
                        {
                            _newFile(folder);
                        }

                        var t = tables[i];

                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();

                        // 说明
                        if (_Context.IsMySql)
                        {
                        }
                        else
                        {
                            properties.SingleOrDefault(d => d.TableId == t.TableId &&
                                                       d.Field == string.Empty && d.Name == FIELD_SUMMARY &&
                                                       !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                            {
                                sb.AppendLine(@"/// <summary>");
                                sb.AppendLine($"/// {d.Value}");
                                sb.AppendLine(@"/// </summary>");
                            });
                        }

                        if (keys.Count == 0)
                        {
                            doneToConfirmContinue($"Error: no primary key found for {t.Name}");
                            continue;
                        }

                        // Decide base class
                        var isCompoundKey = keys.Count > 1;
                        var singleKeyType = string.Empty;
                        var baseType      = "EntityDto";
                        var ignoreKeys    = new List <string>();

                        if (!
                            isCompoundKey)
                        {
                            singleKeyType = _getType(columns.First(c => c.Name == keys[0]));
                            ignoreKeys.Add(keys[0]);
                        }

                        if (columns.Exists(c => c.Name == "CreationTime" && c.Type.StartsWith("datetime")) &&
                            columns.Exists(c => c.Name == "CreatorId" && c.Type.StartsWith("uniqueidentifier")))
                        {
                            baseType = "CreationAuditedEntityDto";
                            ignoreKeys.AddRange(new string[] { "CreationTime", "CreatorId" });

                            if (columns.Exists(c => c.Name == "LastModificationTime" && c.Type.StartsWith("datetime")) &&
                                columns.Exists(c => c.Name == "LastModifierId" && c.Type.StartsWith("uniqueidentifier")))
                            {
                                ignoreKeys.AddRange(new string[] { "LastModificationTime", "LastModifierId" });
                                baseType = "AuditedEntityDto";

                                if (columns.Exists(c => c.Name == "DeletionTime" && c.Type.StartsWith("datetime")) &&
                                    columns.Exists(c => c.Name == "DeleterId" && c.Type.StartsWith("uniqueidentifier")) &&
                                    columns.Exists(c => c.Name == "IsDeleted" && c.Type.StartsWith("bit")))
                                {
                                    ignoreKeys.AddRange(new string[] { "DeletionTime", "DeleterId", "IsDeleted" });
                                    baseType = "FullAuditedEntityDto";
                                }
                            }
                        }

                        if (!isCompoundKey)
                        {
                            baseType += $"<{singleKeyType}>";
                        }

                        // 表格名字
                        sb.AppendLine("[Serializable]");
                        sb.AppendLine($"public partial class {t.Name}Dto:{baseType}{{");

                        columns.ForEach(c =>
                        {
                            if (ignoreKeys.Contains(c.Name))
                            {
                                return;
                            }

                            // Summary
                            if (_Context.IsMySql)
                            {
                            }
                            else
                            {
                                // 说明
                                properties.SingleOrDefault(d =>
                                                           d.TableId == t.TableId &&
                                                           d.Field == c.Name && d.Name == FIELD_SUMMARY &&
                                                           !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                                {
                                    sb.AppendLine(@"/// <summary>");
                                    sb.AppendLine($"{d.Value}");
                                    sb.AppendLine(@"</summary>");
                                });
                            }

                            if (!c.Nullable)
                            {
                                sb.AppendLine("[Required]");
                            }

                            if ((c.CharMaxLength ?? 0) > 0)
                            {
                                sb.AppendLine($"[MaxLength({c.CharMaxLength})]");
                            }

                            // Body
                            var s = "public ";
                            s    += _getType(c) + " ";
                            s    += c.Name;
                            s    += " { get; set; }";

                            sb.AppendLine(s);
                        });

                        sb.AppendLine("}");

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }

                        if (i > 0 && (i % batchSize) == 0)
                        {
                            _saveAndClose();
                        }
                    }

                    if (!saved)
                    {
                        _saveAndClose();
                    }
                }
            }
        }
		private static void MoveUsingsInsideNameSpace(ProjectItem projectItem, TextSelection txtSel, CodeNamespace nameSpace)
		{
			var usingsOutsideNameSpace = SearchService.FindUsings(projectItem.FileCodeModel.CodeElements);
			if (usingsOutsideNameSpace.Any())
			{
				List<string> linesToMove = new List<string>();
				for (int i = 0; i < usingsOutsideNameSpace.Count(); i++)
				{
					linesToMove.Add(usingsOutsideNameSpace[i].InnerText());
					usingsOutsideNameSpace[i].Delete();
				}

				var editPoint = nameSpace.GetStartPoint().CreateEditPoint();
				editPoint.FindPattern("{", (int)vsFindOptions.vsFindOptionsNone, ref editPoint);
				txtSel.MoveToPoint(editPoint);
				txtSel.NewLine();
				foreach (var line in linesToMove)
				{
					txtSel.Insert(line);
					txtSel.NewLine();
				}
			}
		}
Exemplo n.º 11
0
        public static void ApplyPrefeence(DTE2 dte, string region, string controller, string field, string property, string preferredValue)
        {
            //string preferredValue = GetMostPreferredValue(region, controller, field, property);
            List <PreviousPropertyValue> listDefault = new List <PreviousPropertyValue>();

            foreach (ProjectItem pi in dte.Solution.Projects.Item(1).ProjectItems)
            {
                if (pi.ProjectItems != null)
                {
                    foreach (ProjectItem p in pi.ProjectItems)
                    {
                        if (p.Name.EndsWith(".Designer.cs"))
                        {
                            p.Open(EnvDTE.Constants.vsViewKindCode);
                            p.Document.Activate();
                            TextSelection     ts           = (TextSelection)dte.ActiveDocument.Selection;
                            TextSelection     ts2          = (TextSelection)dte.ActiveDocument.Selection;
                            string            srchPattern1 = "new System.Windows.Forms.Button();";
                            EnvDTE.TextRanges textRanges   = null;

                            ts.StartOfDocument(false);

                            int count = 0;

                            string   nameLine = "";
                            string   name     = "";
                            string[] np       = new string[50];

                            while (ts.FindPattern(srchPattern1, 0, ref textRanges))
                            {
                                ts.SelectLine();
                                nameLine = ts.Text;
                                count++;
                                string[] sp  = nameLine.Split('.');
                                string   spi = sp[1];
                                string[] sp2 = spi.Split('=');
                                name      = sp2[0];
                                np[count] = name;
                            }

                            int i = 1;
                            while (ts2.FindPattern(".BackColor = System.Drawing.Color", 0, ref textRanges))
                            {
                                PreviousPropertyValue def = new PreviousPropertyValue();

                                ts2.SelectLine();
                                string codeLine = ts2.Text;
                                codeLine = codeLine.Trim();
                                foreach (string s in np)
                                {
                                    string ss = s;
                                    if (ss != null)
                                    {
                                        ss = ss.Trim();
                                        if (codeLine.Contains(ss) == true)
                                        {
                                            ts2.ReplacePattern(codeLine, "this." + s + ".BackColor = System.Drawing.Color." + preferredValue + ";", 0, ref textRanges);
                                            np                 = np.Where(w => w != s).ToArray();
                                            def.FileName       = p.Name;
                                            def.ControllerType = controller;
                                            def.Property       = property;
                                            def.ControllerName = ss;
                                            def.DefaultValue   = codeLine;
                                            listDefault.Add(def);
                                        }
                                        //else
                                        //{
                                        //    ts2.LineDown();
                                        //    ts2.NewLine();
                                        //    ts2.Insert("this." + np[i] + ".BackColor = System.Drawing.Color." + preferredValue + ";");
                                        //}
                                        //def.FileName = p.Name;
                                        //def.ControllerType = controller;
                                        //def.Property = property;
                                        //def.ControllerName = ss;
                                        //def.DefaultValue = codeLine;
                                        //listDefault.Add(def);
                                    }
                                }

                                //i++;
                            }
                            if (np != null)
                            {
                                foreach (string s in np)
                                {
                                    if (s != null)
                                    {
                                        ts2.EndOfLine();

                                        ts2.NewLine();
                                        ts2.Insert("this." + np[i] + ".BackColor = System.Drawing.Color." + preferredValue + ";");
                                        np = np.Where(w => w != s).ToArray();
                                    }
                                }
                            }
                            SaveDefaultValues(listDefault);
                            dte.ActiveDocument.Save(p.Document.FullName);
                            dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesNo);
                        }
                    }
                }
            }
        }
        private void _Do_4(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace:extensionClassName:objectPrefix");
                return;
            }

            if (!_Namespace.Contains(":"))
            {
                MessageBox.Show("Please provide a namespace:extensionClassName:objectPrefix");
                return;
            }

            var parts    = _Namespace.SplitEx(':');
            var template = GetTemplatePath("ABP.Context");
            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            var boPrefix = parts[2];

            // 准备插入代码
            ProjectItem   file = null;
            Window        win  = null;
            TextSelection ts   = null;
            StringBuilder sb   = null;

            var batchIndex = -1;
            var saved      = true;

            Action <ProjectItem> _newFile = f =>
            {
                batchIndex++;
                file = f.ProjectItems.AddFromTemplate(template, $"{parts[1]}.cs");
                win  = file.Open(Constants.vsViewKindCode);
                sb   = new StringBuilder();

                ts = win.Document.Selection as TextSelection;
                // ts.EndOfDocument();

                // 插入生成日期
                sb.AppendLine(@"/// <summary>");
                sb.AppendLine($"/// {now}");
                sb.AppendLine(@"/// </summary>");

                // 插入 namespace 行
                sb.AppendLine("namespace " + parts[0]);
                sb.AppendLine("{");

                saved = false;
            };

            Action _saveAndClose = () =>
            {
                ts.EndOfDocument();
                ts.Insert(sb.ToString());
                ts.Insert("}");
                ts.NewLine();
                ts.SelectAll();

                win.Activate();
                win.Document.Activate();

                _App.ExecuteCommand("Edit.FormatDocument");

                win.Close(vsSaveChanges.vsSaveChangesYes);
                saved = true;
            };

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("_Database", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    _newFile(folder);

                    sb.AppendLine($"public static class {parts[1]}");
                    sb.AppendLine("{");

                    sb.AppendLine($"public static void ConfigureInternal(this ModelBuilder builder)");
                    sb.AppendLine("{");

                    sb.AppendLine($"Check.NotNull(builder, nameof(builder));");

                    for (int i = 0; i < tables.Count; i++)
                    {
                        var t = tables[i];

                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        if (keys.Count == 0)
                        {
                            doneToConfirmContinue($"Error: no primary key found for {t.Name}");
                            continue;
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();


                        sb.AppendLine($"            builder.Entity<{boPrefix}_{t.Name}>(b =>");
                        sb.AppendLine("             {");
                        sb.AppendLine($"                b.ToTable(\"{t.Name}\", AbpCommonDbProperties.DbSchema);");
                        sb.AppendLine("                 b.ConfigureByConvention();");

                        if (keys.Count > 1)
                        {
                            sb.AppendLine($"                b.HasKey({ string.Join(", ", keys.Select(k => $"\"{k}\"")) });");
                        }
                        else if (keys.Count == 1)
                        {
                            sb.AppendLine($"                b.HasKey(\"Id\");");
                        }

                        columns.ForEach(c =>
                        {
                            var propConfig   = $"                b.Property(x => x.{c.Name})";
                            var shouldConfig = false;

                            if (keys.Count == 1 && c.Name == keys[0])
                            {
                                propConfig = $"                b.Property(x => x.Id)";

                                if (!c.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    propConfig   = $"                b.Property(x => x.Id).HasColumnName(\"{(c.Name)}\")";
                                    shouldConfig = true;
                                }
                            }

                            if (!c.Nullable)
                            {
                                propConfig  += ".IsRequired()";
                                shouldConfig = true;
                            }

                            if (c.CharMaxLength.HasValue && c.CharMaxLength > 0)
                            {
                                propConfig  += $".HasMaxLength({c.CharMaxLength})";
                                shouldConfig = true;
                            }

                            if (c.Type.Contains("decimal") ||
                                c.Type.Contains("datetime2") ||
                                c.Type.Contains("numeric") ||
                                c.Type.Contains("money") ||
                                c.Type.Contains("float") ||
                                c.Type.Contains("binary") ||
                                c.Type.Contains("time")
                                )
                            {
                                propConfig  += $".HasColumnType(\"{_getSqlType(c)}\")";
                                shouldConfig = true;
                            }

                            if (shouldConfig)
                            {
                                sb.AppendLine($"                {propConfig};");
                            }
                        });

                        sb.AppendLine("            });");

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }
                    }

                    sb.AppendLine("}");
                    sb.AppendLine("}");

                    if (!saved)
                    {
                        _saveAndClose();
                    }
                }
            }
        }