Example #1
0
        public void SetState(CodeSnippet snippet)
        {
            _supressTextChanged = true;

            _StateSnippet         = snippet;
            _mainform.tbPath.Text = snippet.GetPath();
            _mainform.rtfEditor.ClearUndo();
            _mainform.rtfEditor.ResetText();

            _mainform.rtfEditor.OwnTheme = snippet.RTFOwnTheme;
            if (_mainform.rtfEditor.OwnTheme)
            {
                _mainform.rtfEditor.SetOwnTheme(snippet.RTFTheme);
            }
            else
            {
                _mainform.rtfEditor.Theme = Config.Theme;
            }

            _mainform.rtfEditor.Rtf = snippet.GetRTF();

            _mainform.rtfEditor.Zoom = Config.Zoom;

            _supressTextChanged = false;
        }
Example #2
0
        public static int GetImageIndex(CodeSnippet snippet)
        {
            if (snippet.CodeType == CodeType.ReferenceLink)
            {
                return(14);
            }

            if (snippet.Important)
            {
                return(2);
            }

            if (snippet.CodeType == CodeType.System && snippet.Id == Constants.TRASHCAN)
            {
                return(3);
            }

            if (snippet.CodeType == CodeType.System && snippet.Id == Constants.CLIPBOARDMONITOR)
            {
                return(11);
            }

            if (snippet.AlarmActive)
            {
                return(5);
            }

            return(GetImageIndex(snippet.CodeType));
        }
        public async Task AddCodeSnippetToResume(string personEmail, CodeSnippet codeSnippet)
        {
            Resume toUpdate = await this.GetCompleteResumeByPersonEmail(personEmail, false);

            toUpdate.CodeSnippets.Add(codeSnippet);
            await this.SaveChangesAsync();
        }
