working on it ...

Filters

Explore Public Snippets

Sort by

Found 606k snippets matching: c#

    public by MarcoDeMagistris  558985  64  7  0

    Converts Unicode string to Ansi String

    Converts Unicode string to Ansi String
    public static string ConvertUnicodeToAnsi(String s)
            {
                /// <summary>
                /// Description: Converts Unicode string to Ansi String
                ///              
                /// </summary>
                /// <exception cref="ArgumentNullException"></code></exception>
                /// <exception cref="EncoderExceptionFallback"></exception>
                /// <exception cref="DecoderExceptionFallback"></exception>
                /// <exception cref="ArgumentException"></exception>
                try
                {
                    byte[] unicodeBytes = Encoding.Unicode.GetBytes(s);
                    byte[] ansiBytes = Encoding.Convert(Encoding.Unicode, Encoding.Default, unicodeBytes);
                    return Encoding.Default.GetString(ansiBytes).ToString();
                }
                catch {
                    throw;
                }
            }

    public by cghersi  475215  5  7  0

    C#: Parse a comma separated string into a collection of numeric items

    This method can be used with any separator you need, just setting the 'separator' input
    public static List<long> ParseIntoListOfLongs(string content, char separator = ',')
    {
        List<long> ids = new List<long>();
    
        if (string.IsNullOrEmpty(content))
            return ids;
    
        string[] strIds = content.Split(separator);
        foreach (string str in strIds)
        {
            long id = -1;
            if (long.TryParse(str, out id))
            {
                if (id > 0)
                    ids.Add(id);
            }
        }
    
        return ids;
    }
    

    public by lbottaro  476235  9  6  2

    JavaScript equivalent to C# String.format

    The code below is the Javascript equivalent to C# String.Format() for replacing elements like {0}, {1}, {2} with parameters. In this case the String prototype is modified, adding the new format() method to all string instances. How to use var mystring = "Hello {0}, how are you? My name is {1}. Bye {0}!" mystring.format("Alice", "Bob") //
    // First, checks if it isn't implemented yet.
    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) { 
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
          ;
        });
      };
    }            

    public by cghersi  369759  4  6  3

    How to prettify a number with thousands or millions

    Prepares a pretty version of the given number, with the ability to match the right plural/singular form for English text
    public static string PaintNumber(int number, string followingText = "", bool numberInBold = false)
    {
      string content = String.Format("{0:N0}", number);
      if (number >= 10000)
      {
        double numberInThousands = number / 1000.0;
        if (numberInThousands < 100)
          content = String.Format("{0:N0}k", numberInThousands);
        else
          content = String.Format("{0:0.#}M", numberInThousands / 1000.0);
      }
      if (number >= 1000000)
      {
        double numberInMillions = number / 1000000.0;
        if (numberInMillions < 100)
          content = String.Format("{0:N0}M", numberInMillions);
        else
          content = String.Format("{0:0.#}B", numberInMillions / 1000.0);
      }
    
      if (numberInBold)
        content = "<b>" + content + "</b>";
    
      if (!string.IsNullOrEmpty(followingText))
        content += " " + followingText + (number != 1 ? "s" : "");
    
      return content;
    }
    

    public by lbottaro  332811  2  4  0

    C# enum iteration

    This c# code allows to iterate through all element of an enum
    public enum Suit
    {
            Spades,
            Hearts,
            Clubs,
            Diamonds
    }
    
    foreach (Suit suit in Enum.GetValues(typeof(Suit)))
    {
       Console.WriteLine(suit);
    }

    public by clsw  350051  0  6  1

    Image upload to API, return direct link. (IMGUR)

    Imgur, one of the best image hosts in the world, has a fantastic API, this is a VERY simple and usable implementation of it, just pass an image to the function and it will return the direct link to yout image, heavily commented and easy to use.
    public string UploadImage(Image img)
            {
                //get a dev key from api.imgur.com, anonymous usage (no user auth) only.
                string devkey = "YOUR_CLIENT_ID (e.g. abcde1f234567g8)";
    
                //define the WebClient we'll use to communicate with Imgur.
                WebClient w = new WebClient();
                
                //adds the Header to authorize this application with Imgur, must include a valid CLIENT_ID from 'devkey' above.
                w.Headers.Add("Authorization", "Client-ID " + devkey);
    
                System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection();
                try
                {
                    //Converts the image to a byte array so it can be turned into a string for upload.
                    using (MemoryStream stream = new MemoryStream())
                    {
                        img.Save(stream, ImageFormat.Png);
                        Keys.Add("image", Convert.ToBase64String(stream.ToArray()));
                    }
                    
                    //uploads the string-formatted-image and waits for the response.
                    byte[] responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys);
                    dynamic result = Encoding.ASCII.GetString(responseArray);
    
                    //formats the (long and technical) result into just the direct image link.
                    Regex reg = new Regex("link\":\"(.*?)\""); Match match = reg.Match(result);
                    string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/");
    
                    //returns the online address of the image.
                    return url;
                }
                catch (Exception s) { MessageBox.Show(s.Message); return "err"; }
            }

    public by zonaro  323292  2  7  0

    Crop Image on C#

    Simple snippet to Crop Image from up-left point
    public static Bitmap CropImage(this Bitmap source, Rectangle section)
           {
               Bitmap bmp = new Bitmap(section.Width, section.Height);
               Graphics g = Graphics.FromImage(bmp); 
               g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel); 
               return bmp;
           }
    

    public by cghersi  283405  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  246963  1  6  1

    Calculate the occurrences of words in Rss feed

    Creates a dictionary with keys=words and values=occurrences of that word in the given Rss (specified by the URL). The caller should specify the maximum number of items in the returning dictionary and, optionally, the minimum length of the words that will be added to the output.
    public static Dictionary<string, int> ComputeWordsOccurrencesInRss(string url, int maxItems, int minLenOfAcceptedWords = 1)
    {
      Dictionary<string, int> occurrences = new Dictionary<string, int>();
    
      IList<RssReader.RssItem> singleRssResult = RssReader.ReadRss(url, maxItems, true);
      string[] splitted = null;
      foreach (RssReader.RssItem rss in singleRssResult)
      {
        List<string> words = new List<string>();
    
        //split title in words:
        splitted = StringHelper.SplitIntoWords(rss.Title);
        if (splitted != null)
          words.AddRange(splitted);
    
        //split summary in words:
        splitted = StringHelper.SplitIntoWords(rss.Summary);
        if (splitted != null)
          words.AddRange(splitted);
    
        //compute occurrences of words:
        for (int w = 0; w < words.Count; w++)
        {
          string word = words[w].ToLower();
          if (word.Length < minLenOfAcceptedWords)
            continue;
          if (occurrences.ContainsKey(word))
            occurrences[word]++;
          else
            occurrences.Add(word, 1);
        }
      }
    
      return occurrences;
    }
    

    public by bojan.hrnkas  225152  0  7  0

    Serializing a C# object to XML

    We use a simplified object WSCustomer, since we only want some members of Customer to get serialized.
    public string GetCustomerData(int customers_Id)
    {
        Customer customers = IoC.Resolve<ICustomerService>().GetCustomerById(customers_Id);
        WSCustomer wsCustomer = WSMapping(customers);
        StringBuilder sb = new StringBuilder();
        using (TextWriter tw = new StringWriter(sb))
        {
            XmlSerializer xmlS = new XmlSerializer(typeof(WSCustomer));
            xmlS.Serialize(tw, wsCustomer);
            string serialized = sb.ToString();
            return serialized;
        }
    }
    
    
    • Public Snippets
    • Channels Snippets