/// <summary>
        /// Maps a specified <see cref="CodeSnippetElement"/> to the newly created <see cref="Snippet"/>.
        /// </summary>
        /// <param name="element">A <see cref="CodeSnippetElement"/> that contains deserialized snippet data.</param>
        /// <returns>Newly created <see cref="Snippet"/>.</returns>
        public static Snippet MapFromElement(CodeSnippetElement element)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            var snippet = new Snippet();

            if (element.Format != null)
            {
                Version version = null;

                if (Version.TryParse(element.Format, out version)
                    && ValidationHelper.IsValidVersion(version))
                {
                    snippet.FormatVersion = version;
                }
            }

            if (element.Header != null)
                LoadHeaderElement(element.Header, snippet);

            if (element.Snippet != null)
                LoadSnippetElement(element.Snippet, snippet);

            return snippet;
        }
 public Snippet this[string name]
 {
   get
   {
     Snippet result;
     var key = CleanFileName(name);
     if (!_cache.TryGetValue(key, out result))
     {
       var path = GetFolder() + key + ".txt";
       if (System.IO.File.Exists(path))
         result = new Snippet(System.IO.File.ReadAllText(path));
       else
         result = new Snippet();
       _cache[key] = result;
     }
     return result;
   }
   set
   {
     var key = CleanFileName(name);
     _cache[key] = value;
     var path = GetFolder() + key + ".txt";
     WriteAllText(path, value.ToString());
   }
 }
Example #3
0
        public Emitter st(Snippet dest)
        {
            if (dest is NodeSnippet)
            {
                var ns = dest as NodeSnippet;
                if (ns.Node is Ref)
                {
                    var @ref = (Ref)ns.Node;
                    var layout = _alloc[@ref].AssertCast<SlotLayout>();
                    return st((Atom)layout.Slot);
                }
                else
                {
                    throw AssertionHelper.Fail();
                }
            }
            else if (dest is PtxexprSnippet)
            {
                var pes = dest as PtxexprSnippet;
                if (pes.Expr is Reg) st((Reg)pes.Expr);
                else if (pes.Expr is Var) st((Var)pes.Expr);
                else throw AssertionHelper.Fail();
            }
            else
            {
                throw AssertionHelper.Fail();
            }

            return this;
        }
        private void lookForNewSnippet(string text, int lineNumber)
        {
            var name = _scanner.DetermineName(text);

            if (name.IsNotEmpty())
            {
                var snippet = new Snippet(name){
                    Class = _scanner.LanguageClass,
                    File = _file.RelativePath,
                    BottleName = _file.Provenance
                };

                _readAction = (txt, num) =>
                {
                    if (_scanner.IsAtEnd(txt))
                    {
                        _onFound(snippet);
                        _readAction = lookForNewSnippet;
                    }
                    else
                    {
                        snippet.Append(txt, num);
                    }
                };
            }
        }
        public ActionResult CreateSnippet(CreateSnippetVM vm)
        {
            if (ModelState.IsValid)
            {
                Snippet snippet = new Snippet
                {
                    Title = vm.Title,
                    Content = vm.Content,
                    DatePublished = DateTime.Now
                };

                if (webSecurity.IsAuthenticated)
                {
                    snippet.UserId = webSecurity.CurrentUserId;
                }

                this.snippetRepo.Add(snippet);

                return RedirectToAction("Show", new { id = snippet.Id });
            }
            else
            {
                return View();
            }
        }
 public void ReadXml(XmlReader reader)
 {
     var elementName = string.Empty;
     while (reader.Read())
     {
         if (reader.NodeType == XmlNodeType.Element)
         {
             elementName = reader.Name;
             switch (elementName)
             {
                 case "TypeAliases":
                     {
                         var subReader = reader.ReadSubtree();
                         var aliases = new List<NetTypeAlias>();
                         while (subReader.ReadToFollowing("TypeAlias"))
                         {
                             var aliasReader = subReader.ReadSubtree();
                             var typeAlias = new NetTypeAlias();
                             typeAlias.ReadXml(aliasReader);
                             aliases.Add(typeAlias);
                         }
                         TypeAliases = aliases.ToArray();
                         break;
                     }
                 case "Snippets":
                     {
                         var subReader = reader.ReadSubtree();
                         var snippets = new List<Snippet>();
                         while (subReader.ReadToFollowing("Snippet"))
                         {
                             var snippet = new Snippet();
                             snippet.ReadXml(subReader);
                             snippets.Add(snippet);
                         }
                         Snippets = snippets.ToArray();
                         break;
                     }
             }
         }
         else if (reader.NodeType == XmlNodeType.Text)
         {
             switch (elementName)
             {
                 case "Modifiers":
                     Modifiers = reader.Value.Split(' ');
                     break;
                 case "MemberIdentifiers":
                     MemberIdentifiers = reader.Value.Split(' ');
                     break;
                 case "Keywords":
                     Keywords = reader.Value.Split(' ');
                     break;
             }
         }
         else if (reader.NodeType == XmlNodeType.EndElement)
         {
             elementName = string.Empty; 
         }
     }
 }
