public void Can_Init_NHibernate_Session()
        {
            var session = NHibernateSession.Current;

            using (var trans = session.BeginTransaction())
            {
                var result = session.QueryOver<Category>().List();
                var item1 = result.FirstOrDefault();

                var news = new News { Title = "Title 2", ShortDescription = "Sort description 1", Content = "Content 1" };

                var poll = new Poll { Value = 1, WhoVote = "ThangChung", VoteDate = DateTime.Now };

                var user = new User { UserName = "******", Password = "******" };

                news.AssignCategory(item1);

                news.AssignPoll(poll);

                user.AssignPoll(poll);

                session.Save(news);

                session.Save(poll);

                session.Save(user);

                session.Flush();
            }
        }
Example #2
0
        protected String GetOptionResultText(Object oOrder, Object oAnswer, Object oVotes)
        {
            int order = (int)oOrder;
            String answer = oAnswer as String;
            int votes = (int)oVotes;

            String orderNumber = String.Empty;
            if (poll.ShowOrderNumbers)
            {
                orderNumber = order.ToString() + ". ";
            }

            String votesText = (votes == 1) ? PollResources.PollVoteText : PollResources.PollVotesText;

            // TODO: Some pattern based resource...
            String text = orderNumber + answer + ", " + votes + " " + votesText;

            poll = new Poll(ModuleId);
            if (poll.TotalVotes != 0)
            {
                int percent = (int)((double)votes * 100 / poll.TotalVotes + 0.5);
                text += " (" + percent + " %)";
            }

            return text;
        }
 public  IEnumerable<PollQuestion> GetQuestionByPoll(Poll ActivePoll)
 {
     if (ActivePoll == null) return null;
     return ActivePoll.PollQuestions.Where(p => p.Status == EntityStatuses.Actived.ToString())
         .OrderBy(p=>p.Order)
         .AsEnumerable();
 }
Example #4
0
    public void Initialize(Poll poll)
    {
        state = poll.state;
        date = poll.date;
        scores = poll.scores;

        // setup the sphere array to be the size of the non-null scores
        for (int i = 0; i < scores.Length; i++) {
            Score score = scores [i];
            if (score == null) {
                spheres = new GameObject[i];
                break;
            }
        }

        float posCursor = 1;
        for (int i = 0; i < scores.Length; i++) {
            Score score = scores[i];
            if (score != null){
                GameObject sphere = (GameObject)Instantiate(Sphere.spherePrefab);
                sphere.GetComponent<Sphere>().Initialize(score);
                // make the sphere's orientation relative to this Pin
                sphere.transform.parent = transform;
                // set the sphere's position just underneath the last sphere
                sphere.transform.localPosition = new Vector3(0, posCursor - (0.5f * sphere.transform.localScale.y), 0);
                posCursor = posCursor - sphere.transform.localScale.y;
                sphere.GetComponent<Renderer>().material.color = sphere.GetComponent<Sphere>().candidate.color;
                // add the sphere to the sphere array
                spheres[i] = sphere;
            }
        }
        transform.position = StatesLookup.pos[state];

        // set each sphere's position based on its ranking
    }
Example #5
0
 public List<PollAnswer> GetAllPollAnswersByPoll(Poll poll)
 {
     var cacheKey = string.Concat(CacheKeys.PollAnswer.StartsWith, "GetAllPollAnswersByPoll-", poll.Id);
     return _cacheService.CachePerRequest(cacheKey, () => _context.PollAnswer
                                                             .Include(x => x.Poll)
                                                             .AsNoTracking()
                                                             .Where(x => x.Poll.Id == poll.Id).ToList());
 }
 public  Poll Add(string name, string status)
 {
     Poll poll = new Poll();
     poll.PollName = name.Trim();
     poll.Status = status.Trim();
     this.Polls.InsertOnSubmit(poll);
     Commit();
     return poll;
 }
Example #7
0
 private IEnumerable<PollResultViewModel> CountVotes(Poll poll)
 {
     var results = from o in poll.Options
                   orderby o.Shortcut descending
                   select new PollResultViewModel() {
                     Option = o.Answer,
                     Count = (from v in poll.Votes where v.Value == o.Shortcut select v).Count()
                   };
     return results;
 }
Example #8
0
 void TimerHandler(DateTime signal)
 {
     try
     {
         Poll poll = new Poll(new PollRequest());
         _mainPort.Post(poll);
     }
     finally
     {
         Activate(
             Arbiter.Receive(false, TimeoutPort(50), TimerHandler)
         );
     }
 }
Example #9
0
    protected void OnItemCommandOccur(object sender, ListViewCommandEventArgs e)
    {
        try
        {
            SaveChanges();
            switch (e.CommandName)
            {
                case "AddItem":
                    Choice choice = new Choice(((TextBox)poll.FindControl("newAnswerTextBox")).Text);
                    choice.Id = GenerateChoiceID();
                    ((TextBox)poll.FindControl("newAnswerTextBox")).Text = String.Empty;
                    choices.Add(choice);
                    enableButtons = (choices.Count > 2) ? true : false;
                    BindData();
                    break;
                case "RemoveItem":
                    choices.Remove(choices.Find(delegate(Choice curChoice) { return curChoice.Id == Convert.ToInt32(e.CommandArgument); }));
                    enableButtons = (choices.Count > 2) ? true : false;
                    BindData();
                    break;
                case "SubmitWidget":
                    string question = ((TextBox)poll.FindControl("questionTextBox")).Text;
                    if (question == String.Empty)
                    {
                        throw new Exception("Question field can't be empty");
                    }

                    Poll newPoll = new Poll();
                    newPoll.Description = question;
                    newPoll.Choices = choices;
                    newPoll.Name = "WidgetPoll";

                    pollID = PollDAL.CreatePoll(newPoll);

                    resultWidget.Visible = true;
                    widgetSrc.InnerText = "<iframe style=\"border: solid 1px #A30313; width: 320px; height: 165px\" scrolling=\"auto\" src=\"PollWidget.aspx?poll_id=" + pollID.ToString() + "\"></iframe>";

                    break;
            }
        }
        catch (Exception exception)
        {
            errorLabel.Text = exception.Message;
        }
    }
    protected void btnvote_Click(object sender, EventArgs e)
    {
        if (rdb1.Checked == false && rdb2.Checked == false
            && rdb3.Checked == false && rdb4.Checked == false) {
               // Alert.Show("กรุณาเลือกโปรแกรมด้วย !!!");
                return;
        }
        try
        {
            Poll p = new Poll();
            if (rdb1.Checked == true)
            {
                p.ProgramID = "1";    // 1. โปรแกรมบัญชี
            }
            else if (rdb2.Checked == true)
            {
                p.ProgramID = "2"; // 2. โปรแกรมสต๊อก
            }
            else if (rdb3.Checked == true)
            {
                p.ProgramID = "3";  // 3. โปรแกรมบริหารร้านค้า
            }
            else if (rdb4.Checked == true)
            {
                p.ProgramID = "0";  // 3. โปรแกรมบริหารร้านค้า
                p.PrograName = txtorther.Text.Trim();
            }

            MemberService service = new MemberService();
            if (service.CreatePoll(p))
            {
                Alert.Show("บันทึกเรียบร้อย");
                txtorther.Text = "";

            }

        }
        catch (Exception ex) {
            Alert.Show("ไม่สามารถบันทึกได้เนื่องจาก"+ ex.Message);
        }
    }
Example #11
0
    public static bool AddPoll(Dictionary<string, object> arguments)
    {
        Poll poll = new Poll();

        // trying... if fields are set
        try
        {
            poll.Name = arguments["poll_name"].ToString();
            poll.Description = arguments["poll_desc"].ToString();
            poll.CustomChoiceEnabled = Convert.ToBoolean(arguments["poll_custom"]);
        }
        catch (Exception)
        {
            return false;
        }

        int surveyID = Convert.ToInt32(arguments["surveyID"]);
        (HttpContext.Current.Session["survey_" + surveyID] as Survey).Polls.Add(poll);

        return true;
    }
Example #12
0
        public ActionResult Index(Poll poll)
        {
            var client = new TwilioRestClient(Credentials.AccountSid, Credentials.AuthToken);

            var result = client.AddIncomingPhoneNumber(new PhoneNumberOptions() {
                PhoneNumber = poll.PhoneNumber,
                SmsUrl = "http://tallyvu.apphb.com/Polls/Tally", 
                SmsMethod = "POST" 
            });

            if (result.RestException != null)
            {
                // TODO: Fix this 
                return new EmptyResult(); 
            }

            poll.PhoneNumber = result.PhoneNumber;

            _repository.Add(poll);

            return Redirect(string.Format("/{0}", poll.Key));
        }
