Monday, July 27, 2015

Slug generator or Make Friendly URL from a post title


  • Normally we want to generate Friendly URL or we can say Slug from our post title.
  • Just pass your string to below "GenerateSlug" function and it will return you Friendly URL.



        public string GenerateSlug(string phrase)
        {
            string str = RemoveAccent(phrase).ToLower();
            // invalid chars           
            str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
            // convert multiple spaces into one space   
            str = Regex.Replace(str, @"\s+", " ").Trim();
            // cut and trim 
            str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();
            str = Regex.Replace(str, @"\s", "-"); // hyphens   
            return str;
        }

        public string RemoveAccent(string txt)
        {
            byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
            return System.Text.Encoding.ASCII.GetString(bytes);
        }


  • You can find more detail discussion and other solutions here.

Convert Image to byte or Base64 String



  • We have to just provide input stream as "FileUpload1.PostedFile.InputStream" to below function

Image Stream to Byte :-

public static byte[] StreamToByte(Stream input)
        {
            byte[] buffer = new byte[input.Length];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }


Image Stream to Base64String :-

public static string StreamToBase64(Stream input)
        {
            byte[] buffer = new byte[input.Length];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                string temp_inBase64 = Convert.ToBase64String(ms.ToArray());
                return temp_inBase64;
            }
        }