protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                using (var ctx = new EF.RepositoryContext("LogoDB"))
                {
                    var channel = GetChannel(ctx);
                    if (channel != null)
                    {
                        channel.Website     = tbxChannelWebsite.Text.Trim();
                        channel.Description = tbxChannelDescription.Text.Trim();

                        if (listNewAliases.Items.Count == 0)
                        {
                            throw new Exception("A Channel must have at least one Alias!");
                        }

                        // delete aliases that are no longer there
                        if (channel.Aliases != null)
                        {
                            foreach (var alias in channel.Aliases.ToList())
                            {
                                if (listNewAliases.Items.FindByText(alias.Name) == null)
                                {
                                    ctx.Aliases.Remove(alias);
                                }
                            }
                        }

                        // add new aliases
                        foreach (ListItem item in listNewAliases.Items)
                        {
                            string newAliasTrimmed = item.Text.Trim();
                            if (!string.IsNullOrEmpty(newAliasTrimmed))
                            {
                                if (!channel.Aliases.Any(a => a.Name == newAliasTrimmed))
                                {
                                    var alias = ctx.Aliases.Create();
                                    alias.Id      = Guid.NewGuid();
                                    alias.Name    = newAliasTrimmed;
                                    alias.Created = DateTime.Now;
                                    alias.Channel = channel;
                                    channel.Aliases.Add(alias);
                                }
                            }
                        }

                        // new logo
                        if (uploadLogoFile.HasFile)
                        {
                            var repo = ctx.Repositorys.FirstOrDefault();

                            var membership = System.Web.Security.Membership.GetUser();
                            var user       = membership != null?ctx.Users.FirstOrDefault(u => u.Id == (Guid)membership.ProviderUserKey) : null;

                            // check that file is PNG
                            byte[] logoData = uploadLogoFile.FileBytes;
                            using (MemoryStream ms = new MemoryStream(logoData))
                            {
                                using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true, true))
                                {
                                    if (image.RawFormat.Guid != System.Drawing.Imaging.ImageFormat.Png.Guid)
                                    {
                                        throw new Exception("The supplied Logo file is not a valid PNG image!");
                                    }

                                    if (string.IsNullOrEmpty(tbxLogoName.Text.Trim()))
                                    {
                                        throw new Exception("Please give the new Logo an unique name!");
                                    }

                                    // delete old logo
                                    var oldLogo = channel.Logos.First(l => l.Suggestion == null);
                                    ctx.Logos.Remove(oldLogo);
                                    File.Delete(Thumbnailer.GetThumbFilePath(oldLogo.Id));
                                    File.Delete(Path.Combine(Server.MapPath("~/Logos"), oldLogo.Id + ".png"));

                                    // create new logo
                                    var logo = ctx.Logos.Create();
                                    logo.Id           = Guid.NewGuid();
                                    logo.Name         = tbxLogoName.Text.Trim();
                                    logo.Origin       = tbxLogoOrigin.Text.Trim();
                                    logo.LastModified = DateTime.Now;
                                    logo.Width        = image.Width;
                                    logo.Height       = image.Height;
                                    logo.SizeInBytes  = logoData.Length;
                                    repo.Logos.Add(logo);
                                    logo.Creator = user;
                                    logo.Channels.Add(channel);
                                    File.WriteAllBytes(Path.Combine(Server.MapPath("~/Logos"), logo.Id + ".png"), logoData);
                                    Thumbnailer.CreateLogoThumb(image, logo.Id);

                                    imgChannelLogo.ImageUrl    = Thumbnailer.GetThumbFileUrl(logo.Id);
                                    imgChannelLogo.NavigateUrl = "/Logos/" + logo.Id + ".png";
                                }
                            }
                        }

                        ctx.ChangeTracker.DetectChanges();
                        ctx.SaveChanges();
                    }
                }

                lblReturnMessage.Visible   = true;
                lblReturnMessage.ForeColor = System.Drawing.Color.Green;
                lblReturnMessage.Text      = "Channel successfully saved!";
            }
            catch (Exception ex)
            {
                lblReturnMessage.Visible   = true;
                lblReturnMessage.ForeColor = System.Drawing.Color.Red;
                lblReturnMessage.Text      = ex.Message;
            }
        }