Example #13
0
 private void btnActivateDeactivate_Click(object sender, EventArgs e)
 {
     Poll poll = new Poll(new Guid(btnActivateDeactivate.CommandArgument));
     if (btnActivateDeactivate.CommandName == "Activate")
     {
         poll.Activate();
         poll.Save();
         WebUtils.SetupRedirect(this,
             SiteRoot + "/Poll/PollEdit.aspx?PollGuid=" + pollGuid.ToString()
             + "&pageid=" + pageId.ToInvariantString()
             + "&mid=" + moduleId.ToInvariantString()
             );
     }
     else if (btnActivateDeactivate.CommandName == "Deactivate")
     {
         poll.Deactivate();
         poll.Save();
         WebUtils.SetupRedirect(this,
             SiteRoot + "/Poll/PollEdit.aspx?PollGuid=" + pollGuid.ToString()
             + "&pageid=" + pageId.ToInvariantString()
             + "&mid=" + moduleId.ToInvariantString()
             );
     }
 }
        public async Task <IActionResult> CreatePollAsync([FromBody] CreatePollModel createPoll)
        {
            if (ModelState.IsValid)
            {
                //Variablen
                int        concernStatusId = 0;
                int        userId          = (await userManager.GetUserAsync(HttpContext.User)).Id;
                List <int> answerOptionId  = new List <int>();
                Poll       poll            = new Poll
                {
                    Text              = createPoll.Text,
                    Title             = createPoll.Title,
                    End               = createPoll.End,
                    NeedsLocalCouncil = createPoll.NeedsLocalCouncil,
                    LastUpdatedBy     = userId,
                    LastUpdatedAt     = DateTime.UtcNow,
                    UserId            = userId,
                    StatusId          = 2,
                    CategoryId        = createPoll.CategoryId
                };
                //Nur, wenn Umfrage aus Anliegen erstellt wird, wird das Anliegen auf Status "abgeschlossen" gesetzt.
                if (createPoll.ConcernId != 0)
                {
                    Concern concern = db.Concern.Where(c => c.Id == createPoll.ConcernId).SingleOrDefault();
                    concernStatusId  = 6; //concern.StatusId;
                    concern.StatusId = concernStatusId;
                    db.Update(concern);
                }

                //Antworten aus Objekt auslesen und in Datenbank speichern
                foreach (string answer in createPoll.Answers)
                {
                    AnswerOptions answerOption = null;
                    //Prüfung, ob Antwort schon einmal verwendet wurde
                    answerOption = db.AnswerOptions.Where(ao => ao.Description.Equals(answer)).SingleOrDefault();
                    if (answerOption != null)
                    {
                        answerOptionId.Add(answerOption.Id);
                    }
                    else
                    {
                        answerOption = new AnswerOptions {
                            Description = answer
                        };
                        db.Add(answerOption);
                        answerOptionId.Add(answerOption.Id);
                    }
                }

                if (!poll.NeedsLocalCouncil)
                {
                    poll.Approved = true;
                }
                else
                {
                    poll.Approved = false;
                }
                //Umfrage Speichern
                db.Add(poll);

                //Antworten Speichern
                foreach (int aoId in answerOptionId)
                {
                    db.Add(new AnswerOptionsPoll {
                        PollId = poll.Id, AnswerOptionsId = aoId
                    });
                }

                //Dokumente aus dem Anliegen in die Umfrage übernehmen
                if (createPoll.FileIds != null)
                {
                    foreach (int fileId in createPoll.FileIds)
                    {
                        File file = db.File.Where(f => f.Id == fileId).SingleOrDefault();
                        file.PollId = poll.Id;
                        db.Update(file);
                    }
                }
                //Bilder aus dem Anliegen in die Umfrage übernehmen
                if (createPoll.ImageIds != null)
                {
                    foreach (int imageId in createPoll.ImageIds)
                    {
                        Image image = db.Image.Where(i => i.Id == imageId).SingleOrDefault();
                        image.PollId = poll.Id;
                        db.Update(image);
                    }
                }
                //Commit
                int result = db.SaveChanges();
                return(Json(new { result, concernStatusId, concernId = createPoll.ConcernId }));
            }

            return(Json(new { result = 0 }));
        }
Example #15
0
 public IActionResult Details(Poll poll)
 {
     return(View(poll));
 }
Example #16
0
        public void TestPollReqCommand1()
        {
            string expected = File.ReadAllText("PollRequestCommand1.xml");

            var command = new Poll { Type = "req" };
            command.TransactionId = "ABC-12345";

            Assert.AreEqual(expected, command.ToXml().InnerXml);
        }
 //news items
 public static PollModel ToModel(this Poll entity)
 {
     return(entity.MapTo <Poll, PollModel>());
 }
Example #18
0
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         if (!IsPostBack)
         {
             int pollID = Convert.ToInt32(Request["poll_id"]);
             poll = PollDAL.GetPoll(pollID);
             BindData();
         }
     }
     catch (Exception exception)
     {
         errorLabel.Text = exception.Message;
     }
 }
Example #19
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (pollGuid != Guid.Empty)
            {
                Poll poll = new Poll(pollGuid);
                poll.Delete();

                WebUtils.SetupRedirect(this,
                    SiteRoot + "/Poll/PollChoose.aspx"
                    + "?pageid=" + pageId.ToInvariantString()
                    + "&mid=" + moduleId.ToInvariantString()
                    );
            }
        }
 public override void DeleteContent(int moduleId, Guid moduleGuid)
 {
     Poll.RemoveFromModule(moduleId);
 }
Example #21
0
        void OnPollConnection(Poll handle, PollStatus status)
        {
            var context = (ConnectionContext)handle.UserToken;

            PollMask pollMask  = status.Mask;
            PollMask newEvents = context.EventMask;
            var      random    = new Random(10);

            if ((pollMask & PollMask.Readable) == PollMask.Readable)
            {
                int action = random.Next() % 7;

                if (action == 0 ||
                    action == 1)
                {
                    // Read a couple of bytes.
                    var buffer = new byte[74];
                    int count  = TryReceive(context.Socket, buffer);
                    if (count > 0)
                    {
                        context.Receive += count;
                    }
                    else
                    {
                        // Got FIN.
                        context.ReceiveFinished = true;
                        newEvents &= ~PollMask.Readable;
                    }
                }
                else if (action == 2 ||
                         action == 3)
                {
                    // Read until EAGAIN.
                    var buffer = new byte[931];
                    int count  = TryReceive(context.Socket, buffer);
                    while (count > 0)
                    {
                        context.Receive += count;
                        count            = TryReceive(context.Socket, buffer);
                    }

                    if (count == 0)
                    {
                        // Got FIN.
                        context.ReceiveFinished = true;
                        newEvents &= ~PollMask.Readable;
                    }
                }
                else if (action == 4)
                {
                    // Ignore.
                }
                else if (action == 5)
                {
                    // Stop reading for a while. Restart in timer callback.
                    newEvents &= ~PollMask.Readable;

                    if (!context.TimerHandle.IsActive)
                    {
                        context.DelayedEventMask = PollMask.Readable;
                        context.TimerHandle.Start(this.OnTimerDelay, 10, 0);
                    }
                    else
                    {
                        context.DelayedEventMask |= PollMask.Readable;
                    }
                }
                else if (action == 6)
                {
                    // Fudge with the event mask.
                    context.PollHandle.Start(PollMask.Writable, this.OnPollConnection);
                    context.PollHandle.Start(PollMask.Readable, this.OnPollConnection);
                    context.EventMask = PollMask.Readable;
                }
            }

            if ((pollMask & PollMask.Writable) == PollMask.Writable &&
                !this.deplux && context.IsServerConnection)
            {
                // We have to send more bytes.
                int action = random.Next() % 7;

                if (action == 0 ||
                    action == 1)
                {
                    // Send a couple of bytes.
                    var buffer = new byte[103];

                    int send  = Math.Min(TransferBytes - context.Sent, buffer.Length);
                    int count = TrySend(context.Socket, buffer, send);
                    if (count < 0)
                    {
                        this.spuriousWritableWakeups++;
                    }
                    else
                    {
                        context.Sent += count;
                        this.validWritableWakeups++;
                    }
                }
                else if (action == 2 ||
                         action == 3)
                {
                    // Send until EAGAIN.
                    var buffer = new byte[1234];
                    int send   = Math.Min(TransferBytes - context.Sent, buffer.Length);
                    int count  = TrySend(context.Socket, buffer, send);
                    if (count < 0)
                    {
                        this.spuriousWritableWakeups++;
                    }
                    else
                    {
                        context.Sent += count;
                        this.validWritableWakeups++;
                    }

                    while (context.Sent < TransferBytes)
                    {
                        send  = Math.Min(TransferBytes - context.Sent, buffer.Length);
                        count = TrySend(context.Socket, buffer, send);
                        if (count < 0)
                        {
                            break;
                        }
                        else
                        {
                            context.Sent += count;
                        }
                    }
                }
                else if (action == 4)
                {
                    // Ignore.
                }
                else if (action == 5)
                {
                    // Stop sending for a while. Restart in timer callback.
                    newEvents &= ~PollMask.Writable;
                    if (!context.TimerHandle.IsActive)
                    {
                        context.DelayedEventMask = PollMask.Writable;
                        context.TimerHandle.Start(this.OnTimerDelay, 100, 0);
                    }
                    else
                    {
                        context.DelayedEventMask |= PollMask.Writable;
                    }
                }
                else if (action == 6)
                {
                    // Fudge with the event mask.
                    context.PollHandle.Start(PollMask.Readable, this.OnPollConnection);
                    context.PollHandle.Start(PollMask.Writable, this.OnPollConnection);
                    context.EventMask = PollMask.Writable;
                }
            }
            else
            {
                // Nothing more to write. Send FIN.
                context.Socket.Shutdown(SocketShutdown.Send);
                context.SentFinished = true;
                newEvents           &= ~PollMask.Writable;
            }

            if ((pollMask & PollMask.Disconnect) == PollMask.Disconnect)
            {
                context.Disconnected = true;
                newEvents           &= ~PollMask.Disconnect;
            }

            if (context.SentFinished ||
                context.ReceiveFinished ||
                context.Disconnected)
            {
                if (context.SentFinished ||
                    context.ReceiveFinished)
                {
                    this.DestroyConnectionContext(context);
                }
                else
                {
                    /* Poll mask changed. Call uv_poll_start again. */
                    context.EventMask = newEvents;
                    context.PollHandle.Start(newEvents, this.OnPollConnection);
                }
            }
        }
Example #22
0
        /// <summary>
        /// Prepare paged poll answer list model
        /// </summary>
        /// <param name="searchModel">Poll answer search model</param>
        /// <param name="poll">Poll</param>
        /// <returns>Poll answer list model</returns>
        public virtual PollAnswerListModel PreparePollAnswerListModel(PollAnswerSearchModel searchModel, Poll poll)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (poll == null)
            {
                throw new ArgumentNullException(nameof(poll));
            }

            //get poll answers
            var pollAnswers = poll.PollAnswers.OrderBy(pollAnswer => pollAnswer.DisplayOrder).ToList().ToPagedList(searchModel);

            //prepare list model
            var model = new PollAnswerListModel().PrepareToGrid(searchModel, pollAnswers,
                                                                () => pollAnswers.Select(pollAnswer => pollAnswer.ToModel <PollAnswerModel>()));

            return(model);
        }