Example #7
0
 public SnippetModel(Snippet snippet)
     : this()
 {
     Snippet = snippet;
     if (Snippet != null)
         CategoryId = Snippet.Category.CategoryId;
 }
Example #8
0
        //, string sourceName, string sourceTypeName, string authorFirstName, string authorLastName, string comment = "Default comment")
        public static Snippet CreateKb(string text, string pageOrLocation)
        {
            using (var db = new SnippetAppDB())
            {
                Snippet sp = new Snippet();
                sp.Text = text;
                sp.PageorLocation = pageOrLocation;
                db.Snippets.Add(sp);

                //Source sourcevar = new Source();
                //sourcevar.SourceName = sourceName;
                //db.Sources.Add(sourcevar);

                //Comments commentsvar = new Comments();
                //commentsvar.CommentsText = comment;
                //if (comment != "Default comment")
                //{

                //}
                //db.Comments.Add(commentsvar);

                //SourceType sourcetypevar = new SourceType();
                //sourcetypevar.SourceTypeName = sourceTypeName;
                //db.SoureTypes.Add(sourcetypevar);

                //Author authorvar = new Author();
                //authorvar.AuthorFirstName = authorFirstName;
                //authorvar.AuthorLastName = authorLastName;
                //db.Authors.Add(authorvar);

                db.SaveChanges();
                return sp;

            }
        }
 public ActionResult Create(SnippetBindingModel model,string language, string labels)
 {
     if (model != null && this.ModelState.IsValid)
     {
         var userId = this.User.Identity.GetUserId();
         var snippet = new Snippet()
         {
             Title = model.Title,
             Description = model.Description,
             Author = this.Data.Users.Find(userId),
             Language = this.Data.Languages.All().FirstOrDefault(l => l.Name == language),
         };
         if (!labels.IsEmpty())
         {
             var allLabels = labels.Split(';');
             foreach (var l in allLabels)
             {
                 var labelToCheck = l.Trim();
                 var label = this.Data.Labels.All().FirstOrDefault(la => la.Text.ToLower() == labelToCheck.ToLower());
                 if (label == null)
                 {
                     var newLabel = new Label(){Text = l};
                     this.Data.Labels.Add(newLabel);
                     this.Data.SaveChanges();
                 }
                 label = this.Data.Labels.All().FirstOrDefault(la => la.Text == l);
                 snippet.Labels.Add(label);
             }
         }
         this.Data.SaveChanges();
         return RedirectToAction("Details", "Snippets", new { id = snippet.Id });
     }
     return RedirectToAction("Index", "Users");
 }
        public CreateSnippetResponse CreateSnippet(CreateSnippetRequest request)
        {
            var response = new CreateSnippetResponse();
            var newSnippet = new Snippet
                                 {
                                     Id = request.Id,
                                     Guid = request.Guid,
                                     Name = request.Name,
                                     Description = request.Description,
                                     PreviewData = request.PreviewData,
                                     Data = request.Data,
                                     LastModified = request.LastModified,
                                     IsPublic = request.IsPublic,
                                     Language_Id = request.Language_Id,
                                     User_Id = request.User_Id,
                                     User_FormsAuthId = request.User_FormsAuthId
                                 };
            try
            {
                _unitOfWork.SnippetRepository.Insert(newSnippet);
                _unitOfWork.Save();

                response.SnippetId = newSnippet.Id;
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.FailureInformation = ex.Message;
                Logger.LogError("CreateSnippet Method Failed", ex);
            }
            return response;
        }
Example #11
0
 private SnippetExpander(string snippetName, string originalText, int caretPosition)
 {
     _snippetName = snippetName;
     _caretPosition = caretPosition;
     _originalText = originalText;
     _snippet = Snippets[snippetName];
 }
        public Snippet Format(IFubuFile file, string languageClass = null)
        {
            var snippet = new Snippet(file.Path){
                Class = languageClass ?? "lang-" + Path.GetExtension(file.Path).Replace(".", "")
            };

            file.ReadContents(stream =>
            {
                using (var reader = new StreamReader(stream))
                {
                    int lineNumber = 0;

                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        lineNumber++;

                        if (line.Contains(Snippets.SAMPLE) || line.Contains(Snippets.END))
                        {
                            snippet.Append(string.Empty, lineNumber);
                        }
                        else
                        {
                            snippet.Append(line, lineNumber);
                        }
                    }
                }
            });



            return snippet;
        }
        public void SnippetLibrary_Remove()
        {
            List<string> s1Content = new List<string>()
            {
                "lorem ipsum dot sit amet,",
                "consectetur adipisicing elit"
            };
            Snippet s1 = new Snippet("lorem", s1Content);
            List<string> s2Content = new List<string>()
            {
                "if ()",
                "{",
                "",
                "}"
            };
            Snippet s2 = new Snippet("if", s2Content);

            snippetLibrary.Add(s1);
            snippetLibrary.Add(s2);
            this.snippetLibrary = null;
            this.snippetLibrary = new SnippetLibrary();
            this.snippetLibrary.Remove("lorem");
            Assert.IsNull(this.snippetLibrary.GetByName("lorem"));
            Assert.AreEqual(1, this.snippetLibrary.Names.Count);
        }
