working on it ...

Filters

Explore Public Snippets

Sort by

Found 131 snippets matching: .NETFramework >= 4.0

    public by cghersi modified Jan 31, 2014  474422  4  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 zonaro modified Nov 13, 2015  322976  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 Uriahs modified Jun 29, 2015  310190  1  6  0

    Move borderless form VB.NET

    Code to move a borderless winform which is not moveable by default
    Dim drag As Boolean
       Dim mousex As Integer
       Dim mousey As Integer
       Private Sub Form1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseDown
           drag = True 'Sets the variable drag to true.
           mousex = Windows.Forms.Cursor.Position.X - Me.Left 'Sets variable mousex
           mousey = Windows.Forms.Cursor.Position.Y - Me.Top 'Sets variable mousey
       End Sub
    
       Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
           'If drag is set to true then move the form accordingly.
           If drag Then
               Me.Top = Windows.Forms.Cursor.Position.Y - mousey
               Me.Left = Windows.Forms.Cursor.Position.X - mousex
           End If
       End Sub
    
       Private Sub Form1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp
           drag = False 'Sets drag to false, so the form does not move according to the code in MouseMove
       End Sub
    

    public by cghersi modified Nov 4, 2014  283131  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 modified Nov 4, 2014  246586  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 modified Jan 22, 2013  224924  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 by zonaro modified Oct 23, 2015  205172  1  7  0

    Image toBase64 String

    Extension method to convert a System.Drawing.Image to Base64 String
    public static string toBase64(this System.Drawing.Image OriginalImage)
          {
              using (MemoryStream ms = new MemoryStream())
              {
                  OriginalImage.Save(ms, OriginalImage.RawFormat);
                  byte[] imageBytes = ms.ToArray();
                  return Convert.ToBase64String(imageBytes);
              }
          }
    

    public by zonaro modified Oct 28, 2015  196889  0  8  0

    Sum (Excel port for VB.NET)

    Like in Excel, this method sum the numbers of a ParamArray
    Function Sum(ByVal ParamArray Nums As Decimal()) As Decimal
            Dim s = 0
            For Each i As Decimal In Nums
                s += i
            Next
            Return s
        End Function            

    public by cghersi @ MailUp API DEV modified Nov 19, 2014  112656  9  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by lekodeveloperweb modified Mar 23, 2015  98593  0  6  0

    NUnit Test Method

    [Test]
    public void Metodo_Cenario_Resultado()
    {
    
    }
    • Public Snippets
    • Channels Snippets