Example #23
0
        public void Create()
        {
            var now       = DateTime.UtcNow;
            var generator = new RandomObjectGenerator();
            var userId    = generator.Generate <int>();

            var pollEntity = EntityCreator.Create <MVPoll>(_ =>
            {
                _.PollDeletedFlag = false;
                _.PollStartDate   = now.AddDays(-2);
                _.PollEndDate     = now.AddDays(2);
                _.PollMinAnswers  = 2;
                _.PollMaxAnswers  = 3;
            });

            pollEntity.MVPollOptions = new List <MVPollOption>
            {
                EntityCreator.Create <MVPollOption>(),
                EntityCreator.Create <MVPollOption>(),
                EntityCreator.Create <MVPollOption>(),
                EntityCreator.Create <MVPollOption>()
            };

            var category = EntityCreator.Create <MVCategory>(_ => _.CategoryID = pollEntity.PollCategoryID);

            Poll poll = null;

            var pollFactory = new Mock <IObjectFactory <IPoll> >(MockBehavior.Strict);

            pollFactory.Setup(_ => _.Fetch(pollEntity.PollID))
            .Returns <int>(_ =>
            {
                poll = DataPortal.Fetch <Poll>(_);
                return(poll);
            });

            var pollSubmissionResponsesFactory = new Mock <IObjectFactory <IPollSubmissionResponseCollection> >(MockBehavior.Strict);

            pollSubmissionResponsesFactory.Setup(_ => _.CreateChild(It.IsAny <object[]>()))
            .Callback <object[]>(_ => Assert.AreSame(poll.PollOptions, _[0]))
            .Returns <object[]>(_ => DataPortal.CreateChild <PollSubmissionResponseCollection>(_[0] as BusinessList <IPollOption>));

            var entities = new Mock <IEntities>(MockBehavior.Strict);

            entities.Setup(_ => _.MVPolls)
            .Returns(new InMemoryDbSet <MVPoll> {
                pollEntity
            });
            entities.Setup(_ => _.MVPollSubmissions)
            .Returns(new InMemoryDbSet <MVPollSubmission>());
            entities.Setup(_ => _.MVCategories)
            .Returns(new InMemoryDbSet <MVCategory> {
                category
            });
            entities.Setup(_ => _.Dispose());

            var pollOptions = new Mock <IObjectFactory <BusinessList <IPollOption> > >();

            pollOptions.Setup(_ => _.FetchChild()).Returns(new BusinessList <IPollOption>());

            var pollOption = new Mock <IObjectFactory <IPollOption> >();

            pollOption.Setup(_ => _.FetchChild(It.IsAny <object[]>()))
            .Returns <object[]>(_ => DataPortal.FetchChild <PollOption>(_[0] as MVPollOption));

            var pollSubmissionResponseFactory = new Mock <IObjectFactory <IPollSubmissionResponse> >();

            pollSubmissionResponseFactory.Setup(_ => _.CreateChild(It.IsAny <object[]>()))
            .Returns <object[]>(_ => DataPortal.CreateChild <PollSubmissionResponse>(_[0] as IPollOption));

            var builder = new ContainerBuilder();

            builder.Register <IEntities>(_ => entities.Object);
            builder.Register <IObjectFactory <IPoll> >(_ => pollFactory.Object);
            builder.Register <IObjectFactory <BusinessList <IPollOption> > >(_ => pollOptions.Object);
            builder.Register <IObjectFactory <IPollOption> >(_ => pollOption.Object);
            builder.Register <IObjectFactory <IPollSubmissionResponseCollection> >(_ => pollSubmissionResponsesFactory.Object);
            builder.Register <IObjectFactory <IPollSubmissionResponse> >(_ => pollSubmissionResponseFactory.Object);

            using (new ObjectActivator(builder.Build(), new ActivatorCallContext())
                   .Bind(() => ApplicationContext.DataPortalActivator))
            {
                var criteria   = new PollSubmissionCriteria(pollEntity.PollID, userId);
                var submission = DataPortal.Create <PollSubmission>(criteria);

                Assert.AreEqual(pollEntity.PollID, submission.PollID, nameof(submission.PollID));
                Assert.AreEqual(pollEntity.PollImageLink, submission.PollImageLink, nameof(submission.PollImageLink));
                Assert.AreEqual(userId, submission.UserID, nameof(submission.UserID));
                Assert.AreEqual(pollEntity.PollQuestion, submission.PollQuestion, nameof(submission.PollQuestion));
                Assert.AreEqual(category.CategoryName, submission.CategoryName, nameof(submission.CategoryName));
                Assert.AreEqual(pollEntity.PollDescription, submission.PollDescription, nameof(submission.PollDescription));
                Assert.AreEqual(pollEntity.PollMaxAnswers.Value, submission.PollMaxAnswers, nameof(submission.PollMaxAnswers));
                Assert.AreEqual(pollEntity.PollMinAnswers.Value, submission.PollMinAnswers, nameof(submission.PollMinAnswers));
                Assert.AreEqual(4, submission.Responses.Count, nameof(submission.Responses));

                submission.BrokenRulesCollection.AssertRuleCount(1);
                submission.BrokenRulesCollection.AssertRuleCount(PollSubmission.ResponsesProperty, 1);
                submission.BrokenRulesCollection.AssertBusinessRuleExists <MinimumAndMaximumPollSubmissionResponsesRule>(
                    PollSubmission.ResponsesProperty, true);
            }

            entities.VerifyAll();
            pollFactory.VerifyAll();
            pollSubmissionResponsesFactory.VerifyAll();
        }
 /**
  * Resolve the voting initiated by this event card
  *
  * Arguments
  * - Poll counter - The vote counter
  * - int playerNumber - The player that made the last vote
  */
 void ResolveCard(Poll counter, int playerNumber)
 {
     int placeholder; // Placeholder for the highest vote count
     if (counter.CheckPoll(ListNumber, VoteCap)) { // All players have voted
         Debug.Log("Hit vote count");
         placeholder = counter.ReturnHighestCount(ListNumber, VoteCap);
         if (TeamEvent) {
             if (placeholder != -1) { // Enough votes. Execute the effect of this event card
                 CardEffect(placeholder);
                 ChatTest.Instance.GetComponent<PhotonView>().RPC("Big", PhotonTargets.All, new object[]
                                                                  {"Event Successful"});
             } else // Not enough votes
                 ChatTest.Instance.GetComponent<PhotonView>().RPC("Big", PhotonTargets.All, new object[]
                                                                  {"Event Failed"});
         }
         counter.ClearCount(ListNumber); // Need to clear the vote counter
     }
 }
Example #25
0
        private void ShowResult()
        {
            //LoadPoll();
            poll = new Poll(ModuleId);

            if (currentUser != null)
            {
                userHasVoted = poll.UserHasVoted(currentUser);
            }
            else
            {
                userHasVoted = CookieHelper.CookieExists(poll.PollGuid.ToString());
            }

            if (userHasVoted) { lblVotingStatus.Text = PollResources.AlreadyVotedMessage; }

            rblOptions.Visible = false;
            dlResults.Visible = true;
            btnBackToVote.Visible = !userHasVoted;
            btnShowResults.Visible = false;

            lblMessage.Text = PollResources.PollTotalVotesLabel + poll.TotalVotes;
            //IDataReader reader = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            List<PollOption> pollOptions = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            dlResults.DataSource = pollOptions;
            dlResults.DataBind();
            //reader.Close();

            //rptResults.DataSource = PollOption.GetOptionsByPollGuid(poll.PollGuid);
            //rptResults.DataBind();
        }
Example #26
0
 private void LoadPoll()
 {
     if (poll == null) poll = new Poll(ModuleId);
 }
Example #27
0
 void OnClose(Poll handle)
 {
     handle.Dispose();
     this.closeCount++;
 }
Example #28
0
 public Poll Add(Poll poll)
 {
     return(_context.Poll.Add(poll));
 }
Example #29
0
 public static Poll ToEntity(this PollModel model, Poll destination)
 {
     return(Mapper.Map(model, destination));
 }
Example #30
0
 public void Delete(Poll item)
 {
     _context.Poll.Remove(item);
 }
Example #31
0
        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);

            if (moduleSettings.Contains("ResultBarColor"))
            {
                resultBarColor = moduleSettings["ResultBarColor"].ToString();
            }

            currentModule = GetModule(moduleId, Poll.FeatureGuid);
            currentPoll = new Poll(moduleId);

            AddClassToBody("pollchoose");
        }
Example #32
0
        /// <summary>
        /// Prepare paged poll answer list model
        /// </summary>
        /// <param name="searchModel">Poll answer search model</param>
        /// <param name="poll">Poll</param>
        /// <returns>Poll answer list model</returns>
        public virtual PollAnswerListModel PreparePollAnswerListModel(PollAnswerSearchModel searchModel, Poll poll)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (poll == null)
            {
                throw new ArgumentNullException(nameof(poll));
            }

            //get poll answers
            var pollAnswers = poll.PollAnswers.OrderBy(pollAnswer => pollAnswer.DisplayOrder).ToList();

            //prepare list model
            var model = new PollAnswerListModel
            {
                //fill in model values from the entity
                Data = pollAnswers.PaginationByRequestModel(searchModel).Select(pollAnswer => new PollAnswerModel
                {
                    Id            = pollAnswer.Id,
                    PollId        = pollAnswer.PollId,
                    Name          = pollAnswer.Name,
                    NumberOfVotes = pollAnswer.NumberOfVotes,
                    DisplayOrder  = pollAnswer.DisplayOrder
                }),
                Total = pollAnswers.Count
            };

            return(model);
        }