Example #14
0
 /// <summary>
 /// Adds new snippet to library.
 /// </summary>
 /// <param name="snippet">Snippet to add.</param>
 public void Add(Snippet snippet)
 {
     if (this.snippets.Where(s => s.Name == snippet.Name).Count() == 0)
     {
         this.snippets.Add(snippet);
         this.Save();
     }
 }
        protected string GenerateSource(Snippet snippet)
        {
            var builder = new StringBuilder(GenerateHeader(snippet));
            builder.AppendLine("            " + snippet.Code);
            builder.Append(GenerateFooter(snippet));

            return builder.ToString();
        }
Example #16
0
 public SnippetInstance(Snippet snippet, SnippetInstance parent)
 {
     Debug.Assert(!snippet.IsTopLevel);
     this.Snippet = snippet;
     this.Snippet.UI.SnippetInstances.Add(this);
     this.parent = parent;
     this.node = new SnippetTNode(snippet.Title, this);
 }
Example #17
0
 static void Main(string[] args)
 {
     Snippet InstantiatedSnippet = new Snippet();
     Author InstantiatedAuthor = new Author();
     Source InstantiatedSource = new Source();
     SourceType InstantiatedSourceType = new SourceType();
     Comments InstantiatedComments = new Comments();
 }
Example #18
0
        public void Rule_Script_Contains_Run_Which_Is_Not_A_Function()
        {
            var snippet = new Snippet();
            var ruleCode = new StringBuilder();
            ruleCode.AppendLine("run = 100");

            var rule = new PyRule() { Code = ruleCode.ToString(), Weight = 1 };
            rule.Rank(snippet);
        }
Example #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SnippetCode"/> class with the specified snippet.
        /// </summary>
        /// <param name="snippet">A snippet</param>
        /// <exception cref="ArgumentNullException"><paramref name="snippet"/> is <c>null</c>.</exception>
        public SnippetCode(Snippet snippet)
        {
            if (snippet == null)
                throw new ArgumentNullException(nameof(snippet));

            Snippet = snippet;

            snippet.TextChanged += (object sender, EventArgs e) => _indexes = null;
        }
Example #20
0
 public void AddPropertySet(Snippet parent)
 {
     PropertySet pane = new PropertySet(parent);
     pane.ParentContainer = this;
     propertiesPanes.Add(pane);
     pane.DoubleClick += new EventHandler(PropertiesPaneHolder_DoubleClick);
     ToolTip tip = new ToolTip();
     tip.SetToolTip(pane, "Double click here to remove this PropertySet.");
 }
Example #21
0
 public ActionResult Edit(Snippet snippet)
 {
     var newSnippet = Helper.EditKb(snippet.Text, snippet.PageorLocation);
     if (newSnippet != null)
     {
         return RedirectToAction("Detail", new { id = newSnippet.TextID });
     }
     return View();
 }
Example #22
0
 public Node(int id, Graphics obj, int x0, int y0, string name)
 {
     this.__X = new Snippet() { first = x0, second = x0};
     this.__Y = new Snippet() { first = y0, second = y0};
     this.centr = new Snippet() { first = x0, second = y0};
     this.__obj = obj;
     this.name = name;
     this.id = id;
 }
        protected override string GenerateFooter(Snippet snippet)
        {
            var builder = new StringBuilder();
            builder.AppendLine("        }");
            builder.AppendLine("    }");
            builder.AppendLine("}");

            return builder.ToString();
        }
 private void addButton_Click(object sender, RoutedEventArgs e)
 {
     if (!string.IsNullOrEmpty(this.snippetNameTextBox.Text) && !string.IsNullOrWhiteSpace(this.snippetNameTextBox.Text))
     {
         Snippet newSnippet = new Snippet(this.snippetNameTextBox.Text, new List<string>());
         this.snippetLibrary.Add(newSnippet);
         this.Close();
     }
 }
        public ActionResult CodeSnippet(SnippetViewModel snippet)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Snippet newSnippet = new Snippet();
                    newSnippet.Name = snippet.Name.Trim();
                    newSnippet.Description = snippet.Description.Trim();
                    newSnippet.GroupName = snippet.GroupName.ToLower().Trim();
                    newSnippet.Keys = _utilityService.ResolveKeys(snippet.Keys);
                    newSnippet.DateCreated = DateTime.Now;
                    if (!string.IsNullOrEmpty(snippet.Website))
                        newSnippet.Website = snippet.Website.Trim();
                    newSnippet.Code = snippet.Code;
                    newSnippet.ProgrammingLanguageID = snippet.ProgrammingLanguageID;

                    try
                    {
                        _snippetService.CreateSnippet(newSnippet);
                        _snippetService.SaveSnippet();
                    }
                    catch (DbEntityValidationException ex)
                    {
                        var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                        // Join the list to a single string.
                        var fullErrorMessage = string.Join("; ", errorMessages);

                        // Combine the original exception message with the new one.
                        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                        // Throw a new DbEntityValidationException with the improved exception message.
                        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
                    }

                    SetLanguagesTypes();
                    return RedirectToAction("Code", "Snippets", new { id = newSnippet.ID })
                        .WithSuccess(newSnippet.Name + " saved successfully.");
                }
                else
                {
                    ModelState.AddModelError("", "Validation errors occured.");

                    SetLanguagesTypes();
                    return View(snippet);
                }
            }
            catch (Exception ex)
            {
                SetLanguagesTypes();
                return View(snippet).WithError(ex.Message);
            }
        }
