Пример #1
0
        // The id parameter name should match the DataKeyNames value set on the control
        public void Categories_DeleteItem(Guid id)
        {
            QRCodeContext db = new QRCodeContext();
            QRJ.Models.Category category = db.Categories.Where(c => c.Id == id).First();

            // Remove the blob from storage
            // Gdt the storage connection string
            CloudStorageAccount storageAccount =
                CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference("videos");
            // Set permission to public
            container.SetPermissions(
            new BlobContainerPermissions
            {
                PublicAccess =
                    BlobContainerPublicAccessType.Blob
            });

            foreach(QRJ.Models.CategoryContent categoryContent in category.Contents)
            {
                try
                {
                    CloudBlockBlob deleteBlob = container.GetBlockBlobReference(categoryContent.FilePath);
                    deleteBlob.DeleteIfExists();
                }
                catch { }
            }

            db.Categories.Remove(category);
            db.SaveChanges();
        }
Пример #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Guid horoscopeQrCodeId = new Guid(Request.QueryString["id"]);
            QRJ.Models.Sign sign = GetSign(horoscopeQrCodeId);

            // Get easter date/time
            TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            DateTime today = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, easternZone).Date;

            // Check if there is a horoscope for this date
            QRCodeContext db = new QRCodeContext();
            QRJ.Models.Horoscope horoscope = db.Horoscopes.Where(h => h.Date == today).FirstOrDefault();
            // If we have the horoscope then just display it
            if (horoscope == null)
            {
                // Otherwise get it from the service
                WebRequest request = WebRequest.Create("http://horoscopeservices.co.uk/daily_delivery/xmlaccess.asp?uid=608364284&date=" + today.ToString("yyyy-MM-dd"));
                WebResponse response = request.GetResponse();
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();

                // Save the horoscope in the db
                horoscope = new Models.Horoscope { Id = Guid.NewGuid(), Date = today, Data = responseFromServer };
                db.Horoscopes.Add(horoscope);
                db.SaveChanges();
            }

            imgBackground.Src = "../../Content/themes/base/images/horoscopeBackgrounds/" + sign.ToString() + "/" + "1" + ".png";
            txtHoroscope.InnerText = horoscope.GetHoroscope(sign);
        }
Пример #3
0
 // The id parameter name should match the DataKeyNames value set on the control
 public void Products_DeleteItem(Guid id)
 {
     QRCodeContext db = new QRCodeContext();
     QRJ.Models.QRCode qrCode = db.QRCodes.Where(c => c.Id == id).First();
     qrCode.ProductName = "";
     qrCode.ActivatedBy = null;
     qrCode.ActivatedOn = null;
     qrCode.SuscribedCategories.RemoveRange(0, qrCode.SuscribedCategories.Count);
     db.SaveChanges();
 }
Пример #4
0
        protected void btnHoroscopeSet_Click(object sender, EventArgs e)
        {
            // Database management
            QRCodeContext db = new QRCodeContext();
            // Save a new set
            HoroscopeSet newSet = new HoroscopeSet();
            newSet.Id = Guid.NewGuid();
            newSet.GeneratedOn = DateTime.Now;
            HoroscopeSet lastSet = db.HoroscopeSets.OrderByDescending(s => s.SetNumber).FirstOrDefault();
            newSet.SetNumber = lastSet == null ? 1 : lastSet.SetNumber + 1;
            db.HoroscopeSets.Add(newSet);

            // Generate QR code imges
            string folderBatch = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
            System.IO.Directory.CreateDirectory(folderBatch);
            foreach(HoroscopeSign sign in db.HoroscopeSigns)
            {
                Guid qrId = Guid.NewGuid();
                string url = string.Format(Properties.Settings.Default.ViewPath, Properties.Settings.Default.DomainName, qrId.ToString());
                string shortUrl = GetShortUrl(url).Replace("http://", "");

                // Initialize the QR witer
                BarcodeWriter writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.QR_CODE
                };
                Bitmap qrCode = writer.Write(shortUrl);
                qrCode.SetResolution(1200, 1200);
                qrCode.Save(Path.Combine(folderBatch, qrId.ToString()) + ".jpg");

                // Save the item to the database
                db.HoroscopeQrCodes.Add(new HoroscopeQrCode
                {
                    Id = qrId,
                    HoroscopeSignId = sign.Id,
                    HoroscopeSetId = newSet.Id,
                    LongURL = url,
                    ShortURL = shortUrl
                });
            }

            // Save the database changes
            db.SaveChanges();

            // Zip the package
            string zipFileName = folderBatch + ".zip";
            ZipFile.CreateFromDirectory(folderBatch, zipFileName);

            //Download file
            Response.ContentType = "application/x-zip-compressed";
            Response.AppendHeader("Content-Disposition", "attachment; filename=QRCodes.zip");
            Response.TransmitFile(zipFileName);
            Response.End();
        }
Пример #5
0
        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public object Products_GetData()
        {
            Guid userId = (Guid)System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey;
            QRCodeContext db = new QRCodeContext();
            var products = db.QRCodes.Where(c => c.ActivatedBy == userId).ToList().Select(p => new
                           {
                               Id = p.Id,
                               ProductName = p.ProductName,
                               ActivatedOn = p.ActivatedOn.Value.ToLocalTime(),
                               Subscriptions = string.Join(",", p.SuscribedCategories.Select(s => s.Name).ToArray())
                           });

            return products;
        }
Пример #6
0
 // The return type can be changed to IEnumerable, however to support
 // paging and sorting, the following parameters must be added:
 //     int maximumRows
 //     int startRowIndex
 //     out int totalRowCount
 //     string sortByExpression
 public IQueryable Categories_GetData(int maximumRows, int startRowIndex, out int totalRowCount)
 {
     QRCodeContext db = new QRCodeContext();
     var categories = from c in db.Categories
                      select new
                      {
                          Id = c.Id,
                          Name = c.Name,
                          Frequency = c.Frequency == Frequency.Daily ? "Daily" : "On-Demand",
                          NumberOfContents = c.Contents.Count
                      };
     totalRowCount = categories.Count();
     return categories.OrderBy(c => c.Name).Skip(startRowIndex).Take(maximumRows);
 }
Пример #7
0
        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable Subscriptions_GetData()
        {
            Frequency frequency = (Frequency)Enum.Parse(typeof(Frequency), Frequency.SelectedValue);
            QRCodeContext db = new QRCodeContext();
            var subscriptions = from c in db.Categories
                                where c.Frequency == frequency
                                select new
                                {
                                    Id = c.Id,
                                    Name = c.Name
                                };

            return subscriptions;
        }
Пример #8
0
        // The return type can be changed to IEnumerable, however to support
        // paging and sorting, the following parameters must be added:
        //     int maximumRows
        //     int startRowIndex
        //     out int totalRowCount
        //     string sortByExpression
        public IQueryable CategoryContents_GetData(int maximumRows, int startRowIndex, out int totalRowCount)
        {
            QRCodeContext db = new QRCodeContext();
            var categoryContents = from c in db.CategoryContents
                                   where c.CategoryId == _categoryId
                                select new
                                {
                                    Id = c.Id,
                                    Name = c.Name,
                                    FilePath = c.FilePath
                                };

            totalRowCount = categoryContents.Count();
            return categoryContents.OrderBy(c => c.Name).Skip(startRowIndex).Take(maximumRows);
        }
Пример #9
0
        protected void UploadVideo_Click(object sender, EventArgs e)
        {
            // Before attempting to save the file, verify
            // that the FileUpload control contains a file.
            if (FileUpload.HasFile)
            {
                // Gdt the storage connection string
                CloudStorageAccount storageAccount =
                    CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
                // Create the blob client.
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                // Retrieve a reference to a container.
                CloudBlobContainer container = blobClient.GetContainerReference("videos");
                // Create the container if it doesn't already exist.
                container.CreateIfNotExists();
                // Set permission to public
                container.SetPermissions(
                new BlobContainerPermissions
                {
                    PublicAccess =
                        BlobContainerPublicAccessType.Blob
                });
                // Create a new file name
                string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(FileUpload.FileName).ToLower();
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);
                // Create or overwrite the blob.
                blockBlob.UploadFromStream(FileUpload.FileContent);
                blockBlob.Properties.ContentType = "video/mp4";
                blockBlob.SetProperties();

                // Save the video path for each selected QECode
                QRCodeContext db = new QRCodeContext();
                foreach (GridViewRow row in QRCodes.Rows)
                {
                    // Access the CheckBox
                    CheckBox cb = (CheckBox)row.FindControl("ProductSelector");
                    if (cb.Checked)
                    {
                        Guid rowId = new Guid(QRCodes.DataKeys[row.RowIndex]["Id"].ToString());
                        db.QRCodes.Where(q => q.Id == rowId).First().FilePath = fileName;
                    }
                }

                // Save the updates in the db
                db.SaveChanges();
            }
        }
Пример #10
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     // Get the QR Record from the DB
     string activationCode = ActivationCode.Text;
     QRCodeContext db = new QRCodeContext();
     QRCode qrCode = db.QRCodes.Where(q => q.ActivationCode == activationCode).FirstOrDefault();
     if (qrCode == null)
     {
         //Invaid activation code (not found)
         ErrorMessage.Text = "The activation code is invalid.";
         errorsDiv.Visible = true;
     }
     else if (qrCode.ActivatedOn != null)
     {
         // Product has already been activated
         ErrorMessage.Text = "The activation code entered belongs to a product that has already been activated.";
         errorsDiv.Visible = true;
     }
     else
     {
         // Check that the name is unique for the user
         Guid userId = (Guid)System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey;
         string productName = ProductName.Text;
         if (db.QRCodes.Where(q => q.ActivatedBy == userId && q.ProductName == productName).FirstOrDefault() != null)
         {
             // The product name is in use
             ErrorMessage.Text = "Your already have an activated product with that product name. Please enter a different product name.";
             errorsDiv.Visible = true;
         }
         else
         {
             // Activate the product
             qrCode.ActivatedBy = userId;
             qrCode.ActivatedOn = DateTime.Now.ToUniversalTime();
             qrCode.ProductName = ProductName.Text;
             db.SaveChanges();
             Response.Redirect("~/MemberPages/Home.aspx");
         }
     }
 }
Пример #11
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     QRCodeContext db = new QRCodeContext();
     // Check that the name is unique
     string name = Name.Text;
     if (db.Categories.Where(c => c.Name == name && c.Id != _categoryId).FirstOrDefault() != null)
     {
         // The name is in use
         ErrorMessage.Text = "Your already have a category with that name. Please enter a different name.";
         errorsDiv.Visible = true;
     }
     else
     {
         if (_categoryId == Guid.Empty)
         {
             _categoryId = Guid.NewGuid();
             // Create the new category
             // Save the item to the database
             db.Categories.Add(new QRJ.Models.Category
             {
                 Id = _categoryId,
                 Name = name,
                 Frequency = (Frequency)Enum.Parse(typeof(Frequency), Frequency.SelectedValue)
             });
             db.SaveChanges();
             Response.Redirect("Category?id=" + _categoryId);
         }
         else
         {
             QRJ.Models.Category category = db.Categories.Where(c => c.Id == _categoryId).FirstOrDefault();
             category.Name = Name.Text;
             category.Frequency = (Frequency)Enum.Parse(typeof(Frequency), Frequency.SelectedValue);
             db.SaveChanges();
             Response.Redirect("ManageContent");
         }
     }
 }