Example #33
0
    public bool CreatePoll(Poll _poll)
    {
        bool result = false;

        try
        {
            Conn = db.openConn();
            tr = Conn.BeginTransaction();

            sb = new StringBuilder();

            sb.Remove(0, sb.Length);
            sb.Append("INSERT INTO tbPoll(ProgramID,ProgramName)");
            sb.Append(" VALUES (");
            sb.Append(" '" + _poll.ProgramID + "',");
            sb.Append(" '" + _poll.PrograName + "')");

            string sqlSave;
            sqlSave = sb.ToString();

            com = new OleDbCommand();
            com.Connection = Conn;
            com.CommandText = sqlSave;
            com.Transaction = tr;
            com.Parameters.Clear();

            com.ExecuteNonQuery();
            tr.Commit();

            result = true;

        }
        catch (Exception ex)
        {
            tr.Rollback();
            Conn.Close();
            return result;
            throw ex;
        }
        finally
        {
            Conn.Close();
        }

        return result;
    }
Example #34
0
        /// <summary>
        /// Prepare poll answer search model
        /// </summary>
        /// <param name="searchModel">Poll answer search model</param>
        /// <param name="poll">Poll</param>
        /// <returns>Poll answer search model</returns>
        protected virtual PollAnswerSearchModel PreparePollAnswerSearchModel(PollAnswerSearchModel searchModel, Poll poll)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            if (poll == null)
            {
                throw new ArgumentNullException(nameof(poll));
            }

            searchModel.PollId = poll.Id;

            //prepare page parameters
            searchModel.SetGridPageSize();

            return(searchModel);
        }
Example #35
0
        private void PopulateControls()
        {
            if (currentModule == null) return;

            lnkPageCrumb.Text = currentModule.ModuleTitle;

            lnkPolls.Text = string.Format(CultureInfo.InvariantCulture,
                PollResources.ChooseActivePollFormatString,
                currentModule.ModuleTitle);

            if (IsPostBack) return;
            if (Page.IsCallback) return;

            if (pollGuid == Guid.Empty)
            {
                btnDelete.Visible = false;
                btnActivateDeactivate.Visible = false;
                btnAddNewPoll.Visible = false;
                if (timeZone != null)
                {
                    dpActiveFrom.Text = DateTimeHelper.LocalizeToCalendar(DateTime.UtcNow.ToLocalTime(timeZone).ToString("g"));
                    dpActiveTo.Text = DateTimeHelper.LocalizeToCalendar(DateTime.UtcNow.AddYears(1).ToLocalTime(timeZone).ToString("g"));
                }
                else
                {
                    dpActiveFrom.Text = DateTimeHelper.LocalizeToCalendar(DateTime.UtcNow.AddHours(timeOffset).ToString("g"));
                    dpActiveTo.Text = DateTimeHelper.LocalizeToCalendar(DateTime.UtcNow.AddYears(1).AddHours(timeOffset).ToString("g"));
                }

                return;
            }

            lblStartDeactivated.Visible = false;
            chkStartDeactivated.Visible = false;

            Poll poll = new Poll(pollGuid);

            txtQuestion.Text = poll.Question;
            chkAllowViewingResultsBeforeVoting.Checked = poll.AllowViewingResultsBeforeVoting;
            chkAnonymousVoting.Checked = poll.AnonymousVoting;
            chkShowOrderNumbers.Checked = poll.ShowOrderNumbers;
            chkShowResultsWhenDeactivated.Checked = poll.ShowResultsWhenDeactivated;

            if (timeZone != null)
            {
                dpActiveFrom.Text = DateTimeHelper.LocalizeToCalendar(poll.ActiveFrom.ToLocalTime(timeZone).ToString("g"));
                dpActiveTo.Text = DateTimeHelper.LocalizeToCalendar(poll.ActiveTo.ToLocalTime(timeZone).ToString("g"));
            }
            else
            {
                dpActiveFrom.Text = DateTimeHelper.LocalizeToCalendar(poll.ActiveFrom.AddHours(timeOffset).ToString("g"));
                dpActiveTo.Text = DateTimeHelper.LocalizeToCalendar(poll.ActiveTo.AddHours(timeOffset).ToString("g"));
            }

            List<PollOption> pollOptions = PollOption.GetOptionsByPollGuid(pollGuid);
            ListItem li;
            foreach(PollOption option in pollOptions)
            {
                li = new ListItem(option.Answer, option.OptionGuid.ToString());
                lbOptions.Items.Add(li);
            }

            if (poll.Activated)
            {
                btnActivateDeactivate.Text = PollResources.PollEditDeactivateButton;
                btnActivateDeactivate.ToolTip = PollResources.PollEditDeactivateToolTip;
                btnActivateDeactivate.CommandName = "Deactivate";
            }
            else
            {
                btnActivateDeactivate.Text = PollResources.PollEditActivateButton;
                btnActivateDeactivate.ToolTip = PollResources.PollEditActivateToolTip;
                btnActivateDeactivate.CommandName = "Activate";
            }
            btnActivateDeactivate.CommandArgument = poll.PollGuid.ToString();
        }
Example #36
0
        public IActionResult CreatePoll([FromQuery] string question,
                                        [FromQuery] int selectableOptionsCount,
                                        [FromQuery] DateTime?limitDate,
                                        [FromBody] ICollection <String> options) //2020-02-02T22:15:57Z
        {
            try
            {
                // Make sure to use the same instant of time to compute all validations
                DateTime now = DateTime.Now;

                // Validate question string size
                if (question.Length < 5)
                {
                    return(BadRequest("Question text too little, request refused."));
                }

                // Check if there is another active poll with the same name
                if (_database.Polls.FirstOrDefault(p => p.QuestionText == question && now < p.CloseDate) != null)
                {
                    return(BadRequest("There is already an active poll with that alias. Try another question."));
                }

                // validate selectableOptionsCount (at least 1 option should be selected on voting)
                if (selectableOptionsCount < 1)
                {
                    return(BadRequest("Invalid argument selectableOptionsCount, must be one (1) or greater."));
                }

                // check if request sent at least 2 options and at max 30 options
                if (options.Count < 2 || options.Count > 30)
                {
                    return(BadRequest("A poll should have from two (2) to thirty (30) options."));
                }

                limitDate ??= now.AddDays(30); // default limit date to 30 days after created

                // check if sent an already outdated close date
                if (limitDate <= now)
                {
                    return(BadRequest($"Outdated close date {limitDate}. Server Timezone is {TimeZoneInfo.Local}."));
                }

                // check minimum date
                if (limitDate <= now.AddMinutes(1))
                {
                    return(BadRequest($"Poll should have a minimum 1 minute duration. Date sent: {limitDate}. Make sure it is timezone +0."));
                }

                // check maximum date
                else if (limitDate > now.AddDays(30))
                {
                    return(BadRequest($"Poll should have a maximum 30 days duration. Date sent: {limitDate}. Make sure it is timezone +0."));
                }

                Poll p = new Poll
                {
                    QuestionText           = question,
                    SelectableOptionsCount = selectableOptionsCount,
                    CloseDate     = (DateTime)limitDate,
                    CreatorUserIp = Request.HttpContext.Connection.RemoteIpAddress.ToString()
                };
                _database.Polls.Add(p);

                int i = 1;
                foreach (var optext in options)
                {
                    _database.PollOptions.Add(
                        new PollOption()
                    {
                        Poll           = p, // foreign key reference
                        PollOptionText = optext,
                        PollOptionId   = i
                    }
                        );
                    i++;
                }
                _database.SaveChanges();
                return(new ContentResult {
                    Content = GetPollJsonWithOptions(p).ToString(Formatting.None), ContentType = "application/json"
                });
            }
            catch (DbUpdateException due)
            {
                return(BadRequest("Error updating data to data source. Check your request parameters.\nStack trace: " + due.StackTrace.ToString()));
            }
            catch (Exception e)
            {
                return(BadRequest("Error from server. Check your request parameters.\nStack trace: " + e.StackTrace.ToString()));
            }
        }
