Updates from April, 2010 Toggle Comment Threads | Keyboard Shortcuts

  • Ali BaderEddin 9:18 pm on April 1, 2010 Permalink | Reply  

    Xml Editor Control 


    If you have a Windows Forms application that involves Xml editing or viewing, you can use this control to save yourself the effort of formatting the Xml content. For now, only syntax highlighting is implemented. I expect to add more features in the future like spacing, grouping, intellisense, etc…

    Usage

    Simply add the files (XmlToken.cs, XmlTokenizer.cs, XmlEditor.cs, XmlEditor.designer.cs) to your project then drag and drop the XmlEditor control from the Toolbox into your Windows Form.

    The XmlEditor control currently has three public properties. Use AllowXmlFormatting to enable or disable formatting on the Xml content in the editor. The ReadOnly property tells whether or not to allow the user to change the text. The Text property sets or gets the text of the Xml editor.

    Here is how the control looks like when AllowXmlFormatting = true and ReadOnly = false (default values):

    Implementation

    To color the Xml string, we have to split it into multiple tokens, then color each token based on its type. I have identified the following token types (based on syntax highlighting behavior in Visual Studio 2008):

    • A “Value” is anything between double quotes
    • A “Comment” is anything that starts with <!– and ends with –> (or starts with <!– and is never closed with –>)
    • An “Element” is any letter or digit that falls between < and a space or >
    • An “Attribute” is any letter or digit that falls after a < followed by space and not closed by >
    • An “Escape” is anything that starts with & and ends with ; (For example &quote;)
    • A “SpecialChar” is any character that is not a letter or a digit
    • A “None” is anything else

    The Tokenize() public static method of the XmlTokenizer class does the job of splitting a string into Xml tokens.

    An XmlToken object is a representation of an Xml token with details about the exact text of that token, its location in the string and its type.

    Here is the code in the XmlEditor control that does the syntax highlighting:

    List<XmlToken> tokens = XmlTokenizer.Tokenize(xmlEditor.Text);
    
    foreach (XmlToken token in tokens)
    {
        xmlEditor.Select(token.Index, token.Text.Length);
    
        switch (token.Type)
        {
            case XmlTokenType.Attribute:
                xmlEditor.SelectionColor = Color.Red;
                break;
            case XmlTokenType.Comment:
                xmlEditor.SelectionColor = Color.DarkGreen;
                break;
    
            //  and so on for the other token types
        }
    }

    Download source and exe.

     
    • maria judi 5:37 pm on November 15, 2010 Permalink | Reply

      thak u_______

      ths is very useful for my project

    • Ali BaderEddin 8:55 pm on November 15, 2010 Permalink | Reply

      Glad it is..

    • Marco van Tintelen 5:58 am on January 10, 2011 Permalink | Reply

      Very nice!

    • rishi 10:02 am on February 9, 2011 Permalink | Reply

      intellisense: do you have support for that ? If not can you tell me how can I implement it. thanks in advance.

    • Colby Africa 8:32 am on March 4, 2011 Permalink | Reply

      Nice work! Are you okay if I start with this and extend it or is this “as-is” only?

      Thank you!

      Colby

    • Ali BaderEddin 12:38 am on March 5, 2011 Permalink | Reply

      Sure… Please share the final version that you come up with.

      If you are planning to distribute it, it’s OK as long as you keep reference that it was originally created by me and link to this post in the source code…

    • Joseph Gordon 7:07 am on August 17, 2011 Permalink | Reply

      Great work here. Small performance tip: you have a re-entry issue in your FormatXml method, where changing the selectionColor fires the textbox_changed event, causing another call to FormatXml.

    • W 1:16 pm on February 17, 2012 Permalink | Reply

      Thanks. This is really helpful.

    • Sims 4 Cheats 1:11 pm on July 28, 2014 Permalink | Reply

      Heya just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading correctly.
      I’m not sure why but I think its a linking issue. I’ve tried it
      in two different internet browsers and both show the same results.

    • Hack Jungle Heat 12:03 pm on August 5, 2014 Permalink | Reply

      This is very interesting, You are a very skilled blogger. I have joined your
      feed and look forward to seeking more of your magnificent post.
      Also, I have shared your web site in my social networks!

    • Cookie Clicker Hack 12:56 am on August 6, 2014 Permalink | Reply

      Thank you for every other informative web site.
      Where else could I get that type of info written in such a perfect way?

      I have a venture that I’m just now operating on, and I have been on the look out for such info.

    • tsunade cosplay 10:49 am on August 19, 2014 Permalink | Reply

      If possibly you paint your head’s hair, you may obtain a cost-effective
      hair painting for any couple of bucks, its surely not high-priced in any way, then you may really start off searching great!
      . If you ever generally have the very head of hair coloration then thats a plus and a issue a lot less to bother with.
      In the future you may wish to discover the crucial naruto costume, due to the surplus head of hair which it is actually got all around the throat, you will get a thing kind a
      sister or simply a cosing or almost certainly some girl it
      becomes clear that seems to have purchased a sweater or some element much like what has got the unique head of
      hair details, next the only dilemma leftover may be to position several orange attire have on more than this to be positive the hairs go on top of
      the top rated of this orange t-shirts or dresses making it look
      and also believe that this had been a particular.

    • home skin whitening tips 2:24 am on September 4, 2014 Permalink | Reply

      Nice blog here! Also your site loads up fast! What host are you using?

      Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

    • wihylof.wordpress.com 10:19 am on September 6, 2014 Permalink | Reply

      Just desire to say your article is as surprising.
      The clarity in your post is just nice and i can assume you’re an expert on this subject.

      Fine with your permission let me to grab your feed to keep updated
      with forthcoming post. Thanks a million and please continue the
      rewarding work.

  • Ali BaderEddin 5:02 pm on March 18, 2010 Permalink | Reply  

    SPList Image and SPFile Icon 


    If you ever wanted to create a WinForms app for SharePoint that displays or interacts with lists, document libraries and files, then taking advantage of the SPList.ImageUrl and SPFile.IconUrl would help improve the user experience for your app.

    Below is an app that displays all the webs, lists, document libraries and files in a selected site collection.

    We can improve this a little bit by adding icons (taken from TEMPLATE\IMAGES frolder on a SharePiont installation) for some of the nodes, as follows:

    However, this is not good enough since we’ll have all lists with the same icon, all doc libs with the same icon and so on… Here is the same app taking advantage of the list image url and file icon url.

    For the list or document library, this is done by using the SPList.ImageUrl attribute. Here is howthe tree node was added:

    TreeNode listNode = parentNode.Nodes.Add(list.Title);
    listNode.SelectedImageIndex = listNode.ImageIndex = GetImage(GetImageFullPath(list.ImageUrl));

    For the file, this is done by using the SPFile.IconUrl attribute. Here is howthe tree node was added:

    TreeNode fileNode = parentNode.Nodes.Add(file.Name);
    fileNode.SelectedImageIndex = fileNode.ImageIndex = GetImage(GetImageFullPath(file.IconUrl));

    The GetImageFullPath method simply gets the full path of the image:

    /// <summary>
    /// Gets the SharePoint full path from the relative path
    /// </summary>
    /// <param name="relativePath"></param>
    /// <returns></returns>
    private static string GetImageFullPath(string relativePath)
    {
        //  Get image name
        string imageName = Path.GetFileName(relativePath);
    
        //  Get SharePoint IMAGES folder path
        string fullPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\IMAGES");
    
        return Path.Combine(fullPath, imageName);
    }

    Given that now we have the full file system path to the image, all we have to do now is create an image from the file path then add it to the ImageList of the TreeView. The GetImage() method below does the job.

    /// <summary>
    /// Gets the image of the sp element from specified url
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private int GetImage(string url)
    {
        //  Get image index from the Image List
        int imageIndex = spImageList.Images.IndexOfKey(url);
    
        //  Image is not in the list, so add it
        if (imageIndex == -1)
        {
            //  Get the image from specified path
            Image image = Image.FromFile(url);
    
            //  Add the image to the image list
            spImageList.Images.Add(url, image);
    
            //  Get its index
            imageIndex = spImageList.Images.Count - 1;
        }
    
        return imageIndex;
    }

    Here is how the final app looks like. Click on the image below to download the src and exe.

     
    • best nokia lumia 5:21 am on August 19, 2014 Permalink | Reply

      Woah! I’m really digging the template/theme
      of this blog. It’s straight-forward, yet beneficial. A lot of times it’s hard to get that
      “best symmetry” between superb usability and visual appeal.
      I must say you’ve done a amazing job with this. Additionally, the blog loads super
      quick for me on Safari. Superb Blog!

    • partouze hardcore 12:37 am on September 26, 2014 Permalink | Reply

      Je peux vߋus dire quee c’est clairement un bonheur
      dе vesnir suг cе blog

    • argan oi 6:58 am on October 1, 2014 Permalink | Reply

      Though a clarifying face cleaner works wonderful to minimize all traces of oil and give you a tidy feeling, in case you begin experiencing terribly itchy skin or red spots quickly stop the use of that particular facial cleanser.

      There are upscale shops that offer good quality Argan oils and are
      priced at a premium. When the make-up is left unaltered, oils manage to mix
      well with the natural structure of the human body, offering very desirable
      results.

    • vimeo.com 2:44 am on October 19, 2014 Permalink | Reply

      It’ll be worthwhile for the prospect to find the accreditation.
      Hairstyles in waves, curls, poker straight that smaller profitable
      thinning hair frizzy hair these days. Children and grandchildren can be shown the photographs of the wedding ceremony.

    • ช่างเหล็กภูเก็ต 8:46 am on November 7, 2014 Permalink | Reply

      I don’t even understand how I ended up here, but I
      thought this post was once good. I do not recognize who you might be but definitely you are going to
      a well-known blogger if you are not already. Cheers!

    • film hard 12:53 pm on December 6, 2014 Permalink | Reply

      On ѵa vous dire que сe n’est guèгe inexact …

  • Ali BaderEddin 6:18 pm on March 3, 2010 Permalink | Reply  

    How To Get All Site Urls Without Creating an SPSite object? 


    Let’s say you are trying to create a SharePoint admin tool that shows all site collections in the farm, then allows the user to interact with only the site collections of interest to him.

    To get all the site collection Urls in the farm, you’d usually go with the following approach:

    foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
    {
        foreach (SPSite site in webApp.Sites)
        {
            string fullSiteUrl = site.Url;
            Console.WriteLine(fullSiteUrl);
            site.Close();
        }
    }

    The disadvantage in using such an approach is that we have to create an SPSite object for every site collection in the farm, then close it. That’ll mean a lot of work allocating and deallocating memory. Luckily, there is a better approach to do this, shown below:

    foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
    {
        string webAppUrl = webApp.GetResponseUri(SPUrlZone.Default).AbsoluteUri; 
    
        foreach (string siteUrl in webApp.Sites.Names)
        {
            string fullSiteUrl = webAppUrl + siteUrl;
            Console.Writeline(fullSiteUrl);
        }
    }

    This way, we don’t have to create any of the expensive SPSite objects then close them. On a small farm, that’ll help your application load faster, but on a large farm with hundreds of site collections, this approach is necessary.

    You can find the full source for the SPSite ListView here. This was created as a Visual Studio 2008 project on top of SharePoint 2010 Beta, but you can easily remove the reference and add a reference to the 2007 Microsoft.SharePoint.dll.

     
    • Reset.exe virus 12:37 pm on July 11, 2014 Permalink | Reply

      Very shortly this website will be famous among all blog visitors, due to it’s nice articles or reviews

    • blastcln.exe 1:26 pm on July 11, 2014 Permalink | Reply

      It’s hard to find well-informed people in this particular subject, however, you seem like you know what you’re talking about!
      Thanks

    • TabTip.exe 11:56 am on July 12, 2014 Permalink | Reply

      Great post. I will be facing a few of these issues as well..

    • apds.dll 10:58 pm on July 15, 2014 Permalink | Reply

      Fantastic blog! Do you have any suggestions
      for aspiring writers? I’m hoping to start my own blog soon but I’m a little lost on everything.

      Would you recommend starting with a free platform like WordPress or go for a paid option? There are so many options out there
      that I’m totally confused .. Any recommendations? Appreciate
      it!

    • dcomp.dll 11:04 pm on July 16, 2014 Permalink | Reply

      I appreciate, result in I discovered exactly what I used to be having a look for.
      You’ve ended my four day long hunt! God Bless you man. Have a great day.
      Bye

    • aeinv.dll 5:09 am on July 21, 2014 Permalink | Reply

      Just want to say your article is as amazing. The clearness on your put up is just excellent and i could suppose you are a professional on this
      subject. Well with your permission let me to clutch your RSS feed to keep updated
      with forthcoming post. Thanks a million and please keep up the rewarding work.

  • Ali BaderEddin 4:50 am on February 11, 2010 Permalink | Reply  

    C# Windows Form is Busy 


    There are two very common ways of telling the user that your application is busy. One is to show a progress bar that gets updated based on the progress getting done, and another is to show the “Waiting” cursor while the application is doing work.

    Waiting Cursor

    To show the user the Waiting cursor while your program is busy, all you have to do is to set the current cursor to the Waiting cursor before your code runs, then set it back to an arrow after your code completes.

    Cursor.Current = Cursors.WaitCursor;
    
    //  Your Code
    
    Cursor.Current = Cursors.Default;

    Progress Bar

    The progress bar is a more user-friendly solution, but in most cases showing the waiting cursor does the job. Here is the simplest way to use a progress bar:

    int totalSteps = 10;
    for (int i = 1; i <= totalSteps; i++)
    {
        //  One chunk of your code
    
        int progress = i * 100 / totalSteps;
        blocksProgressBar.Value = progress;
    }
    blocksProgressBar.Value = 0;

    Yes, it’s that easy to implement a progress bar that gets updated based on the work done by your app. However, while progress is shown, the user can’t interact with the UI or do any other operation (the UI thread is the single thread doing the work here). To get the multi-threaded behavior, the easiest way is to use a background worker process, as shown below:

    So instead of putting your code in the event handler method, you will replace it with a call to start the worker process then move the code to the worker process events.

    private void doButton_Click(object sender, EventArgs e)
    {
        backgroundWorker.RunWorkerAsync();
    }

    The worker process will do its work in the DoWork event. To show progress, the code needs to be split into segments and the background worker ReportProgress method needs to be called whenever a segment of code is executed.

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        int totalSteps = 10;
    
        for (int i = 1; i <= totalSteps; i++)
        {
            //  One chunk of your code
    
            int progress = i * 100 / totalSteps;
            backgroundWorker.ReportProgress(progress);
        }
    }

    Whenever progress changes, we need to update the value of the progress bar.

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        blocksProgressBar.Value = e.ProgressPercentage;
    }

    When the worker process is done (progress = 100%), we reset the progress bar.

    private void backgroundWorker_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        blocksProgressBar.Value = 0;
    }

    Below is a Windows Form application that lets you try the concepts explained above, and also shows you how the Marquee progress bar works, which is shockingly harder than the more realistic single-threaded progress bar we’ve discussed above.

    Download source and exe from here.

     
    • Paul 9:09 am on May 11, 2011 Permalink | Reply

      Thank You! That is exactly what I was looking for.

    • Mike 10:45 am on October 4, 2011 Permalink | Reply

      How do you tie a progress bar to sql query, returning data into a datagridview? It doesn’t have to be totally accurate, just doing something while the data is loading, then stopping once it has loaded…

    • Rudi Larno 8:49 am on December 8, 2011 Permalink | Reply

      Seems like the Marquee style does its work using the UI thread. So then it is logical that your options using System.Threading.Thread.Sleep(milliSecondsToWait); do not work, as you are blocking the UI Thread, not allowing your UI to get updated.

      Nice write up however.

    • yogesh makwana 8:58 pm on January 18, 2012 Permalink | Reply

      i want to know how to use marque in c#.net windowform…??????

    • Ankit Baria 5:31 am on September 14, 2012 Permalink | Reply

      Really helpful post. Thanks

    • http://tinyurl.com/guileasy48296 3:31 am on January 9, 2013 Permalink | Reply

      “C# Windows Form is Busy The Code Log” was
      in fact a truly awesome post, . Keep publishing and I’ll try to continue to keep reading through! Thanks for your time ,Louie

    • caret caretaker careworn carfare cargo carhop caribou caricature caries carillon carillonneur carina carinate carioca cariole carious caritas cark carl carline carling carload carmagnole carman carminative carmine carnage carnal carnal knowledge carnallit 11:42 am on August 5, 2013 Permalink | Reply

      Hi there! I just would like to give a huge thumbs up for the nice information youve gotten here on this post.
      I might be coming again to your weblog for more soon.

    • Khursheed Fateh 10:17 pm on May 12, 2014 Permalink | Reply

      See the modifivations I made to ylour program. Now Timer base progressbar is working.


      private Stopwatch s = new Stopwatch(); // Stopwatch
      private void progressButton2_Click(object sender, EventArgs e)
      {
      showProgress = true;
      timer.Enabled = true;
      timer.Start();

      s.Start(); // start stopwatch in this method

      marqueeProgressBar.Style = ProgressBarStyle.Marquee; // set progressbar style in this method
      }

      private void timer_Tick(object sender, EventArgs e)
      {
      if ( s.Elapsed < TimeSpan.FromSeconds((double)secondsToWaitSpinner2.Value))
      {
      // as long as elapsed time is less then the delay time
      // keep going
      toolStripStatusLabel1.Text = s.Elapsed.ToString(); // show elapsed time
      }
      else
      {
      marqueeProgressBar.Style = ProgressBarStyle.Blocks;
      timer.Stop();
      s.Stop(); // stop stop-watch here
      s.Reset(); // reset stop watch so that when you click again
      // it starts from begining and
      // not from where it stoped last time
      timer.Enabled = false;
      toolStripStatusLabel1.Text = "";
      }
      }

    • Khursheed Fateh 10:32 pm on May 12, 2014 Permalink | Reply

      “Before and after” part of your code is not working because it is freezing/stoping UI/Form for specified time. Because for the duration marquee is set Form remain froozen/unresponsive progressbar fails to show. You can see this by commenting last statement of method like this. Now you will see progressbar marquee was started but was unable to update itself because form was not responding during that time.

      private void progressButton_Click(object sender, EventArgs e)
      {
      marqueeProgressBar.Style = ProgressBarStyle.Marquee;

      int milliSecondsToWait = (int)secondsToWaitSpinner.Value * 1000;
      System.Threading.Thread.Sleep(milliSecondsToWait);

      // marqueeProgressBar.Style = ProgressBarStyle.Blocks;
      }

    • Marty 7:08 pm on July 21, 2014 Permalink | Reply

      I was curious if you ever considered changing the
      structure of your blog? Its very well written; I love what youve
      got to say. But maybe you could a little more in the way of content so people could
      connect with it better. Youve got an awful lot of text
      for only having one or two images. Maybe yyou could space iit out better?

    • Eleanore 1:10 am on July 22, 2014 Permalink | Reply

      I’m impressed, I must say. Rarely do I encounter a blog that’s both educative and amusing,
      and let me tell you, you have hit the nail on the head.
      The problem is an issue that not enough men and women are speaking intelligently about.
      Now i’m very happy I came across this during my search for something regarding this.

    • altin yuzuk 4:41 am on August 2, 2014 Permalink | Reply

      Hello to every , because I am actually eager of reading this
      blog’s post to be updated daily. It consists of nice data.

    • No pain, No Gain - Bodybuilding Documentary 11:20 am on September 20, 2014 Permalink | Reply

      Link exchange iis nothing eelse but it is just placing the other person’s web site link on your page at proper place and other person will also
      do similar in favor oof you.

    • https://sites.google.com/site/workview12/creating-pals-on-the-internet-will-earn-dollars-online 7:55 am on September 30, 2014 Permalink | Reply

      I was curious if you ever considered changing the layout of your blog?
      Its very well written; I love what youve got to say.
      But maybe you could a little more in the way of content so people could connect with
      it better. Youve got an awful lot of text for only having 1 or two pictures.
      Maybe you could space it out better?

    • aktivfun.blogg.de 7:38 pm on September 30, 2014 Permalink | Reply

      After going over a number of the blog posts
      on your web site, I truly like your technique of writing a blog.
      I saved it to my bookmark webpage list and will be checking back in the
      near future. Please check out my web site as well and tell me what you think.

    • steroid abuse in young athletes 2:12 pm on October 2, 2014 Permalink | Reply

      Hello are using WordPress for your blog platform?
      I’m new to the blog world but I’m trying to get started and
      set up my own. Do you require any coding knowledge to make your own blog?
      Any help would be really appreciated!

    • Frederick 7:37 am on December 19, 2014 Permalink | Reply

      MyLeadSystemPro has obtained a remarkable reputation to
      take everyday entrepreneurs and turning them into advertising leaders that were extraordinary.
      You’re presented methods, training’s and all the tools that you’ll require to develop into that Community Marketer
      that you are planning to become.

  • Ali BaderEddin 11:41 pm on January 16, 2010 Permalink | Reply  

    Sortable ListView 


    The Windows Forms ListView control doesn’t provide column sorting functionality. So if you click on a column in a ListView Details view, don’t expect the items to be sorted by the clicked column. To get this functionality, we’ll need to sort the items by the clicked column in the ListView ColumnClick event. I searched online for “Sortable ListView” and I found three MSDN articles talking about this: Sort ListView Column in Visual C#, Sorting ListView Items by Column Using Windows Forms, and How to: Sort ListView Items. None of those implementations takes into consideration the type of the column being sorted. That is, they all do string sorting. If you have dates and numbers in your list, then they’ll not be sorted properly. For example, number 2 will be considered greater than 11. Date time 9/9/1400 will be considered greater than 11/11/2020. Below is an implementation that takes into consideration string, DateTime, int and double types. It can be easily extended to handle more types.

    • Add the SortableListView control to your Windows Form
    • When adding columns to the SortableListView, set the Tag attribute to the type of the column.
    sortableListView.Columns.Add("String Field").Tag = typeof(string);
    sortableListView.Columns.Add("DateTime Field").Tag = typeof(DateTime);
    sortableListView.Columns.Add("Int Field").Tag = typeof(int);
    sortableListView.Columns.Add("Double Field").Tag = typeof(double);
    • Now, you can add the items as usual.

    For example, the below list is sorted by the DateTime field.

    Sortable ListView

    Sortable ListView

     Click on the above image to download the SortableListView control.

     
    • Mayank Raichura 9:21 am on October 6, 2011 Permalink | Reply

      Great article and a really nice control. Just one question…. why didn’t you add a new Property of, say, ColumnType? I mean this could let the tag property to be used for other purposes….

      Anyways….thank you very much for the control….its really really awesome…

c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: