Inheritance: System.Web.UI.Page
Ejemplo n.º 1
0
    public bool commitInsert(string _date1, string _date2, string _date3, string _date4, string _title1, string _title2, string _title3, string _title4, string _text1, string _text2, string _text3, string _text4, string _image1, string _image2, string _image3, string _image4)
    {
        newsDataContext objNewsDC = new newsDataContext();
        using (objNewsDC)
        {
            New objNewNew = new New();
            objNewNew.date1 = _date1;
            objNewNew.date2 = _date2;
            objNewNew.date3 = _date3;
            objNewNew.date4 = _date4;
            objNewNew.title1 = _title1;
            objNewNew.title2 = _title2;
            objNewNew.title3 = _title3;
            objNewNew.title4 = _title4;
            objNewNew.text1 = _text1;
            objNewNew.text2 = _text2;
            objNewNew.text3 = _text3;
            objNewNew.text4 = _text4;
            objNewNew.image1 = _image1;
            objNewNew.image2 = _image2;
            objNewNew.image3 = _image3;
            objNewNew.image4 = _image4;

            objNewsDC.News.InsertOnSubmit(objNewNew);
            objNewsDC.SubmitChanges();
            return true;



        }
    }
Ejemplo n.º 2
0
    public static int Insert(NewsModel model)
    {
        try
        {
            using (DataContentDataContext dc = new DataContentDataContext())
            {
                New newItem = new New();
                newItem.Id = model.ID;
                newItem.Title = model.Title;
                newItem.Header = model.Header;
                newItem.Contents = model.Contents;
                newItem.Author = model.Author;
                newItem.Link_Image = model.Link_Image;
                newItem.Link_Image_Small = model.Link_Image_Small;
                newItem.Type_News = model.Type_News;
                newItem.Poster = model.Poster;
                newItem.PosterID = model.PosterID;
                newItem.Creater = model.Creater;
                newItem.CreateDate = model.CreateDate;
                newItem.Modifier = model.Modifier;
                newItem.ModifyDate = model.ModifyDate;
                dc.News.InsertOnSubmit(newItem);
                dc.SubmitChanges();

            }
            return 1;
        }
        catch (Exception)
        {
            return 0;

        }
    }
Ejemplo n.º 3
0
 Qualification GetOrCreateQualification(New.Person person)
 {
     var qual = newDatabase.Qualifications.FirstOrDefault(x => x.PersonId == person.PersonId);
     if (qual == null)
     {
         qual = new Qualification
         {
             Person = person,
         };
         newDatabase.Qualifications.InsertOnSubmit(qual);
         newDatabase.SubmitChanges();
     }
     return qual;
 }
Ejemplo n.º 4
0
 void UpdatePerson(New.Person person, Formrecord record)
 {
     switch (record.Formfield.Name)
     {
         case "Middle Initial": person.MiddleInitial = record.Storedvalue; return;
         case "SSN Last Four": person.SocialSecurityLastFour = TakeLastFourDigits(record.Storedvalue); return;
         case "Date of Birth": person.DateOfBirth = TryParseDate(record.Storedvalue); return;
         case "Gender": person.Gender = MaleOrFemale(record.Storedvalue); return;
         case "Phone": person.PrimaryPhoneNumber = StripExtraPhoneCharacters(record.Storedvalue); return;
         case "Alt. Phone": person.AlternatePhoneNumber = StripExtraPhoneCharacters(record.Storedvalue); return;
         case "E-mail Address": person.AlternateEmail = record.Storedvalue; return;
         case "Emergency Contact Name": person.EmergencyContactName = record.Storedvalue; return;
         case "Emergency Contact Phone": person.EmergencyContactPhoneNumber = StripExtraPhoneCharacters(record.Storedvalue); return;
         case "Position": person.Position = TryGetPosition(record.Storedvalue); return;
         case "Address": person.StreetAddress = record.Storedvalue; return;
         default: return;
     };
 }
Ejemplo n.º 5
0
        public void When_trying_to_create_new_project_ensure_all_elements_show()
        {
            // Instantiate the view directly. This is made possible by
            // the fact that we precompiled it
            var newProjectView = new New();

            // Create the model to be sent to the view if needed
            //var model = new Model();

            // Set up the data that needs to be accessed by the view
            //newProjectView.ViewBag.Title = "Testing";

            // Render it in an HtmlAgilityPack HtmlDocument. Note that
            // you can pass a 'model' object here if your view needs one.
            // Generally, what you do here is similar to how a controller
            //action sets up data for its view.
            var doc = newProjectView.RenderAsHtml();

            // Use the HtmlAgilityPack object model to verify the view.
            // Here, we simply check that the first <h2> tag contains
            // what we put in view.ViewBag.Message

            //var nameTextbox = doc.

            var nameTextbox = doc.GetElementbyId("name");
            var visionTextbox = doc.GetElementbyId("vision");
            var codeTextbox = doc.GetElementbyId("code");
            var submitBtn = doc.GetElementbyId("submit");

            Assert.IsNotNull(nameTextbox);
            Assert.IsNotNull(visionTextbox);
            Assert.IsNotNull(codeTextbox);
            Assert.IsNotNull(submitBtn);

            //Assert.AreEqual("Testing", node.InnerHtml.Trim());
        }
Ejemplo n.º 6
0
 public void Add(New.songVerse newVerse)
 {
     lyricArray.Add(newVerse);
 }
Ejemplo n.º 7
0
 public virtual object Visit(New newExpression)
 {
     return(null);
 }
Ejemplo n.º 8
0
        public T Find(StreamAction stream, IDocumentSession session)
        {
            var returnValue = stream.ActionType == StreamActionType.Start ? New <T> .Instance() : session.Load <T>(stream.Key) ?? New <T> .Instance();

            _setId(returnValue, stream.Key);

            return(returnValue);
        }
Ejemplo n.º 9
0
 public PatternDetails(SourceFileContext ctx, ResourceDetails.Definition def, ResourceDetails.Definition.Pattern pattern)
 {
     PatternString = pattern.PatternString;
     PathSegments  = pattern.Template.Segments.Select(x => new PathSegment(ctx, def, x)).ToList();
     if (pattern.Template.ParameterNames.Count() == 0)
     {
         // Path-template contains no parameters, special naming required.
         UpperName = PatternString.ToUpperCamelCase();
         LowerName = PatternString.ToLowerCamelCase();
     }
     else
     {
         // Standard naming, concat all parameter names.
         UpperName = string.Join("", PathElements.Select(x => x.UpperCamel));
         LowerName = string.Join("", PathElements.Take(1).Select(x => x.LowerCamel).Concat(PathElements.Skip(1).Select(x => x.UpperCamel)));
     }
     PathTemplateField = Field(Private | Static, ctx.Type <PathTemplate>(), $"s_{LowerName}").WithInitializer(New(ctx.Type <PathTemplate>())(pattern.Template.PathTemplateString));
 }