Example #37
0
        public Group_PollStatusViewModel(Poll poll)
        {
            if (UserContext.Current != null)
            {
                var userId = UserContext.Current.Id;

                var gm =
                    DataService.PerThread.GroupMemberSet.FirstOrDefault(
                        x => x.UserId == userId && x.GroupId == poll.GroupId);

                if (gm != null)
                {
                    var bulletin = DataService.PerThread.BulletinSet.OfType <PollBulletin>().FirstOrDefault(
                        x => x.OwnerId == gm.Id && x.PollId == poll.Id);

                    if (bulletin != null)
                    {
                        PollBulletinId = bulletin.Id.ToString();
                    }
                }
            }

            ReportsUrl = "\\MediaContent\\Reports\\" + poll.Id + ".csv";

            if (poll != null)
            {
                PollId            = poll.Id;
                ParticipantsCount = poll.Bulletins.Count;
                HasOpenProtocol   = poll.HasOpenProtocol;

                if (poll.PublishDate.HasValue)
                {
                    StartDate  = poll.PublishDate.Value;
                    FinishDate = poll.PublishDate.Value.AddDays(poll.Duration.Value);
                    IsFinished = poll.IsFinished;
                    if (IsFinished)
                    {
                        switch ((VoteOption)poll.Result)
                        {
                        case VoteOption.Yes: VoteResult = "<span class='vote yes'>Решение принято положительно</span>"; break;

                        case VoteOption.No: VoteResult = "<span class='vote no'>Решение принято отрицательно</span>"; break;

                        case VoteOption.Refrained: VoteResult = "<span class='vote forefit'>Решение не принято</span>"; break;

                        case VoteOption.NotVoted: VoteResult = "<span class='vote not'>В связи с низкой явкой, <span>голосование не состоялось</span></span>"; break;
                        }
                    }
                    else
                    {
                        var ts = FinishDate - DateTime.Now;
                        TimeRemaing = string.Format("{0} дней {1:00}:{2:00}:{3:00}", (int)ts.TotalDays, ts.Hours, ts.Minutes, ts.Seconds);
                        SecondsLeft = (int)ts.TotalSeconds;
                    }
                }

                if (ParticipantsCount > 0)
                {
                    foreach (var result in poll.Bulletins)
                    {
                        if (result.Result != (byte)VoteOption.NotVoted)
                        {
                            if (result.Result == (byte)VoteOption.Yes)
                            {
                                PositiveVotes += result.Weight;
                            }
                            if (result.Result == (byte)VoteOption.No)
                            {
                                NegativeVotes += result.Weight;
                            }
                            if (result.Result == (byte)VoteOption.Refrained)
                            {
                                ForefitVotes += result.Weight;
                            }

                            TookPart += result.Weight;
                        }
                    }
                    NotVoted = ParticipantsCount - TookPart;

                    double temp = 0;
                    temp = PositiveVotes;
                    RelativePositiveVotes = (int)Math.Round(100 * temp / ParticipantsCount, 0, MidpointRounding.ToEven);
                    temp = NegativeVotes;
                    RelativeNegativeVotes = (int)Math.Round(100 * temp / ParticipantsCount, 0, MidpointRounding.ToEven);
                    temp = ForefitVotes;
                    RelativeForefitVotes = (int)Math.Round(100 * temp / ParticipantsCount, 0, MidpointRounding.ToEven);
                    temp             = NotVoted;
                    RelativeNotVoted = (int)Math.Round(100 * temp / ParticipantsCount, 0, MidpointRounding.ToEven);

                    poll.Bulletins.OrderByDescending(x => x.Weight).Take(5);
                }
            }
        }
Example #38
0
        public async Task <Note> CreateAsync(string text            = null, string visibility = null, List <string> visibleUserIds = null, string cw = null, bool?viaMobile = null, Geo geo = null, List <string> fileIds = null, string replyId = null, string renoteId = null, Poll poll = null, bool?localOnly = null,
                                             bool?noExtractMentions = null, bool?noExtractHashtags = null, bool?noExtractEmojis    = null)
        {
            var parameters = new List <KeyValuePair <string, object> >();

            parameters.AddIfValidValue("text", text);
            parameters.AddIfValidValue("visibility", visibility);
            parameters.AddIfValidValue("visibleUserIds", visibleUserIds);
            parameters.AddIfValidValue("cw", cw);
            parameters.AddIfValidValue("viaMobile", viaMobile);
            parameters.AddIfValidValue("geo", geo);
            parameters.AddIfValidValue("fileIds", fileIds);
            parameters.AddIfValidValue("replyId", replyId);
            parameters.AddIfValidValue("renoteId", renoteId);
            parameters.AddIfValidValue("poll", poll);
            parameters.AddIfValidValue("localOnly", localOnly);
            parameters.AddIfValidValue("noExtractMentions", noExtractMentions);
            parameters.AddIfValidValue("noExtractHashtags", noExtractHashtags);
            parameters.AddIfValidValue("noExtractEmojis", noExtractEmojis);

            var response = await PostAsync <ApiResponse>("/create", parameters).Stay();

            return(response.Extends["createdNote"].ToObject <Note>());
        }
 public static Poll ToEntity(this PollModel model, Poll destination)
 {
     return(model.MapTo(destination));
 }
 public PollsEditTemplateHelper(Poll inRecord) : base(inRecord)
 {
 }
Example #41
0
 /// <inheritdoc />
 public Poll Add(Poll poll)
 {
     poll.DateCreated = DateTime.Now;
     poll.IsClosed    = false;
     return(_context.Poll.Add(poll));
 }
Example #42
0
        /// <summary>
        /// The bind data.
        /// </summary>
        private void BindData()
        {
            this.pollAndChoices = this.GetRepository <Poll>().GetPollAndChoices(this.PollId.Value);

            this.poll = this.pollAndChoices.FirstOrDefault().Item1;

            // if the page user can change the poll. Only a group owner, forum moderator  or an admin can do it.   );
            this.canChange = this.poll.UserID == this.PageContext.PageUserID || this.PageContext.IsAdmin ||
                             this.PageContext.ForumModeratorAccess;

            if (this.pollAndChoices.Any())
            {
                // Check if the user is already voted in polls in the group
                this.userPollVotes = this.GetRepository <PollVote>().VoteCheck(this.poll.ID, this.PageContext.PageUserID);

                // We don't display poll command row to everyone
                this.PollCommandRow.Visible = this.HasOwnerExistingGroupAccess();

                this.QuestionLabel.Text = this.HtmlEncode(this.Get <IBadWordReplace>().Replace(this.poll.Question));

                this.TotalVotes.Text = this.pollAndChoices.Sum(x => x.Item2.Votes).ToString();

                this.EditPoll.Visible   = this.CanEditPoll();
                this.CreatePoll.Visible = this.CanCreatePoll();

                // Binding question image
                this.BindPollQuestionImage();

                var pollChoiceList = this.PollChoiceList1;

                var isNotVoted = this.userPollVotes.Any();

                pollChoiceList.UserPollVotes = this.userPollVotes;

                // If guest are not allowed to view options we don't render them
                pollChoiceList.Visible = !(!this.HasVoteAccess() && isNotVoted &&
                                           this.PageContext.IsGuest);

                // This is not a guest w/o poll option view permissions, we bind the control.
                if (pollChoiceList.Visible)
                {
                    pollChoiceList.DataSource = this.pollAndChoices;
                }

                if (this.poll.PollFlags.ShowVoters)
                {
                    pollChoiceList.Voters = this.GetRepository <PollVote>().Voters(this.poll.ID);
                }

                pollChoiceList.PollId = this.poll.ID;
                pollChoiceList.Votes  = this.pollAndChoices.Sum(x => x.Item2.Votes);

                // returns number of day to run - null if poll has no expiration date
                var daysToRun    = this.DaysToRun(out var closesSoon);
                var isPollClosed = this.IsPollClosed();

                var isClosedBound = this.poll.Closes.HasValue && this.poll.PollFlags.IsClosedBound &&
                                    this.poll.Closes.Value < DateTime.UtcNow;

                if (isClosedBound && isPollClosed)
                {
                    this.showResults = true;
                }

                if (!isClosedBound)
                {
                    this.showResults = true;
                }

                // The poll had an expiration date and expired without voting
                // show results anyway if poll has no expiration date days to run is null
                if (daysToRun == 0)
                {
                    this.showResults = true;
                }

                pollChoiceList.HideResults = !this.showResults;

                // Clear the fields after the child repeater is bound
                this.showResults = false;

                // Add confirmations to delete buttons
                this.RemovePoll.Visible = this.CanRemovePoll();

                // *************************
                // Poll warnings section
                // *************************
                var notificationString = new StringBuilder();

                if (this.PageContext.IsGuest)
                {
                    notificationString.Append(this.GetText("POLLEDIT", "POLLOPTIONSHIDDEN_GUEST"));
                }
                else
                {
                    // Here warning labels are treated
                    if (this.poll.PollFlags.AllowMultipleChoice)
                    {
                        notificationString.Append(this.GetText("POLLEDIT", "POLL_MULTIPLECHOICES_INFO"));
                    }
                }

                if (!isNotVoted && this.PageContext.ForumVoteAccess)
                {
                    notificationString.AppendFormat(" {0}", this.GetText("POLLEDIT", "POLL_VOTED"));
                }

                // Poll has expiration date
                if (daysToRun > 0)
                {
                    notificationString.AppendFormat(
                        " {0}",
                        !closesSoon
                            ? this.GetTextFormatted("POLL_WILLEXPIRE", daysToRun)
                            : this.GetText("POLLEDIT", "POLL_WILLEXPIRE_HOURS"));

                    if (isClosedBound)
                    {
                        notificationString.AppendFormat(" {0}", this.GetText("POLLEDIT", "POLL_CLOSEDBOUND"));
                    }
                }
                else if (daysToRun == 0)
                {
                    notificationString.Clear();
                    notificationString.Append(this.GetText("POLLEDIT", "POLL_EXPIRED"));

                    this.PollClosed.Text =
                        $"<span class=\"badge bg-danger ms-1\"><i class=\"fa fa-lock fa-fw\"></i>&nbsp;{this.GetText("POLLEDIT", "POLL_CLOSED")}</span>";
                    this.PollClosed.Visible = true;
                }

                pollChoiceList.CanVote   = this.HasVoteAccess() && isNotVoted;
                pollChoiceList.DaysToRun = daysToRun;

                // we should double bind if it is not a vote event bubble.
                if (this.isVoteEvent)
                {
                    pollChoiceList.DataBind();
                }

                pollChoiceList.ChoiceVoted += this.VoteBubbleEvent;

                var notification = notificationString.ToString();

                // we don't display warnings row if no info
                if (notification.IsSet())
                {
                    this.PollNotification.Text = notification;
                    this.Alert.Visible         = true;
                }

                // we hide new poll row if a poll exist
                this.NewPollRow.Visible = false;
            }

            this.DataBind();
        }
Example #43
0
 void OnPoll(Poll poll, PollStatus status)
 {
     poll.CloseHandle(this.OnClose);
     this.pollCount++;
 }
Example #44
0
        public PollModelResponse Build(Poll poll)
        {
            var questions = _questionsModelResponseBuilder.Build(poll.Questions);

            return(new PollModelResponse(poll.Id, poll.Title, questions));
        }
