using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text.RegularExpressions; using System.Text; using System.Data.Sql; using System.Data.SqlClient; namespace MusicJetInstallation { public partial class FriendlyLinks : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public string MakeFriendlyLink(string oldlink, string newlink) { if (String.IsNullOrEmpty(oldlink)) { return "ERROR: Empty link!"; } if (String.IsNullOrEmpty(newlink)) { return "ERROR: Empty new link!"; } Regex r = new Regex(@".*?link=(.*?)\&.*"); Match match = r.Match(oldlink); if (match.Success) oldlink = match.Groups[1].Value; else { return "The link has incorrect format!"; } StringBuilder sb = new StringBuilder(); string pom = newlink.Replace(' ', '-').ToLower(); pom = pom.Replace('_', '-'); pom = pom.Replace("-+-", "-"); /* INFO z http://stackoverflow.com/questions/695438/safe-characters-for-friendly-url */ StringBuilder sb2 = new StringBuilder(); int i = 0; while (i < pom.Length) { if (!((pom[i] == '-') || (pom[i] >= 'a' && pom[i] <= 'z') || (pom[i] >= '0' && pom[i] <= '9'))) sb2.Append(pom[i]); i++; } if (sb2.Length > 0) { string[] s = pom.Split(sb2.ToString().ToCharArray()); i = 0; while (i < s.Length - 1) { sb.Append(s[i]); sb.Append("-"); i++; } sb.Append(s[i]); } else sb.Append(pom); pom = sb.ToString(); pom = Regex.Replace(pom, @"-+", "-"); string reslink = "http://musicjet.cz/lp/" + pom; string ConString = "Server=localhost;Database=musicjet;User ID=kubrt;Password=referent;Trusted_Connection=False;"; //string ConString = "Server=77.93.200.13;Database=musicjet;User ID=kubrt;Password=referent;Trusted_Connection=False;"; using (SqlConnection connection = new SqlConnection(ConString)) { connection.Open(); string queryString = String.Format("select * from Links where nicelink='{0}'", pom); SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader reader = command.ExecuteReader(); if (!reader.Read()) { queryString = String.Format("insert into Links (nicelink, link) values ('{0}', '{1}')", pom, HttpUtility.UrlEncode(oldlink)); command = new SqlCommand(queryString, connection); reader.Close(); command.ExecuteNonQuery(); } else { return "Duplicate nice link"; } } return reslink; } } }