Пример #12
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     QRCodeContext db = new QRCodeContext();
     // Check that the name is unique for the user
     Guid userId = (Guid)System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey;
     string productName = Name.Text;
     if (db.QRCodes.Where(q => q.ActivatedBy == userId && q.Id != _productId && q.ProductName == productName).FirstOrDefault() != null)
     {
         // The name is in use
         ErrorMessage.Text = "Your already have a product with that name. Please enter a different name.";
         errorsDiv.Visible = true;
     }
     else
     {
         QRJ.Models.QRCode product = db.QRCodes.Where(c => c.Id == _productId).FirstOrDefault();
         product.ProductName = Name.Text;
         product.SuscribedCategories.RemoveRange(0, product.SuscribedCategories.Count);
         if (product.ActivatedBy == null)
         {
             product.ActivatedBy = userId;
             product.ActivatedOn = DateTime.Now.ToUniversalTime();
         }
         foreach (GridViewRow row in Subscriptions.Rows)
         {
             // Access the CheckBox
             CheckBox cb = (CheckBox)row.FindControl("SubscriptionSelector");
             if (cb.Checked)
             {
                 Guid rowId = new Guid(Subscriptions.DataKeys[row.RowIndex]["Id"].ToString());
                 QRJ.Models.Category category = db.Categories.Where(c => c.Id == rowId).FirstOrDefault();
                 product.SuscribedCategories.Add(category);
             }
         }
         db.SaveChanges();
         Response.Redirect("Home");
     }
 }
Пример #13
0
 protected void btnSubmit_Click(object sender, EventArgs e)
 {
     QRCodeContext db = new QRCodeContext();
     // Check that the name is unique
     string name = Name.Text;
     if (db.CategoryContents.Where(c => c.Name == name && c.CategoryId == _categoryId && c.Id != _categoryContentId).FirstOrDefault() != null)
     {
         // The name is in use
         ErrorMessage.Text = "Your already have a video with that name in this category. Please enter a different name.";
         errorsDiv.Visible = true;
     }
     else
     {
         if (_categoryContentId == Guid.Empty)
         {
             Guid categoryContentId = Guid.NewGuid();
             // Create the new category content
             // Save the item to the database
             db.CategoryContents.Add(new QRJ.Models.CategoryContent
             {
                 Id = categoryContentId,
                 CategoryId = _categoryId,
                 Name = name
             });
             db.SaveChanges();
             Response.Redirect("CategoryContent?categoryId=" + _categoryId.ToString() + "&id=" + categoryContentId);
         }
         else
         {
             QRJ.Models.CategoryContent categoryContent = db.CategoryContents.Where(c => c.Id == _categoryContentId).FirstOrDefault();
             categoryContent.Name = Name.Text;
             db.SaveChanges();
             Response.Redirect("Category?id=" + _categoryId.ToString());
         }
     }
 }