Example #45
0
 //news items
 public static PollModel ToModel(this Poll entity)
 {
     return(Mapper.Map <Poll, PollModel>(entity));
 }
    /**
     * Create the card
     */
    public GameObject CreateCard()
    {
        Counter = GameObject.FindGameObjectWithTag("GameController").GetComponent<Poll>();
        Counter.ClearCount(ListNumber);
        bool placeholder = true;
        foreach (Transform objectTransform in GameObject.Find("Main_Canvas").transform) {
            if (objectTransform.name.Equals("EventCard(Clone)")) {
                placeholder = false;
                break;
            }
        }

        if (placeholder) { // An event card already exists
            Card = Instantiate(Resources.Load("EventCard")) as GameObject;
            GameObject UI = GameObject.Find("Main_Canvas");
            Card.transform.SetParent(UI.transform, false);
            ChangeCard();
        }

        return Card;
    }
Example #47
0
        public ActionResult Create()
        {
            var poll = new Poll();

            return(ViewOrPartialView(poll));
        }
Example #48
0
        public AttachmentsItem(double width, Thickness margin, List <Attachment> attachments, Geo geo, string itemId, bool friendsOnly = false, bool isCommentAttachments = false, bool isMessage = false, bool isHorizontal = false, double horizontalWidth = 0.0, bool rightAlign = false, bool wallPostWithCommentsPage = false, string hyperlinkId = "")
            : base(width, margin, new Thickness())
        {
            this._hyperlinkId            = hyperlinkId;
            this._itemId                 = itemId;
            this._attachments            = attachments ?? new List <Attachment>();
            this._gifAttachments         = new List <Attachment>();
            this._photoAttachments       = new List <Attachment>();
            this._videoAttachments       = new List <Attachment>();
            this._albumAttachments       = new List <Attachment>();
            this._marketAlbumAttachments = new List <Attachment>();
            this._audioAttachments       = new List <Attachment>();
            this._docImageAttachments    = new List <Attachment>();
            if (this._attachments != null)
            {
                foreach (Attachment attachment in this._attachments)
                {
                    string type = attachment.type;

                    //uint stringHash = PrivateImplementationDetails.ComputeStringHash(type);

                    /*
                     * if (stringHash <= 2322801903U)
                     * {
                     * if (stringHash <= 1665450665U)
                     * {
                     * if ((int) stringHash != 232457833)
                     * {
                     *  if ((int) stringHash != 611394536)
                     *  {
                     *    if ((int) stringHash == 1665450665 && type == "market_album")
                     *    {
                     *      this._marketAlbumAttachments.Add(attachment);
                     *      continue;
                     *    }
                     *    continue;
                     *  }
                     *  if (!(type == "wall_ads"))
                     *    continue;
                     * }
                     * else
                     * {
                     *  if (type == "link")
                     *  {
                     *    Link link = attachment.link;
                     *    if ((link != null ? link.photo : (Photo) null) != null && link.photo.width > 0 && link.photo.height > 0)
                     *    {
                     *      this._link = link;
                     *      continue;
                     *    }
                     *    continue;
                     *  }
                     *  continue;
                     * }
                     * }
                     * else
                     * {
                     * if (stringHash <= 1876330552U)
                     * {
                     *  if ((int) stringHash != 1694181484)
                     *  {
                     *    if ((int) stringHash == 1876330552 && type == "poll")
                     *    {
                     *      this._poll = attachment.poll;
                     *      continue;
                     *    }
                     *    continue;
                     *  }
                     *  if (type == "album")
                     *  {
                     *    this._albumAttachments.Add(attachment);
                     *    continue;
                     *  }
                     *  continue;
                     * }
                     * if ((int) stringHash != -2128144669)
                     * {
                     *  if ((int) stringHash == -1972165393 && type == "gift")
                     *  {
                     *    this._giftAttachment = attachment.gift;
                     *    continue;
                     *  }
                     *  continue;
                     * }
                     * if (type == "photo")
                     * {
                     *  this._photoAttachments.Add(attachment);
                     *  continue;
                     * }
                     * continue;
                     * }
                     * }
                     * else if (stringHash <= 3343004700U)
                     * {
                     * if ((int) stringHash != -1490670315)
                     * {
                     * if ((int) stringHash != -1242026383)
                     * {
                     *  if ((int) stringHash == -951962596 && type == "sticker")
                     *  {
                     *    this._sticker = attachment.sticker;
                     *    continue;
                     *  }
                     *  continue;
                     * }
                     * if (type == "market")
                     * {
                     *  this._product = attachment.market;
                     *  continue;
                     * }
                     * continue;
                     * }
                     * if (!(type == "wall"))
                     * continue;
                     * }
                     * else
                     * {
                     * if (stringHash <= 3472427884U)
                     * {
                     * if ((int) stringHash != -896901342)
                     * {
                     *  if ((int) stringHash == -822539412 && type == "video")
                     *  {
                     *    this._videoAttachments.Add(attachment);
                     *    continue;
                     *  }
                     *  continue;
                     * }
                     * if (type == "wall_reply")
                     * {
                     *  this._commentAttachment = attachment.wall_reply;
                     *  continue;
                     * }
                     * continue;
                     * }
                     * if ((int) stringHash != -530499175)
                     * {
                     * if ((int) stringHash == -362233003 && type == "doc")
                     * {
                     *  if (!attachment.doc.IsVideoGif)
                     *  {
                     *    if (new DocumentHeader(attachment.doc, 0, false).HasThumbnail)
                     *    {
                     *      this._docImageAttachments.Add(attachment);
                     *      continue;
                     *    }
                     *    continue;
                     *  }
                     *  this._gifAttachments.Add(attachment);
                     *  continue;
                     * }
                     * continue;
                     * }
                     * if (type == "audio")
                     * {
                     * this._audioAttachments.Add(attachment);
                     * continue;
                     * }
                     * continue;
                     * }*/
                    if (type == "photo")
                    {
                        this._photoAttachments.Add(attachment);
                        continue;
                    }
                    else if (type == "link")
                    {
                        Link link = attachment.link;
                        if ((link != null ? link.photo : null) != null && link.photo.width > 0 && link.photo.height > 0)
                        {
                            this._link = link;
                            continue;
                        }
                        continue;
                    }
                    else if (type == "audio")
                    {
                        this._audioAttachments.Add(attachment);
                        continue;
                    }
                    else if (type == "doc")
                    {
                        if (attachment.doc.IsGraffiti)// UPDATE: 4.8.0
                        {
                            this._graffitiDoc = attachment.doc;
                            continue;
                        }
                        if (!attachment.doc.IsVideoGif)
                        {
                            if (new DocumentHeader(attachment.doc, 0, false).HasThumbnail)
                            {
                                this._docImageAttachments.Add(attachment);
                                continue;
                            }
                            continue;
                        }
                        this._gifAttachments.Add(attachment);
                        continue;
                    }
                    else if (type == "video")
                    {
                        this._videoAttachments.Add(attachment);
                        continue;
                    }
                    else if (type == "wall_reply")
                    {
                        this._commentAttachment = attachment.wall_reply;
                        continue;
                    }
                    else if (type == "album")
                    {
                        this._albumAttachments.Add(attachment);
                        continue;
                    }
                    else if (type == "poll")
                    {
                        this._poll = attachment.poll;
                        continue;
                    }
                    else if (type == "gift")
                    {
                        this._giftAttachment = attachment.gift;
                        continue;
                    }
                    else if (type == "sticker")
                    {
                        this._sticker = attachment.sticker;
                        continue;
                    }
                    else if (type == "market")
                    {
                        this._product = attachment.market;
                        continue;
                    }
                    else if (type == "market_album")
                    {
                        this._marketAlbumAttachments.Add(attachment);
                        continue;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("AttachmentsItem.AttachmentsItem " + type);
                    }

                    this._wallAttachment = attachment.wall;
                }
            }
            this._geo                      = geo;
            this._friendsOnly              = friendsOnly;
            this._isCommentAttachments     = isCommentAttachments;
            this._isMessage                = isMessage;
            this._isHorizontal             = isHorizontal;
            this._horizontalWidth          = horizontalWidth;
            this._verticalWidth            = width;
            this._wallPostWithCommentsPage = wallPostWithCommentsPage;
            this._rightAlign               = rightAlign;
            if (this._isHorizontal)
            {
                this.Width = horizontalWidth;
            }
            this.CreateOrUpdateLayout();
        }
Example #49
0
        private void dlPolls_ItemCommand(object source, DataListCommandEventArgs e)
        {
            Poll poll;

            switch (e.CommandName)
            {

                case "Choose":

                    Guid pollGuid = new Guid(e.CommandArgument.ToString());
                    poll = new Poll(pollGuid);
                    poll.AddToModule(moduleId);

                    WebUtils.SetupRedirect(this, Request.RawUrl);
                    return;

                    //break;

                case "Copy":
                    poll = new Poll(new Guid(e.CommandArgument.ToString()));
                    Poll newPoll;
                    if (poll.CopyToNewPoll(out newPoll))
                    {
                        WebUtils.SetupRedirect(this, SiteRoot
                            + "/Poll/PollEdit.aspx?PollGuid="
                            + newPoll.PollGuid.ToString()
                            + "&pageid="
                            + pageId.ToString(CultureInfo.InvariantCulture)
                            + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                            );

                        return;
                    }

                    break;

            }
        }
Example #50
0
 public async Task SendPollToGroup(Poll poll)
 {
     await Clients.Groups(poll.Id.ToString()).SendAsync("UpdatePoll", poll);
 }
Example #51
0
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string redirectPage = string.Empty;
        try
        {
            Poll pollInfo = new Poll();

            pollInfo.TitleAr = txtQuestionAr.Text.Trim();
            pollInfo.TitleEn = txtQuestionEn.Text.Trim();

            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                pollInfo.ID = Convert.ToInt32(Request.QueryString["ID"]);

                if (pollOperator.UpdatePoll(pollInfo))
                {
                    redirectPage = Utility.AppendQueryString(PagesPathes.ConfirmUpdate, new KeyValue(CommonStrings.BackUrl, CommonStrings.PollList));
                }
            }
            else
            {
                pollInfo.Options = optionsList;

                if (pollOperator.AddPoll(pollInfo))
                {
                    redirectPage = Utility.AppendQueryString(PagesPathes.ConfirmInsert, new KeyValue(CommonStrings.BackUrl, CommonStrings.PollAdd));
                }
            }
        }
        catch
        {
            redirectPage = Utility.AppendQueryString(PagesPathes.ErrorPage, new KeyValue(CommonStrings.BackUrl, CommonStrings.AdminDefault));
        }
        finally
        {
            Response.Redirect(redirectPage);
        }
    }
