working on it ...

Filters

Explore Public Snippets

Sort by

Found 15 snippets

    public by cghersi  173426  8  7  0

    Nice way to show the current time of day

    Current Time printed in a nice way
    public static string NiceCurrentTime()
    {  
      int hour = DateTime.Now.Hour;
    
      if (hour <= 5)
        return "this night oh yeah";
      else if (hour > 5 && hour <= 12)
        return "this morning";
      else if (hour > 12 && hour < 18)
        return "this afternoon";
      else 
        return "this evening";
    }                                                                                    

    public by cghersi  3417  1  6  0

    How to create an asynchronous task in C#

    This is a simple way to create a task that will run asynchronously with respect to the current thread
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
      log.Info("This will run async");
    });
    

    public by cghersi  4629  2  6  2

    Read the content of an rss feed

    Retrieves the RSS Item at the specified URL and prepares a list of RSS Items with tile, summary and id. The caller should specify the maximum number of items to download and can decide to strip HTML from title and summary.
    public class RssReader
    {
      public class RssItem
      {
        public string Title { get; set; }
        public string Summary { get; set; }
        public string Id { get; set; }
      }
      
      /// <summary>
      /// Requires System.ServiceModel to be added as a reference
      /// </summary>
      /// <param name="url"></param>
      /// <param name="maxItems"></param>
      public static IList<RssItem> ReadRss(string url, int maxItems, bool stripHtml = false)
      {
        IList<RssItem> result = new List<RssItem>();
        XmlReader reader = XmlReader.Create(url);
        SyndicationFeed feed = null;
        try
        {
          feed = SyndicationFeed.Load(reader);
        }
        catch
        {
          return result;
        }
        finally
        {
          reader.Close();
        }
      
        int totCount = 0;
        foreach (SyndicationItem item in feed.Items)
        {
          if (totCount++ > maxItems)
            break;
          string subject = (item.Title == null ? "" : item.Title.Text);
          string summary = (item.Summary == null ? "" : item.Summary.Text);
          if (stripHtml)
            summary = HtmlHelper.RemoveHtmlTag(HtmlHelper.RemoveHtmlTag(HtmlHelper.RemoveHtmlTag(HtmlHelper.RemoveHtmlTag(HtmlHelper.RemoveHtmlTag(summary, "div"), "a"), "img"), "table"), "br");
          string id = item.Id;
          result.Add(new RssItem() { Title = subject, Summary = summary, Id = id});
        }
        return result;
      }
    }
    

    public by cghersi  2262  0  7  0

    Print Object content with null check

    Tries to invoke the ToString() method on the given input. If the input is null, it returns "null".
    public static string PrintNullSafe(object input)
    {
      return (input == null ? "null" : input.ToString());  
    }

    public by cghersi  283425  2  6  1

    Remove HTML tags from text

    Removes the given tag (and all its content) from the specified text.
    static public string RemoveHtmlTag(string pageString, string tagName)
    {
      string output = pageString;
      int exprIni = 0;
      int firstChar = 0;
      int lastChar = 0;
    
      // find html element
      exprIni = output.IndexOf("<" + tagName, 0, output.Length,
                                      StringComparison.InvariantCultureIgnoreCase);
      while (exprIni >= 0)
      {
        // extract the html
        firstChar = exprIni;
    
        // find <tag ... />
        lastChar = output.IndexOf("/>", (firstChar + 1)) + 1;
        int nextCloseTag = output.IndexOf('>', (firstChar + 1));
    
        // closed with </tag> marker..
        if ((lastChar <= 0) || (nextCloseTag < lastChar))
        {
          // find </tag>
          lastChar = output.IndexOf("</" + tagName, (firstChar + 1), (output.Length - firstChar - 1),
                                                          StringComparison.InvariantCultureIgnoreCase);
          lastChar = output.IndexOf('>', (lastChar + 1));
        }
    
        if ((firstChar < 0) || (lastChar <= 0) || (firstChar == lastChar))
          return output.Substring(0, firstChar);
        else
        {
          output = String.Format("{0} {1}",
                      output.Substring(0, firstChar).Trim(),
                      output.Substring((lastChar + 1), (output.Length - lastChar - 1)).Trim());
        }
        exprIni = output.IndexOf("<" + tagName, 0, output.Length,
                                    StringComparison.InvariantCultureIgnoreCase);
      }
    
      return output;
    }
    

    public by cghersi  2767  0  7  2

    XOR in C#

    Given that technically there isn't a XOR conditional operator (like &&, ||, etc.), the best way to perform a XOR in a conditional statement is to use != operator, because it evaluates to a boolean
    bool a = true;
    bool b = false;
    if (a != b)
      return true;
    else
      return false;

    public by cghersi  1809  0  5  0

    Read A text File and return the content splitted by line

    public static string[] ReadLinesFromFile(string absolutePath)
    {
      return File.ReadAllLines(absolutePath);
    }
    

    public by cghersi  1747  4  5  1

    Split a string into words

    This is the fastest method to split a string separating the different words with blank spaces (space, tabs, end of line).
    public static string[] SplitIntoWords(string text)
    {
      if (string.IsNullOrEmpty(text))
        return new string[0];
      return text.Split(' ', '\t', '\n', '\r');
    }
    

    public by cghersi  2829  0  5  1

    Write a message onto the console for debug purpose

    public static void LogOnConsole(string message)
    {
      Console.WriteLine(message);
    }
    

    public by cghersi  2707  1  6  4

    Safely Manage Asynchronous Invoke in Winforms

    When dealing with multithreading in WinForms one of the worst issues you encounter are the management of Invoke() method on controls. Instead of spreading the code of blocks if (control.InvokeRequired) { controlInvoke(...); } else { ... } this is a little method that can elegantly solve your issues!
    private delegate object SafeInvokeCallback(Control control, Delegate method, params object[] parameters);
    public static object SafeInvoke(this Control control, Delegate method, params object[] parameters)
    {
        if (control == null)
            throw new ArgumentNullException("control");
        if (control.InvokeRequired)
        {
            log.DebugFormat("Calling with BeginInvoke: {0}", method.Method.Name);
            IAsyncResult result = null;
            try { result = control.BeginInvoke(new SafeInvokeCallback(SafeInvoke), control, method, parameters); }
            catch (InvalidOperationException) { /* This control has not been created or was already (more likely) closed. */ }
            if (result != null)
                return control.EndInvoke(result);
        }
        else
        {
            log.DebugFormat("Calling sync: {0}", method.Method.Name);
            if (!control.IsDisposed)
                return method.DynamicInvoke(parameters);
        }
        return null;
    }
    
    • Public Snippets
    • Channels Snippets