Пример #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Set the link to the home page
            string url = string.Format("{0}{1}", "http://", Properties.Settings.Default.DomainName);
            homePage.HRef = url;
            homePage.InnerText = Properties.Settings.Default.DomainName;
            // Get the qr code id from the query string
            Guid qrCodeId;
            bool validGuid = Guid.TryParse(Request.QueryString["id"], out qrCodeId);
            // If the id is not a valid Guid then alert the user
            if (!validGuid)
            {
                Response.Redirect("~/NotFound");
            }

            // Get the QR Record from the DB
            QRCodeContext db = new QRCodeContext();
            QRCode qrCode = db.QRCodes.Where(q => q.Id == qrCodeId).FirstOrDefault();
            // If the qr code is not found then present user with an error message
            if (qrCode == null)
            {
                Response.Redirect("~/NotFound");
            }
            // If the code is not active or categories are not configured then the user must register/login
            else if (qrCode.ActivatedBy == null || qrCode.SuscribedCategories.Count == 0)
            {
                Session["qrCodeId"] = qrCode.Id;
                Response.Redirect("~/Account/Login");
            }
            // If no videos are found for any category then present the user with an error message
            else if (qrCode.SuscribedCategories.Sum(s => s.Contents.Count) == 0)
            {
                Response.Redirect("~/ContentNotFound");
            }
            // If the code is valid and activated and has categories then determine which video to show
            else
            {
                int indexNextCategory = 0;
                // Find the last category seen
                QRCodeViewedCategoryContent lastCategoryContentSeen = qrCode.ViewedCategoryContents.OrderByDescending(v => v.LastViewedOn).FirstOrDefault();
                List<Category> sortedSubscriptions = qrCode.SuscribedCategories.OrderBy(s => s.Name).ToList();
                if (lastCategoryContentSeen != null)
                {
                    // Move to the next category
                    indexNextCategory = sortedSubscriptions.IndexOf(lastCategoryContentSeen.CategoryContent.Category) + 1;
                    if (indexNextCategory == qrCode.SuscribedCategories.Count)
                        indexNextCategory = 0;
                }

                Category categoryToWatch = sortedSubscriptions[indexNextCategory];
                CategoryContent contentToWatch = null;
                // Special case for daily videos
                if (categoryToWatch.Frequency == Frequency.Daily)
                {
                    // For daily subscriptions, see if there is a video that has already been watched today
                    QRCodeViewedCategoryContent lastWatched = qrCode.ViewedCategoryContents.Where(v => v.CategoryContent.CategoryId == categoryToWatch.Id).OrderByDescending(v => v.LastViewedOn).FirstOrDefault();
                    // If there was a video watched today then display the same one
                    if (lastWatched != null && lastWatched.ExpiresOn > DateTime.Now)
                    {
                        contentToWatch = lastWatched.CategoryContent;
                        lastWatched.LastViewedOn = DateTime.Now;
                    }
                }

                // If not daily or if daily video expired then find next video to show
                if (contentToWatch == null)
                {
                    // Find a video in that category that has not been seen before
                    foreach (CategoryContent categoryContent in categoryToWatch.Contents)
                    {
                        if (qrCode.ViewedCategoryContents.Where(v => v.CategoryContentId == categoryContent.Id).FirstOrDefault() == null)
                        {
                            contentToWatch = categoryContent;
                            qrCode.ViewedCategoryContents.Add(
                                new QRCodeViewedCategoryContent { CategoryContentId = categoryContent.Id,
                                    QrCodeId = qrCode.Id, LastViewedOn = DateTime.Now, ExpiresOn = DateTime.Now.AddDays(1) });
                            break;
                        }
                    }

                    // If all the videos in the category have been watched we just show the oldest one
                    if (contentToWatch == null)
                    {
                        QRCodeViewedCategoryContent watched = qrCode.ViewedCategoryContents.Where(v => v.CategoryContent.CategoryId == categoryToWatch.Id).OrderBy(v => v.LastViewedOn).FirstOrDefault();
                        // Update the watched date and expiration date
                        watched.LastViewedOn = DateTime.Now;
                        watched.ExpiresOn = DateTime.Now.AddDays(1);
                        contentToWatch = watched.CategoryContent;
                    }
                }

                // Update the viewed category contents
                db.SaveChanges();

                // Show the video
                Response.Redirect("~/Watch?filePath=" + contentToWatch.FilePath);
            }
        }