Example #52
0
 public async Task JoinPollGroup(Poll poll)
 {
     await Groups.AddToGroupAsync(Context.ConnectionId, poll.Id.ToString());
 }
Example #53
0
 static void buildCandidateStructure()
 {
     //build map Dictionary
     int numAttributes = (intermediaryMap.GetUpperBound(1) - 1) / 2;
     for (int i = 0; i <= intermediaryMap.GetUpperBound(0); i++)
     {
             //build poll container, key value pair with key date and value poll occurring on that date
             Score[] scores = new Score[numAttributes];
             for (int j = 0; j < numAttributes-1; j++) {
                 var candidate = candidates.FirstOrDefault(c => c.name == intermediaryMap[i, (j+j+3)]);
                 string v = intermediaryMap[i, 2];
                 string percent = intermediaryMap[i, (j + j + 4)];
                 if (candidate != null && percent != null && v != null) {
                     if (percent != "" && v != "") {
                         float voters = float.Parse(v);
                         float perc = float.Parse(percent);
                         //if (voters <= perc)
                             //print(intermediaryMap[i, 0] + " " + intermediaryMap[i,1] + " " + candidate.name + ": Votes: " + percent + " out of " + voters);
                         scores[j] = new Score(((perc/voters)*100).ToString(), candidate);
                     }
                 }
             }
             if (intermediaryMap[i, 0] != null) {
             //print (intermediaryMap[i, 0]);
             //print (intermediaryMap[i, 1]);
                 Poll poll = new Poll(intermediaryMap[i, 1],intermediaryMap[i, 0],scores);
                 //print (poll.date);
                 if (pollByDate.ContainsKey(poll.date)) {
                     pollByDate[poll.date].Add(poll);
                 } else {
                     List<Poll> list = new List<Poll>();
                     list.Add(poll);
                     pollByDate.Add(poll.date, list);
                 }
             }
     }
     //build coaster Dictionary
     numAttributes = (intermediaryCoaster.GetUpperBound(1) - 1) / 2;
     for (int i = 0; i <= intermediaryCoaster.GetUpperBound(0); i++)
     {
         //build poll container, key value pair with key date and value poll occurring on that date
         Score[] scores = new Score[numAttributes];
         for (int j = 0; j < numAttributes-1; j++) {
             var candidate = candidates.FirstOrDefault(c => c.name == intermediaryCoaster[i, (j+j+2)]);
             string v = intermediaryCoaster[i, 1];
             string percent = intermediaryCoaster[i, (j + j + 3)];
             if (candidate != null && percent != null && v != null) {
                 if (percent != "" && v != "") {
                     float voters = float.Parse(v);
                     float perc = float.Parse(percent);
                     //if (voters <= perc)
                     //print(intermediaryMap[i, 0] + " " + intermediaryMap[i,1] + " " + candidate.name + ": Votes: " + percent + " out of " + voters);
                     //if (intermediaryCoaster[i, 0].Equals("2010-10-28"))
                     //	print(intermediaryCoaster[i, 0] + " " + candidate.name + " " + perc + " " + voters + " " + (perc/voters)*100);
                     scores[j] = new Score(((perc/voters)*100).ToString(), candidate);
                 }
             }
         }
         if (intermediaryCoaster[i, 0] != null) {
             Poll poll = new Poll("USA",intermediaryCoaster[i, 0],scores);
             //print (poll.date);
             if (pollByDateCoaster.ContainsKey(poll.date)) {
                 pollByDateCoaster[poll.date] = poll;
             } else {
                 pollByDateCoaster.Add(poll.date, poll);
             }
         }
     }
 }
Example #54
0
 public async Task LeavePollGroup(Poll poll)
 {
     await Groups.RemoveFromGroupAsync(Context.ConnectionId, poll.Id.ToString());
 }
Example #55
0
 public void CreatePoll(Poll poll)
 {
     poll.CreationDate = DateTime.Now;
     this.catalog.Polls.Create(poll);
 }
Example #56
0
        public virtual IEnumerator<ITask> PollHandler(Poll poll)
        {
            Substate updated = _state.Update(DateTime.Now);

            if ((updated & Substate.Axes) != Substate.None)
            {
                SendNotification<UpdateAxes>(_subMgr, _state.Axes);
            }
            if ((updated & Substate.Buttons) != Substate.None)
            {
                SendNotification<UpdateButtons>(_subMgr, _state.Buttons);
            }
            if ((updated & Substate.PovHats) != Substate.None)
            {
                SendNotification<UpdatePovHats>(_subMgr, _state.PovHats);
            }
            if ((updated & Substate.Sliders) != Substate.None)
            {
                SendNotification<UpdateSliders>(_subMgr, _state.Sliders);
            }

            poll.ResponsePort.Post(DefaultSubmitResponseType.Instance);
            yield break;
        }
Example #57
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            Page.Validate("poll");
            if (Page.IsValid)
            {
                Poll poll = new Poll(pollGuid);
                poll.SiteGuid = siteSettings.SiteGuid;
                poll.Question = txtQuestion.Text;
                poll.AnonymousVoting = chkAnonymousVoting.Checked;
                poll.AllowViewingResultsBeforeVoting = chkAllowViewingResultsBeforeVoting.Checked;
                poll.ShowOrderNumbers = chkShowOrderNumbers.Checked;
                poll.ShowResultsWhenDeactivated = chkShowResultsWhenDeactivated.Checked;

                if (dpActiveFrom.Text.Length > 0 && poll.ActiveFrom >= DateTime.UtcNow)
                {
                    // You can't change date if poll has started.

                    // TODO: promt user if invalid format/date

                    DateTime activeFrom;
                    DateTime.TryParse(dpActiveFrom.Text, out activeFrom);

                    if (timeZone != null)
                    {
                        activeFrom = activeFrom.ToUtc(timeZone);
                    }
                    else
                    {
                        activeFrom = activeFrom.AddHours(-timeOffset);
                    }

                    poll.ActiveFrom = activeFrom;
                }

                if (dpActiveTo.Text.Length > 0)
                {
                    // TODO: promt user if invalid format/date
                    DateTime activeTo;
                    DateTime.TryParse(dpActiveTo.Text, out activeTo);

                    if (timeZone != null)
                    {
                        activeTo = activeTo.ToUtc(timeZone);
                    }
                    else
                    {
                        activeTo = activeTo.AddHours(-timeOffset);
                    }

                    // Make time 23:59:59
                    //activeTo = activeTo.AddHours(23).AddMinutes(59).AddSeconds(59);

                    // You can't change to past date.
                    if (activeTo >= DateTime.UtcNow)
                    {
                        poll.ActiveTo = activeTo;
                    }
                }

                if (chkStartDeactivated.Checked)
                {
                    // This only happens when new poll.
                    poll.Deactivate();
                }
                else
                {
                    poll.Activate();
                }

                poll.Save();

                // Get options
                PollOption option;
                int order = 1;
                foreach (ListItem item in lbOptions.Items)
                {
                    if (item.Text == item.Value)
                    {
                        option = new PollOption();
                    }
                    else
                    {
                        if (item.Value.Length == 36)
                        {
                            option = new PollOption(new Guid(item.Value));
                        }
                        else
                        {
                            option = new PollOption();
                        }
                    }

                    option.PollGuid = poll.PollGuid;
                    option.Answer = item.Text;
                    option.Order = order++;
                    option.Save();
                }

                WebUtils.SetupRedirect(this,
                    SiteRoot + "/Poll/PollChoose.aspx"
                    + "?pageid=" + pageId.ToInvariantString()
                    + "&mid=" + moduleId.ToInvariantString()
                    );

            }
        }