Example #26
0
        public void Running_Rule_With_Incorrect_Syntax_Throws_An_Exception()
        {
            var snippet = new Snippet();
            var ruleCode = new StringBuilder();
            ruleCode.AppendLine("de run(snippet):");
            ruleCode.AppendLine("  return 100;");

            var rule = new PyRule() { Code = ruleCode.ToString(), Weight = 1 };
            rule.Rank(snippet);
        }
Example #27
0
        public void init(AssetManagerForm mainForm, Snippet snippet)
        {
            form = this.snippetEditor1.NewDocument();

            this.mainForm = mainForm;
            this.snippet = snippet;

            this.form.Scintilla.Text = snippet.Function;
            this.DisplayObjectProperties();
        }
Example #28
0
        public void Rule_Script_Returns_A_Value_Of_Incompatible_Type()
        {
            var snippet = new Snippet();
            var ruleCode = new StringBuilder();
            ruleCode.AppendLine("def run(snippet):");
            ruleCode.AppendLine("  pass");

            var rule = new PyRule() { Code = ruleCode.ToString(), Weight = 1 };
            rule.Rank(snippet);
        }
Example #29
0
        public void Rule_Script_Does_Not_Contain_Run_Function()
        {
            var snippet = new Snippet();
            var ruleCode = new StringBuilder();
            ruleCode.AppendLine("def notrun(snippet):");
            ruleCode.AppendLine("  return 100;");

            var rule = new PyRule() { Code = ruleCode.ToString(), Weight = 1 };
            rule.Rank(snippet);
        }
Example #30
0
 public void RegisterProperty(Snippet property, List<Snippet> selectedSnippets)
 {
     PropertyComboBox box = new PropertyComboBox(property);
     if (selectedSnippets != null)
         box.Edit(selectedSnippets);
     Controls.Add(box);
     this.propertyCombos.Add(box);
     box.MouseDown += new MouseEventHandler(box_MouseDown);
     box.label1.MouseDown += new MouseEventHandler(box_MouseDown);
 }
Example #31
0
        private void ApplyCodeRefs(XmlDocument document, string key)
        {
            XPathNavigator    docNavigator = document.CreateNavigator();
            XPathNodeIterator iterator     = docNavigator.Select(_codeRefSelector);

            if (iterator == null || iterator.Count == 0)
            {
                return;
            }

            XPathNavigator navigator = null;

            XPathNavigator[] arrNavigator =
                BuildComponentUtilities.ConvertNodeIteratorToArray(iterator);

            int itemCount = arrNavigator.Length;

            for (int i = 0; i < itemCount; i++)
            {
                navigator = arrNavigator[i];
                if (navigator == null) // not likely!
                {
                    continue;
                }
                string input = navigator.Value;
                if (Snippet.IsValidReference(input) == false)
                {
                    this.WriteMessage(MessageLevel.Warn, String.Format(
                                          "The code reference '{0}' is not well-formed", input));

                    navigator.DeleteSelf();

                    continue;
                }

                SnippetInfo[] arrayInfo = Snippet.ParseReference(input);
                if (arrayInfo.Length == 1)
                {
                    ApplySnippetInfo(navigator, arrayInfo[0], input);
                }
                else
                {
                    ApplyMultiSnippetInfo(navigator, arrayInfo, input);
                }
            }
        }
Example #32
0
        public void TestSelected()
        {
            var snippet = new Snippet(
                "if",
                "if (true) {\r\n    $body$\r\n}\r\n",
                new Declaration("false", "if (false) {\r\n    $body$\r\n}\r\n")
                );

            using (var solution = BasicProject.Generate().ToVs()) {
                var app = TestOneTabSnippet(solution, snippet);

                Keyboard.Type("testing");
                app.WaitForText("if (false) {\r\n    testing\r\n}\r\n");

                solution.CloseActiveWindow(vsSaveChanges.vsSaveChangesNo);
            }
        }