Exemplo n.º 2
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                using (var ctx = new EF.RepositoryContext("LogoDB"))
                {
                    var repo = ctx.Repositorys.FirstOrDefault();

                    var suggestion = ctx.Suggestions.Create();
                    suggestion.Id           = Guid.NewGuid();
                    suggestion.Created      = DateTime.Now;
                    suggestion.LastModified = DateTime.Now;

                    var membership = System.Web.Security.Membership.GetUser();
                    if (membership != null)
                    {
                        suggestion.User = ctx.Users.FirstOrDefault(u => u.Id == (Guid)membership.ProviderUserKey);
                    }

                    if (!string.IsNullOrEmpty(tbxSuggestionInfo.Text.Trim()))
                    {
                        suggestion.Messages.Add(new Message()
                        {
                            Id = Guid.NewGuid(), Created = DateTime.Now, Suggestion = suggestion, Text = tbxSuggestionInfo.Text.Trim(), User = suggestion.User
                        });
                    }
                    repo.Suggestions.Add(suggestion);

                    Channel channel = null;
                    if (TabContainer1.ActiveTab == tabPanelNewChannel)
                    {
                        string channelName = tbxChannelName.Text.Trim();
                        var    channelType = (ChannelType)byte.Parse(rblChannelType.SelectedValue);

                        if (string.IsNullOrEmpty(channelName))
                        {
                            throw new Exception("Please give the new Channel an unique name!");
                        }

                        if (ctx.Channels.Any(c => c.Name == channelName && c.Type == channelType))
                        {
                            throw new Exception(string.Format("A {0}-Channel '{1}' already exists!", channelType, channelName));
                        }

                        string channelWebsite = tbxChannelWebsite.Text.Trim();
                        if (!string.IsNullOrEmpty(channelWebsite) && !channelWebsite.Contains("://"))
                        {
                            channelWebsite = "http://" + channelWebsite;
                        }

                        channel             = ctx.Channels.Create();
                        channel.Id          = Guid.NewGuid();
                        channel.Suggestion  = suggestion;
                        channel.Name        = channelName;
                        channel.Website     = channelWebsite;
                        channel.RegionCode  = ddlChannelRegion.SelectedValue;
                        channel.Description = tbxChannelDescription.Text.Trim();
                        channel.Type        = channelType;
                        repo.Channels.Add(channel);
                    }
                    else
                    {
                        string channelName = listFoundChannels.SelectedValue;
                        if (string.IsNullOrEmpty(channelName))
                        {
                            throw new Exception("Please select an existing Channel!");
                        }
                        channel = ctx.Channels.Include("Aliases").Include("Logos").FirstOrDefault(c => c.Name == channelName);
                    }

                    foreach (ListItem newAlias in listNewAliases.Items)
                    {
                        string newAliasTrimmed = newAlias.Value.Trim();
                        if (!string.IsNullOrEmpty(newAliasTrimmed))
                        {
                            if (!channel.Aliases.Any(a => a.Name == newAliasTrimmed))
                            {
                                var alias = ctx.Aliases.Create();
                                alias.Id      = Guid.NewGuid();
                                alias.Name    = newAliasTrimmed;
                                alias.Created = DateTime.Now;
                                alias.Channel = channel;
                                channel.Aliases.Add(alias);
                                alias.Suggestion = suggestion;
                            }
                        }
                    }

                    if (channel.Aliases.Count == 0)
                    {
                        throw new Exception("A Channel must have at least one Alias!");
                    }

                    if (uploadLogoFile.HasFile)
                    {
                        // check that file is PNG
                        byte[] logoData = uploadLogoFile.FileBytes;
                        using (MemoryStream ms = new MemoryStream(logoData))
                        {
                            using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true, true))
                            {
                                if (image.RawFormat.Guid != System.Drawing.Imaging.ImageFormat.Png.Guid)
                                {
                                    throw new Exception("The supplied Logo file is not a valid PNG image!");
                                }
                                else
                                {
                                    var logo = ctx.Logos.Create();
                                    logo.Id   = Guid.NewGuid();
                                    logo.Name = tbxLogoName.Text.Trim();
                                    if (string.IsNullOrEmpty(logo.Name))
                                    {
                                        throw new Exception("Please give the new Logo an unique name!");
                                    }
                                    logo.Origin       = tbxLogoOrigin.Text.Trim();
                                    logo.LastModified = DateTime.Now;
                                    logo.Width        = image.Width;
                                    logo.Height       = image.Height;
                                    logo.SizeInBytes  = logoData.Length;
                                    repo.Logos.Add(logo);
                                    logo.Suggestion = suggestion;
                                    logo.Creator    = suggestion.User;
                                    logo.Channels.Add(channel);
                                    File.WriteAllBytes(Path.Combine(Server.MapPath("~/Logos"), logo.Id + ".png"), logoData);
                                    Thumbnailer.CreateLogoThumb(image, logo.Id);
                                }
                            }
                        }
                    }

                    ctx.ChangeTracker.DetectChanges();

                    if (channel.Logos.Count == 0)
                    {
                        throw new Exception("Please specify a logo for the new Channel!");
                    }

                    if (!suggestion.Channels.Any() && !suggestion.Aliases.Any() && !suggestion.Logos.Any())
                    {
                        throw new Exception("Please suggest at least a new logo or new alias!");
                    }

                    ctx.SaveChanges();

                    Response.Redirect(Request.Url.AbsoluteUri, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    this.Visible = false;
                }
            }
            catch (Exception ex)
            {
                lblReturnMessage.Visible = true;
                lblReturnMessage.Text    = ex.Message;
            }
        }
        Tuple <Dictionary <string, HashSet <string> >, string, EF.Logo> GetChannel(XmlElement channel, int type, EF.RepositoryContext ctx, ref List <string> errors)
        {
            try
            {
                var file = channel.SelectSingleNode("File");
                if (file != null)
                {
                    var logoFileName = file.InnerText.Trim().Replace("\t", " ");
                    var logoUrl      = (type == 0 ? tbxTVLogosBaseUrl.Text : tbxRadioLogosBaseUrl.Text) + logoFileName;
                    if (!string.IsNullOrEmpty(logoFileName))
                    {
                        byte[] logoData = null;
                        try
                        {
                            logoData = new System.Net.WebClient().DownloadData(logoUrl);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception(string.Format("Error downloading logo '{0}' : {1}", logoFileName, ex.Message));
                        }
                        using (MemoryStream ms = new MemoryStream(logoData))
                        {
                            using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true, true))
                            {
                                if (image.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid)
                                {
                                    var aliases = new Dictionary <string, HashSet <string> >();

                                    foreach (XmlElement item in channel.SelectNodes("Item"))
                                    {
                                        string name = item.GetAttribute("Name").Trim();
                                        if (!string.IsNullOrEmpty(name))
                                        {
                                            HashSet <string> providerNames = null;

                                            if (!aliases.TryGetValue(name, out providerNames))
                                            {
                                                providerNames = new HashSet <string>();
                                            }

                                            foreach (XmlElement provider in item.SelectNodes("Provider"))
                                            {
                                                if (!string.IsNullOrWhiteSpace(provider.InnerText))
                                                {
                                                    providerNames.Add(provider.InnerText.Trim());
                                                }
                                            }
                                            foreach (XmlElement satellite in item.SelectNodes("Satellite"))
                                            {
                                                if (!string.IsNullOrWhiteSpace(satellite.InnerText))
                                                {
                                                    providerNames.Add(satellite.InnerText.Trim());
                                                }
                                            }
                                            foreach (XmlElement place in item.SelectNodes("Place"))
                                            {
                                                if (!string.IsNullOrWhiteSpace(place.InnerText))
                                                {
                                                    providerNames.Add(place.InnerText.Trim());
                                                }
                                            }

                                            aliases[name] = providerNames;
                                        }
                                    }

                                    if (aliases.Count > 0)
                                    {
                                        var logo = ctx.Logos.Create();
                                        logo.Id           = Guid.NewGuid();
                                        logo.Name         = System.IO.Path.GetFileNameWithoutExtension(logoFileName);
                                        logo.Width        = image.Width;
                                        logo.Height       = image.Height;
                                        logo.SizeInBytes  = logoData.Length;
                                        logo.LastModified = DateTime.Now;
                                        logo.Origin       = logoUrl;
                                        File.WriteAllBytes(Path.Combine(Server.MapPath("~/Logos"), logo.Id + ".png"), logoData);
                                        Thumbnailer.CreateLogoThumb(image, logo.Id);
                                        return(new Tuple <Dictionary <string, HashSet <string> >, string, EF.Logo>(aliases, logoFileName, logo));
                                    }
                                    else
                                    {
                                        throw new Exception(string.Format("No aliases defined for logo '{0}'", logoFileName));
                                    }
                                }
                                else
                                {
                                    throw new Exception(string.Format("Logo '{0}' is not a valid PNG", logoFileName));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
            return(null);
        }