Example #58
0
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel();

            #region BindingOnly
            kernel.Bind <IPollRepository>().To <PollRepository>();
            kernel.Bind <IRegionRepository>().To <RegionRepository>();
            kernel.Bind <IUserRepository>().To <UserRepository>();
            kernel.Bind <IVoteRepository>().To <VoteRepository>();

            kernel.Bind <IManagePolicy>().To <ManagePolicy>();
            kernel.Bind <IPolicyChecker>().To <PolicyChecker>();
            kernel.Bind <IPollService>().To <PollService>();
            kernel.Bind <IRegistrationUserService>().To <RegistrationUserService>();
            kernel.Bind <IVoteService>().To <VoteService>();


            UserRepository      userRepository      = new UserRepository();
            ContextRegistration contextRegistration = new ContextRegistration(userRepository);
            var              managePolicy           = new ManagePolicy(userRepository);
            VoteRepository   voteRepository         = new VoteRepository();
            RegionRepository regionRepository       = new RegionRepository();
            PollRepository   pollRepository         = new PollRepository();
            PolicyChecker    policyChecker          = new PolicyChecker(userRepository, contextRegistration);
            VoteService      voteService            = new VoteService(voteRepository, pollRepository, contextRegistration);
            PollService      pollService            = new PollService(contextRegistration, regionRepository,
                                                                      pollRepository, managePolicy,
                                                                      voteService, policyChecker, voteRepository);
            UserInterface            userInterface           = new UserInterface(userRepository, contextRegistration, pollRepository, policyChecker);
            IRegistrationUserService registrationUserService = new RegistrationUserService(contextRegistration,
                                                                                           voteRepository,
                                                                                           regionRepository,
                                                                                           userRepository);
            #endregion
            while (true)
            {
                Console.Clear();
                System.Console.WriteLine($"Hello, Person. Here's some service for you to make your own choice for the future of your country \n" +
                                         $"Please enter your passport data to verify your identity:");
                string passport = Console.ReadLine();
                Console.WriteLine("Now identification code:");
                int indefcode = Int32.Parse(Console.ReadLine());
                contextRegistration.SetPasswordInfo(passport, indefcode);
                //int user_temp_id = userService.GetUserByMainInfo(contextRegistration.GetPassportInfo().Item1, contextRegistration.GetPassportInfo().Item2).Id;
                bool response;
                try
                {
                    response = userRepository.UserExists(contextRegistration.GetPassportInfo().Item1,
                                                         contextRegistration.GetPassportInfo().Item2);
                }
                catch (Exception)
                {
                    Console.WriteLine("We don't have information about you");
                    Console.ReadLine();
                    response = false;
                }
                if (response == false)
                {
                    Console.WriteLine("Sorry, but you are not allowed to vote");
                }
                else
                {
                    bool choice = true;

                    int user_temp_id = userRepository.GetUser(contextRegistration.GetPassportInfo().Item1, contextRegistration.GetPassportInfo().Item2).Id;
                    while (choice)
                    {
                        Console.Clear();
                        Console.WriteLine("Welcome to our service!");
                        Console.WriteLine("Select option:\n" +
                                          "1. Create Poll;\n" +
                                          "2. Add Choice to Poll;\n" +
                                          "3. Vote;\n" +
                                          "4. Give Policy;\n" +
                                          "5. Show poll results;\n" +
                                          "0. Exit this shit;");
                        var answer = Int32.Parse(Console.ReadLine());
                        switch (answer)
                        {
                            #region Create Poll
                        case 1:
                            PollCreationDTO pollCreation = userInterface.CreatePollConsole();
                            pollService.CreatePoll(pollCreation);
                            break;

                            #endregion
                            #region AddChoice
                        case 2:
                            ChoiceCreationDTO choiceCreation = userInterface.CreateChoiceConsole();
                            if (choiceCreation == null)
                            {
                                break;
                            }
                            pollService.CreateChoice(choiceCreation);
                            break;

                            #endregion
                            #region Vote
                        case 3:
                            userInterface.ShowPollsConsole();
                            Console.WriteLine("Choose the poll:");
                            string poll_temp_name         = Console.ReadLine();
                            var    pollPolicyFailedChecks = pollService.CheckAllPolicy(poll_temp_name);
                            if (pollPolicyFailedChecks.Count > 0)
                            {
                                foreach (var a in pollPolicyFailedChecks)
                                {
                                    Console.WriteLine(a.Value);
                                    Console.ReadLine();
                                }
                                break;
                            }

                            Poll poll1 = pollRepository.Get(poll_temp_name);
                            foreach (var a in poll1.Choices)
                            {
                                Console.WriteLine($"{a.Name} \n {a.Description} \n");
                            }
                            Console.WriteLine("Write what you choose:");
                            List <int> allChoices = new List <int>();
                            if (poll1.MutlipleSelection == true)
                            {
                                string option = Console.ReadLine();
                                allChoices.Add(poll1.GetChoiceByName(option).Id);
                                Console.WriteLine("Do you want to choose smth more? (Y/N)");
                                string multipleResponse = Console.ReadLine();
                                while (multipleResponse == "Y")
                                {
                                    option = Console.ReadLine();
                                    allChoices.Add(poll1.GetChoiceByName(option).Id);
                                    Console.WriteLine("Do you want to choose smth more? (Y/N)");
                                    multipleResponse = Console.ReadLine();
                                }
                            }
                            else
                            {
                                string option = Console.ReadLine();
                                allChoices.Add(poll1.GetChoiceByName(option).Id);
                            }

                            voteService.Vote(allChoices);
                            break;

                            #endregion
                            #region Policy
                        case 4:
                            userInterface.ShowPollsConsole();
                            Console.WriteLine("Enter PollName for future policy:");
                            string pollName = Console.ReadLine();

                            int?pollId = pollRepository.GetPollId(pollName);

                            if (pollId == null)
                            {
                                Console.WriteLine("Invalid poll name");
                                Console.ReadLine();
                                break;
                            }

                            bool policyresponse = policyChecker.CheckAdminPolicy(pollId.Value);

                            if (policyresponse == false)
                            {
                                Console.WriteLine("You have no rights to give policy for this poll!");
                                Console.ReadLine();
                                break;
                            }
                            Console.WriteLine("Which rights do you want to give? (Admin/Access)");
                            string answer_for_rights = Console.ReadLine();
                            if (!Enum.TryParse(answer_for_rights, out PolicyType policyType))
                            {
                                Console.WriteLine("F**k you dumbass paralytic idiot who cannot type needed shit!");
                                break;
                            }

                            Console.WriteLine("Enter email for user who you want to give policy:");
                            string email = Console.ReadLine();

                            User user = userRepository.GetUser(email);
                            managePolicy.GivePolicyToUser(user.Id, pollId.Value, policyType);
                            break;

                            #endregion
                            #region Results
                        case 5:
                            userInterface.ShowPollsConsole();
                            Console.WriteLine("Enter Pollname to see the results:");
                            string pollResultName = Console.ReadLine();
                            foreach (var a in voteService.GetPollResult(pollResultName))
                            {
                                Console.WriteLine($"{a.Key.ToString()}  - {a.Value.ToString()} ");
                            }
                            Console.ReadLine();
                            break;

                            #endregion
                            #region Exit
                        case 0:
                            choice = false;
                            break;

                            #endregion
                        default:
                            break;
                        }
                    }
                }
            }
        }
Example #59
0
        protected override void Seed(BlogContext context)
        {
            base.Seed(context);
            var tags = new List <Tag>
            {
                new Tag
                {
                    Name = "tag1"
                },
                new Tag
                {
                    Name = "tag2"
                }
            };
            //tags.ForEach(s=>context.Tags.Add(s));
            //context.SaveChanges();
            // create temp value for add init data for our project
            var articles = new List <Article>
            {
                new Article
                {
                    Name = "Article 1",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Autem voluptate aspernatur incidunt maxime beatae deleniti exercitationem repellat, adipisci tempora repellendus doloremque ratione, laboriosam hic dolores ipsa asperiores illo reiciendis similique ut, eos itaque quasi tempore excepturi? Magnam esse voluptatibus dolor.",
                    Tags = tags.ToList()
                },
                new Article
                {
                    Name = "Article 2",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Autem voluptate aspernatur incidunt maxime beatae deleniti exercitationem repellat, adipisci tempora repellendus doloremque ratione, laboriosam hic dolores ipsa asperiores illo reiciendis similique ut, eos itaque quasi tempore excepturi? Magnam esse voluptatibus dolor.",
                    Tags = tags.ToList()
                },
                new Article
                {
                    Name = "Article 3",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Autem voluptate aspernatur incidunt maxime beatae deleniti exercitationem repellat, adipisci tempora repellendus doloremque ratione, laboriosam hic dolores ipsa asperiores illo reiciendis similique ut, eos itaque quasi tempore excepturi? Magnam esse voluptatibus dolor.",
                    Tags = tags.ToList()
                },
                new Article
                {
                    Name = "Article 4",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Autem voluptate aspernatur incidunt maxime beatae deleniti exercitationem repellat, adipisci tempora repellendus doloremque ratione, laboriosam hic dolores ipsa asperiores illo reiciendis similique ut, eos itaque quasi tempore excepturi? Magnam esse voluptatibus dolor.",
                    Tags = new List <Tag> {
                        new Tag {
                            Name = "TAG3"
                        }
                    }
                }
            };

            // and add entity
            articles.ForEach(s => context.Articles.Add(s));//.Tags.AddRange(tags));
            context.SaveChanges();


            var feedbackItems = new List <FeedBack>
            {
                new FeedBack
                {
                    Name = "Author 1",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Velit in animi, quisquam vel non placeat minus numquam accusamus voluptatibus atque."
                },
                new FeedBack
                {
                    Name = "Author 2",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Velit in animi, quisquam vel non placeat minus numquam accusamus voluptatibus atque."
                },
                new FeedBack
                {
                    Name = "Author 3",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Velit in animi, quisquam vel non placeat minus numquam accusamus voluptatibus atque."
                },
                new FeedBack
                {
                    Name = "Author 4",
                    Date = DateTime.Parse("2019-09-19").ToShortDateString(),
                    Text = "Lorem ipsum dolor sit, amet consectetur adipisicing elit. Velit in animi, quisquam vel non placeat minus numquam accusamus voluptatibus atque."
                },
            };

            feedbackItems.ForEach(s => context.FeedbackItems.Add(s));
            context.SaveChanges();

            Profile profile = new Profile
            {
                ProfilePreview = "На сколько вы человек?",

                Questions = new List <Question>
                {
                    new Question
                    {
                        Text = "Ты человек?"
                    },
                    new Question
                    {
                        Text = "Ты мужчина?"
                    },
                    new Question
                    {
                        Text = "Ты женщина?"
                    }
                }
            };

            var poll = new Poll
            {
                Active        = false,
                Question      = "How you doing?",
                PollOptionses = new List <PollOptions>
                {
                    new PollOptions
                    {
                        Answer = "Ok",
                        Votes  = 100
                    },
                    new PollOptions
                    {
                        Answer = "ne ok",
                        Votes  = 200
                    }
                }
            };

            context.Profiles.Add(profile);
            context.SaveChanges();
            context.Polls.Add(poll);
            context.SaveChanges();
        }
Example #60
0
        public void TestPollAckCommand1()
        {
            string expected = File.ReadAllText("PollAckCommand1.xml");

            var command = new Poll { MessageId = "12345", Type = "ack" };
            command.TransactionId = "ABC-12345";

            Assert.AreEqual(expected, command.ToXml().InnerXml);
        }