Example #33
0
        private static IEditor VerifySnippet(Snippet snippet, string body, IEditor server)
        {
            Keyboard.Type(snippet.Shortcut + "\t");

            server.WaitForText(snippet.Expected.Replace("$body$", body));

            foreach (var decl in snippet.Declarations)
            {
                Console.WriteLine("Declaration: {0}", decl.Replacement);
                Keyboard.Type(decl.Replacement);
                Keyboard.Type("\t");
                server.WaitForText(decl.Expected.Replace("$body$", body));
                Keyboard.Type("\t");
            }
            Keyboard.Type("\r");
            return(server);
        }
Example #34
0
        protected override void Execute(ExecutionContext context, Snippet snippet)
        {
            snippet.PrefixTitle($"{Modifier.Keyword} ");

            snippet.PrefixShortcut(Modifier.Shortcut);

            snippet.PrefixDescription($"{Modifier.Keyword} ");

            if (!Modifier.Tags.Contains(KnownTags.Default))
            {
                snippet.AddTag(KnownTags.ExcludeFromReadme);
            }

            snippet.RemoveLiteralAndReplacePlaceholders(LiteralIdentifiers.Modifiers, Modifier.Keyword);

            snippet.PrefixFileName(Modifier.Name);
        }
Example #35
0
        public SourceWriter WriteCode(IEnumerable <Snippet> snippets)
        {
            // compact snippets so vs language service doesn't have to
            var     compacted = new Snippets(snippets.Count());
            Snippet prior     = null;

            foreach (var snippet in snippets)
            {
                if (prior != null && SnippetAreConnected(prior, snippet))
                {
                    prior = new Snippet
                    {
                        Value = prior.Value + snippet.Value,
                        Begin = prior.Begin,
                        End   = snippet.End
                    };
                    continue;
                }
                if (prior != null)
                {
                    compacted.Add(prior);
                }
                prior = snippet;
            }
            if (prior != null)
            {
                compacted.Add(prior);
            }

            // write them out and keep mapping-to-spark source information
            foreach (var snippet in compacted)
            {
                if (snippet.Begin != null)
                {
                    Mappings.Add(new SourceMapping
                    {
                        Source      = snippet,
                        OutputBegin = Length,
                        OutputEnd   = Length + snippet.Value.Length
                    });
                }
                Write(snippet.Value);
            }

            return(this);
        }
Example #36
0
        public Snippet codeHtml(EntityModel defs)
        {
            var template = @"
<div *ngIf=""!showForm"">
    <div>
        <button type=""button"" class=""btn btn-primary"" (click)=""addTrip()"">
            Add New Trip
        </button>
    </div>
  <div *ngFor=""let model of trip.list; let i = index"" class=""tripList"">
    <h4>
      <b>{{model.tripDate | date : ""MM/dd/yyyy""}} </b>
      <b>{{model.airportInfo?.text}}</b>
    </h4>
    {{model.airportInfo?.text2}}
    <p>{{model.transTypeDesc}}</p>
    <p>{{model.groupName}} {{model.groupSize}}</p>
    <button type=""button"" class=""btn btn-link"" (click)=""editTrip(model)"">Edit</button>
    <button type=""button"" class=""btn btn-link"" (click)=""deleteTrip(model)"">Delete</button>

  </div>
</div>

<div class=""col""  *ngIf=""showForm && trip.model"">
    <div style=""max-width:300px"" *ngIf=""trip.model"">
        <app-trip-form
        [model]=""trip.model""
        [enableDelete]=""false""
        (save)=""saveTrip($event)""
        (cancel)=""cancel($event)""
        (selete)=""deleteTrip($event)""
        ></app-trip-form>
    </div>
  </div>

";
            var snippet  = new Snippet();

            snippet.header     = "Navigate To Form";
            snippet.language   = Language.HTML;
            snippet.desription = "Angular UI Component";
            snippet.code       = replaceNames(defs, template);

            return(snippet);
        }
Example #37
0
        public static string GetTitle(
            this Snippet snippet,
            bool trimLeadingShortcut    = true,
            bool trimTrailingUnderscore = true)
        {
            string s = snippet.Title;

            int i = 0;

            if (trimLeadingShortcut &&
                snippet.HasTag(KnownTags.TitleStartsWithShortcut))
            {
                while (i < s.Length &&
                       s[i] != ' ')
                {
                    i++;
                }

                while (i < s.Length &&
                       s[i] == ' ')
                {
                    i++;
                }
            }

            int j = s.Length - 1;

            if (trimTrailingUnderscore &&
                snippet.HasTag(KnownTags.TitleEndsWithUnderscore))
            {
                while (j >= 0 &&
                       s[j] == '_')
                {
                    j--;
                }

                while (j >= 0 &&
                       s[j] == ' ')
                {
                    j--;
                }
            }

            return(s.Substring(i, j - i + 1));
        }