Example #4
0
        // #TODO verhuizen naar TreeviewHelper
        private void FormToCodeCollection(TreeNodeCollection nodes)
        {
            int _order = 0;

            foreach (TreeNode node in nodes)
            {
                CodeSnippet _snippet = CodeLib.Instance.CodeSnippets.Get(node.Name);

                bool _changed = false;
                _snippet.SetPath(node.FullPath, out _changed);
                _snippet.Name = node.Name;

                if (string.IsNullOrWhiteSpace(_Find))
                {
                    _snippet.Order = _order;
                }

                _order++;

                if (_snippet.CodeType == CodeType.System && _snippet.Id == Constants.TRASHCAN)
                {
                    _snippet.Order = -2;
                }

                if (_snippet.CodeType == CodeType.System && _snippet.Id == Constants.CLIPBOARDMONITOR)
                {
                    _snippet.Order = -1;
                }

                FormToCodeCollection(node.Nodes);
            }
        }
        public int SaveCodeSnippet(CodeSnippet codeSnippet)
        {
            using (var ctx = new SqlConnection(connectionString))
            {
                ctx.Open();

                using (var cmd = new SqlCommand("dbo.USP_SaveCodeSnippet", ctx))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 255).Value = codeSnippet.Description;
                    // TODO: check how to deal with NVarChar(max) ...
                    cmd.Parameters.Add("@CodeSample", SqlDbType.NVarChar).Value = codeSnippet.CodeSample;
                    cmd.Parameters.Add("@LanguageId", SqlDbType.Int).Value      = codeSnippet.Language.Id;
                    cmd.Parameters.Add("@CodeSnippetId", SqlDbType.Int).Value   = codeSnippet.CodeSnippetId;

                    cmd.Parameters.Add(new SqlParameter("@ReturnVal", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.ReturnValue
                    });

                    cmd.ExecuteNonQuery();

                    return((int)cmd.Parameters["@ReturnVal"].Value);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Extracts code snippets from given folder and stores it in given container.
        /// </summary>
        /// <param name="dir">Path to the directory with code snippets.</param>
        /// <param name="container">Container to store snippets in.</param>
        private static void Extract(string dir, CodeSnippetsContainer container)
        {
            XmlSerializer snippetSer = SerializersManager.GetSerializer(typeof(CodeSnippet));

            string[] files = Directory.GetFiles(dir, "*.snippet");

            foreach (string snippetFileName in files)
            {
                XmlReader reader = new XmlTextReader(snippetFileName);
                reader.MoveToContent();
                reader.Read();                 // Read "CodeSnippets" element.
                reader.MoveToContent();

                while (reader.Name == "CodeSnippet")
                {
                    CodeSnippet snippet = ( CodeSnippet )snippetSer.Deserialize(reader);
                    container.AddSnippet(snippet);
                }
            }

            string[] dirs = Directory.GetDirectories(dir);

            foreach (string dirName in dirs)
            {
                CodeSnippetsContainer newContainer = new CodeSnippetsContainer();
                int lastSlash = dirName.LastIndexOf(@"\");
                newContainer.Name = dirName.Substring(lastSlash + 1);
                Extract(dirName, newContainer);
                container.AddContainer(newContainer);
            }
        }
Example #7
0
        public ActionResult New(string message = null)
        {
            ViewData["UserState"] = AppUserState;

            var snippet = new CodeSnippet();

            snippet.Author = this.AppUserState.Name;

            string codeUrl = Request.QueryString["url"];

            if (!string.IsNullOrEmpty(codeUrl))
            {
                HttpClient client = new HttpClient();
                client.Timeout = 4000;
                snippet.Code   = client.DownloadString(codeUrl);

                snippet.Title = Path.GetFileName(codeUrl);
                string extension = Path.GetExtension(codeUrl);

                snippet.Language = CodeFormatFactory.GetStringLanguageFromExtension(extension);
                Response.Write(snippet.Language);
            }

            if (!string.IsNullOrEmpty(message))
            {
                this.ErrorDisplay.ShowMessage(message);
            }

            return(this.View("New", snippet));
        }
Example #8
0
        public ActionResult Create([Bind(Include = "SourceCode")] CodeSnippet snippet)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    snippet.CreatedAt = DateTime.UtcNow;

                    using (StackExchange.Profiling.MiniProfiler.StepStatic("Service call"))
                    {
                        snippet.HighlightedCode = HighlightSource(snippet.SourceCode);
                        snippet.HighlightedAt   = DateTime.UtcNow;
                    }

                    _db.CodeSnippets.Add(snippet);
                    _db.SaveChanges();

                    return(RedirectToAction("Details", new { id = snippet.Id }));
                }
            }
            catch (HttpRequestException)
            {
                ModelState.AddModelError("", "Highlighting service returned error. Try again later");
            }

            return(View(snippet));
        }
        private void _timer_Tick(object sender, EventArgs e)
        {
            string _text = Clipboard.GetText();

            if (string.IsNullOrWhiteSpace(_text))
            {
                return;
            }

            if (_prevClipboard.Equals(_text))
            {
                return;
            }

            CodeSnippet _currentSnippet = _treeviewHelper.FromNode(_treeviewHelper.SelectedNode);

            if (_currentSnippet.Name == Constants.CLIPBOARDMONITOR && _currentSnippet.CodeType == CodeType.System)
            {
                _textBoxHelper.Text = _textBoxHelper.Text + _text + "\r\n";
            }
            else
            {
                CodeSnippet _clipboardSnippet = CodeLib.Instance.ClipboardMonitor;
                _clipboardSnippet.SetCode(_clipboardSnippet.GetCode() + _text + "\r\n", out bool _changed);
            }
            _prevClipboard = _text;
        }