Ejemplo n.º 10
0
        public async Task <IActionResult> List(ListContentsViewModel model, PagerParameters pagerParameters, string ModelName)
        {
            var siteSettings = await _siteService.GetSiteSettingsAsync();

            Pager pager = new Pager(pagerParameters, siteSettings.PageSize);

            model.Id = ModelName;
            var query = _session.Query <ContentItem, ContentItemIndex>();

            switch (model.Options.ContentsStatus)
            {
            case ContentsStatus.Published:
                query = query.With <ContentItemIndex>(x => x.Published);
                break;

            case ContentsStatus.Draft:
                query = query.With <ContentItemIndex>(x => x.Latest && !x.Published);
                break;

            case ContentsStatus.AllVersions:
                query = query.With <ContentItemIndex>(x => x.Latest);
                break;

            default:
                query = query.With <ContentItemIndex>(x => x.Latest);
                break;
            }

            if (!string.IsNullOrEmpty(model.TypeName))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetLastTypeDefinition(model.TypeName);
                if (contentTypeDefinition == null)
                {
                    return(NotFound());
                }

                model.TypeDisplayName = contentTypeDefinition.ToString();

                // We display a specific type even if it's not listable so that admin pages
                // can reuse the Content list page for specific types.
                query = query.With <ContentItemIndex>(x => x.ContentType == model.TypeName);
            }
            else
            {
                var listableTypes = (await GetListableTypesAsync()).Select(t => t.Name).ToArray();
                if (listableTypes.Any())
                {
                    query = query.With <ContentItemIndex>(x => x.ContentType.IsIn(listableTypes));
                }
            }

            switch (model.Options.OrderBy)
            {
            case ContentsOrder.Modified:
                query = query.OrderByDescending(x => x.ModifiedUtc);
                break;

            case ContentsOrder.Published:
                query = query.OrderByDescending(cr => cr.PublishedUtc);
                break;

            case ContentsOrder.Created:
                query = query.OrderByDescending(cr => cr.CreatedUtc);
                break;

            default:
                query = query.OrderByDescending(cr => cr.ModifiedUtc);
                break;
            }

            //if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
            //{
            //    query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
            //}

            //if (model.Options.ContentsStatus == ContentsStatus.Owner)
            //{
            //    query = query.Where<CommonPartRecord>(cr => cr.OwnerId == Services.WorkContext.CurrentUser.Id);
            //}

            model.Options.SelectedFilter = model.TypeName;
            model.Options.FilterOptions  = (await GetListableTypesAsync())
                                           .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                           .ToList().OrderBy(kvp => kvp.Value);

            //model.Options.Cultures = _cultureManager.ListCultures();

            // Invoke any service that could alter the query
            await _contentAdminFilters.InvokeAsync(x => x.FilterAsync(query, model, pagerParameters, this), Logger);

            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            var pagerShape         = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync());
            var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync();

            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "SummaryAdmin"));
            }

            var viewModel = (await New.ViewModel())
                            .ContentItems(contentItemSummaries)
                            .Pager(pagerShape)
                            .Options(model.Options)
                            .TypeDisplayName(model.TypeDisplayName ?? "")
                            .TypeName(model.TypeName ?? "");

            return(View(viewModel));
        }
Ejemplo n.º 11
0
        public override ITimedFuture <Turnaround> NextRequest(float seconds)
        {
            var req = Model.NextAction();

            return(New.TimedFuture(TimeSpan.FromSeconds(seconds), new Turnaround(req, ResponseHandler)));
        }
Ejemplo n.º 12
0
 public static void OutParameter()
 {
     var s = new New(out _);
 }
Ejemplo n.º 13
0
    public string GetNextAvailableID(string type)
    {
        if (type == "" || type == null)
        {
            return(type);
        }

        int result = 0;

        switch (type)
        {
        case "admin":
            AdminUser ad = null;
            while ((ad = (AdminUser)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "article":
            Article ar = null;
            while ((ar = (Article)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "content":
            ContentP co = null;
            while ((co = (ContentP)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "mailList":
            MailList ma = null;
            while ((ma = (MailList)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "log":
            Log lo = null;
            while ((lo = (Log)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "graduate":
            Graduate gr = null;
            while ((gr = (Graduate)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "session":
            GraduateSession ss = null;
            while ((ss = (GraduateSession)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "lead":
            Lead le = null;
            while ((le = (Lead)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        case "news":
            New ne = null;
            while ((ne = (New)this.Get(type, result.ToString())) != null)
            {
                result += 1;
            }
            break;

        default:
            break;
        }
        return(result.ToString());
    }
Ejemplo n.º 14
0
 public override IFuture <RejectCards> Mulligan()
 {
     // keep all cards
     return(New.Future(new RejectCards(Model)));
 }
Ejemplo n.º 15
0
    public void Update(string type, object item, DateTime time)
    {
        if (type == "" || type == null || time == default(DateTime))
        {
            return;
        }

        switch (type)
        {
        case "admin":
            AdminUser ad1 = (AdminUser)item;
            AdminUser ad2 = null;
            if ((ad2 = (AdminUser)this.Get(type, ad1.AdminUserID)) != null)
            {
                ad2.Update(ref ad1, time);
                ad2.LastUpdate   = time;
                ad2.spLastUpdate = time.ToString();
            }
            break;

        case "article":
            Article ar1 = (Article)item;
            Article ar2 = null;
            if ((ar2 = (Article)this.Get(type, ar1.ArticleID)) != null)
            {
                ar2.Update(ref ar1, time);
                ar2.LastUpdate   = time;
                ar2.spLastUpdate = time.ToString();
            }
            break;

        case "content":
            ContentP co1 = (ContentP)item;
            ContentP co2 = null;
            if ((co2 = (ContentP)this.Get(type, co1.ContentID)) != null)
            {
                co2.Update(ref co1, time);
                co2.LastUpdate   = time;
                co2.spLastUpdate = time.ToString();
            }
            break;

        case "log":
            Log lo1 = (Log)item;
            Log lo2 = null;
            if ((lo2 = (Log)this.Get(type, lo1.LogID.ToString())) != null)
            {
                lo2.Update(ref lo1, time);
            }
            break;

        case "graduate":
            Graduate gr1 = (Graduate)item;
            Graduate gr2 = null;
            if ((gr2 = (Graduate)this.Get(type, gr1.GraduateID)) != null)
            {
                gr2.Update(ref gr1, time);
            }
            break;

        case "session":
            GraduateSession ss1 = (GraduateSession)item;
            GraduateSession ss2 = null;
            if ((ss2 = (GraduateSession)this.Get(type, ss1.GraduateSessionID)) != null)
            {
                ss2.Update(ref ss1, time);
            }
            break;

        case "lead":
            Lead le1 = (Lead)item;
            Lead le2 = null;
            if ((le2 = (Lead)this.Get(type, le1.LeadID.ToString())) != null)
            {
                le2.Update(ref le1, time);
            }
            break;

        case "news":
            New ne1 = (New)item;
            New ne2 = null;
            if ((ne2 = (New)this.Get(type, ne1.NewsID.ToString())) != null)
            {
                ne2.Update(ref ne1, time);
            }
            break;

        default:
            break;
        }
        this.coachingDal.SubmitChanges();
    }
Ejemplo n.º 16
0
    public void Delete(string type, string itemID)
    {
        if (type == "" || type == null ||
            itemID == null || itemID == "")
        {
            return;
        }

        switch (type)
        {
        case "admin":
            AdminUser m = null;
            if ((m = (AdminUser)this.Get(type, itemID)) != null)
            {
                this.coachingDal.AdminUsers.DeleteOnSubmit(m);
            }
            break;

        case "article":
            Article ar = null;
            if ((ar = (Article)this.Get(type, itemID)) != null)
            {
                this.coachingDal.Articles.DeleteOnSubmit(ar);
            }
            break;

        case "content":
            ContentP co = null;
            if ((co = (ContentP)this.Get(type, itemID)) != null)
            {
                this.coachingDal.ContentPs.DeleteOnSubmit(co);
            }
            break;

        case "mailList":
            MailList ma = null;
            if ((ma = (MailList)this.Get(type, itemID)) != null)
            {
                this.coachingDal.MailLists.DeleteOnSubmit(ma);
            }
            break;

        case "log":
            Log lo = null;
            if ((lo = (Log)this.Get(type, itemID)) != null)
            {
                this.coachingDal.Logs.DeleteOnSubmit(lo);
            }
            break;

        case "graduate":
            Graduate gr = null;
            if ((gr = (Graduate)this.Get(type, itemID)) != null)
            {
                this.coachingDal.Graduates.DeleteOnSubmit(gr);
            }
            break;

        case "session":
            GraduateSession se = null;
            if ((se = (GraduateSession)this.Get(type, itemID)) != null)
            {
                this.coachingDal.GraduateSessions.DeleteOnSubmit(se);
            }
            break;

        case "lead":
            Lead le = null;
            if ((le = (Lead)this.Get(type, itemID)) != null)
            {
                this.coachingDal.Leads.DeleteOnSubmit(le);
            }
            break;

        case "news":
            New ne = null;
            if ((ne = (New)this.Get(type, itemID)) != null)
            {
                this.coachingDal.News.DeleteOnSubmit(ne);
            }
            break;

        default:
            break;
        }
        this.coachingDal.SubmitChanges();
    }
Ejemplo n.º 17
0
    public void Add(string type, object item, DateTime time)
    {
        if (type == "" || type == null || item == null ||
            time == default(DateTime) || time == default(DateTime))
        {
            return;
        }
        switch (type)
        {
        case "admin":
            AdminUser ad = (AdminUser)item;
            if (this.Get(type, ad.AdminUserID) == null)
            {
                ad.CreationTime   = time;
                ad.spCreationTime = time.ToShortDateString();
                this.coachingDal.AdminUsers.InsertOnSubmit(ad);
            }
            break;

        case "article":
            Article ar = (Article)item;
            if (this.Get(type, ar.ArticleID) == null)
            {
                ar.CreationTime = time;
                this.coachingDal.Articles.InsertOnSubmit(ar);
            }
            break;

        case "content":
            ContentP co = (ContentP)item;
            if (this.Get(type, co.ContentID) == null)
            {
                co.CreationTime = time;
                this.coachingDal.ContentPs.InsertOnSubmit(co);
            }
            break;

        case "mailList":
            MailList ma = (MailList)item;
            if (this.Get(type, ma.MailListID) == null)
            {
                ma.MailListJoinTime     = time;
                ma.spMailListLastUpdate = time.ToShortDateString();
                this.coachingDal.MailLists.InsertOnSubmit(ma);
            }
            break;

        case "log":
            Log lo = (Log)item;
            if (this.Get(type, lo.LogID.ToString()) == null)
            {
                lo.LogDate   = time;
                lo.spLogDate = time.ToShortDateString();
                this.coachingDal.Logs.InsertOnSubmit(lo);
            }
            break;

        case "graduate":
            Graduate gr = (Graduate)item;
            if (this.Get(type, gr.GraduateID.ToString()) == null)
            {
                gr.CreationTime   = time;
                gr.spCreationTime = time.ToShortDateString();
                this.coachingDal.Graduates.InsertOnSubmit(gr);
            }
            break;

        case "session":
            GraduateSession se = (GraduateSession)item;
            if (this.Get(type, se.GraduateSessionID.ToString()) == null)
            {
                se.CreationTime   = time;
                se.spCreationTime = time.ToShortDateString();
                this.coachingDal.GraduateSessions.InsertOnSubmit(se);
            }
            break;

        case "lead":
            Lead le = (Lead)item;
            if (this.Get(type, le.LeadID.ToString()) == null)
            {
                le.LeadDate   = time;
                le.spLeadDate = time.ToString();
                this.coachingDal.Leads.InsertOnSubmit(le);
            }
            break;

        case "news":
            New ne = (New)item;
            if (this.Get(type, ne.NewsID) == null)
            {
                ne.NewsCreationDate   = time;
                ne.spNewsCreationDate = time.ToShortDateString();
                this.coachingDal.News.InsertOnSubmit(ne);
            }
            break;

        default:
            break;
        }

        this.coachingDal.SubmitChanges();
    }
Ejemplo n.º 18
0
 public override ITransient TurnStart()
 {
     return(New.Nop());
 }
Ejemplo n.º 19
0
        /// <summary>
        /// change the ranking for the current record and updates the other ones accordingly.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="d"></param>
        /// <param name="ss"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public void UpdateRanking(int id, int d, int ss, int?pid)
        {
            if ((d != 1) && (d != -1))
            {
                throw new Exception("Direction value incorrect");
            }
            IQueryable <New>      allNews  = null;
            IQueryable <NewsType> allTypes = null;

            if (pid.HasValue && pid.Value > 0)
            {
                NewsManager nMgr           = new NewsManager();
                New         selectedRecord = nMgr.NewsData.News.SingleOrDefault(x => x.NewsId == id);
                if (selectedRecord == null)
                {
                    throw new Exception("Record not found");
                }
                allNews = from newsTypeView in nMgr.NewsData.News
                          where
                          newsTypeView.NewsType == pid
                          select newsTypeView;
                // increasing priority
                if (d == -1)
                {
                    //select all where priority > currentPriority and limiting results to maximum the stepsize
                    var recordsToUpdate = (from s in allNews
                                           where s.Ranking > selectedRecord.Ranking
                                           orderby s.Ranking
                                           select s).Take(ss);
                    if (recordsToUpdate.Count() > 0)
                    {
                        int maxPriority = Convert.ToInt32(recordsToUpdate.Max(x => x.Ranking));
                        foreach (var s in recordsToUpdate)
                        {
                            s.Ranking--;
                        }
                        selectedRecord.Ranking = maxPriority;
                        nMgr.Save();
                    }
                }
                // lowering priority
                if (d == 1)
                {
                    if (selectedRecord == null)
                    {
                        throw new Exception("Record not found");
                    }
                    //select all where priority < currentPriority and limiting results to maximum the stepsize
                    var recordsToUpdate = (from s in allNews
                                           where s.Ranking < selectedRecord.Ranking
                                           orderby s.Ranking descending
                                           select s).Take(ss);
                    if (recordsToUpdate.Count() > 0)
                    {
                        int minimumPriority = Convert.ToInt32(recordsToUpdate.Min(x => x.Ranking));
                        foreach (var s in recordsToUpdate)
                        {
                            s.Ranking++;
                        }
                        selectedRecord.Ranking = minimumPriority;
                        nMgr.Save();
                    }
                }
            }
            else
            {
                NewsType selectedRecord = GetType(id);
                allTypes = from newsType in GetTypes()
                           where
                           newsType.ParentId == 12
                           select newsType;
                if (selectedRecord == null)
                {
                    throw new Exception("Record not found");
                }
                // increasing priority
                if (d == -1)
                {
                    //select all where priority > currentPriority and limiting results to maximum the stepsize
                    var recordsToUpdate = (from s in allTypes
                                           where s.Ranking > selectedRecord.Ranking
                                           orderby s.Ranking
                                           select s).Take(ss);
                    if (recordsToUpdate.Count() > 0)
                    {
                        int maxPriority = Convert.ToInt32(recordsToUpdate.Max(x => x.Ranking));
                        foreach (var s in recordsToUpdate)
                        {
                            s.Ranking--;
                        }
                        selectedRecord.Ranking = maxPriority;
                        this.Save();
                    }
                }
                // lowering priority
                if (d == 1)
                {
                    //select all where priority < currentPriority and limiting results to maximum the stepsize
                    var recordsToUpdate = (from s in allTypes
                                           where s.Ranking < selectedRecord.Ranking
                                           orderby s.Ranking descending
                                           select s).Take(ss);
                    if (recordsToUpdate.Count() > 0)
                    {
                        int minimumPriority = Convert.ToInt32(recordsToUpdate.Min(x => x.Ranking));
                        foreach (var s in recordsToUpdate)
                        {
                            s.Ranking++;
                        }
                        selectedRecord.Ranking = minimumPriority;
                        this.Save();
                    }
                }
            }
        }
Ejemplo n.º 20
0
 public void InsetrNew(New model)
 {
     MongoDbHelper.Insert(DbConfigParams.ConntionString, DbConfigParams.DbName, CollectionNames.New, model);
 }
Ejemplo n.º 21
0
 protected override IGpioConnectionDriverFactory CreateGpioConnectionDriverFactory()
 {
     this.GpioConnectionDriverFactory = New.Mock <IGpioConnectionDriverFactory>();
     return(this.GpioConnectionDriverFactory);
 }
			public override object Visit (New newExpression)
			{
				var result = new ObjectCreateExpression ();
				var location = LocationsBag.GetLocations (newExpression);
				result.AddChild (new CSharpTokenNode (Convert (newExpression.Location), ObjectCreateExpression.NewKeywordRole), ObjectCreateExpression.NewKeywordRole);
				
				if (newExpression.TypeRequested != null)
					result.AddChild (ConvertToType (newExpression.TypeRequested), Roles.Type);
				if (location != null)
					result.AddChild (new CSharpTokenNode (Convert (location [0]), Roles.LPar), Roles.LPar);
				AddArguments (result, location, newExpression.Arguments);
				
				if (location != null && location.Count > 1)
					result.AddChild (new CSharpTokenNode (Convert (location [1]), Roles.RPar), Roles.RPar);
				
				return result;
			}
Ejemplo n.º 23
0
        public async Task <New> SetNewUserRating(int rating, int newId, ApplicationUser user, New oneNew)
        {
            var userNewRating = Context.UserNewRatings.Where(uer => uer.NewId == newId && uer.UserId == user.Id).FirstOrDefault();

            if (userNewRating == null)
            {
                AddNewRating(rating, newId, user, oneNew);
            }
            else
            {
                UpdateOldRating(rating, newId, user, oneNew, userNewRating);
            }
            await Context.SaveChangesAsync();

            return(oneNew);
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> List(ListContentsViewModel model, PagerParameters pagerParameters, string contentTypeId = "")
        {
            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            var query = _session.Query <ContentItem, ContentItemIndex>();

            if (!string.IsNullOrEmpty(model.Options.DisplayText))
            {
                query = query.With <ContentItemIndex>(x => x.DisplayText.Contains(model.Options.DisplayText));
            }

            switch (model.Options.ContentsStatus)
            {
            case ContentsStatus.Published:
                query = query.With <ContentItemIndex>(x => x.Published);
                break;

            case ContentsStatus.Draft:
                query = query.With <ContentItemIndex>(x => x.Latest && !x.Published);
                break;

            case ContentsStatus.AllVersions:
                query = query.With <ContentItemIndex>(x => x.Latest);
                break;

            default:
                query = query.With <ContentItemIndex>(x => x.Latest);
                break;
            }

            if (contentTypeId != "")
            {
                model.Options.SelectedContentType = contentTypeId;
            }

            if (!string.IsNullOrEmpty(model.Options.SelectedContentType))
            {
                var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.Options.SelectedContentType);
                if (contentTypeDefinition == null)
                {
                    return(NotFound());
                }

                // We display a specific type even if it's not listable so that admin pages
                // can reuse the Content list page for specific types.
                query = query.With <ContentItemIndex>(x => x.ContentType == model.Options.SelectedContentType);
            }
            else
            {
                var listableTypes = (await GetListableTypesAsync()).Select(t => t.Name).ToArray();
                if (listableTypes.Any())
                {
                    query = query.With <ContentItemIndex>(x => x.ContentType.IsIn(listableTypes));
                }
            }

            switch (model.Options.OrderBy)
            {
            case ContentsOrder.Modified:
                query = query.OrderByDescending(x => x.ModifiedUtc);
                break;

            case ContentsOrder.Published:
                query = query.OrderByDescending(cr => cr.PublishedUtc);
                break;

            case ContentsOrder.Created:
                query = query.OrderByDescending(cr => cr.CreatedUtc);
                break;

            case ContentsOrder.Title:
                query = query.OrderBy(cr => cr.DisplayText);
                break;

            default:
                query = query.OrderByDescending(cr => cr.ModifiedUtc);
                break;
            }

            //if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
            //{
            //    query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
            //}

            //if (model.Options.ContentsStatus == ContentsStatus.Owner)
            //{
            //    query = query.Where<CommonPartRecord>(cr => cr.OwnerId == Services.WorkContext.CurrentUser.Id);
            //}

            //model.Options.Cultures = _cultureManager.ListCultures();

            // Invoke any service that could alter the query
            await _contentAdminFilters.InvokeAsync(x => x.FilterAsync(query, model, pagerParameters, this), Logger);

            var maxPagedCount = siteSettings.MaxPagedCount;

            if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
            {
                pager.PageSize = maxPagedCount;
            }

            //We prepare the pager
            var routeData = new RouteData();

            routeData.Values.Add("DisplayText", model.Options.DisplayText);

            var pagerShape         = (await New.Pager(pager)).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync()).RouteData(routeData);
            var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync();

            //We prepare the content items SummaryAdmin shape
            var contentItemSummaries = new List <dynamic>();

            foreach (var contentItem in pageOfContentItems)
            {
                contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "SummaryAdmin"));
            }

            //We populate the SelectLists
            model.Options.ContentStatuses = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = T["latest"].Value, Value = ContentsStatus.Latest.ToString()
                },
                new SelectListItem()
                {
                    Text = T["owned by me"].Value, Value = ContentsStatus.Owner.ToString()
                },
                new SelectListItem()
                {
                    Text = T["published"].Value, Value = ContentsStatus.Published.ToString()
                },
                new SelectListItem()
                {
                    Text = T["unpublished"].Value, Value = ContentsStatus.Draft.ToString()
                },
                new SelectListItem()
                {
                    Text = T["all versions"].Value, Value = ContentsStatus.AllVersions.ToString()
                }
            };

            model.Options.ContentSorts = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = T["recently created"].Value, Value = ContentsOrder.Created.ToString()
                },
                new SelectListItem()
                {
                    Text = T["recently modified"].Value, Value = ContentsOrder.Modified.ToString()
                },
                new SelectListItem()
                {
                    Text = T["recently published"].Value, Value = ContentsOrder.Published.ToString()
                },
                new SelectListItem()
                {
                    Text = T["title"].Value, Value = ContentsOrder.Title.ToString()
                }
            };

            model.Options.ContentsBulkAction = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = T["Publish Now"].Value, Value = ContentsBulkAction.PublishNow.ToString()
                },
                new SelectListItem()
                {
                    Text = T["Unpublish"].Value, Value = ContentsBulkAction.Unpublish.ToString()
                },
                new SelectListItem()
                {
                    Text = T["Delete"].Value, Value = ContentsBulkAction.Remove.ToString()
                }
            };

            var ContentTypeOptions = (await GetListableTypesAsync())
                                     .Select(ctd => new KeyValuePair <string, string>(ctd.Name, ctd.DisplayName))
                                     .ToList().OrderBy(kvp => kvp.Value);

            model.Options.ContentTypeOptions = new List <SelectListItem>();
            model.Options.ContentTypeOptions.Add(new SelectListItem()
            {
                Text = T["All content types"].Value, Value = ""
            });
            foreach (var option in ContentTypeOptions)
            {
                model.Options.ContentTypeOptions.Add(new SelectListItem()
                {
                    Text = option.Value, Value = option.Key
                });
            }

            var viewModel = new ListContentsViewModel
            {
                ContentItems = contentItemSummaries,
                Pager        = pagerShape,
                Options      = model.Options
            };

            return(View(viewModel));
        }
Ejemplo n.º 25
0
        public async System.Threading.Tasks.Task  AddNew(New news)
        {
            await _dataBaseContext.New.AddAsync(news);

            await _dataBaseContext.SaveChangesAsync();
        }
Ejemplo n.º 26
0
 public void addNews(New news)
 {
     news = context.News.Add(news);
     context.SaveChanges();
 }
Ejemplo n.º 27
0
 public void TestDebugLog()
 {
     Root.Add(New.Log("Hello World"));
     Step(5);
 }
        public ActionResult AddNewNewsItem(string newsItemName)
        {
            var newNewsItem = new New
            {
                Headline = newsItemName,
                PublishDate = DateTime.Now,
                LinkPath = "/News/" + MakeUrl(newsItemName),
                Culture = _curCult
            };
            try
            {
                _context.News.Add(newNewsItem);

                if (_settings.CreateContentOnAllLanguages)
                {
                    var cultList = _settings.ImplementedCultures;
                    cultList.Remove(_curCult);
                    foreach (var cult in cultList)
                    {
                        var newItem = new New
                        {
                            Headline = newsItemName,
                            PublishDate = DateTime.Now,
                            LinkPath = "/News/" + MakeUrl(newsItemName),
                            Culture = cult
                        };
                        _context.News.Add(newItem);
                    }
                }

                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Json(new { status = "SPCD: ERR - " + ex.Message });
            }

            return Json(new { status = "SPCD: NIADDED", newsItem = newNewsItem });
        }
Ejemplo n.º 29
0
 public void Update(GameTime gameTime)
 {
     Load.Update(gameTime);
     New.Update(gameTime);
 }
Ejemplo n.º 30
0
        public async Task <T> FindAsync(StreamAction stream, IDocumentSession session, CancellationToken token)
        {
            var returnValue = stream.ActionType == StreamActionType.Start ? New <T> .Instance() : await session.LoadAsync <T>(stream.Key, token).ConfigureAwait(false) ?? New <T> .Instance();

            _setId(returnValue, stream.Key);

            return(returnValue);
        }
Ejemplo n.º 31
0
 public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
 {
     Load.Draw(gameTime, spriteBatch);
     New.Draw(gameTime, spriteBatch);
 }
Ejemplo n.º 32
0
    protected void btSave_Click(object sender, EventArgs e)
    {
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
        clsSecurity security = new clsSecurity();
        clsIO IO = new clsIO();

        string strDetailSub = string.Empty;
        string strDetail = txtDetail.Text.Replace("<p>", "");
        strDetail = strDetail.Replace("</p>", "");
        string PicFull = "null";
        string PicThumb = "null";
        string pathPhoto = "/Images/News/";
        string pathImages = @"\Images\News\";
        string outError;


        //upload Photo to server
        if (txtImgFull.HasFile)
        {
            //Full Images
            if (IO.UploadPhoto(txtImgFull, pathPhoto, "f_pic" + DateTime.Now.ToString("yyyyMMddHHmmss"), 5120, 0, 0, "", 0, out outError, out PicFull) == false)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Information", "alert('" + outError.ToString() + "')", true);
                return;
            }
            else
            {
                PicFull = pathImages + "" + PicFull;
            }
        }
        else
        {
            PicFull = lblImagesFull.Text.Trim();
        }
        if (txtImgThum.HasFile)
        {
            //Thumb Images
            if (IO.UploadPhoto(txtImgThum, pathPhoto, "t_pic" + DateTime.Now.ToString("yyyyMMddHHmmss"), 2048, 0, 0, "", 0, out outError, out PicThumb) == false)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Information", "alert('" + outError.ToString() + "')", true);
                return;
            }
            else
            {
                PicThumb = pathImages + "" + PicThumb;
            }
        }
        else
        {
            PicThumb = lblImagesThumb.Text.Trim();
        }
        //insert data to database
        try
        {
            if (txtDetail.Text.Length >= 200)
            {
                strDetailSub = "<p>" + strDetail.Substring(0, 200) + ".....</p>";
            }
            else
            {
                strDetailSub = "<p>" + strDetail + ".....</p>";
            }
            //Insert news
            if (string.IsNullOrEmpty(lblUID.Text) == true)
            {
                New tbnews = new New();

                //Assign values for insert into database
                tbnews.Subject = txtSubject.Text.Trim();
                tbnews.Detail = txtDetail.Text;
                tbnews.PicFull = PicFull;
                tbnews.PicThumbnail = PicThumb;
                tbnews.ActiveDateFrom = Convert.ToDateTime(txtDateFrom.Text);
                tbnews.ActiveDateTo = Convert.ToDateTime(txtDateTo.Text);
                tbnews.Remark = txtRemark.Text.Trim();
                tbnews.CWhen = DateTime.Now;
                tbnews.CUser = Convert.ToInt32(security.LoginUID);
                tbnews.MWhen = DateTime.Now;
                tbnews.MUser = Convert.ToInt32(security.LoginUID);
                tbnews.StatusFlag = rdbActive.Checked == true ? "A" : "D";
                tbnews.LanguageUID = Convert.ToInt32(ddlLanguage.SelectedValue);
                tbnews.MetaKeywords = txtMetaKeywords.Text.Trim();
                tbnews.MetaDescription = txtMetaDescription.Text.Trim();
                tbnews.DetailSub = strDetailSub;

                //Insert data of news to database
                db.News.InsertOnSubmit(tbnews);
            }
            else //Update existing Event
            {
                var tbnews = from n in db.News
                              where n.UID == Convert.ToInt32(lblUID.Text.Trim())
                              select n;
                foreach (New n in tbnews)
                {
                    n.Subject = txtSubject.Text.Trim();
                    n.Detail = txtDetail.Text;
                    n.PicFull = PicFull;
                    n.PicThumbnail = PicThumb;
                    n.ActiveDateFrom = Convert.ToDateTime(txtDateFrom.Text);
                    n.ActiveDateTo = Convert.ToDateTime(txtDateTo.Text);
                    n.Remark = txtRemark.Text.Trim();
                    n.MWhen = DateTime.Now;
                    n.MUser = Convert.ToInt32(security.LoginUID);
                    n.StatusFlag = rdbActive.Checked == true ? "A" : "D";
                    n.MetaKeywords = txtMetaKeywords.Text.Trim();
                    n.MetaDescription = txtMetaDescription.Text.Trim();
                    try
                    {
                        n.LanguageUID = Convert.ToInt32(ddlLanguage.SelectedValue);
                    }
                    catch (Exception ex)
                    {
                        ex.ToString();
                    }
                    n.DetailSub = strDetailSub;
                }
            }
            db.SubmitChanges();
            clsColorBox clsColorBox = new clsColorBox();
            clsColorBox.Refresh();
            //Page.ClientScript.RegisterStartupScript(Page.GetType(), "closeWindow", "<script language='javascript'>parent.$.colorbox.close();</script>");
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Information", "alert('" + ex.ToString() + "')", true);
        }
    }
Ejemplo n.º 33
0
        public Expression TypeCheck(New @new, Scope scope)
        {
            var position = @new.Position;
            var typeName = @new.TypeName;

            var typedTypeName = (Name)TypeCheck(typeName, scope);

            var constructorType = typedTypeName.Type as NamedType;

            if (constructorType == null || constructorType.Name != "Rook.Core.Constructor")
            {
                LogError(CompilerError.TypeNameExpectedForConstruction(typeName.Position, typeName));
                return @new;
            }

            var constructedType = constructorType.GenericArguments.Last();

            return new New(position, typedTypeName, constructedType);
        }
Ejemplo n.º 34
0
		//
		// Initializes all hoisted variables
		//
		public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
		{
			// There can be only one instance variable for each storey type
			if (Instance != null)
				throw new InternalErrorException ();

			//
			// Create an instance of this storey
			//
			ResolveContext rc = new ResolveContext (ec.MemberContext);
			rc.CurrentBlock = block;

			var storey_type_expr = CreateStoreyTypeExpression (ec);
			var source = new New (storey_type_expr, null, Location).Resolve (rc);

			//
			// When the current context is async (or iterator) lift local storey
			// instantiation to the currect storey
			//
			if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
				//
				// Unfortunately, normal capture mechanism could not be used because we are
				// too late in the pipeline and standart assign cannot be used either due to
				// recursive nature of GetStoreyInstanceExpression
				//
				var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
					LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);

				field.Define ();
				field.Emit ();

				var fexpr = new FieldExpr (field, Location);
				fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
				fexpr.EmitAssign (ec, source, false, false);
				Instance = fexpr;
			} else {
				var local = TemporaryVariableReference.Create (source.Type, block, Location);
				if (source.Type.IsStruct) {
					local.LocalInfo.CreateBuilder (ec);
				} else {
					local.EmitAssign (ec, source);
				}

				Instance = local;
			}

			EmitHoistedFieldsInitialization (rc, ec);

			// TODO: Implement properly
			//SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
		}
Ejemplo n.º 35
0
 partial void UpdateNew(New instance);
Ejemplo n.º 36
0
		public virtual object Visit (New newExpression)
		{
			return null;
		}
Ejemplo n.º 37
0
void case_540()
#line 3968 "cs-parser.jay"
{
		if (yyVals[0+yyTop] != null) {
			if (lang_version <= LanguageVersion.ISO_2)
				FeatureIsNotAvailable (GetLocation (yyVals[-5+yyTop]), "object initializers");
				
			yyVal = new NewInitialize ((FullNamedExpression) yyVals[-4+yyTop], (Arguments) yyVals[-2+yyTop], (CollectionOrObjectInitializers) yyVals[0+yyTop], GetLocation (yyVals[-5+yyTop]));
		} else {
			yyVal = new New ((FullNamedExpression) yyVals[-4+yyTop], (Arguments) yyVals[-2+yyTop], GetLocation (yyVals[-5+yyTop]));
		}
		
		lbag.AddLocation (yyVal, GetLocation (yyVals[-3+yyTop]), GetLocation (yyVals[-1+yyTop]));
	  }
Ejemplo n.º 38
0
 public void Reset()
 {
     Load.Reset();
     New.Reset();
 }
Ejemplo n.º 39
0
 public override ITransient TurnEnd()
 {
     Info("Turn End");
     return(New.Nop());
 }
Ejemplo n.º 40
0
 partial void InsertNew(New instance);
Ejemplo n.º 41
0
        public async Task <IActionResult> Index(SearchIndexOptions options, PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Intelli.Comments.Permissions.ManageComments))
            {
                return(Unauthorized());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            if (options == null)
            {
                options = new SearchIndexOptions();
            }

            //var query = _session.Query<WorkflowType, WorkflowTypeIndex>();

//            switch (options.Filter)
//            {
//                case WorkflowTypeFilter.All:
//                default:
//                    break;
//            }

//            if (!string.IsNullOrWhiteSpace(options.Search))
//            {
//                query = query.Where(w => w.Name.Contains(options.Search));
//            }

//            switch (options.Order)
//            {
//                case WorkflowTypeOrder.Name:
//                    query = query.OrderBy(u => u.Name);
//                    break;
//            }

            // var count = await query.CountAsync();

//            var workflowTypes = await query
//                .Skip(pager.GetStartIndex())
//                .Take(pager.PageSize)
//                .ListAsync();
            var comments = await _commentsRepository.FindAllAsync();// GetAllAsync();


            var currentCommentList = comments
                                     //  .Where(c => (currentUserGroupIds.Contains(c.GroupId) || c.GroupId == currentUserId) && c.Parent == null && c.CommentGroupTypeId != CommentGroupType.GroupChat)
                                     .OrderByDescending(c => c.CreatedUtc).ToList();

//            var workflowTypeIds = workflowTypes.Select(x => x.WorkflowTypeId).ToList();
//            var workflowGroups = (await _session.QueryIndex<WorkflowIndex>(x => x.WorkflowTypeId.IsIn(workflowTypeIds))
//                .ListAsync())
//                .GroupBy(x => x.WorkflowTypeId)
//                .ToDictionary(x => x.Key);

            // Maintain previous route data when generating page links.
            var routeData = new RouteData();

//            routeData.Values.Add("Options.Filter", options.Filter);
            routeData.Values.Add("Options.Search", options.Search);
//            routeData.Values.Add("Options.Order", options.Order);

            var pagerShape = (await New.Pager(pager)).TotalItemCount(currentCommentList.Count).RouteData(routeData);
            var model      = new CommentsIndexViewModel
            {
                Comments = currentCommentList,
                Options  = options,
                Pager    = pagerShape
            };

            return(View(model));
        }
Ejemplo n.º 42
0
 partial void DeleteNew(New instance);
        public async Task <IActionResult> Index(WorkflowTypeIndexOptions options, PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows))
            {
                return(Forbid());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            if (options == null)
            {
                options = new WorkflowTypeIndexOptions();
            }

            var query = _session.Query <WorkflowType, WorkflowTypeIndex>();

            switch (options.Filter)
            {
            case WorkflowTypeFilter.All:
            default:
                break;
            }

            if (!string.IsNullOrWhiteSpace(options.Search))
            {
                query = query.Where(w => w.Name.Contains(options.Search));
            }

            switch (options.Order)
            {
            case WorkflowTypeOrder.Name:
                query = query.OrderBy(u => u.Name);
                break;
            }

            var count = await query.CountAsync();

            var workflowTypes = await query
                                .Skip(pager.GetStartIndex())
                                .Take(pager.PageSize)
                                .ListAsync();

            var workflowTypeIds = workflowTypes.Select(x => x.WorkflowTypeId).ToList();
            var workflowGroups  = (await _session.QueryIndex <WorkflowIndex>(x => x.WorkflowTypeId.IsIn(workflowTypeIds))
                                   .ListAsync())
                                  .GroupBy(x => x.WorkflowTypeId)
                                  .ToDictionary(x => x.Key);

            // Maintain previous route data when generating page links.
            var routeData = new RouteData();

            routeData.Values.Add("Options.Filter", options.Filter);
            routeData.Values.Add("Options.Search", options.Search);
            routeData.Values.Add("Options.Order", options.Order);

            var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData);
            var model      = new WorkflowTypeIndexViewModel
            {
                WorkflowTypes = workflowTypes
                                .Select(x => new WorkflowTypeEntry
                {
                    WorkflowType  = x,
                    Id            = x.Id,
                    WorkflowCount = workflowGroups.ContainsKey(x.WorkflowTypeId) ? workflowGroups[x.WorkflowTypeId].Count() : 0,
                    Name          = x.Name
                })
                                .ToList(),
                Options = options,
                Pager   = pagerShape
            };

            model.Options.WorkflowTypesBulkAction = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Delete"].Value, Value = nameof(WorkflowTypeBulkAction.Delete)
                }
            };

            return(View(model));
        }