Example #38
0
        /// <summary>
        /// PropertyChangedCallback for Snippet
        /// </summary>
        private static void SnippetChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            if (obj is SnippetEditor)
            {
                SnippetEditor owner = (SnippetEditor)obj;

                Snippet s = (args.NewValue as Snippet);

                // create a local backup of the editable properties (for the cancel operation)

                if (s != null)
                {
                    owner._name     = s.Name;
                    owner._shortcut = s.Shortcut;
                    owner._text     = s.Text;
                }
            }
        }
        protected override string GenerateHeader(Snippet snippet)
        {
            var builder = new StringBuilder();

            foreach (var @namespace in snippet.Imports)
            {
                builder.AppendFormat("using {0};", @namespace);
                builder.AppendLine();
            }
            builder.AppendLine("namespace SnippetCompiler");
            builder.AppendLine("{");
            builder.AppendLine("    public partial class UserSnippet");
            builder.AppendLine("    {");
            builder.AppendLine("        public static void Main(string[] args)");
            builder.AppendLine("        {");

            return(builder.ToString());
        }
Example #40
0
        private static Snippet WithAttribute(Snippet s)
        {
            s.SuffixTitle(" (with attribute)");
            s.SuffixShortcut(AttributeShortcut);
            s.SuffixDescription(" (with attribute)");

            s.ReplacePlaceholders(AttributeIdentifier, $" ${AttributeIdentifier}$");

            if (s.Code.Placeholders.Contains(ContentIdentifier))
            {
                s.ReplacePlaceholders(EndIdentifier, "");
                s.ReplacePlaceholders(ContentIdentifier, $"${EndIdentifier}$");
            }

            s.SuffixFileName("WithAttribute");

            return(s);
        }
Example #41
0
        void l1_MouseMove(object sender, MouseEventArgs e)
        {
            if (m_clickedSnippet)
            {
                Label   l  = (Label)sender;
                Snippet sn = (Snippet)l.Tag;

                string itemName = sn.Shortcut;

                m_editors.StartDrag();

                DataFormats.Format format = DataFormats.GetFormat("ChameleonSnippet");
                DataObject         dobj   = new DataObject(format.Name, itemName);
                DragDropEffects    dde    = DoDragDrop(dobj, DragDropEffects.Copy);

                m_editors.EndDrag();
            }
        }
Example #42
0
        public void SnippetPlaceholderTextWithUrlShouldParseCorrectly()
        {
            string text = @"var testIdentifier = '${1:http://test-content-url.nupkg}'";

            var snippet = new Snippet(text);

            snippet.Text.Should().Be(text);

            snippet.Placeholders.Should().SatisfyRespectively(
                x =>
            {
                x.Index.Should().Be(1);
                x.Name.Should().Be("http://test-content-url.nupkg");
                x.Span.ToString().Should().Be("[22:56]");
            });

            snippet.FormatDocumentation().Should().Be("var testIdentifier = 'http://test-content-url.nupkg'");
        }
Example #43
0
 private void mnuNewScript_Click(object sender, EventArgs e)
 {
     using (NewSnippetDialog dialog = new NewSnippetDialog())
     {
         if (dialog.ShowDialog(this) == DialogResult.OK)
         {
             string  text   = string.IsNullOrEmpty(txtCode.Selection.Text) ? txtCode.Text : txtCode.Selection.Text;
             Snippet script = new Snippet()
             {
                 Name = dialog.ScriptName,
                 Text = text,
                 Type = CommandType
             };
             script.Save();
             LoadSnippets();
         }
     }
 }
Example #44
0
        private async Task <int> GetAuthorsCount(Submission submission, Snippet foundSnippet, DateTime useSubmissionsFromDate)
        {
            using (var transaction = db.Database.BeginTransaction(IsolationLevel.ReadUncommitted))
            {
                var result = await db.SnippetsOccurences
                             .Where(o => o.SnippetId == foundSnippet.Id &&
                                    o.Submission.ClientId == submission.ClientId &&
                                    o.Submission.TaskId == submission.TaskId &&
                                    o.Submission.AddingTime > useSubmissionsFromDate)
                             .Select(o => o.Submission.AuthorId)
                             .Distinct()
                             .CountAsync();

                await transaction.CommitAsync();

                return(result);
            }
        }
        public void AddComment(AddCommentBindingModel model)
        {
            Snippet    snippet     = this.Context.Snippets.FirstOrDefault(s => s.Id == model.SnippetId);
            DateTime   currentTime = DateTime.Now;
            UserLogged author      = this.Context.UserLoggeds.FirstOrDefault(u => u.User.Id == model.UserId);
            string     content     = model.Content;

            Comment comment = new Comment()
            {
                Author       = author,
                Content      = content,
                CreationTime = currentTime,
                Snippet      = snippet
            };

            this.Context.Comments.Add(comment);
            this.Context.SaveChanges();
        }
