Example #1
0
        static void Main(string[] args)
        {
            // This application creates a number of envelopes for the surface of the globe
            // The number of envelopes depends upon your delta for lat and long

            // Map sheets
            var mapSheets = new List<MapSheet>();

            double latitude = -90;
            double longitude = -180;

            // The amount of change per map sheet
            double deltaLat = 0.08;
            double deltaLong = 0.08;

            // Calculate how many maps we will need to make
            // 360 is the -180 to +180 long
            var iterationsLong = 360 / deltaLong;

            // Fill our maps
            for (int iLong = 0; iLong < iterationsLong; iLong++)
            {
                // 180 is the -90 to +90 lat
                var iterationsLat = 180 / deltaLat;

                // Populate our envelopes for each latitude in our iteration
                for (int iLat = 0; iLat < iterationsLat; iLat++)
                {
                    var mapSheet = new MapSheet()
                    {
                        Name = $"{iLat}",
                        AMGZone = "56",
                        Envelope = new Envelope(latitude, longitude, (latitude + deltaLat), (longitude + deltaLong)),
                        Number = iLat,
                        Scale = "1:25,000"
                    };
                    mapSheets.Add(mapSheet);

                    // Increment our Lat
                    latitude += deltaLat;
                }

                // Increment our long
                longitude += deltaLong;

                // Reset our lat
                latitude = -90;
            }

            // Query by coordinate
            var dateStart = DateTime.UtcNow;
            var map = mapSheets.FirstOrDefault(a => a.Envelope.Contains(new Coordinate(0.5, 0.5)));
            var dateEnd = DateTime.UtcNow;

            var elapsed = dateEnd - dateStart;

            Console.WriteLine($"{elapsed} to find one envelope in {mapSheets.Count} envelopes ({map.Name})");
            Console.ReadKey();
        }
        public RoleAuthorization GetTopAuthorization(List<RoleAuthorization> list, RoleAuthorization info)
        {
            var parent = list.FirstOrDefault(t => t.FunctionId == info.ParentId);
            if (parent == null)
                return null;
            if (parent.Level == 1)
                return parent;

            return GetTopAuthorization(list, parent);
        }
        public Invoice FirstInvoice()
        {
            MyOrders = new List<Order>();
            var client1Orders = new FakeClient1Order().MyOrders;
            foreach (var order in client1Orders)
            {
                MyOrders.Add(order);
            }

            var firstOrder = MyOrders.FirstOrDefault();
            if (firstOrder == null) return null;
            var firstOrderCharge = new OrderCharge().Calculate(firstOrder);

            //Add it is is a subscriptions

            var firstOrderInvoice = new Invoice
            {

                InvoiceId = 1,

                OrderId = firstOrder.OrderId,
                ClientId = firstOrder.ClientId,
                OrderDate = firstOrder.OrderDate,
                DeliveryDate = firstOrder.DeliveryDate,
                CurrencyId = firstOrder.CurrencyId,

                CookerId = firstOrderCharge.CookerId,
                OrderTypeValue = firstOrderCharge.OrderTypeValue,
                PaymentMethodValue = firstOrderCharge.PaymentMethodValue,

                PromotionTitle = firstOrderCharge.PromotionTitle,
                PromotionPrice = firstOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstOrderCharge.PromotionCurrencyId,

                CouponTitle = firstOrderCharge.CouponTitle,
                CouponPrice = firstOrderCharge.CouponPrice,
                CouponCurrencyId = firstOrderCharge.CouponCurrencyId,

                PlanTitle = firstOrderCharge.PlanTitle,
                SalesTax = firstOrderCharge.SalesTaxes,
                DeliveryFees = firstOrderCharge.DeliveryFee,
                SubTotal = firstOrderCharge.Subtotal,
                Total = firstOrderCharge.TotalCharges,

                OrderModelTypeId = (int)Util.OrderModelType.Values.Transaction,
                CookerSubscriptionId = null,
                ServingPriceId = null,
                PlanId = null

            };
            return firstOrderInvoice;
        }
        public override bool Match(GuideEnricherProgram enrichedGuideProgram, List<TvdbEpisode> episodes)
        {
            var episodeNumber = enrichedGuideProgram.GetValidEpisodeNumber();

            this.MatchAttempts++;

            var matchedEpisode = episodes.FirstOrDefault(x => x.SeasonNumber == episodeNumber / 100 && x.EpisodeNumber == episodeNumber % 100);
            if (matchedEpisode != null)
            {
                return this.Matched(enrichedGuideProgram, matchedEpisode);
            }
            
            return this.Unmatched(enrichedGuideProgram);
        }
        public override bool Match(GuideEnricherProgram guideProgram, List<TvdbEpisode> episodes)
        {
            if (guideProgram == null) throw new ArgumentNullException("enrichedGuideProgram");
            if (IsStringPropertyNull(guideProgram, guideProgram.Description, "Description")) return false;
            //
            var description = guideProgram.Description.ToLower();
            this.MatchAttempts++;
            var matchedEpisode = episodes.FirstOrDefault(x => !string.IsNullOrEmpty(x.EpisodeName) && new Regex(string.Concat("^", x.EpisodeName, "\\W"), RegexOptions.IgnoreCase).IsMatch(description));
            if (matchedEpisode != null)
            {
                return this.Matched(guideProgram, matchedEpisode);
            }

            return false;
        }
        public override bool Match(GuideEnricherProgram guideProgram, List<TvdbEpisode> episodes)
        {
            if (guideProgram == null) throw new ArgumentNullException("enrichedGuideProgram");
            if (IsStringPropertyNull(guideProgram, guideProgram.Description, "Description")) return false;
            //
            var match = quotedSentence.Match(guideProgram.Description);
            if (match == null || string.IsNullOrEmpty(match.Value))
                return false;

            this.MatchAttempts++;
            var matchedEpisode = episodes.FirstOrDefault(x => x.EpisodeName == match.Value);
            if (matchedEpisode != null)
            {
                return this.Matched(guideProgram, matchedEpisode);
            }
            return this.Unmatched(guideProgram);
        }
        public Invoice FirstInvoice()
        {
            MyOrders = new List<Order>();
            var client2Orders = new FakeClient2Order().MyOrders;
            foreach (var order in client2Orders)
            {
                MyOrders.Add(order);
            }

            var firstOrder = MyOrders.FirstOrDefault();
            if (firstOrder == null) return null;
            var firstOrderCharge = new OrderCharge().Calculate(firstOrder);
            var firstOrderInvoice = new Invoice
            {
                InvoiceId = 2,
                OrderId = firstOrder.OrderId,
                ClientId = firstOrder.ClientId,
                OrderDate = firstOrder.OrderDate,
                DeliveryDate = firstOrder.DeliveryDate,
                CurrencyId = firstOrder.CurrencyId,

                CookerId = firstOrderCharge.CookerId,
                OrderTypeValue = firstOrderCharge.OrderTypeValue,
                PaymentMethodValue = firstOrderCharge.PaymentMethodValue,

                PromotionTitle = firstOrderCharge.PromotionTitle,
                PromotionPrice = firstOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstOrderCharge.PromotionCurrencyId,

                CouponTitle = firstOrderCharge.CouponTitle,
                CouponPrice = firstOrderCharge.CouponPrice,
                CouponCurrencyId = firstOrderCharge.CouponCurrencyId,

                PlanTitle = firstOrderCharge.PlanTitle,
                SalesTax = firstOrderCharge.SalesTaxes,
                DeliveryFees = firstOrderCharge.DeliveryFee,
                SubTotal = firstOrderCharge.Subtotal,
                Total = firstOrderCharge.TotalCharges
            };
            return firstOrderInvoice;
        }
        public RoleAuthorization GetTopAuthorization(List<RoleAuthorization> list, string url)
        {
            RoleAuthorization info = list.FirstOrDefault(t => t.Url.ToLower() == url.ToLower());

            if (info != null)
            {
                //Func<RoleAuthorization,RoleAuthorization> rf =
                //    (RoleAuthorization item) =>
                //    {
                //        var parent = list.FirstOrDefault(t=>t.FunctionId == item.ParentId);
                //        if(parent == null)
                //            return null;
                //        if(parent.Level == 1)
                //            return parent;

                //        return rf(parent);
                //    };

                return GetTopAuthorization(list, info);
            }

            return null;
        }
 public override bool Match(GuideEnricherProgram guideProgram, List<TvdbEpisode> episodes)
 {
     if (guideProgram == null) throw new ArgumentNullException("enrichedGuideProgram");
     //
     Match match = null;
     int index = 0;
     do
     {
         match = regexes[index++].Match(guideProgram.Description);
     } while (string.IsNullOrEmpty(match.Value) && index < regexes.Count);
     if (match != null && !string.IsNullOrEmpty(match.Value))
     {
         this.MatchAttempts++;
         int seasonNumber = 0;
         int episodeNumber = 0;
         if (!int.TryParse(match.Groups["season"].Value, out seasonNumber))
         {
             // roman literal?
             seasonNumber = this.RomanToNumeric(match.Groups["season"].Value);
         }
         if (!int.TryParse(match.Groups["episode"].Value, out episodeNumber))
         {
             // roman literal?
             episodeNumber = this.RomanToNumeric(match.Groups["episode"].Value);
         }
         if (seasonNumber != 0 && episodeNumber != 0)
         {
             var matchedEpisode = episodes.FirstOrDefault(x => x.SeasonNumber == seasonNumber && x.EpisodeNumber == episodeNumber);
             if (matchedEpisode != null)
             {
                 return this.Matched(guideProgram, matchedEpisode);
             }
         }
     }
     return this.Unmatched(guideProgram);
 }
        public void RestoreAzureWebsiteDeploymentTest()
        {
            // Setup
            SimpleWebsitesManagement channel = new SimpleWebsitesManagement();

            channel.GetWebSpacesThunk = ar => new WebSpaces(new List<WebSpace> { new WebSpace { Name = "webspace1" }, new WebSpace { Name = "webspace2" } });
            channel.GetSitesThunk = ar =>
            {
                if (ar.Values["webspaceName"].Equals("webspace1"))
                {
                    return new Sites(new List<Site> { new Site { Name = "website1", WebSpace = "webspace1", SiteProperties = new SiteProperties
                        {
                            Properties = new List<NameValuePair>
                            {
                                new NameValuePair { Name = "repositoryuri", Value = "http" },
                                new NameValuePair { Name = "PublishingUsername", Value = "user1" },
                                new NameValuePair { Name = "PublishingPassword", Value = "password1" }
                            }
                        }}
                    });
                }

                return new Sites(new List<Site> { new Site { Name = "website2", WebSpace = "webspace2" } });
            };

            SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement();

            var deployments = new List<DeployResult> { new DeployResult { Id = "id1", Current = false }, new DeployResult { Id = "id2", Current = true } };
            deploymentChannel.GetDeploymentsThunk = ar => deployments;
            deploymentChannel.DeployThunk = ar =>
            {
                // Keep track of currently deployed id
                DeployResult newDeployment = deployments.FirstOrDefault(d => d.Id.Equals(ar.Values["commitId"]));
                if (newDeployment != null)
                {
                    // Make all inactive
                    deployments.ForEach(d => d.Complete = false);

                    // Set new to active
                    newDeployment.Complete = true;
                }
            };

            // Test
            RestoreAzureWebsiteDeploymentCommand restoreAzureWebsiteDeploymentCommand =
                new RestoreAzureWebsiteDeploymentCommand(channel, deploymentChannel)
            {
                Name = "website1",
                CommitId = "id2",
                ShareChannel = true,
                CommandRuntime = new MockCommandRuntime(),
                CurrentSubscription = new SubscriptionData { SubscriptionId = base.subscriptionName }
            };

            restoreAzureWebsiteDeploymentCommand.ExecuteCmdlet();
            Assert.AreEqual(1, ((MockCommandRuntime) restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.Count);
            var responseDeployments = (IEnumerable<DeployResult>)((MockCommandRuntime) restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.FirstOrDefault();
            Assert.IsNotNull(responseDeployments);
            Assert.AreEqual(2, responseDeployments.Count());
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id2") && d.Complete));
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id1") && !d.Complete));

            // Change active deployment to id1
            restoreAzureWebsiteDeploymentCommand = new RestoreAzureWebsiteDeploymentCommand(channel, deploymentChannel)
            {
                Name = "website1",
                CommitId = "id1",
                ShareChannel = true,
                CommandRuntime = new MockCommandRuntime(),
                CurrentSubscription = new SubscriptionData { SubscriptionId = base.subscriptionName }
            };

            restoreAzureWebsiteDeploymentCommand.ExecuteCmdlet();
            Assert.AreEqual(1, ((MockCommandRuntime)restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.Count);
            responseDeployments = (IEnumerable<DeployResult>)((MockCommandRuntime)restoreAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline.FirstOrDefault();
            Assert.IsNotNull(responseDeployments);
            Assert.AreEqual(2, responseDeployments.Count());
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id1") && d.Complete));
            Assert.IsTrue(responseDeployments.Any(d => d.Id.Equals("id2") && !d.Complete));
        }
        public Invoice FirstSubscriptionInvoice()
        {
            //TODO CHANGE IT TO REFLECT THE SUBSCRIPTION

            MyOrders = new List<Order>();
            var client1Orders = new FakeClient1SubscriptionsOrder().MyOrders;
            foreach (var order in client1Orders)
            {
                MyOrders.Add(order);
            }

            var firstOrder = MyOrders.FirstOrDefault();
            if (firstOrder == null) return null;
            var firstOrderCharge = new OrderCharge().Calculate(firstOrder);

            //Add it is is a subscriptions

            var firstOrderInvoice = new Invoice
            {

                InvoiceId = 10,

                #region Orders Fields
                OrderId = null,
                OrderDate = null,
                DeliveryDate = null,
                #endregion

                #region Subscription Fields

                SubscriptionStartDate = DateTime.Now.Date,
                SubscriptionEndDate = DateTime.Now.Date,
                SubscriptionInvoiceDate = DateTime.Now.Date,
                ClientSubscriptionId = 1,
                CookerSubscriptionId = 1,
                ServingPriceId = 3,
                PlanId = 1,
                PlanTitle = firstOrderCharge.PlanTitle,

                #endregion

                #region Common Fields

                ClientId = firstOrder.ClientId,
                CookerId = firstOrderCharge.CookerId,
                OrderModelTypeId = 2,
                OrderTypeValue = firstOrderCharge.OrderTypeValue,
                PaymentMethodValue = firstOrderCharge.PaymentMethodValue,
                CurrencyId = firstOrder.CurrencyId,

                PromotionTitle = firstOrderCharge.PromotionTitle,
                PromotionPrice = firstOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstOrderCharge.PromotionCurrencyId,

                CouponTitle = firstOrderCharge.CouponTitle,
                CouponPrice = firstOrderCharge.CouponPrice,
                CouponCurrencyId = firstOrderCharge.CouponCurrencyId,

                SalesTax = firstOrderCharge.SalesTaxes,
                DeliveryFees = firstOrderCharge.DeliveryFee,
                SubTotal = firstOrderCharge.Subtotal,
                Total = firstOrderCharge.TotalCharges,

                #endregion

            };
            return firstOrderInvoice;
        }
        private static void SetFixtures(Series series, int season, IEnumerable<SeriesFixturesSummaryEntity> seriesFixturesResult)
        {
            var teams = new List<Team>();
            var seriesFixture = series.SeriesFixtures;
            foreach (var match in seriesFixturesResult.First(s => s.LeagueLevelUnitID == series.HtSeriesId).Matches)
            {
                var fixture = seriesFixture.FirstOrDefault(f => f.HtMatchId == match.MatchID);
                if (fixture == null)
                {
                    fixture = new SeriesFixture();
                    var homeTeam = teams.FirstOrDefault(t => t.TeamId == match.HomeTeamID);
                    if (homeTeam == null)
                    {
                        homeTeam = new Team
                                       {
                                           Country = series.Country,
                                           TeamId = match.HomeTeamID,
                                           TeamName = match.HomeTeamName
                                       };
                        teams.Add(homeTeam);
                    }

                    var awayTeam = teams.FirstOrDefault(t => t.TeamId == match.AwayTeamID);
                    if (awayTeam == null)
                    {
                        awayTeam = new Team
                                       {
                                           Country = series.Country,
                                           TeamId = match.AwayTeamID,
                                           TeamName = match.AwayTeamName
                                       };
                        teams.Add(awayTeam);
                    }
                    fixture.HtMatchId = match.MatchID;
                    fixture.AwayTeam = awayTeam;
                    fixture.HomeTeam = homeTeam;
                    fixture.MatchDate = match.MatchDate;
                    fixture.MatchRound = match.MatchRound;
                    fixture.Season = (short)season;
                    series.AddSeriesFixture(fixture);
                }
                fixture.AwayGoals = (short?)match.AwayGoals;
                fixture.HomeGoals = (short?)match.HomeGoals;
            }
        }
        public Invoice FirstSubscriptionInvoice()
        {
            MySubscriptionsOrders = new List<OrderSubscription>();
            var client1SubscriptionsOrders = new FakeClient1SubscriptionsOrder().MyOrders;
            foreach (var order in client1SubscriptionsOrders)
            {
                MySubscriptionsOrders.Add(order);
            }

            var firstSubscriptionOrder = MySubscriptionsOrders.FirstOrDefault();
            if (firstSubscriptionOrder == null) return null;
            var subscriptionHelper = new SubscriptionHelper();
            var firstSubscriptionOrderCharge = new SubscriptionCharge().Calculate(firstSubscriptionOrder.ClientId, firstSubscriptionOrder);

            var firstSubscriptionOrderInvoice = new Invoice
            {

                InvoiceId = 20,

                #region Orders Fields
                //OrderId = null,
                OrderDate = null,
                DeliveryDate = null,
                #endregion

                #region Subscription Fields
                OrderId = firstSubscriptionOrder.OrderSubscriptionId,
                SubscriptionStartDate = DateTime.Now.Date,
                SubscriptionEndDate = DateTime.Now.Date.AddMonths(1),
                SubscriptionInvoiceDate = DateTime.Now.Date,

                ClientSubscriptionId = firstSubscriptionOrder.ClientSubscriptionId,
                CookerSubscriptionId = subscriptionHelper.GetCookerSubscription(firstSubscriptionOrder.ClientSubscriptionId).CookerSubscriptionId,
                ServingPriceId = subscriptionHelper.GetCookerServingPriceModel(firstSubscriptionOrder.ClientSubscriptionId).ServicePriceId,
                PlanId = firstSubscriptionOrder.PlanId,
                PlanTitle = subscriptionHelper.GetPlanTitle(firstSubscriptionOrder.PlanId),

                #endregion

                #region Common Fields

                ClientId = firstSubscriptionOrder.ClientId,
                CookerId = firstSubscriptionOrderCharge.CookerId,

                OrderModelTypeId = firstSubscriptionOrder.OrderTypeId,
                OrderTypeValue = firstSubscriptionOrderCharge.OrderTypeValue,

                PaymentMethodValue = firstSubscriptionOrderCharge.PaymentMethodValue,
                CurrencyId = firstSubscriptionOrder.CurrencyId,

                PromotionTitle = firstSubscriptionOrderCharge.PromotionTitle,
                PromotionPrice = firstSubscriptionOrderCharge.PromotionPrice,
                PromotionCurrencyId = firstSubscriptionOrderCharge.PromotionCurrencyId,

                CouponTitle = firstSubscriptionOrderCharge.CouponTitle,
                CouponPrice = firstSubscriptionOrderCharge.CouponPrice,
                CouponCurrencyId = firstSubscriptionOrderCharge.CouponCurrencyId,

                SalesTax = firstSubscriptionOrderCharge.SalesTaxes,
                DeliveryFees = firstSubscriptionOrderCharge.DeliveryFee,
                SubTotal = firstSubscriptionOrderCharge.Subtotal,
                Total = firstSubscriptionOrderCharge.TotalCharges

                #endregion

            };
            return firstSubscriptionOrderInvoice;
        }
        /// <summary>
        /// CreateRequisition
        /// </summary>
        /// <param name="itemList">CartItems List (EmpID, ItemID, Qty)</param>
        /// <returns></returns>
        public int createRequisition(List<CartItems> itemList)
        {
            int result = 0;
            int ReqID = 0;

            if (itemList.FirstOrDefault() != null)
            {
                //create and add new requisition
                Requisition req = new Requisition();
                req.EmpID = itemList.First().EmpID;
                int empid = itemList.First().EmpID;
                req.DeptID = ctx.Employee.Where(x => x.EmpID == empid).First().DeptID;
                req.Date = DateTime.Now;
                req.StatusID = 1;
                ctx.Requisition.Add(req);
                ctx.SaveChanges();

                //obtain the ReqID of the newly added requisition
                List<Requisition> reqList = ctx.Requisition.Where(x => x.EmpID == empid).ToList();
                ReqID = reqList.Last().ReqID ;

                //create and add new requisition details
                foreach (CartItems item in itemList)
                {
                    RequisitionDetail reqDetail = new RequisitionDetail();
                    reqDetail.ReqID = ReqID;
                    reqDetail.ItemID = item.ItemID;
                    reqDetail.RequestQty = item.Qty;
                    ctx.RequisitionDetail.Add(reqDetail);
                }

                //delete items from request cart
                foreach (CartItems item in itemList)
                {
                    CartItems cartItem = ctx.CartItems.Where(x => x.EmpID == item.EmpID && x.ItemID == item.ItemID).FirstOrDefault();
                    ctx.CartItems.Remove(cartItem);
                }

            }

            int count = ctx.SaveChanges();

            if (count > 0)
                result = ReqID;

            if (result == ReqID)
            {
                //send notification:
                NotificationController nt = new NotificationController();
                nt.sendNotification(1, itemList.First().EmpID, Convert.ToString(ReqID));
            }

            return result;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Session[Settings.Default.FlashSessionKey] != null)
            {
                this.FlashLiteralWrapper.Visible = true;
                this.FlashLiteral.Text = this.Session[Settings.Default.FlashSessionKey].ToString();
                this.Session[Settings.Default.FlashSessionKey] = null;
            }
            else
            {
                this.FlashLiteralWrapper.Visible = false;
            }

            this._petIdString = this.Request.QueryString["petid"];

            if (String.IsNullOrEmpty(this._petIdString))
            {
                this.StatsLiteral.Text = "Add a New Pet";
                this.SaveStatsButton.Text = "Save New Pet";
            }
            else
            {
                this.PhotoPanel.Visible = true;
            }

            this._userBucketName = String.Format(Settings.Default.BucketNameFormat, this.Context.User.Identity.Name, this._petIdString);
            this._itemName = this._petIdString ?? Guid.NewGuid().ToString();
            this._domainName = String.Format(Settings.Default.SimpleDbDomainNameFormat, this.Context.User.Identity.Name);

            if (!this.Page.IsPostBack)
            {
                List<int> years = new List<int>(100);
                for (int i = 0; i < 100; i++)
                {
                    years.Add(DateTime.Now.AddYears(i * -1).Year);
                }
                this.YearDropDownList.DataSource = years.OrderByDescending(y => y);
                this.YearDropDownList.DataBind();
                this.SelectMonth();
                this.SelectDay();

                Pet pet = default(Pet);
                List<string> files = new List<string>();
                if (!String.IsNullOrEmpty(this._petIdString))
                {
                    //
                    // Try to get the requested pet from the user's private domain
                    //
                    DomainHelper.CheckForDomain(this._domainName, _simpleDBClient);

                    GetAttributesRequest getAttributeRequest = new GetAttributesRequest()
                        .WithDomainName(this._domainName)
                        .WithItemName(this._itemName);
                    GetAttributesResponse getAttributeResponse = _simpleDBClient.GetAttributes(getAttributeRequest);
                    List<Attribute> attrs = null;
                    bool showPublic = false;

                    if (getAttributeResponse.IsSetGetAttributesResult())
                    {
                        attrs = getAttributeResponse.GetAttributesResult.Attribute;

                        showPublic = false;

                        //
                        // If we can't find it try the public domain
                        //
                        if (attrs.Count == 0)
                        {
                            showPublic = true;
                        }
                    }

                    if (showPublic)
                    {
                        Response.Redirect(String.Concat("PetProfile.aspx?petid", _petIdString));
                        return;
                    }

                    pet = new Pet
                    {
                        Name = attrs.First(a => a.Name == "Name").Value,
                        Birthdate = attrs.First(a => a.Name == "Birthdate").Value,
                        Sex = attrs.First(a => a.Name == "Sex").Value,
                        Type = attrs.First(a => a.Name == "Type").Value,
                        Breed = attrs.First(a => a.Name == "Breed").Value,
                        Likes = attrs.First(a => a.Name == "Likes").Value,
                        Dislikes = attrs.First(a => a.Name == "Dislikes").Value
                    };

                    this.Public.Checked = bool.Parse(attrs.First(a => a.Name == "Public").Value);

                    using (AmazonS3Client s3Client = new AmazonS3Client(Settings.Default.AWSAccessKey.Trim(), Settings.Default.AWSSecretAccessKey.Trim()))
                    {
                        BucketHelper.CheckForBucket(this._petIdString, s3Client);
                        ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
                            .WithBucketName(this._userBucketName);
                        using (ListObjectsResponse listObjectsResponse = s3Client.ListObjects(listObjectsRequest))
                        {
                            files = listObjectsResponse.S3Objects.Select(o => String.Format(Settings.Default.S3BucketUrlFormat, this._userBucketName, o.Key)).ToList();
                            string firstPhoto = files.FirstOrDefault();
                            this.PhotoThumbUrl.Value = firstPhoto ?? String.Empty;
                        }
                    }
                }

                if (pet != default(Pet))
                {
                    this.PetNameHeader.Text = pet.Name;
                    this.NameTextBox.Text = pet.Name;
                    this.AnimalDropDownList.SelectedValue = pet.Type;
                    this.BreedTextBox.Text = pet.Breed;
                    this.SexDropDownList.SelectedValue = pet.Sex;
                    if (pet.Birthdate != null)
                    {
                        DateTime birthdate = DateTime.Parse(pet.Birthdate);
                        this.YearDropDownList.SelectedValue = birthdate.Year.ToString();
                        this.MonthDropDownList.SelectedValue = birthdate.Month.ToString();
                        this.DayDropDownList.SelectedValue = birthdate.Day.ToString();
                    }
                    this.LikesTextBox.Text = pet.Likes;
                    this.DislikesTextBox.Text = pet.Dislikes;
                    this.PhotoRepeater.DataSource = files;
                    this.PhotoRepeater.DataBind();
                }
            }
        }
Example #16
0
        public FormularioVersao BuscaForm(Data.DB _db, int? idFormulario, int idProjeto, bool IsPost, FormularioVersao _formPost)
        {
            Projeto _projeto = _db.getProjeto(idProjeto);

            //BUSCANDO OS FORMS DO FLUXO
            List<Formulario> _listaForms = listaForms(idProjeto).OrderBy(f => f.Ordem).ToList();

            //BUSCANDO AS VERSOES DOS FORMULARIOS
            List<FormularioVersao> _listaFormsVersao = new List<FormularioVersao>();
            foreach (var item in _listaForms)
            {
                _listaFormsVersao.Add(listaFormsVersao(item.Id, item.Ordem, _projeto.DtCriacao));
            }

            ViewBag.Forms = _listaFormsVersao;
            ViewBag.IdProjeto = idProjeto;

            FormularioVersao formRenderizado = _listaFormsVersao.FirstOrDefault(f => idFormulario == null || f.IdFormulario == idFormulario.Value);
            ViewBag.Message = formRenderizado.Nome;

            formRenderizado.Componentes = _db.getFormComponentes(formRenderizado.Id, idProjeto).OrderBy(e => e.Ordem).ToList();
            int idFluxo = Convert.ToInt32(Session["FluxoId"]);//Session?


            List<Resposta> ListaRespostasOld = new List<Resposta>();

            if (!IsPost)
                ListaRespostasOld = _db.getRespostas(formRenderizado.Id, idFluxo, idProjeto);

            Resposta respostaOld = null;
            FormularioComponente _comp;
            FormularioElemento _elem;
            foreach (var componente in formRenderizado.Componentes)
            {
                componente.Elementos = _db.getComponenteElementos(componente.IdComponente).OrderBy(e => e.Linha).ThenBy(e => e.Ordem).ToList();

                foreach (var elemento in componente.Elementos)
                {
                    if (IsPost)
                    {
                        //se a chave mudar para permitir ter varios componentes iguais, mudar aqui a busca para chave primaria!
                        _comp = _formPost.Componentes.FirstOrDefault(c => c.IdComponente == elemento.IdComponente);

                        //complemento no formulario postado deve existir, nem todos os componentes são mandados no Post                        
                        if (_formPost.Componentes.FirstOrDefault(c => c.IdComponente == elemento.IdComponente) != null)
                        {
                            _elem = _comp.Elementos.FirstOrDefault(e => e.Id == elemento.Id);
                            if (_elem != null)//nem todos os elementos vem no Post, por isso verificar se algum deve salvar
                                respostaOld = _elem.Respostas;
                        }
                    }
                    else
                        respostaOld = ListaRespostasOld.FirstOrDefault(r => r.IdComponenteElemento == elemento.Id && r.IdComponenteExpansao == 0); //soh o original do modelo do form tera expansao nula

                    if (respostaOld != null)
                        elemento.Respostas = respostaOld;

                    if (elemento.IdTipoElemento == 5 || elemento.IdTipoElemento == 7) //combo || radio
                        elemento.Valores = _db.getFormElementoValores(elemento.Id);
                }

                ComponenteExpansao compExp;
                respostaOld = null;
                //agora os expandidos, pegar os elementos e respostas
                if (componente.IsExpansivel)
                {
                    _comp = new FormularioComponente();
                    if (IsPost)
                    {
                        _comp = _formPost.Componentes.FirstOrDefault(c => c.Id == componente.Id); //pegando o componente que foi postado
                        componente.ListaComponenteExpansao = _comp.ListaComponenteExpansao; //pegar o que cliente modificou, no caso soh posta as expansoes modificadas
                    }

                    foreach (var item in componente.ListaComponenteExpansao)
                    {
                        item.Elementos = _db.getComponenteElementos(componente.IdComponente).OrderBy(e => e.Linha).ThenBy(e => e.Ordem).ToList();

                        foreach (var elemento in item.Elementos)
                        {
                            if (IsPost)
                            {
                                compExp = _comp.ListaComponenteExpansao.FirstOrDefault(ce => ce.Id == item.Id);
                                if (compExp != null)
                                {
                                    //buscar elementos da expansao
                                    _elem = compExp.Elementos.FirstOrDefault(e => e.Id == elemento.Id);
                                    if (_elem != null)//nem todos os elementos vem no Post, por isso verificar se algum deve salvar
                                        respostaOld = _elem.Respostas;
                                }
                            }
                            else
                                respostaOld = ListaRespostasOld.FirstOrDefault(r => r.IdComponenteElemento == elemento.Id && r.IdComponenteExpansao == item.Id); //todas expansoes tem id

                            if (respostaOld != null)
                                elemento.Respostas = respostaOld;

                            if (elemento.IdTipoElemento == 5 || elemento.IdTipoElemento == 7) //combo || radio
                                elemento.Valores = _db.getFormElementoValores(elemento.Id);
                        }
                    }
                }
            }

            return formRenderizado;
        }