Ejemplo n.º 44
0
void case_546()
#line 4020 "cs-parser.jay"
{
		Error_SyntaxError (yyToken);
		/* It can be any of new expression, create the most common one*/
		yyVal = new New ((FullNamedExpression) yyVals[-1+yyTop], null, GetLocation (yyVals[-2+yyTop]));
	  }
Ejemplo n.º 45
0
        public ActionResult Index(AdminIndexOptions options, PagerParameters pagerParameters)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to list workflows")))
            {
                return(new HttpUnauthorizedResult());
            }

            var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);

            // default options
            if (options == null)
            {
                options = new AdminIndexOptions();
            }

            var queries = _workflowDefinitionRecords.Table;

            switch (options.Filter)
            {
            case WorkflowDefinitionFilter.All:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (!String.IsNullOrWhiteSpace(options.Search))
            {
                queries = queries.Where(w => w.Name.Contains(options.Search));
            }

            var pagerShape = New.Pager(pager).TotalItemCount(queries.Count());

            switch (options.Order)
            {
            case WorkflowDefinitionOrder.Name:
                queries = queries.OrderBy(u => u.Name);
                break;
            }

            if (pager.GetStartIndex() > 0)
            {
                queries = queries.Skip(pager.GetStartIndex());
            }

            if (pager.PageSize > 0)
            {
                queries = queries.Take(pager.PageSize);
            }

            var results = queries.ToList();

            var model = new AdminIndexViewModel {
                WorkflowDefinitions = results.Select(x => new WorkflowDefinitionEntry {
                    WorkflowDefinitionRecord = x,
                    WokflowDefinitionId      = x.Id,
                    Name = x.Name
                }).ToList(),
                Options = options,
                Pager   = pagerShape
            };

            // maintain previous route data when generating page links
            var routeData = new RouteData();

            routeData.Values.Add("Options.Filter", options.Filter);
            routeData.Values.Add("Options.Search", options.Search);
            routeData.Values.Add("Options.Order", options.Order);

            pagerShape.RouteData(routeData);

            return(View(model));
        }
        public async Task <ActionResult> Index(WorkflowDefinitionListOptions options, PagerParameters pagerParameters)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageWorkflows))
            {
                return(Unauthorized());
            }

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var pager = new Pager(pagerParameters, siteSettings.PageSize);

            if (options == null)
            {
                options = new WorkflowDefinitionListOptions();
            }

            switch (options.Filter)
            {
            default:
                break;
            }

            if (!string.IsNullOrWhiteSpace(options.Search))
            {
                //query = query.Where(w => w.Name.Contains(options.Search));
            }

            switch (options.Order)
            {
//                case WorkflowTypeOrder.Name:
//                    query = query.OrderBy(u => u.Name);
//                    break;
            }

            var count = 0;

            var workflowDefinitionEntries = new List <WorkflowDefinitionListEntry>();

            // Maintain previous route data when generating page links.
            var routeData = new RouteData();

            routeData.Values.Add("Options.Filter", options.Filter);
            routeData.Values.Add("Options.Search", options.Search);
            routeData.Values.Add("Options.Order", options.Order);

            var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData);
            var model      = new WorkflowDefinitionListViewModel
            {
                WorkflowDefinitions = workflowDefinitionEntries
                                      .Select(x => new WorkflowDefinitionListEntry()
                {
                    WorkflowDefinition    = x.WorkflowDefinition,
                    WorkflowInstanceCount = 0
                })
                                      .ToList(),
                Options = options,
                Pager   = pagerShape
            };

            model.Options.BulkActions = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = S["Delete"].Value, Value = nameof(WorkflowDefinitionListBulkAction.Delete)
                }
            };

            return(View(model));
        }
Ejemplo n.º 47
0
        public ClassDeclarationSyntax GenerateServiceClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, ServiceTyp).WithXmlDoc(XmlDoc.Summary($"The {ClassName} Service."));

            using (ctx.InClass(cls))
            {
                var discoveryVersionTyp = Typ.Manual("Google.Apis.Discovery", "DiscoveryVersion");
                var version             = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), "Version")
                                          .WithInitializer(ApiVersion)
                                          .WithXmlDoc(XmlDoc.Summary("The API version."));
                var discoveryVersion = Field(Modifier.Public | Modifier.Static, ctx.Type(discoveryVersionTyp), "DiscoveryVersionUsed")
                                       .WithInitializer(ctx.Type(discoveryVersionTyp).Access(nameof(DiscoveryVersion.Version_1_0)))
                                       .WithXmlDoc(XmlDoc.Summary("The discovery version used to generate this service."));

                var parameterlessCtor = Ctor(Modifier.Public, cls, ThisInitializer(New(ctx.Type <BaseClientService.Initializer>())()))()
                                        .WithBody()
                                        .WithXmlDoc(XmlDoc.Summary("Constructs a new service."));

                var initializerParam = Parameter(ctx.Type <BaseClientService.Initializer>(), "initializer");

                var featuresArrayInitializer = Features.Any()
                    ? NewArray(ctx.ArrayType(Typ.Of <string[]>()))(Features.ToArray())
                    : NewArray(ctx.ArrayType(Typ.Of <string[]>()), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
                var features = Property(Modifier.Public | Modifier.Override, ctx.Type <IList <string> >(), "Features")
                               .WithGetBody(featuresArrayInitializer)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service supported features."));

                var nameProperty = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "Name")
                                   .WithGetBody(ApiName)
                                   .WithXmlDoc(XmlDoc.Summary("Gets the service name."));

                // TODO: BaseURI without BaseUriOverride, via #if
                var baseUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BaseUri")
                              .WithGetBody(IdentifierName("BaseUriOverride").NullCoalesce(BaseUri))
                              .WithXmlDoc(XmlDoc.Summary("Gets the service base URI."));

                var basePath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BasePath")
                               .WithGetBody(BasePath)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service base path."));

                // TODO: #if !NET40 for both of these
                var batchUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchUri")
                               .WithGetBody(BatchUri)
                               .WithXmlDoc(XmlDoc.Summary("Gets the batch base URI; ", XmlDoc.C("null"), " if unspecified."));
                var batchPath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchPath")
                                .WithGetBody(BatchPath)
                                .WithXmlDoc(XmlDoc.Summary("Gets the batch base path; ", XmlDoc.C("null"), " if unspecified."));

                var resourceProperties = Resources
                                         .Select(resource => AutoProperty(Modifier.Public | Modifier.Virtual, ctx.Type(resource.Typ), resource.PropertyName)
                                                 .WithXmlDoc(XmlDoc.Summary($"Gets the {resource.PropertyName} resource.")))
                                         .ToArray();

                var parameterizedCtor = Ctor(Modifier.Public, cls, BaseInitializer(initializerParam))(initializerParam)
                                        .WithBlockBody(resourceProperties.Zip(Resources).Select(pair => pair.First.Assign(New(ctx.Type(pair.Second.Typ))(This))).ToArray())
                                        .WithXmlDoc(
                    XmlDoc.Summary("Constructs a new service."),
                    XmlDoc.Param(initializerParam, "The service initializer."));

                cls = cls.AddMembers(version, discoveryVersion, parameterlessCtor, parameterizedCtor, features, nameProperty, baseUri, basePath, batchUri, batchPath);

                if (AuthScopes.Any())
                {
                    var scopeClass = Class(Modifier.Public, Typ.Manual(PackageName, "Scope"))
                                     .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scopes for use with the {Title}."));
                    using (ctx.InClass(scopeClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Static, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeClass = scopeClass.AddMembers(field);
                        }
                    }

                    var scopeConstantsClass = Class(Modifier.Public | Modifier.Static, Typ.Manual(PackageName, "ScopeConstants"))
                                              .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scope constants for use with the {Title}."));
                    using (ctx.InClass(scopeConstantsClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeConstantsClass = scopeConstantsClass.AddMembers(field);
                        }
                    }

                    cls = cls.AddMembers(scopeClass, scopeConstantsClass);
                }

                foreach (var method in Methods)
                {
                    cls = cls.AddMembers(method.GenerateMethodDeclaration(ctx));
                }

                cls = cls.AddMembers(resourceProperties);
            }
            return(cls);
        }