Example #10
0
        private void mnuCopyImageAsBase64String_Click(object sender, EventArgs e)
        {
            CodeSnippet _snippet = CodeLib.Instance.CodeSnippets.Get(_treeviewHelper.SelectedId);
            string      _base64  = Convert.ToBase64String(_snippet.Blob);

            Clipboard.SetText(_base64);
        }
        private string SnippetToText(CodeSnippet snippet, CodeType targetType)
        {
            string _result = string.Empty;

            if (snippet.CodeType == CodeType.ReferenceLink)
            {
                snippet = CodeLib.Instance.CodeSnippets.Get(snippet.ReferenceLinkId);
            }
            if (snippet.CodeType == CodeType.Image)
            {
                string _base64 = Convert.ToBase64String(snippet.Blob);
                switch (targetType)
                {
                case CodeType.MarkDown:
                    _result = string.Format(@"![{0}](data:image/png;base64,{1})", snippet.GetPath(), _base64);
                    break;

                default:
                    _result = string.Format(@"<img src=""data:image/png;base64,{0}"" />", _base64);
                    break;
                }
            }
            else
            {
                _result = snippet.GetCode();
            }
            return(_result);
        }
        public static void Initialize(ResumeContext context)
        {
            // Uncomment to clear database each time.
            //context.Database.EnsureDeleted();
            if (context.Database.EnsureCreated())
            {
                Person      me          = GeneratePerson();
                CodeSnippet codeSnippet = new CodeSnippet()
                {
                    Name     = "Test Example",
                    RepoLink = "Test",
                    Snippet  = "public static int Test(){\nint test = 1\n}\n"
                };

                List <CodeSnippet> codeSnippets = new List <CodeSnippet>()
                {
                    codeSnippet
                };
                List <ExperienceHistory> experienceHistories = new List <ExperienceHistory>()
                {
                    GetRaytheonHistory(), GetGoDaddyHistory()
                };

                Resume resume = new Resume()
                {
                    Person = me,
                    ProfessionalExperienceHistories = experienceHistories,
                    EducationHistory = GetEducationHistory(),
                    ProjectsHistory  = GetProjectsHistory(),
                    CodeSnippets     = codeSnippets
                };

                context.AddResume(resume).Wait();
            }
        }
        public void AddCodeSnippet(CodeSnippet snippet, bool isNew = true)
        {
            if (isNew)
            {
                if (Settings.Instance.CodeSnippets.Exists(x => x.Name.Equals(snippet.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    throw new Exception("Snippet with same name already exists.");
                }
            }

            var newRowIndex = dataGridView1.Rows.Add();
            var nameColumn  = (DataGridViewTextBoxCell)dataGridView1.Rows[newRowIndex].Cells[0];

            nameColumn.Value = snippet.Name;

            var descriptionColumn = (DataGridViewTextBoxCell)dataGridView1.Rows[newRowIndex].Cells[1];

            descriptionColumn.Value = snippet.Description;

            var codeColumn = (DataGridViewTextBoxCell)dataGridView1.Rows[newRowIndex].Cells[2];

            codeColumn.Value = snippet.Code;

            if (isNew)
            {
                Settings.Instance.CodeSnippets.Add(snippet);
                Settings.Instance.Save();
            }
        }
Example #14
0
        private void EditNodeProperties(bool keepFocus = false)
        {
            if (_treeHelper.IsSystem(treeViewLibrary.SelectedNode) || treeViewLibrary.SelectedNode == null)
            {
                return;
            }

            CodeSnippet    _snippet = _treeHelper.FromNode(treeViewLibrary.SelectedNode);
            FormProperties _form    = new FormProperties(_themeHelper)
            {
                Snippet = _snippet
            };

            _form.ShowDialog(this);

            CodeLib.Instance.Refresh();

            _treeHelper.RefreshCurrentTreeNode();
            if (keepFocus)
            {
                //
            }
            else
            {
                fastColoredTextBox.Focus();
            }
        }
Example #15
0
        private void mnuGotoReference_Click(object sender, EventArgs e)
        {
            CodeSnippet _snippet = CodeLib.Instance.CodeSnippets.Get(treeViewLibrary.SelectedNode.Name);
            TreeNode    _node    = CodeLib.Instance.TreeNodes.Get(_snippet.ReferenceLinkId);

            _treeHelper.SetSelectedNode(_node, false);
        }
Example #16
0
        private ExpansionTemplate Convert(CodeTemplate codeTemplate)
        {
            var codeSnippet = new CodeSnippet();

            codeSnippet.Code        = codeTemplate.Code;
            codeSnippet.Description = codeTemplate.Description;
            codeSnippet.Fields      = new List <ExpansionField> ();
            foreach (var variable in codeTemplate.Variables)
            {
                var field = new ExpansionField();
                field.Editable = variable.IsEditable;
                field.Function = ConvertFunctionName(variable.Function);
                field.ToolTip  = variable.ToolTip;
                field.Default  = variable.Default ?? "";
                if ("GetConstructorModifier()" == variable.Function && string.IsNullOrEmpty(field.Default))
                {
                    field.Default = "public ";
                }
                field.ID = variable.Name;
                codeSnippet.Fields.Add(field);
            }
            codeSnippet.Language = codeTemplate.MimeType;
            codeSnippet.Shortcut = codeTemplate.Shortcut;
            codeSnippet.Title    = codeTemplate.Shortcut;
            return(new ExpansionTemplate(codeSnippet));
        }
Example #17
0
        private void mnuCopyImageAsMarkDownImage_Click(object sender, EventArgs e)
        {
            CodeSnippet _snippet = CodeLib.Instance.CodeSnippets.Get(_treeviewHelper.SelectedId);
            string      _base64  = Convert.ToBase64String(_snippet.Blob);

            Clipboard.SetText(string.Format(@"![{0}](data:image/png;base64,{1})", _snippet.Title(), _base64));
        }
Example #18
0
        private void mnuCopyImageAsHTMLIMG_Click(object sender, EventArgs e)
        {
            CodeSnippet _snippet = CodeLib.Instance.CodeSnippets.Get(_treeviewHelper.SelectedId);
            string      _base64  = Convert.ToBase64String(_snippet.Blob);

            Clipboard.SetText(string.Format(@"<img src=""data:image/png;base64,{0}"" />", _base64));
        }
Example #19
0
        static void Main(string[] args)
        {
            var libDir = args.Length == 0 ? GetLibraryDirectory() : args[0];

            if (!Directory.Exists(libDir))
            {
                throw new DirectoryNotFoundException("指定されたディレクトリが見つかりません。");
            }

            var srcDir      = Path.Combine(libDir, "src");
            var snippetsDir = Path.Combine(libDir, "snippets");

            Directory.CreateDirectory(snippetsDir);
            Directory.CreateDirectory(srcDir);

            var snippets = new CodeSnippets();

            foreach (var path in Directory.GetFiles(srcDir, "*.csx", SearchOption.AllDirectories))
            {
                using StreamReader reader = new StreamReader(path);
                var parsed = CodeSnippet.Parse(reader);
                if (parsed is null)
                {
                    continue;
                }
                snippets.CodeSnippet.Add(parsed);
            }

            var serializer = new XmlSerializer(typeof(CodeSnippets));

            using StreamWriter writer = new StreamWriter(Path.Combine(snippetsDir, "snippet.snippet"));
            serializer.Serialize(writer, snippets);
        }
        public string Merge(string text, CodeType targetType)
        {
            string _newText = text;
            var    _matches = _regexWildCards.Matches(text);

            if (_matches == null)
            {
                return(text);
            }

            string _text = string.Empty;

            foreach (Match match in _matches)
            {
                CodeSnippet _snippet = CodeLib.Instance.CodeSnippets.GetByPath(match.Value);
                if (_snippet == null)
                {
                    var           _snippets = CodeLib.Instance.CodeSnippets.GetChildsByPathAndPattern(match.Value);
                    StringBuilder _sb       = new StringBuilder();
                    foreach (CodeSnippet snippet in _snippets)
                    {
                        _sb.Append(SnippetToText(snippet, targetType));
                    }
                    _text = _sb.ToString();
                }
                else
                {
                    _text = SnippetToText(_snippet, targetType);
                }

                _newText = _newText.Replace($"#[{match.Value}]#", _text);
            }

            return(_newText);
        }
Example #21
0
 public SnippetCompletionData(CodeSnippet snippet)
     : this()
 {
     _snippet    = snippet;
     Name        = _snippet.Name;
     DisplayText = Name;
 }
        /// <summary>
        /// Applies the code snippet.
        /// </summary>
        /// <param name="visualStudioService">The visual studio service.</param>
        /// <param name="codeSnippet">The code snippet.</param>
        /// <returns>The messages.</returns>
        internal IEnumerable <string> ApplyCodeSnippet(
            IVisualStudioService visualStudioService,
            CodeSnippet codeSnippet)
        {
            TraceService.WriteLine("CodeConfigService::ApplyCodeSnippet");

            List <string> messages = new List <string>();

            //// find the project
            IProjectService projectService = visualStudioService.GetProjectServiceBySuffix(codeSnippet.Project);

            //// find the class
            IProjectItemService projectItemService = projectService?.GetProjectItem(codeSnippet.Class + ".cs");

            //// find the method.
            CodeFunction codeFunction = projectItemService?.GetFirstClass().GetFunction(codeSnippet.Method);

            string code = codeFunction?.GetCode();

            if (code?.Contains(codeSnippet.Code.Trim()) == false)
            {
                codeFunction.InsertCode(codeSnippet.Code, true);

                string message = string.Format(
                    "Code added to project {0} class {1} method {2}.",
                    projectService.Name,
                    codeSnippet.Class,
                    codeSnippet.Method);

                messages.Add(message);
            }

            return(messages);
        }
Example #23
0
        private void SnippetCreateSafe(CodeSnippet snippet)
        {
            var snip = SearchSnippet(snippet.code);

            if (string.IsNullOrEmpty(snip))
            {
                return;
            }

            var dir = cps.basepath + snippet.folder;

            dir = dir.Replace("%Z1%", Area);
            dir = dir.Replace("%Z%", Module);
            dir = dir.Replace("%N%", Class2);

            var fle = snippet.file.Replace("%H%", Class1);

            fle = fle.Replace("%N%", Class2);
            fle = fle.Replace("%Z%", Module);
            fle = fle.Replace("%Z1%", Area);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (File.Exists(dir + fle))
            {
                return;
            }
            File.WriteAllText(dir + fle, snip);
        }
 /// <summary>
 /// Implements the code snippet.
 /// </summary>
 /// <param name="codeSnippet">The code snippet.</param>
 /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param>
 public void ImplementCodeSnippet(
     CodeSnippet codeSnippet,
     bool formatFunctionParameters)
 {
     this.projectItem.ImplementCodeSnippet(
         codeSnippet,
         formatFunctionParameters);
 }
        public CodeSnippetModel GetCodeSnippetID(Guid id)
        {
            CodeSnippetModel codeSnippetModel = new CodeSnippetModel();

            CodeSnippet codeSnippet = clubmembershipDataContext.CodeSnippets.FirstOrDefault(x => x.IDCodeSnippet == id);

            return(MapDbObjectToModel(codeSnippet));
        }
Example #26
0
        public ActionResult DeleteConfirmed(int id)
        {
            CodeSnippet codesnippet = db.CodeSnippets.Find(id);

            db.CodeSnippets.Remove(codesnippet);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #27
0
 private static CodeSnippetDto ItemToDto(CodeSnippet snippet) =>
 new CodeSnippetDto
 {
     Id       = snippet.Id,
     Name     = snippet.Language,
     Language = snippet.Language,
     Snippet  = snippet.Snippet
 };
        public void Edit(string id, CodeSnippet codeSnippet)
        {
            var filter = Builders <CodeSnippet> .Filter.Eq(cs => cs.Id, id);

            var update = Builders <CodeSnippet> .Update.Set(cs => cs.Name, codeSnippet.Name).Set(cs => cs.Code, codeSnippet.Code);

            codeSnippets.UpdateOne(filter, update);
        }
Example #29
0
        public void TestTranslator()
        {
            CodeSnippetTranslator translator = new CodeSnippetTranslator();

            CodeSnippet codeSnippet = translator.Translate(Helper.GetTestDataPath("CodeSnippet.xml"));

            Assert.IsTrue(codeSnippet.Interfaces.Count > 0);
            Assert.IsTrue(codeSnippet.References.Count > 0);
        }
Example #30
0
        private void Selector_OnSelected(object sender, RoutedEventArgs e)
        {
            var item = View.SelectedItem as CodeSnippet;

            DeleteButton.IsEnabled = item != null;
            Current              = item;
            textEditor.Text      = item?.Code;
            textEditor.IsEnabled = item != null;
        }
        /// <summary>
        /// Injects the mocking details.
        /// </summary>
        /// <param name="codeSnippet">The code snippet.</param>
        public void InjectMockingDetails(CodeSnippet codeSnippet)
        {
            TraceService.WriteLine("MoqMockingService::InjectMockingDetails");

            codeSnippet.MockingVariableDeclaration = TestingConstants.Moq.MockingVariableDeclaration;

            codeSnippet.MockConstructorCode = TestingConstants.Moq.MockConstructorCode;

            codeSnippet.MockInitCode = TestingConstants.Moq.MockInitCode;
        }
        /// <summary>
        /// Injects the mocking details.
        /// </summary>
        /// <param name="codeSnippet">The code snippet.</param>
        public void InjectMockingDetails(CodeSnippet codeSnippet)
        {
            TraceService.WriteLine("NSubstituteMockingService::InjectMockingDetails");

            codeSnippet.MockInitCode = TestingConstants.NSubstitute.MockInitCode;
        }
        /// <summary>
        /// Implements the code snippet.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="codeSnippet">The code snippet.</param>
        /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param>
        public static void ImplementCodeSnippet(
            this ProjectItem instance,
            CodeSnippet codeSnippet,
            bool formatFunctionParameters)
        {
            TraceService.WriteLine("ProjectItemExtensions::ImplementCodeSnippet in file " + instance.Name);

            if (codeSnippet.UsingStatements != null &&
                codeSnippet.UsingStatements.Any())
            {
                IEnumerable<string> statements = instance.GetUsingStatements();

                foreach (string reference in codeSnippet.UsingStatements)
                {
                    string contains = statements.FirstOrDefault(x => x.Contains(reference));

                    if (contains == null)
                    {
                        instance.AddUsingStatement(reference);

                        TraceService.WriteLine("Using statement added " + reference);
                    }
                }
            }

            instance.GetFirstClass().ImplementCodeSnippet(
                codeSnippet,
                formatFunctionParameters);

            //// now apply any variable substitutions

            if (codeSnippet.ReplacementVariables != null)
            {
                foreach (KeyValuePair<string, string> item in codeSnippet.ReplacementVariables)
                {
                    instance.ReplaceText(item.Key, item.Value);
                }
            }
        }
        /// <summary>
        /// Implements the mock code.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="codeSnippet">The code snippet.</param>
        public static void ImplementMockCode(
            this CodeClass instance, 
            CodeSnippet codeSnippet)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementMockCode file=" + instance.Name);

            CodeFunction codeFunction = instance.GetFunction(codeSnippet.TestInitMethod);

            if (codeFunction != null)
            {
                if (string.IsNullOrEmpty(codeSnippet.GetMockInitCode()) == false)
                {
                    codeFunction.InsertCode(codeSnippet.GetMockInitCode(), true);
                }

                if (string.IsNullOrEmpty(codeSnippet.GetMockConstructorCode()) == false)
                {
                    string code = codeFunction.GetCode();

                    string testFileName = instance.Name;

                    //// remove Test at the start - need a better way of doing this!
                    string fileName = testFileName.Replace("Test", string.Empty);

                    //// TODO : this wont always work if the function spans multiple lines!
                    int index = code.IndexOf(fileName + "(", StringComparison.Ordinal);

                    if (index != 0)
                    {
                        string seperator = string.Empty;

                        //// here we are looking for the closing bracket
                        //// if we dont have a closing bracket then we already have something
                        //// on the constructor and therefore need a ',' to make it work!
                        if (code.Substring(index + fileName.Length + 1, 1) != ")")
                        {
                            //// TODO : do we want to create a new line too!
                            seperator = ", ";
                        }

                        StringBuilder sb = new StringBuilder();
                        sb.Append(code.Substring(0, index + fileName.Length + 1));
                        sb.Append(codeSnippet.GetMockConstructorCode() + seperator);
                        sb.Append(code.Substring(index + fileName.Length + 1));

                        codeFunction.ReplaceCode(sb.ToString());
                    }
                }
            }
        }
        /// <summary>
        /// Implements the function.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="codeSnippet">The code snippet.</param>
        public static void ImplementFunction(
            this CodeClass instance, 
            CodeSnippet codeSnippet)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementFunction file=" + instance.Name);

            CodeFunction codeFunction = instance.AddFunction(
                "temp",
                vsCMFunction.vsCMFunctionFunction,
                vsCMTypeRef.vsCMTypeRefVoid,
                -1,
                vsCMAccess.vsCMAccessPublic,
                null);

            TextPoint startPoint = codeFunction.StartPoint;

            EditPoint editPoint = startPoint.CreateEditPoint();

            instance.RemoveMember(codeFunction);

            editPoint.Insert(codeSnippet.Code);
        }
        /// <summary>
        /// Implements the code snippet.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="codeSnippet">The code snippet.</param>
        /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param>
        public static void ImplementCodeSnippet(
            this CodeClass instance,
            CodeSnippet codeSnippet,
            bool formatFunctionParameters)
        {
            TraceService.WriteLine("CodeClassExtensions::ImplementCodeSnippet file" + instance.Name);

            if (codeSnippet.Variables != null)
            {
                foreach (string[] parts in codeSnippet.Variables
                    .Select(variable => variable.Split(' ')))
                {
                    //// variable could already exist!
                    try
                    {
                        instance.ImplementVariable(parts[1], parts[0], false);
                    }
                    catch (Exception exception)
                    {
                        TraceService.WriteError("Error adding variable exception=" + exception.Message + " variable=" + parts[1]);

                        //// if variable already exists get out - code snippet will already have been applied.
                        return;
                    }
                }
            }

            if (codeSnippet.MockVariables != null)
            {
                foreach (string[] parts in codeSnippet.MockVariables
                    .Select(variable => variable.Split(' ')))
                {
                    //// variable could already exist!
                    try
                    {
                        instance.ImplementMockVariable(parts[1], parts[0]);
                    }
                    catch (Exception exception)
                    {
                        TraceService.WriteError("Error adding mock variable exception=" + exception.Message + " variable=" + parts[1]);

                        //// if variable already exists get out - code snippet will already have been applied.
                        return;
                    }
                }
            }

            if (string.IsNullOrEmpty(codeSnippet.Code) == false)
            {
                instance.ImplementFunction(codeSnippet);
            }

            if (codeSnippet.Interfaces != null &&
                codeSnippet.Interfaces.Count > 0)
            {
                IEnumerable<CodeFunction> constructors = instance.GetConstructors();

                CodeFunction constructor = constructors.FirstOrDefault() ?? instance.AddDefaultConstructor(true);

                foreach (string variable in codeSnippet.Interfaces)
                {
                    instance.ImplementInterface(constructor, variable);
                }

                if (formatFunctionParameters)
                {
                    constructor.FormatParameters();
                }
            }

            if (string.IsNullOrEmpty(codeSnippet.GetMockInitCode()) == false ||
                string.IsNullOrEmpty(codeSnippet.GetMockConstructorCode()) == false)
            {
                instance.ImplementMockCode(codeSnippet);
            }
        }
        /// <summary>
        /// Implements the unit testing code snippet.
        /// </summary>
        /// <param name="codeSnippet">The code snippet.</param>
        /// <param name="codeFile">The code file.</param>
        /// <param name="removeHeader">if set to <c>true</c> [remove header].</param>
        /// <param name="removeComments">if set to <c>true</c> [remove comments].</param>
        /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param>
        public void ImplementUnitTestingCodeSnippet(
            CodeSnippet codeSnippet,
            string codeFile,
            bool removeHeader,
            bool removeComments,
            bool formatFunctionParameters)
        {
            this.ImplementCodeSnippet(
                codeSnippet,
                formatFunctionParameters);

            //// add in the reference to the plugin - doing this way means we don't need it in the xml files
            codeSnippet.UsingStatements.Add(codeFile);

            //// this really shouldn't be done - templates now have a mind of their own - please fix!!
            DTE2 dte2 = this.projectItem.ContainingProject.DTE as DTE2;

            //// change the testable placeholders!
            string instanceName = "this." + codeFile.Substring(0, 1).ToLower() + codeFile.Substring(1);
            bool replaced = dte2.ReplaceText("this.TestableObject", instanceName, true);

            //// sometimes the find/replace doesnt work - god knows why - seems intermittent :-(
            if (replaced == false)
            {
                this.ReplaceText("this.TestableObject", instanceName);
            }

            if (removeHeader)
            {
                this.ProjectItem.RemoveHeader();
            }

            if (removeComments)
            {
                this.ProjectItem.RemoveComments();
            }
        }
 /// <summary>
 /// Implements the code snippet.
 /// </summary>
 /// <param name="codeSnippet">The code snippet.</param>
 /// <param name="formatFunctionParameters">if set to <c>true</c> [format function parameters].</param>
 public void ImplementCodeSnippet(
     CodeSnippet codeSnippet,
     bool formatFunctionParameters)
 {
     this.projectItem.ImplementCodeSnippet(
         codeSnippet,
         formatFunctionParameters);
 }
Example #39
0
        internal PythonCodeSnippets()
        {
            AllSnippets = new CodeSnippet[]{
                     new CodeSnippet(
                        CodeType.Null, "Null Code",
                        null),

                     new CodeSnippet(
                        CodeType.Junk, "Junk Code",
                        "@@3skjdhfkshdfk"),

                     new CodeSnippet(
                        CodeType.Comment, "Comment only code",
                        "#this is a test comment"),

                     new CodeSnippet(
                        CodeType.WhiteSpace1, "WhiteSpace only",
                        "            "),

                     new CodeSnippet(
                       CodeType.ValidExpressionWithMethodCalls, "Valid Expresion Using Method",
                       @"eval('eval(\'2+2\')')"),

                     new CodeSnippet(
                        CodeType.ValidStatement1, "Valid Statement",
                        @"if 1>0 :
            print 1001"),

                    /// <summary>
                    ///  Test Bug : this is not an expression - This is a statement!
                    /// </summary>
                     new CodeSnippet(
                        CodeType.InCompleteExpression1, "Incomplete expression",
                        "print("),

                    /// <summary>
                    ///  Test Bug : this is not an expression - This is a statement!
                    /// </summary>
                     new CodeSnippet(
                        CodeType.InCompleteExpression2, "Incomplete expression",
                        "a = 2+"),

                     new CodeSnippet(
                        CodeType.InCompleteStatement1, "Incomplete statement",
                        "if"),

                     new CodeSnippet(
                        CodeType.Interactive1, "Interactive Code",
                        "<add valid interactive code>"),

                     new CodeSnippet(
                        CodeType.OneLineAssignmentStatement, "Interactive Code",
                        "x =  1+2"),

                     new CodeSnippet(
                        CodeType.LinefeedTerminatorRStatement, "Interactive Code",
                        "x =  1+2\ry= 3+4"),

                    /// <summary>
                    /// A python expression with classic functional language paradigms calling map with
                    /// a lambda function that multiplies the input value by -1.
                    /// </summary>
                     new CodeSnippet(
                        CodeType.CallingFuncWithLambdaArgsToMap, "A python expression with classic functional language paradigms using lambda and map",
                        @"map(lambda x: x * -1, range(0,-10, -1))"
                        ),

                        new CodeSnippet(
                            CodeType.MethodWithThreeArgs,
                            "Simple method with three args",
            @"def concat( a, b, c):
            return str(a + b + c)"),

                    /// <summary>
                    /// Simple FooClass to test ScriptSource.Invocate(...)
                    /// </summary>
                     new CodeSnippet(
                        CodeType.SimpleFooClassDefinition, "Simple Foo class used to test calling member method after execution",
            @"class FooClass:
             'A simple test class'
             def __init__(self):
             self.someInstanceAttribute = 42
             def f(self):return 'Hello World'
             def concat(self, a, b, c):
            return str(a + b + c)
             def add(self, a, b):
            return a + b

            fooTest = FooClass()
            def bar(): return fooTest.f()"),

                    /// <summary>
                    ///  Rot13 function definition
                    /// </summary>
                     new CodeSnippet(
                        CodeType.Rot13Function, "Defined Rot13 function",
                        @"
            def rot13(transstr):
            chklst = list(transstr)
            nlst   = list()
            lookup = list('NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
            for i in range(chklst.Length()):
            rchr = 0
            if(chklst[i].isalpha()):
            if(chklst[i].isupper()):
                rchr = lookup[ord(chklst[i]) % ord('A')]
            else:
                rchr = lookup[ord(chklst[i]) % ord('a') + 26]
            else:
            rchr = chklst[i];
            nlst.append(rchr)
            return ''.join(nlst)
            "),

                    /// <summary>
                    ///  Test Bug : this is not an expression - This is a statement!
                    /// </summary>
                     new CodeSnippet(
                      CodeType.ValidExpression1, "Interactive Code",
                      "x =  1+2"),
                    /// <summary>
                    /// Valid code snippet with both expressions and statements
                    /// </summary>
                     new CodeSnippet(
                      CodeType.ValidMultiLineMixedType, "Valid Code",
            @"
            def increment(arg):
            local = arg + 1
            local2 =local
            del local2
            return local

            global1 = increment(3)
            global2 = global1"),

                     new CodeSnippet(
                        CodeType.Valid1, "Valid Code",
            @"
            def increment(arg):
            local = arg + 1
            local2 =local
            del local2
            return local

            global1 = increment(3)
            global2 = global1"),

                     new CodeSnippet(
                        CodeType.BrokenString, "Broken String",
                        "a = \"a broken string'"),

                     new CodeSnippet(
                        CodeType.SimpleMethod, "Simple method",
                        "def pyf(): return 42"),

                     new CodeSnippet(
                        CodeType.FactorialFunc, "Factorial function",
            @"def fact(x):
            if (x == 1):
            return 1
            return x * fact(x - 1)"),

                     new CodeSnippet(
                        CodeType.ImportFutureDiv, "TrueDiv function",
            @"from __future__ import division
            r = 1/2"),

                     new CodeSnippet(
                        CodeType.ImportStandardDiv, "LegacyZeroResultFromOneHalfDiv function",
                        @"r = 1/2"),

                     new CodeSnippet(
                        CodeType.SevenLinesOfAssignemtStatements, "Very simple code example to be used for testing ScriptSource CodeReader method",
                         @"a1=1
            a2=2
            a3=3
            a4=4
            a5=5
            a6=6
            a7=7"),

                     new CodeSnippet(
                        CodeType.UpdateVarWithAbsValue, "Give a variable set to a negative number -1 and then re-assign abs value of itself",
                         @"
            test1 = -10
            test1 = abs(test1)"),

                     new CodeSnippet(
                        CodeType.SimpleExpressionOnePlusOne, "A very simple expression 1 + 1",
                        "1+1" ),

                     new CodeSnippet(
                        CodeType.IsEvenFunction, "A function that returns true or false depending on if a number is even or not",
                        "def iseven(n): return 1 != n % 2"),

                    new CodeSnippet(
                        CodeType.IsOddFunction, "A function that returns true or false depending on if a number is odd or not",
                        "def isodd(n): return 1 == n % 2;"),

                     new CodeSnippet(
                        CodeType.MethodWithDocumentationAttached, "A very simple method with docs attached",
            @"def doc():
             """"""This function does nothing""""""
             return"),
                     new CodeSnippet(
                        CodeType.SmallDotNetObjectForDocTest, "A .Net Object to use to verify we can see attached documentation",
                        "from System.Runtime.Remoting import ObjectHandle"),

                     new CodeSnippet(
                        CodeType.TimeZoneDotNetObjectForDocTest, "Will this work",
                        "from System import TimeZone"),

                     new CodeSnippet(
                        CodeType.NegativeOneAssignedToX, "Interactive Code",
                        "x = 1"),

                     new CodeSnippet(
                        CodeType.ImportCPythonDateTimeModule, "Import a CPython DateTime Module",
                        "import datetime\ndate=datetime.datetime"),

                     new CodeSnippet(
                        CodeType.ImportDotNetAssemblyDateTimeModule, "Import .Net DateTime for an individual assembly",
                        "import clr\nfrom System import DateTime\nDotNetDate=DateTime")

            };
        }