Example #46
0
        public Snippet codeDao(EntityModel defs)
        {
            var snippet = new Snippet();

            snippet.header     = "CRUD Data Access Object";
            snippet.language   = Language.CSharp;
            snippet.desription = "Implemets REST CRUD Controller";

            var assign  = assignToModel(defs, 5);
            var assign2 = assignToEntity(defs, 4);

            snippet.code = replaceNames(defs, daoTemplate);
            snippet.code = snippet.code
                           .Replace("$$assign$$", assign)
                           .Replace("$$assign2$$", assign2);

            return(snippet);
        }
Example #47
0
        public void TestPassSelected(PythonVisualStudioApp app, PythonProjectGenerator pg)
        {
            var snippet = new Snippet(
                "class",
                "class ClassName(object):\r\n    pass",
                new Declaration("myclass", "class myclass(object):\r\n    pass"),
                new Declaration("(base)", "class myclass(base):\r\n    pass")
                );

            using (var vs = pg.Generate(BasicProjectDefinition).ToVs(app)) {
                var editor = TestOneTabSnippet(vs, snippet);

                Keyboard.Type("42");
                editor.WaitForText("class myclass(base):\r\n    42");

                vs.CloseActiveWindow(vsSaveChanges.vsSaveChangesNo);
            }
        }
Example #48
0
        public void SaveSnippet(Snippet snippet)
        {
            //Set Proper Dates
            snippet.ModifiedDate = DateTime.Now;

            if (snippet.SnippetId == 0)
            {
                snippet.CreationDate = DateTime.Now;
                context.Snippets.AddObject(snippet);
            }
            else
            {
                //context.Snippets.AddObject(snippet);
                context.Snippets.Attach(snippet);
                context.ObjectStateManager.ChangeObjectState(snippet, EntityState.Modified);
            }
            context.SaveChanges();
        }
Example #49
0
        public void SnippetTaken(Snippet snippet)
        {
            if (snippet.ChapterId != this.Chapter.Id || snippet.Page != this.CurrentPage)
            {
                UIHelper.MessageBox("The snippet belong to different Chapter/Page.");
                return;
            }

            snippet.Order = this.Snippets.Count;
            this.snippetRepository.AddSnippet(snippet);
            foreach (var mark in snippet.Marks)
            {
                mark.SnippetId = snippet.Id;
                this.markRepository.AddMark(mark);
            }
            this.LoadSnippets();
            this.Snippet = this.Snippets[this.Snippets.Count - 1];
        }
Example #50
0
                /// <summary>
                /// Gets a specific comment from the Snippet by Note ID
                /// </summary>
                /// <param name="_Config">The _ configuration.</param>
                /// <param name="_Project">The _ projet.</param>
                /// <param name="_Snippet">The _ snippet.</param>
                /// <param name="_ID">The _ identifier.</param>
                /// <returns></returns>
                public static Note GetComment(Config _Config, Project _Project, Snippet _Snippet, int _ID)
                {
                    string URI = _Config.APIUrl + "projects/" + _Project.id.ToString() + "/snippets/" + _Snippet.id.ToString() + "/notes/" + _ID.ToString();

                    HttpResponse <string> R = Unirest.get(URI)
                                              .header("accept", "application/json")
                                              .header("PRIVATE-TOKEN", _Config.APIKey)
                                              .asString();

                    if (R.Code < 200 || R.Code >= 300)
                    {
                        throw new GitLabServerErrorException(R.Body, R.Code);
                    }
                    else
                    {
                        return(JsonConvert.DeserializeObject <Note>(R.Body));
                    }
                }
Example #51
0
        public void Subranges()
        {
            Snippet snippet = new Snippet("aa${1:i}b${2:cc$1d${3:ee}}$1${0}",
                                          new Settings(null), null);

            //aaibccideei
            AssertRanges(
                "-1:2,1:i\n" +
                "  next:\n" +
                "  -1:10,1:i\n" +
                "-2:4,6:ccidee\n" +
                "  subrange:\n" +
                "  -1:2,1:i\n" +
                "  nested:\n" +
                "  -3:4,2:ee\n" +
                "-0:11,0:\n" +
                "", snippet.ranges);
        }
Example #52
0
        public static IEnumerable <Command> GetBasicTypeCommands(Snippet snippet, LanguageDefinition languageDefinition)
        {
            var flg = false;

            foreach (TypeDefinition type in languageDefinition
                     .Types
                     .Where(f => f.HasTag(KnownTags.BasicType) && snippet.RequiresBasicTypeGeneration(f.Name)))
            {
                yield return(new BasicTypeCommand(type));

                if (!flg)
                {
                    yield return(new BasicTypeCommand(TypeDefinition.Default));

                    flg = true;
                }
            }
        }
        private IEnumerable <Command> GetTypeCommands(Snippet snippet)
        {
            bool flg = false;

            foreach (TypeDefinition type in Language
                     .Types
                     .Where(f => snippet.RequiresTypeGeneration(f.Name)))
            {
                yield return(new TypeCommand(type));

                if (!flg)
                {
                    yield return(new TypeCommand(null));

                    flg = true;
                }
            }
        }