Пример #15
0
        protected void FileUpload_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            // Gdt the storage connection string
            CloudStorageAccount storageAccount =
                CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference("videos");
            // Set permission to public
            container.SetPermissions(
            new BlobContainerPermissions
            {
                PublicAccess =
                    BlobContainerPublicAccessType.Blob
            });

            // Rename the blob
            //grab the existing blob
            CloudBlockBlob oldBlockBlob = container.GetBlockBlobReference(e.FileName);
            // Create a new file name
            string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(e.FileName).ToLower();
            CloudBlockBlob newBlockBlob = container.GetBlockBlobReference(fileName);
            //create a new blob
            newBlockBlob.StartCopyFromBlob(oldBlockBlob);
            //delete the old
            oldBlockBlob.Delete();

            // Set the blob properties
            newBlockBlob.Properties.ContentType = "video/mp4";
            newBlockBlob.SetProperties();

            QRCodeContext db = new QRCodeContext();
            Guid categoryId = (Guid)Session["categoryId"];
            Guid categoryContentId = (Guid)Session["categoryContentId"];
            QRJ.Models.CategoryContent categoryContent = db.CategoryContents.Where(c => c.Id == categoryContentId).FirstOrDefault();
            // Delete old video if it exists
            if (!string.IsNullOrEmpty(categoryContent.FilePath))
            {
                CloudBlockBlob deleteBlob = container.GetBlockBlobReference(categoryContent.FilePath);
                deleteBlob.DeleteIfExists();
            }
            categoryContent.FilePath = fileName;
            db.SaveChanges();
        }
Пример #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!FileUpload.IsInFileUploadPostBack)
            {
                _categoryId = new Guid(Request.QueryString["categoryId"]);
                Session["categoryId"] = _categoryId;

                if (Request.QueryString["id"] != null)
                {
                    _categoryContentId = new Guid(Request.QueryString["id"]);
                    Session["categoryContentId"] = _categoryContentId;
                }

                if (!IsPostBack)
                {
                    QRCodeContext db = new QRCodeContext();
                    btnCancel.OnClientClick = "window.location.href='Category?id=" + _categoryId.ToString() + "'; return false;";
                    divVideo.Visible = _categoryContentId != Guid.Empty;
                    divUploader.Visible = _categoryContentId != Guid.Empty;

                    if (_categoryContentId != Guid.Empty)
                    {
                        QRJ.Models.CategoryContent categoryContent = db.CategoryContents.Where(c => c.Id == _categoryContentId).FirstOrDefault();

                        Name.Text = categoryContent.Name;
                        divVideo.Visible = !string.IsNullOrEmpty(categoryContent.FilePath);

                        if (!string.IsNullOrEmpty(categoryContent.FilePath))
                        {
                            // Retrieve storage account from connection string.
                            CloudStorageAccount storageAccount =
                                CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);

                            // Create the blob client.
                            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                            // Retrieve reference to a previously created container.
                            CloudBlobContainer container = blobClient.GetContainerReference("videos");

                            // Retrieve reference to the video
                            CloudBlockBlob blockBlob = container.GetBlockBlobReference(categoryContent.FilePath);

                            // Set the video source
                            videoSource.Src = blockBlob.Uri.ToString();
                        }
                    }
                }
            }
        }
Пример #17
0
 private int GetSet(Guid horoscopeQrCodeId)
 {
     QRCodeContext db = new QRCodeContext();
     HoroscopeQrCode horoscopeQrCode = db.HoroscopeQrCodes.Where(h => h.Id == horoscopeQrCodeId).FirstOrDefault();
     return db.HoroscopeSets.Where(s => s.Id == horoscopeQrCode.HoroscopeSetId).FirstOrDefault().SetNumber;
 }