Example #54
0
        public void TestPassSelected()
        {
            var snippet = new Snippet(
                "class",
                "class ClassName(object):\r\n    pass",
                new Declaration("myclass", "class myclass(object):\r\n    pass"),
                new Declaration("(base)", "class myclass(base):\r\n    pass")
                );

            using (var vs = BasicProjectVS) {
                var app = TestOneTabSnippet(vs, snippet);

                Keyboard.Type("42");
                app.WaitForText("class myclass(base):\r\n    42");

                vs.CloseActiveWindow(vsSaveChanges.vsSaveChangesNo);
            }
        }
Example #55
0
        public void SinglePropertySnippetShouldParseCorrectly()
        {
            const string text = "name: '$0'";

            var snippet = new Snippet(text);

            snippet.Text.Should().Be(text);

            snippet.Placeholders.Should().SatisfyRespectively(
                x =>
            {
                x.Index.Should().Be(0);
                x.Name.Should().BeNull();
                x.Span.ToString().Should().Be("[7:9]");
            });

            snippet.FormatDocumentation().Should().Be("name: ''");
        }
Example #56
0
        protected override void Execute(ExecutionContext context, Snippet snippet)
        {
            snippet.SuffixShortcut("x");
            snippet.SuffixTitle(" definition");
            snippet.SuffixDescription(" definition");
            snippet.SnippetTypes |= SnippetTypes.SurroundsWith;
            snippet.SuffixFileName("Definition");
            snippet.AddTag(KnownTags.ExcludeFromReadme);

            PlaceholderCollection placeholders = snippet.Code.Placeholders;

            if (placeholders.Contains("_definition"))
            {
                snippet.CodeText = snippet.Code.ReplacePlaceholders("_definition", @" {
	$selected$$end$
}");
            }
        }
Example #57
0
        public Snippet codeModel(EntityModel defs)
        {
            var template = @"
export class RefDataModel {
    transTypes: ILookupItem[];
}
";

            var snippet = new Snippet();

            snippet.header     = "Reference Data Model, Client Side";
            snippet.language   = Language.TypeScript;
            snippet.desription = "Web API Reference Data Container Model";

            snippet.code = replaceNames(defs, template);

            return(snippet);
        }
Example #58
0
 static private Snippet GetWrapedSnipet(string title, Snippet innner)
 {
     return(new Snippet()
     {
         Elements =
         {
             new SnippetTextElement()
             {
                 Text = $"#region {title}\n"
             },
             innner,
             new SnippetTextElement()
             {
                 Text = $"\n#endregion\n"
             },
         }
     });
 }
Example #59
0
        protected override void Execute(ExecutionContext context, Snippet snippet)
        {
            snippet.SuffixTitle(" property");
            snippet.SuffixShortcut("py");
            snippet.SuffixDescription(" property");
            snippet.RemoveTag(KnownTags.GenerateXamlProperty);
            snippet.RemoveTag(KnownTags.NonUniqueShortcut);
            snippet.AddTag(KnownTags.AutoGenerated);

            snippet.Literals.Clear();
            snippet.AddLiteral("property", "Property name", ".");

            string name = Path.GetFileNameWithoutExtension(snippet.FilePath);

            snippet.CodeText = $"<{name}$property$>$end$</{name}$property$>";

            snippet.SuffixFileName("Property");
        }
Example #60
0
    public List <Adventure> ConvertToAdventure()
    {
        var adventuresData     = new List <Adventure>();
        var adventureItemsByID = new Dictionary <int, List <AdventureItem> >();

        foreach (var item in this.adventures)
        {
            var adventureItemList = new List <AdventureItem>();

            if (adventureItemsByID.ContainsKey(item.id))
            {
                adventureItemsByID.TryGetValue(item.id, out adventureItemList);
            }

            adventureItemList.Add(item);

            if (adventureItemsByID.ContainsKey(item.id))
            {
                adventureItemsByID[item.id] = adventureItemList;
            }
            else
            {
                adventureItemsByID.Add(item.id, adventureItemList);
            }
        }

        foreach (var key in adventureItemsByID.Keys)
        {
            var adventure = new Adventure();

            foreach (var item in adventureItemsByID[key])
            {
                var snippet = new Snippet();
                snippet.Text = item.text;
                snippet.Need = item.need;
                Debug.Log(item.type);
                adventure.AdventureSnippetDictionary[item.type].Add(snippet);
            }

            adventuresData.Add(adventure);
        }

        return(adventuresData);
    }