Пример #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Insure that the __doPostBack() JavaScript method is created...
            ClientScript.GetPostBackEventReference(this, string.Empty);

            if (this.IsPostBack)
            {
                string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
                string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];

                // Get eastern date/time
                TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
                DateTime clientDateTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, easternZone).Date;

                if (eventTarget == "TimezoneOffsetPostBack")
                {
                    string timezoneOffset = eventArgument;
                    // get client date time
                    clientDateTime = DateTime.UtcNow.AddMinutes(-int.Parse(timezoneOffset) * 60);
                }

                Guid horoscopeQrCodeId = new Guid(Request.QueryString["id"]);
                QRJ.Models.Sign sign = GetSign(horoscopeQrCodeId);

                // Check if there is a horoscope for this date
                QRCodeContext db = new QRCodeContext();
                QRJ.Models.Horoscope horoscope = db.Horoscopes.Where(h => h.Date.Year == clientDateTime.Year &&
                    h.Date.Month == clientDateTime.Month && h.Date.Day == clientDateTime.Day).FirstOrDefault();
                // If we have the horoscope then just display it
                if (horoscope == null)
                {
                    // Otherwise get it from the service
                    WebRequest request = WebRequest.Create("http://horoscopeservices.co.uk/daily_delivery/xmlaccess.asp?uid=608364284&date=" + clientDateTime.ToString("yyyy-MM-dd"));
                    WebResponse response = request.GetResponse();
                    // Get the stream containing content returned by the server.
                    Stream dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();

                    // Save the horoscope in the db
                    horoscope = new Models.Horoscope { Id = Guid.NewGuid(), Date = clientDateTime, Data = responseFromServer };
                    db.Horoscopes.Add(horoscope);
                    db.SaveChanges();
                }

                // Choose between the 12 background images
                int imageIndex = (clientDateTime.Day % 12) + 1;

                imgBackground.Src = "../../Content/themes/base/images/horoscopeBackgrounds/" + sign.ToString() + "/" + imageIndex + ".png";
                txtHoroscope.InnerHtml = string.Format("{0}:<br /><br />{1}", clientDateTime.ToString("D"), horoscope.GetHoroscope(sign));
                // Show the astrobanz link only for Set 1
                lnkAstrobanz.Visible = GetSet(horoscopeQrCodeId) == 1;
            }
            else
            {
                System.Text.StringBuilder javaScript = new System.Text.StringBuilder();

                javaScript.Append("var currentDate = new Date();");
                javaScript.Append("var timezoneOffset = currentDate.getTimezoneOffset() / 60;");
                javaScript.Append("__doPostBack('TimezoneOffsetPostBack', timezoneOffset);");;

                System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "TimezoneOffsetScript", javaScript.ToString(), true);
            }
        }
Пример #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            _productId = new Guid(Request.QueryString["id"]);

            if (!IsPostBack)
            {
                QRCodeContext db = new QRCodeContext();
                QRJ.Models.QRCode product = db.QRCodes.Where(c => c.Id == _productId).FirstOrDefault();

                Name.Text = product.ProductName;
                if (product.SuscribedCategories.Count > 0)
                    Frequency.SelectedValue = product.SuscribedCategories[0].Frequency.ToString();
            }
        }
Пример #20
0
        protected void Subscriptions_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {
                QRCodeContext db = new QRCodeContext();
                QRJ.Models.QRCode product = db.QRCodes.Where(c => c.Id == _productId).FirstOrDefault();
                Guid rowId = new Guid(Subscriptions.DataKeys[e.Row.RowIndex]["Id"].ToString());

                CheckBox cb = (CheckBox)e.Row.FindControl("SubscriptionSelector");
                cb.Checked = product.SuscribedCategories.Exists(s => s.Id == rowId);
            }
        }
Пример #21
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Get the user input
            int numberToGenerate = int.Parse(Number.Text);
            string urlFormat = Format.SelectedValue;
            // Database management
            QRCodeContext db = new QRCodeContext();
            // Get the generator user Id
            Guid userId = (Guid)System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey;

            if (urlFormat == "QRCode")
            {
                string shortUrls = "";
                string longUrls = "";
                // Generate QR code imges
                string folderBatch = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
                System.IO.Directory.CreateDirectory(folderBatch);
                for (int i = 0; i < numberToGenerate; i++)
                {
                    Guid qrId = Guid.NewGuid();
                    string url = string.Format(Properties.Settings.Default.ViewPath, Properties.Settings.Default.DomainName, qrId.ToString());
                    string shortUrl = GetShortUrl(url).Replace("http://", "");

                    shortUrls += shortUrl + " ";
                    longUrls += url + " ";
                    // Initialize the QR witer
                    BarcodeWriter writer = new BarcodeWriter
                    {
                        Format = BarcodeFormat.QR_CODE
                    };
                    Bitmap qrCode = writer.Write(shortUrl);
                    qrCode.SetResolution(1200, 1200);
                    qrCode.Save(Path.Combine(folderBatch, qrId.ToString()) + ".jpg");

                    // Save the item to the database
                    db.QRCodes.Add(new QRCode
                    {
                        Id = qrId,
                        ActivationCode = GenerateActivationCode(),
                        GeneratedBy = userId,
                        GeneratedOn = DateTime.Now,
                        UrlType = UrlType.QrCode
                    });
                }

                // Save the database changes
                db.SaveChanges();

                // Zip the package
                string zipFileName = folderBatch + ".zip";
                ZipFile.CreateFromDirectory(folderBatch, zipFileName);

                //Download file
                Response.ContentType = "application/x-zip-compressed";
                Response.AppendHeader("Content-Disposition", "attachment; filename=QRCodes.zip");
                Response.TransmitFile(zipFileName);
                Response.End();
            }
            else
            {
                using (ExcelPackage pck = new ExcelPackage())
                {
                    //Create the worksheet
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("URLs");

                    for (int i = 1; i <= numberToGenerate; i++)
                    {
                        Guid qrId = Guid.NewGuid();
                        string url = string.Format(Properties.Settings.Default.ViewPath, Properties.Settings.Default.DomainName, qrId.ToString());
                        string shortUrl = GetShortUrl(url);
                        ws.Cells[i, 1].Value = shortUrl;
                        // Save the item to the database
                        db.QRCodes.Add(new QRCode
                        {
                            Id = qrId,
                            ActivationCode = GenerateActivationCode(),
                            GeneratedBy = userId,
                            GeneratedOn = DateTime.Now,
                            UrlType = UrlType.Text
                        });
                    }

                    // Save the database changes
                    db.SaveChanges();

                    //Download file
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=URLs.xlsx");
                    Response.BinaryWrite(pck.GetAsByteArray());
                    Response.End();
                }
            }
        }
Пример #22
0
 // The return type can be changed to IEnumerable, however to support
 // paging and sorting, the following parameters must be added:
 //     int maximumRows
 //     int startRowIndex
 //     out int totalRowCount
 //     string sortByExpression
 public IQueryable QRCodes_GetData()
 {
     Guid userId = (Guid)System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey;
     QRCodeContext db = new QRCodeContext();
     return db.QRCodes.Where(q => q.ActivatedBy == userId).OrderBy(q => q.ProductName);
 }
Пример #23
0
 private QRJ.Models.Sign GetSign(Guid horoscopeQrCodeId)
 {
     QRCodeContext db = new QRCodeContext();
     HoroscopeQrCode horoscopeQrCode = db.HoroscopeQrCodes.Where(h => h.Id == horoscopeQrCodeId).FirstOrDefault();
     return db.HoroscopeSigns.Where(s => s.Id == horoscopeQrCode.HoroscopeSignId).FirstOrDefault().Sign;
 }
Пример #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["id"] != null)
                _categoryId = new Guid(Request.QueryString["id"]);

            if (!IsPostBack)
            {
                if (_categoryId != Guid.Empty)
                {
                    QRCodeContext db = new QRCodeContext();
                    QRJ.Models.Category category = db.Categories.Where(c => c.Id == _categoryId).FirstOrDefault();

                    Name.Text = category.Name;
                    Frequency.SelectedValue = category.Frequency.ToString();
                }
                categoryContentsDiv.Visible = _categoryId != Guid.Empty;
                btnContent.OnClientClick = "window.location.href='CategoryContent?categoryId=" + _categoryId.ToString() + "'; return false;";
            }
        }