Example #1
0
 public override void ApplyDamage(Section s, int power)
 {
     CombatLog.addLine("CRIT STRIKE!");
     base.ApplyDamage (s, power + power * critStrikeBonusPercentage / 100);
     s.attributes.material.SetSectionEffect(new DefaultSectionEffect(appliedSection));
     Destruct();		//Destroy this effect - One time use... unless we want it destroyed at the end of the turn...
 }
Example #2
0
    //
    public void AgreeToTeach(Section s)
    {
        Teaches.Add(s);

        // We need to link this bidirectionally.
        s.Instructor = this;
    }
Example #3
0
        public void TestJsonProperty()
        {
            // Arrange
             var section = new Section
             {
                 TypeName = typeof (SimpleSection).AssemblyQualifiedName
             };
             section.Parameters.Add("Complex", new Parameter
             {
                 Name = "Complex",
                 Translator = "Json",
                 TypeName = typeof(ComplexProperty).AssemblyQualifiedName,
                 Values = new List<ParameterValue>
                 {
                     new ParameterValue
                     {
                         Value = "{ \"Name\": \"Test\", \"Valid\": true }"
                     }
                 }
             });

             // Act
             var service = Configure.With(settings => settings.AddJsonTranslator().AddSection(section));
             var result = service.GetSection<SimpleSection>();

             // Assert
             Assert.IsNotNull(result);
             Assert.IsNotNull(result.Complex);
             Assert.AreEqual("Test", result.Complex.Name);
        }
Example #4
0
		/// <summary>
		/// Create a new <i>Service Description Table</i> instance.
		/// </summary>
		/// <param name="section">The section which is currently parsed.</param>
		public SDT(Section section) : base(section)
		{
			// Get the size of the service entry region
			int offset = 8, length = section.Length - 3 - offset - 4;

			// Minimum size
			if ( length < 0 ) return;

			// Construct
			TransportStreamIdentifier = Tools.MergeBytesToWord(section[1], section[0]);
			OriginalNetworkIdentifier = Tools.MergeBytesToWord(section[6], section[5]);

			// Create helper
			ArrayList services = new ArrayList();

			// Process
			for ( ServiceEntry entry ; null != (entry = ServiceEntry.Create(this, offset, length)) ; )
				if ( entry.IsValid )
				{
					// Remember
					services.Add(entry);

					// Correct
					offset += entry.Length;
					length -= entry.Length;
				}

			// Usefull
			m_IsValid = (0 == length);

			// Convert
			if ( m_IsValid ) Services = (ServiceEntry[])services.ToArray(typeof(ServiceEntry));
		}
Example #5
0
 //returns the cost of the newly added section
 public void AddSection(Section s)
 {
     this.sections.Add(s);
     s.attributes.height = this.sections.Count-1;
     s.attributes.myTower = this;
     StressCheck();
 }
Example #6
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            HeaderView.SetImage(null, Images.Avatar);
            Title = ViewModel.Name;

            ViewModel.Bind(x => x.User, x =>
            {
                var name = x.FirstName + " " + x.LastName;
                HeaderView.SubText = string.IsNullOrWhiteSpace(name) ? x.Username : name;
                HeaderView.SetImage(new Avatar(x.Avatar).ToUrl(128), Images.Avatar);
                RefreshHeaderView();

                var followers = new StyledStringElement("Followers", () => ViewModel.GoToFollowersCommand.Execute(null), Images.Heart);
                var events = new StyledStringElement("Events", () => ViewModel.GoToEventsCommand.Execute(null), Images.Event);
                var organizations = new StyledStringElement("Groups", () => ViewModel.GoToGroupsCommand.Execute(null), Images.Group);
                var repos = new StyledStringElement("Repositories", () => ViewModel.GoToRepositoriesCommand.Execute(null), Images.Repo);
                var members = new StyledStringElement("Members", () => ViewModel.GoToMembersCommand.Execute(null), Images.Team);
                var midSec = new Section(new UIView(new CGRect(0, 0, 0, 20f))) { events, organizations, members, followers };
                Root = new RootElement(Title) { midSec, new Section { repos } };
            });
//          if (!ViewModel.IsLoggedInUser)
//              NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action, (s, e) => ShowExtraMenu());
        }
Example #7
0
		public static IEnumerable<Section> Get(IEnumerable<Assembly> testAssemblies)
		{
			var categories = new Dictionary<string, Section>();
			foreach (var asm in testAssemblies)
			{
				foreach (var type in asm.ExportedTypes)
				{
					#if PCL
					var section = type.GetTypeInfo().GetCustomAttribute<SectionAttribute>(false);
					#else
					var section = type.GetCustomAttribute<SectionAttribute>(false);
					#endif
					if (section != null)
					{
						if (section.Requires != null && !Platform.Instance.Supports(section.Requires))
							continue;

						Section category;
						if (!categories.TryGetValue(section.Category, out category))
							categories.Add(section.Category, category = new Section { Text = section.Category });

						var testType = type;
						category.Add(new SectionItem { Creator = () => Activator.CreateInstance(testType) as Control, Text = section.Name });
					}
				}
			}
			foreach (var category in categories.Values)
				category.Sort((x, y) => string.Compare(x.Text, y.Text, StringComparison.CurrentCultureIgnoreCase));
			return categories.Values.OrderBy(r => r.Text);
		}
Example #8
0
    //**************************************
    //
    public void AgreeToTeach(Section s)
    {
        //��ϰ14.3
          bool theSameTime = true;

          for (int i = 0; i < Teaches.Count; i++)
          {

          if (Teaches[i].OfferedIn == s.OfferedIn)
          {
              if (Teaches[i].DayOfWeek == s.DayOfWeek)
              {
                  if (Teaches[i].TimeOfDay == s.TimeOfDay)
                  {
                      theSameTime = false;
                  }
                  else continue;
              }
              else continue;
          }
          else continue;
          }

          if(theSameTime){
          Teaches.Add(s);
          // We need to link this bidirectionally.
          s.Instructor = this;
          }
          else
          {
          Console.WriteLine("ͬһ�졢ͬһʱ������Ͽ�ʱ���ͻ��");
          }
    }
 public MultipleChoiceEntryElement (string caption, params string[] options): base(caption, new RadioGroup(-1)) {
     var section = new Section(caption);
     foreach(var s in options) {
         section.Add(new RadioEntryElement(s));
     }
     Add(section);
 }
	private void Core()
	{
		var rootStyles = new RootElement ("Add New Styles");

		var styleHeaderElement = new Section ("Style Header");
		var manualEntryRootElement = new RootElement ("Manual Entry");
		styleHeaderElement.Add (manualEntryRootElement);

		var quickFillElement = new Section ("Quick Fill");
		var womenTops = new RootElement ("Womens Tops");
		var womenOutwear = new RootElement ("Womens Outerwear");
		var womenSweaters = new RootElement ("Womens Sweaters");
		quickFillElement.AddAll (new [] { womenTops, womenOutwear, womenSweaters });

		rootStyles.Add (new [] { styleHeaderElement, quickFillElement });

		// DialogViewController derives from UITableViewController, so access all stuff from it
		var rootDialog = new DialogViewController (rootStyles);
		rootDialog.NavigationItem.BackBarButtonItem = new UIBarButtonItem("Back", UIBarButtonItemStyle.Bordered, null);

		EventHandler handler = (s, e) => {
			if(_popover != null)
				_popover.Dismiss(true);
		};

		rootDialog.NavigationItem.SetLeftBarButtonItem(new UIBarButtonItem("Cancel", UIBarButtonItemStyle.Bordered, handler), true);
		rootDialog.NavigationItem.SetRightBarButtonItem(new UIBarButtonItem("Create", UIBarButtonItemStyle.Bordered, null), true);

		NavigationPopoverContentViewController = new UINavigationController (rootDialog);
	}
        public LastfmPreferences (LastfmSource source)
        {
            var service = ServiceManager.Get<PreferenceService> ();
            if (service == null) {
                return;
            }

            this.source = source;

            service.InstallWidgetAdapters += OnPreferencesServiceInstallWidgetAdapters;
            source_page = new Banshee.Preferences.SourcePage (source) {
                (account_section = new Section ("lastfm-account", Catalog.GetString ("Account"), 20) {
                    (username_preference = new SchemaPreference<string> (LastfmSource.LastUserSchema,
                        Catalog.GetString ("_Username")) {
                        ShowLabel = false
                    }),
                    new VoidPreference ("lastfm-signup")
                }),
                (prefs_section = new Section ("lastfm-settings", Catalog.GetString ("Preferences"), 30))
            };

            scrobbler = ServiceManager.Get<Banshee.Lastfm.Audioscrobbler.AudioscrobblerService> ();
            if (scrobbler != null) {
                reporting_preference = new Preference<bool> ("enable-song-reporting",
                    Catalog.GetString ("_Enable Song Reporting"), null, scrobbler.Enabled);
                reporting_preference.ValueChanged += root => scrobbler.Enabled = reporting_preference.Value;
                prefs_section.Add (reporting_preference);
            }
        }
Example #12
0
        public ActionResult Create(Section section)
        {
            RavenSession.Store(section);
              RavenSession.SaveChanges();

              return RedirectToAction("Index");
        }
Example #13
0
        public ActionResult Edit(string id, Section section)
        {
            RavenSession.Store(section);
              RavenSession.SaveChanges();

              return RedirectToAction("Index");
        }
 public override void Initialize()
 {
     sectionCompletion = new Section(Document);
     bullet = new Bullet(Document);
     directives = new Directives(Document);
     base.Initialize();
 }
        public List<ArticleInfo> ScrapePage(Section section, int page)
        {
            var builder = new UriBuilder(section.Host);
            builder.Path += section.RelativeUrl;
            var url = builder.ToString().AddQueryParameterToUrl("page", page);

            var docNode = Utilities.DownloadPage(url);
            var articleDivs = docNode.SelectNodes("//div[@class='category-headline-item']");

            var result = new List<ArticleInfo>();

            foreach (var articleDiv in articleDivs)
            {
                try
                {
                    result.Add(ParseArticleInfoDiv(articleDiv));
                }
                catch (CommonParsingException e)
                {
                }
                catch (Exception e)
                {
                    e.Data["articleDiv"] = articleDiv.OuterHtml;
                    _log.Error("An error occurred while parsing article info div.", e);
                }
            }

            return result;
        }
Example #16
0
 public void RemoveDot(Section sc)
 {
     if(dotRegistry.ContainsKey(sc)) {
         dotRegistry.Remove(sc);
         sc.DotFinished();
     }
 }
    public void OnDestroy()
    {
        if (_section != null)
            _section.Destroy();

        _section = null;
    }
Example #18
0
        private void AppendBulletedList(Section section)
        {
            Paragraph paragraph = null;

            paragraph = section.AddParagraph();

            //Append Text
            paragraph.AppendText("Bulleted List");

            paragraph.ApplyStyle(BuiltinStyle.Heading3);

            paragraph = section.AddParagraph();
            for (int i = 0; i < 5; i++)
            {
                paragraph = section.AddParagraph();
                paragraph.AppendText("Item" + i.ToString());

                if (i == 0)
                {
                    paragraph.ListFormat.ApplyBulletStyle();
                }
                else
                {
                    paragraph.ListFormat.ContinueListNumbering();
                }

                paragraph.ListFormat.ListLevelNumber = 1;
            }
        }
Example #19
0
 public void RegisterDot(Section sc, int damage)
 {
     if(dotRegistry.ContainsKey(sc)) {
         dotRegistry.Remove(sc);
     }
     dotRegistry.Add(sc, new Dot(DOT_DURATION, damage/DOT_DURATION));
 }
        /// <summary>
        /// Creates a topic.
        /// </summary>
        public Topic(Section section, string fixUrl)
        {
            mTopicDoc = new Document();
            mTopicDoc.AppendChild(mTopicDoc.ImportNode(section, true, ImportFormatMode.KeepSourceFormatting));
            mTopicDoc.FirstSection.Remove();

            Paragraph headingPara = (Paragraph)mTopicDoc.FirstSection.Body.FirstChild;
            if (headingPara == null)
                ThrowTopicException("The section does not start with a paragraph.", section);

            mHeadingLevel = headingPara.ParagraphFormat.StyleIdentifier - StyleIdentifier.Heading1;
            if ((mHeadingLevel < 0) || (mHeadingLevel > 8))
                ThrowTopicException("This topic does not start with a heading style paragraph.", section);

            mTitle = headingPara.GetText().Trim();
            if (mTitle == "")
                ThrowTopicException("This topic heading does not have text.", section);

            // We actually remove the heading paragraph because <h1> will be output in the banner.
            headingPara.Remove();

            mTopicDoc.BuiltInDocumentProperties.Title = mTitle;

            FixHyperlinks(section.Document, fixUrl);
        }
Example #21
0
    //**************************************
    //��3��ȷ��һλ���ڲ�����ͬһ�졢ͬһʱ�̽����ſ�
    public void AgreeToTeach(Section s)
    {
        bool isSameTime = true;

          for (int i = 0; i < Teaches.Count; i++)
          {
          if (Teaches[i].OfferedIn == s.OfferedIn)
          {
              if (Teaches[i].DayOfWeek == s.DayOfWeek)
              {
                  if (Teaches[i].TimeOfDay == s.TimeOfDay)
                  {
                      isSameTime = false;
                  }
                  else continue;
              }
              else continue;
          }
          else continue;
          }

          if (isSameTime)
          {
          Teaches.Add(s);
          // We need to link this bidirectionally.
          s.Instructor = this;
          }
          else
          {
          Console.WriteLine("һλ���ڲ�����ͬһ���ͬһʱ�̽������ſΣ�");
          }
    }
        public void ResetTest()
        {
            var objectFile = new ObjectFileMock();
            Context context = new Context(objectFile);

            Section section = new Section("Test");
            var symbol = new Symbol(SymbolType.Public, "test");
            var relocation = new Relocation(symbol, section, 0, 0, RelocationType.Default32);

            context.SymbolTable.Add(symbol);
            context.RelocationTable.Add(relocation);
            context.Section = section;
            context.Address = 123456789;
            Assert.AreEqual(symbol, context.SymbolTable[0]);
            Assert.AreEqual(relocation, context.RelocationTable[0]);
            Assert.AreEqual(section, context.Section);
            Assert.AreEqual((Int128)123456789, context.Address);

            context.Reset();

            // These have not changed
            Assert.AreEqual(symbol, context.SymbolTable[0]);
            Assert.AreEqual(relocation, context.RelocationTable[0]);

            // These are reset
            Assert.AreEqual(null, context.Section);
            Assert.AreEqual((Int128)0, context.Address);
        }
        private async Task LoadLanguages()
        {
            var lRepo = new LanguageRepository();
            var langs = await lRepo.GetLanguages();

            var sec = new Section();

            langs.Insert(0, new Language("All Languages", null));
            sec.AddAll(langs.Select(x =>
            {
                var el = new StringElement(x.Name) { Accessory = UITableViewCellAccessory.None };
                el.Clicked.Subscribe(_ => _languageSubject.OnNext(x));
                return el;
            }));

            Root.Reset(sec);

            if (SelectedLanguage != null)
            {
                var el = sec.Elements.OfType<StringElement>().FirstOrDefault(x => string.Equals(x.Caption, SelectedLanguage.Name));
                if (el != null)
                    el.Accessory = UITableViewCellAccessory.Checkmark;

                var indexPath = el?.IndexPath;
                if (indexPath != null)
                    TableView.ScrollToRow(indexPath, UITableViewScrollPosition.Middle, false);
            }
        }
Example #24
0
        /// <summary>
        /// Create a new <i>Program Association Table</i> instance.
        /// </summary>
        /// <param name="section">The section which is currently parsed.</param>
        public PAT(Section section)
            : base(section)
        {
            // Get position size of the program list
            int offset = 5, length = section.Length - 3 - offset - 4;

            // Minimum size
            if (length < 0) return;

            // Construct
            TransportStreamIdentifier = Tools.MergeBytesToWord(section[1], section[0]);

            // Process all
            for (; length >= 4; offset += 4, length -= 4)
            {
                // Load items
                ushort number = Tools.MergeBytesToWord(section[offset + 1], section[offset + 0]);
                ushort pid = (ushort)(0x1fff&Tools.MergeBytesToWord(section[offset + 3], section[offset + 2]));

                // Remember
                if (0 == number)
                {
                    // The NIT
                    NetworkInformationTable = pid;
                }
                else
                {
                    // Some program
                    ProgramIdentifier[number] = pid;
                }
            }

            // Usefull
            m_IsValid = (0 == length);
        }
Example #25
0
        /// <summary>
        /// Erzeugt eine neue Tabelle.
        /// </summary>
        /// <param name="section">Der Bereich, in den die Tabelle eingebettet ist.</param>
        public TOT( Section section )
            : base( section )
        {
            // Load length
            int length = section.Length - 7;

            // Check for minimum length required
            if (length < 7) 
                return;

            // Load the time
            Time = Tools.DecodeTime( section, 0 );

            // Correct
            length -= 7;

            // Load the length of the descriptors
            int deslen = Tools.MergeBytesToWord( section[6], section[5] ) & 0x0fff;

            // Validate
            if (deslen > length)
                return;

            // Create my descriptors
            Descriptors = Descriptor.Load( this, 7, deslen );

            // Done
            m_IsValid = (deslen == length);
        }
Example #26
0
 /// <summary>
 /// Gets a list of Instrument objects filtered by a section
 /// </summary>
 /// <param name="selectedSection">A section to filter instruments by</param>
 /// <returns></returns>
 //public List<Instrument> GetInstruments(Section selectedSection)
 //{
 //    using (dbconn = new SqlConnection(Music.Properties.Settings.Default.orchestraConnection))
 //    {
 //        dbconn.Open();
 //        dbcomm = new SqlCommand(String.Format("select Instrument, Type from Instruments where Type = '{0}' order by Type asc",selectedSection.ToString()), dbconn);
 //        dbreader = dbcomm.ExecuteReader();
 //        List<Instrument> instruments = new List<Instrument>();
 //        while (dbreader.Read())
 //        {
 //            string instrumentName = dbreader["Instrument"].ToString();
 //            Section instrumentType;
 //            if (Enum.TryParse<Section>(dbreader["Type"].ToString(), true, out instrumentType))
 //                instruments.Add(new Instrument(instrumentName, instrumentType));
 //            else
 //                instruments.Add(new Instrument());
 //        }
 //        dbconn.Close();
 //        return instruments;
 //    }
 //}
 /// <summary>
 /// Gets a list of Instrument objects filtered by an array of Sections
 /// </summary>
 /// <param name="selectedSection">An array to filter instruments by</param>
 /// <returns></returns>
 public List<Instrument> GetInstruments(Section[] selectedSection)
 {
     try
     {
         using (dbconn = new SqlConnection(Music.Properties.Settings.Default.orchestraConnection))
         {
             dbconn.Open();
             //This command creates a sql string that checks for instruments of a type contained in the parameter list which is created by using a string join and some string formats
             dbcomm = new SqlCommand(String.Format("select Instrument, Type from Instruments where Type in({0}) order by Instrument asc", String.Join(",", selectedSection.Select(x => String.Format("'{0}'", x.ToString())).ToArray())), dbconn);
             dbreader = dbcomm.ExecuteReader();
             List<Instrument> instruments = new List<Instrument>();
             while (dbreader.Read())
             {
                 string instrumentName = dbreader["Instrument"].ToString();
                 Section instrumentType;
                 //This sneaky little section tries to parse the instrument value of the instrument by using the Enum.TryParse which returns a bool, if false there is a bad type and a default instrument replaces it
                 if (Enum.TryParse<Section>(dbreader["Type"].ToString(), true, out instrumentType))
                     instruments.Add(new Instrument(instrumentName, instrumentType));
                 else
                     instruments.Add(new Instrument());
             }
             return instruments;
         }
     }
     catch
     {
         throw new ArgumentException("Something has gone horribly, horribly wrong. Most likely my SQL instance is unreachable or down.");
     }
 }
Example #27
0
        internal ConfigurationService()
        {
            var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            _configPath = Path.Combine(appData, AppFolderName);
            _configFileName = Path.Combine(_configPath, ConfigFileName);

            if(!Directory.Exists(_configPath))
            {
                try
                {
                    Directory.CreateDirectory(_configPath);
                }
                catch(Exception exc)
                {
                    if(exc.IsCritical())
                    {
                        throw;
                    }
                    LoggingService.Global.Error(exc);
                }
            }

            _configuration            = LoadConfig(ConfigFileName, "Configuration");
            _rootSection              = _configuration.RootSection;
            _guiSection               = _rootSection.GetCreateSection("Gui");
            _globalSection            = _rootSection.GetCreateSection("Global");
            _viewsSection             = _rootSection.GetCreateSection("Tools");
            _providersSection         = _rootSection.GetCreateSection("Providers");
            _repositoryManagerSection = _rootSection.GetCreateSection("RepositoryManager");
        }
		/// <summary>
		/// Parses the timeout sleep interval settings.
		/// </summary>
		/// <param name="section">The section.</param>
		/// <returns></returns>
		private TimeSpan ParseTimeoutSleepIntervalSettings(Section section)
		{
			TimeSpan timeSpan = _defaultSleepInterval;

			if (section.Settings.ContainsKey("Timeout"))
			{
				int interval;
				if (int.TryParse(section.Settings["Timeout"].Value, out interval))
				{
					timeSpan = TimeSpan.FromMilliseconds(interval);
				}
				else
				{
					UnityResolver.UnityContainer.Resolve<ILogger>().LogEvent(() =>
						Config.AppEvents.GainWinServicesExactTarget.ExactTargetWarning,
						string.Format("Can't parse timeout setting (='{1}') for {0}. {2} msec  will be used by default.",
						GetType().Name, section.Settings["Timeout"].Value, _defaultSleepInterval.TotalMilliseconds));
				}
			}
			else
			{
				UnityResolver.UnityContainer.Resolve<ILogger>().LogEvent(() =>
					Config.AppEvents.GainWinServicesExactTarget.ExactTargetWarning,
					string.Format("Can't read timeout setting for {0}. {1} msec  will be used by default.",
					GetType().Name, _defaultSleepInterval.TotalMilliseconds));
			}

			return timeSpan;
		}
Example #29
0
		/// <summary>
		/// Populates the page with sessions, grouped by time slot
		/// that are marked as 'favorite'
		/// </summary>
		protected override void PopulateTable()
		{
			// get the sessions from the database
			var sessions = BL.Managers.SessionManager.GetSessions ();
			var favs = BL.Managers.FavoritesManager.GetFavorites();
			// extract IDs from Favorites query
			List<string> favoriteIDs = new List<string>();
			foreach (var f in favs) favoriteIDs.Add (f.SessionKey);

			// build list, matching the Favorite.SessionKey with actual
			// Session.Key rows - which might have moved if the data changed
			var root = 	new RootElement ("Favorites") {
						from s in sessions
							where favoriteIDs.Contains(s.Key)
							group s by s.Start.Ticks into g
							orderby g.Key
							select new Section (new DateTime (g.Key).ToString ("dddd HH:mm")) {
							from hs in g
							   select (Element) new SessionElement (hs)
			}};	
			
			if(root.Count == 0) {
				var section = new Section("No favorites") {
					new StyledStringElement("Touch the star to favorite a session") 
				};
				root.Add(section);
			}
			Root = root;
		}	
Example #30
0
 public static async Task<Response<List<Image>>> GetGallery(Section? section = null, Sort? sort = null, Window? window = null, bool? showViral = null, int? page = null)
 {
     string uri = "gallery";
     if (section != null)
     {
         uri += "/" + section.ToString().ToLower();
         if(sort != null)
         {
             uri += "/" + sort.ToString().ToLower();
             if(window != null)
             {
                 uri += "/" + window.ToString().ToLower();
                 if (showViral != null)
                 {
                     uri += "/" + showViral.ToString();
                     if (page != null)
                     {
                         uri += "/" + page;
                     }
                 }
             }
         }
     }
     return await NetworkHelper.GetRequest<List<Image>>(uri);
 }
Example #31
0
        protected override void ParseLine(List <LegacyManiaSkinConfiguration> output, Section section, string line)
        {
            line = StripComments(line);

            switch (section)
            {
            case Section.Mania:
                var pair = SplitKeyVal(line);

                switch (pair.Key)
                {
                case "Keys":
                    currentConfig = new LegacyManiaSkinConfiguration(int.Parse(pair.Value, CultureInfo.InvariantCulture));

                    // Silently ignore duplicate configurations.
                    if (output.All(c => c.Keys != currentConfig.Keys))
                    {
                        output.Add(currentConfig);
                    }

                    // All existing lines can be flushed now that we have a valid configuration.
                    flushPendingLines();
                    break;

                default:
                    pendingLines.Add(line);

                    // Hold all lines until a "Keys" item is found.
                    if (currentConfig != null)
                    {
                        flushPendingLines();
                    }
                    break;
                }

                break;
            }
        }
Example #32
0
        /// <summary>
        /// Create a new <i>Program Map Table</i> instance.
        /// </summary>
        /// <param name="section">The section which is currently parsed.</param>
        public PMT(Section section)
            : base(section)
        {
            // Special recommendation
            if ((0 != SectionNumber) || (0 != LastSectionNumber))
            {
                return;
            }

            // Get the overall length
            int offset = 9, length = section.Length - 3 - offset - 4;

            // Not possible
            if (length < 0)
            {
                return;
            }

            // Read statics
            ProgramNumber = Tools.MergeBytesToWord(Section[1], Section[0]);
            PCRPID        = (ushort)(0x1fff & Tools.MergeBytesToWord(Section[6], Section[5]));

            // Length
            int infoLength = 0xfff & Tools.MergeBytesToWord(Section[8], Section[7]);

            // Validate
            if (length < infoLength)
            {
                return;
            }

            // Create my descriptors
            Descriptors = Descriptor.Load(this, offset, infoLength);

            // Adjust
            offset += infoLength;
            length -= infoLength;

            // Result
            var entries = new List <ProgramEntry>();

            // Fill
            while (length > 0)
            {
                // Create next
                ProgramEntry entry = ProgramEntry.Create(this, offset, length);

                // Failed
                if ((null == entry) || !entry.IsValid)
                {
                    return;
                }

                // Remember
                entries.Add(entry);

                // Adjust
                offset += entry.Length;
                length -= entry.Length;
            }

            // Use it
            ProgramEntries = entries.ToArray();

            // Usefull
            m_IsValid = true;
        }
Example #33
0
    internal static bool smethod_0(Class857 A_0, DocumentObject A_1, Class108 A_2)
    {
        int num = 14;

        A_0.method_39(new Class1052());
        A_0.method_38().method_1(A_0.method_11().method_1());
        A_0.method_38().method_13(string.Format(BookmarkStart.b("伳ص䔷᜹伻儽㔿ぁ❃⍅", 14), A_0.method_38().method_0()));
        string str = A_0.method_38().method_0();

        if (str != null)
        {
            if (!(str == BookmarkStart.b("䀳圵娷嘹夻ጽ⼿⑁楃╅❇⑉㡋⭍㹏♑", num)))
            {
                if (!(str == BookmarkStart.b("唳娵䠷刹崻尽┿㙁ⵃ╅⥇♉態❍㹏㙑ㅓ⹕", num)))
                {
                    goto Label_020E;
                }
                A_0.method_38().method_7(FieldType.FieldIndex);
                A_0.method_38().method_9(BookmarkStart.b("紳砵簷缹搻", num));
            }
            else
            {
                A_0.method_38().method_7(FieldType.FieldTOC);
                A_0.method_38().method_9(BookmarkStart.b("怳礵笷", num));
            }
            Class396 class3 = A_0.method_11();
            A_0.method_38().method_5(class3.method_12(BookmarkStart.b("䜳䈵䄷嘹夻ጽ⸿⍁⥃⍅", num), null));
            if (Class567.smethod_16(A_0.method_38().method_4()))
            {
                Section section = A_2.method_8().Clone();
                section.SectPr.method_57(SectionBreakType.NoBreak);
                Class95 class4 = (Class95)A_0.method_13().method_3(A_0.method_38().method_4(), BookmarkStart.b("䜳匵嬷丹唻儽⸿", num), A_0.method_20());
                if ((class4 != null) && (class4.method_12() != null))
                {
                    ((Class17)section.SectPr.Clone()).method_37(section.SectPr);
                }
                A_0.method_29().Push(section);
                A_0.method_31(true);
            }
            smethod_2(A_0, A_1);
            smethod_1(A_0);
            if (A_1 == null)
            {
                A_1 = A_0.method_9().LastSection.Body;
            }
            List <DocumentObject> childElements = A_1.GetChildElements(DocumentObjectType.Paragraph, false);
            if (childElements.Count != 0)
            {
                Paragraph paragraph1 = (Paragraph)childElements[childElements.Count - 1];
            }
            else
            {
                new Paragraph(A_0.method_9());
            }
            if (Class567.smethod_16(A_0.method_38().method_4()))
            {
                A_0.method_33(true);
                A_0.method_29().Pop();
            }
            return(true);
        }
Label_020E:
        A_0.method_38().method_11(true);
        smethod_2(A_0, A_1);
        return(false);
    }
Example #34
0
 internal void AddSection(Section section)
 {
     Add(Sections, section);
 }
Example #35
0
 public static SectionDTO ToDTO(this Section section) => section?.CopyTo(new SectionDTO());
Example #36
0
 public static Section CreateSection(short maxValue, Section previous)
 {
 }
Example #37
0
        static void Main(string[] args)
        {
            Console.WriteLine("Modelo");
            // Crie uma aplicação que receba o nome,endereço, valor de compra e data do dia da compra. O programa deve gerr um arquivo Word com os dados inseridos no formato abaixo
            //Nota Fiscal
            //Nome:
            //Endereço:
            //Valor:
            //Data:

            decimal  valor;
            DateTime data = DateTime.Now;
            string   nome, endereco;

            Console.WriteLine("Informe seu nome:");
            nome = Console.ReadLine();

            Console.WriteLine("Informe seu endereço:");
            endereco = Console.ReadLine();

            Console.WriteLine("Informe o valor da compra:");
            valor = decimal.Parse(Console.ReadLine());

            Document documento = new Document();

            Section NotaFiscal = documento.AddSection();

            //Titulo

            Paragraph titulo = NotaFiscal.AddParagraph();

            titulo.AppendText("Nota Fiscal\n");

            titulo.Format.HorizontalAlignment = HorizontalAlignment.Left;

            ParagraphStyle titulo01 = new ParagraphStyle(documento);

            titulo01.Name = "Cor do Titulo";

            titulo01.CharacterFormat.TextColor = Color.Black;

            titulo01.CharacterFormat.Bold = true;

            documento.Styles.Add(titulo01);

            titulo.ApplyStyle(titulo01.Name);

            //Nome

            Paragraph Nome = NotaFiscal.AddParagraph();

            Nome.AppendText("Nome: ");

            TextRange tr = Nome.AppendText(nome);

            tr.CharacterFormat.Bold = false;

            Nome.Format.HorizontalAlignment = HorizontalAlignment.Left;

            ParagraphStyle Nome01 = new ParagraphStyle(documento);

            Nome01.Name = "Cor do Nome";

            Nome01.CharacterFormat.TextColor = Color.Black;

            Nome01.CharacterFormat.Bold = true;

            documento.Styles.Add(Nome01);

            Nome.ApplyStyle(Nome01.Name);

            //Endereço

            Paragraph Endereço = NotaFiscal.AddParagraph();

            //CharactereFormat format = new CharactereFormat(documento);
            //format.Bold = true;   ((Serve tbm para nao dar quebra))

            // Endereço.AppendText("Endereço ").ApplyCharactereFormat(format);
            // Endereço.AppendText(endereco);

            Endereço.AppendText("Endereço: ");

            TextRange c = Endereço.AppendText(endereco); //Para ficar na msm linha sem dar quebra.

            c.CharacterFormat.Bold = false;

            Endereço.Format.HorizontalAlignment = HorizontalAlignment.Left;

            ParagraphStyle end01 = new ParagraphStyle(documento);

            end01.Name = "Cor do Endereço";

            end01.CharacterFormat.TextColor = Color.Black;

            end01.CharacterFormat.Bold = true;

            documento.Styles.Add(end01);

            Endereço.ApplyStyle(end01.Name);

            //Valor

            Paragraph Preço = NotaFiscal.AddParagraph();

            Preço.AppendText("Valor: ");

            TextRange b = Preço.AppendText($"R${valor}");

            b.CharacterFormat.Bold = false;

            Preço.Format.HorizontalAlignment = HorizontalAlignment.Left;

            ParagraphStyle Preço01 = new ParagraphStyle(documento);

            Preço01.Name = "Cor do Preço";

            Preço01.CharacterFormat.TextColor = Color.Black;

            Preço01.CharacterFormat.Bold = true;

            documento.Styles.Add(Preço01);

            Preço.ApplyStyle(Preço01.Name);

            //Data

            Paragraph Data = NotaFiscal.AddParagraph();

            Data.AppendText("Data: ");

            TextRange a = Data.AppendText(data.ToString("dd/MM/yyyy"));

            a.CharacterFormat.Bold = false;

            Data.Format.HorizontalAlignment = HorizontalAlignment.Left;

            ParagraphStyle Data01 = new ParagraphStyle(documento);

            Data01.Name = "Cor da Data";

            Data01.CharacterFormat.TextColor = Color.Black;

            Data01.CharacterFormat.Bold = true;

            documento.Styles.Add(Data01);

            Data.ApplyStyle(Data01.Name);

            documento.SaveToFile(@"saida01\Modelo.docx", FileFormat.Docx);
        }
Example #38
0
        // How to add pictures into a document.
        public static void AddPictures()
        {
            string documentPath = @"Pictures.docx";
            string pictPath     = @"..\..\..\..\..\..\Testing Files\image1.jpg";

            // Let's create a simple document.
            DocumentCore dc = new DocumentCore();

            // Add a new section.
            Section s = new Section(dc);

            dc.Sections.Add(s);

            // 1. Picture with InlineLayout:

            // Create a new paragraph with picture.
            Paragraph par = new Paragraph(dc);

            s.Blocks.Add(par);

            par.ParagraphFormat.Alignment = HorizontalAlignment.Left;
            // Add some text content.
            par.Content.End.Insert("Shrek and Donkey ", new CharacterFormat()
            {
                FontName = "Calibri", Size = 16.0, FontColor = Color.Black
            });

            // Our picture has InlineLayout - it doesn't have positioning by coordinates
            // and located as flowing content together with text (Run and other Inline elements).
            Picture pict1 = new Picture(dc, InlineLayout.Inline(new Size(100, 100)), pictPath);

            // Add picture to the paragraph.
            par.Inlines.Add(pict1);

            // Add some text content.
            par.Content.End.Insert(" arrive at Farquaad's palace in Duloc, where they end up in a tournament.", new CharacterFormat()
            {
                FontName = "Calibri", Size = 16.0, FontColor = Color.Black
            });

            // 2. Picture with FloatingLayout:
            // Floating layout means that the Picture (or Shape) is positioned by coordinates.
            Picture pict2 = new Picture(dc, pictPath);

            pict2.Layout = FloatingLayout.Floating(
                new HorizontalPosition(50, LengthUnit.Millimeter, HorizontalPositionAnchor.Page),
                new VerticalPosition(70, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin),
                new Size(LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point),
                         LengthUnitConverter.Convert(10, LengthUnit.Centimeter, LengthUnit.Point))
                );

            // Set the wrapping style.
            (pict2.Layout as FloatingLayout).WrappingStyle = WrappingStyle.Square;

            // Add our picture into the section.
            s.Content.End.Insert(pict2.Content);

            // Save our document into DOCX format.
            dc.Save(documentPath, new DocxSaveOptions());

            // Open the result for demonstation purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath)
            {
                UseShellExecute = true
            });
        }
Example #39
0
            /// <summary>
            /// Create Footer for document
            /// </summary>
            /// <param name="section"></param>
            /// <remarks></remarks>
            private void CreateFooter(Section section)
            {
                //Dim info As ApplicationServices.AssemblyInfo
                //info = New ApplicationServices.AssemblyInfo("RescueTekniq.Doc")

                var with_1 = section.Footers.Primary.AddParagraph();
                var with_2 = with_1.Format;

                with_2.Font.Size = 5;
                with_2.Alignment = ParagraphAlignment.Right;
                with_1.AddDateField();
                with_1.AddLineBreak();
                //.AddText(info.Version.ToString)

                var with_3 = section.Footers.Primary.AddParagraph();
                var with_4 = with_3.Format;

                with_4.Font.Size = 9;
                with_4.Alignment = ParagraphAlignment.Center;
                with_3.AddText("- ");
                with_3.AddPageField();
                with_3.AddText(" / ");
                with_3.AddNumPagesField();
                with_3.AddText(" -");

                var with_5 = section.Footers.Primary.AddParagraph();
                var with_6 = with_5.Format;

                with_6.Font.Size = 7;
                with_5.AddText(Company.name);
                with_5.AddLineBreak();
                with_5.AddText(Company.adresse);
                with_5.AddLineBreak();
                with_5.AddText(Company.zipcode);
                with_5.AddText(" ");
                with_5.AddText(Company.city);
                if (this.FAB.Virksomhed.LandekodeID != 45)
                {
                    with_5.AddText(", ");
                    with_5.AddText(Company.country);
                }
                with_5.AddLineBreak();
                if (this.FAB.Virksomhed.LandekodeID != 45)
                {
                    with_5.AddText("Phone ");
                    with_5.AddText(Company.int_phone);
                }
                else
                {
                    with_5.AddText("Telefon ");
                    with_5.AddText(Company.phone);
                }
                with_5.AddLineBreak();

                with_5.AddText("E-mail: ");
                Hyperlink _email = with_5.AddHyperlink(string.Format("mailto:{0}", Company.email), HyperlinkType.Web);

                _email.AddFormattedText(Company.email);
                with_5.AddLineBreak();

                with_5.AddText("Internet: ");
                Hyperlink link = with_5.AddHyperlink(string.Format("http://{0}", Company.link), HyperlinkType.Web);

                link.AddFormattedText(Company.link);
            }
Example #40
0
        private void BeginTextBlock()
        {
            if (!IsText || IsWriter)
            {
                return;
            }

            _readerSection = new Section();
            var ss = new Stack <Section>();

            ss.Push(_readerSection);
            var curs = _readerSection;

            var rxEnd   = new System.Text.RegularExpressions.Regex(@"\[/(.*?)\]", System.Text.RegularExpressions.RegexOptions.Compiled);
            var rxBegin = new System.Text.RegularExpressions.Regex(@"\[(.*?)\]", System.Text.RegularExpressions.RegexOptions.Compiled);

            // read the entire file into a data structure for flexi-parsing
            string str;

            while ((str = _tr.ReadLine()) != null)
            {
                var end   = rxEnd.Match(str);
                var begin = rxBegin.Match(str);
                if (end.Success)
                {
                    var name = end.Groups[1].Value;
                    if (name != curs.Name)
                    {
                        throw new InvalidOperationException("Mis-formed savestate blob");
                    }

                    curs = ss.Pop();

                    // consume no data past the end of the last proper section
                    if (curs == _readerSection)
                    {
                        _currSection = curs;
                        return;
                    }
                }
                else if (begin.Success)
                {
                    var name = begin.Groups[1].Value;
                    ss.Push(curs);
                    var news = new Section {
                        Name = name
                    };
                    if (!curs.ContainsKey(name))
                    {
                        curs[name] = news;
                    }
                    else
                    {
                        throw new Exception($"Duplicate key \"{name}\" in serializer savestate!");
                    }

                    curs = news;
                }
                else
                {
                    // add to current section
                    if (str.Trim().Length == 0)
                    {
                        continue;
                    }

                    var parts = str.Split(' ');
                    var key   = parts[0];

                    // UGLY: adds whole string instead of splitting the key. later, split the key, and have the individual Sync methods give up that responsibility
                    if (!curs.Items.ContainsKey(key))
                    {
                        curs.Items[key] = parts[1];
                    }
                    else
                    {
                        throw new Exception($"Duplicate key \"{key}\" in serializer savestate!");
                    }
                }
            }

            _currSection = _readerSection;
        }
Example #41
0
        protected void UpdateView()
        {
            var root = new RootElement(Title)
            {
                UnevenRows = true
            };
            var section = new Section();

            root.Add(section);

            var desc = new Gistacular.Elements.MultilinedElement("Description")
            {
                Value = _model.Description
            };

            desc.Tapped += ChangeDescription;
            section.Add(desc);

            if (_public == null)
            {
                _public = new Gistacular.Elements.TrueFalseElement("Public");
            }
            _public.Value = _model.Public;

            if (_publicEditable)
            {
                section.Add(_public);
            }

            var fileSection = new Section();

            root.Add(fileSection);

            foreach (var file in _model.Files.Keys)
            {
                var key = file;
                if (!_model.Files.ContainsKey(key) || _model.Files[file].Content == null)
                {
                    continue;
                }

                var size = System.Text.ASCIIEncoding.UTF8.GetByteCount(_model.Files[file].Content);
                var el   = new StyledElement(file, size + " bytes", UITableViewCellStyle.Subtitle)
                {
                    Accessory = UITableViewCellAccessory.DisclosureIndicator
                };
                el.Tapped += () => {
                    if (!_model.Files.ContainsKey(key))
                    {
                        return;
                    }
                    var createController = new ModifyGistFileController(key, _model.Files[key].Content);
                    createController.Save = (name, content) => {
                        if (string.IsNullOrEmpty(name))
                        {
                            throw new InvalidOperationException("Please enter a name for the file");
                        }

                        //If different name & exists somewhere else
                        if (!name.Equals(key) && _model.Files.ContainsKey(name))
                        {
                            throw new InvalidOperationException("A filename by that type already exists");
                        }

                        //Remove old
                        _model.Files.Remove(key);

                        //Put new
                        _model.Files[name] = new GistCreateModel.File {
                            Content = content
                        };
                    };

                    NavigationController.PushViewController(createController, true);
                };
                fileSection.Add(el);
            }

            fileSection.Add(new StyledElement("Add New File", AddFile));

            Root = root;
        }
        public void MakePage([JetBrains.Annotations.NotNull] Document doc, [JetBrains.Annotations.NotNull] string dstdir, bool requireAll, [JetBrains.Annotations.NotNull] Section tocSection)
        {
            var di =
                new DirectoryInfo(Path.Combine(dstdir, DirectoryNames.CalculateTargetdirectory(MyTargetDirectory)));
            var fi = di.GetFiles("TimeProfiles.*.txt");

            if (fi.Length == 0)
            {
                if (requireAll)
                {
                    throw new LPGException("Missing files for " + SectionTitle);
                }
                return;
            }
            var sec = MakeDescriptionArea(doc, tocSection);

            foreach (var fileInfo in fi)
            {
                var strings = new List <string>();
                using (var sr = new StreamReader(fileInfo.FullName)) {
                    var row = 0;
                    while (!sr.EndOfStream && row < 20)
                    {
                        var s = sr.ReadLine();
                        strings.Add(s);
                        row++;
                    }
                }
                var sb = new StringBuilder();
                foreach (var s in strings)
                {
                    sb.Append(s + Environment.NewLine);
                }
                var para = sec.AddParagraph();
                para.Format.Alignment  = ParagraphAlignment.Justify;
                para.Format.Font.Name  = "Times New Roman";
                para.Format.Font.Size  = 10;
                para.Format.Font.Bold  = false;
                para.Format.SpaceAfter = "0.25cm";
                para.Format.Font.Color = Colors.Black;

                para.AddText(fileInfo.Name);

                para = sec.AddParagraph();
                para.Format.Alignment  = ParagraphAlignment.Left;
                para.Format.Font.Name  = "Times New Roman";
                para.Format.Font.Size  = 10;
                para.Format.Font.Bold  = false;
                para.Format.SpaceAfter = "0.25cm";
                para.Format.Font.Color = Colors.Black;

                para.AddText(sb.ToString());
            }
        }
Example #43
0
        private Section GatherEvents(FetchDrawcall[] draws)
        {
            var sections = new List <List <FetchDrawcall> >();

            foreach (var d in draws)
            {
                if ((d.flags & (DrawcallFlags.SetMarker | DrawcallFlags.Present)) > 0)
                {
                    continue;
                }

                if (m_Core.Config.EventBrowser_HideEmpty)
                {
                    if ((d.children == null || d.children.Length == 0) && (d.flags & (DrawcallFlags.PushMarker | DrawcallFlags.MultiDraw)) != 0)
                    {
                        continue;
                    }
                }

                bool newSection = ((d.flags & (DrawcallFlags.PushMarker | DrawcallFlags.MultiDraw)) > 0 || sections.Count == 0);
                if (!newSection)
                {
                    var lastSection = sections.Last();

                    if (lastSection.Count == 1 && (lastSection[0].flags & (DrawcallFlags.PushMarker | DrawcallFlags.MultiDraw)) > 0)
                    {
                        newSection = true;
                    }
                }

                if (newSection)
                {
                    sections.Add(new List <FetchDrawcall>());
                }

                sections.Last().Add(d);
            }

            Section ret = new Section();

            ret.subsections = new List <Section>();

            foreach (var s in sections)
            {
                Section sec = null;

                if (s.Count == 1 && (s[0].flags & (DrawcallFlags.PushMarker | DrawcallFlags.MultiDraw)) > 0)
                {
                    sec = GatherEvents(s[0].children);
                    if (m_Core.Config.EventBrowser_ApplyColours)
                    {
                        sec.color     = s[0].GetColor();
                        sec.textcolor = s[0].GetTextColor(Color.Black);
                    }
                    else
                    {
                        sec.color     = Color.Transparent;
                        sec.textcolor = Color.Black;
                    }
                    sec.Name = s[0].name;
                }
                else
                {
                    sec       = new Section();
                    sec.draws = s;
                    for (int i = 0; i < sec.draws.Count; i++)
                    {
                        sec.lastPoss.Add(0.0f);
                        sec.lastUsage.Add(false);
                        sec.lastVisible.Add(false);
                    }
                }

                ret.subsections.Add(sec);
            }

            return(ret);
        }
Example #44
0
        public static IDeck Load(this IDeck deck, Game game, string path, bool cloneCards = true)
        {
            var ret = new Deck();

            ret.Sections = new List <ISection>();
            try
            {
                var cards = game.Sets().SelectMany(x => x.Cards).ToArray();
                using (var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    var doc    = XDocument.Load(fs);
                    var gameId = Guid.Parse(doc.Descendants("deck").First().Attribute("game").Value);
                    var shared = doc.Descendants("deck").First().Attr <bool>("shared");
                    foreach (var sectionelem in doc.Descendants("section"))
                    {
                        var section = new Section();
                        section.Cards  = new List <IMultiCard>();
                        section.Name   = sectionelem.Attribute("name").Value;
                        section.Shared = sectionelem.Attr <bool>("shared");
                        // On old style decks, if it's shared, then all subsequent sections are shared
                        if (shared)
                        {
                            section.Shared = true;
                        }
                        foreach (var cardelem in sectionelem.Descendants("card"))
                        {
                            var cardId = Guid.Parse(cardelem.Attribute("id").Value);
                            var cardq  = Int32.Parse(cardelem.Attribute("qty").Value);
                            var card   = cards.FirstOrDefault(x => x.Id == cardId);
                            if (card == null)
                            {
                                var cardN = cardelem.Value;
                                card = cards.FirstOrDefault(x => x.Name.Equals(cardN, StringComparison.CurrentCultureIgnoreCase));
                                if (card == null)
                                {
                                    throw new UserMessageException(
                                              "Problem loading deck {0}. The card with id: {1} and name: {2} is not installed.", path, cardId, cardN);
                                }
                            }
                            (section.Cards as IList <IMultiCard>).Add(card.ToMultiCard(cardq, cloneCards));
                        }
                        if (section.Cards.Any())
                        {
                            (ret.Sections as List <ISection>).Add(section);
                        }
                    }
                    // Add deck notes
                    var notesElem = doc.Descendants("notes").FirstOrDefault();
                    if (notesElem != null)
                    {
                        var cd = (notesElem.FirstNode as XCData);
                        if (cd != null)
                        {
                            ret.Notes = cd.Value.Clone() as string;
                        }
                    }
                    if (ret.Notes == null)
                    {
                        ret.Notes = "";
                    }

                    // Add all missing sections so that the game doesn't get pissed off
                    {
                        var combinedList =
                            game.DeckSections.Select(x => x.Value).Concat(game.SharedDeckSections.Select(y => y.Value));
                        foreach (var section in combinedList)
                        {
                            if (ret.Sections.Any(x => x.Name.Equals(section.Name, StringComparison.InvariantCultureIgnoreCase) && x.Shared == section.Shared) == false)
                            {
                                // Section not defined in the deck, so add an empty version of it.
                                (ret.Sections as List <ISection>).Add(
                                    new Section
                                {
                                    Name   = section.Name.Clone() as string,
                                    Cards  = new List <IMultiCard>(),
                                    Shared = section.Shared
                                });
                            }
                        }
                    }
                    ret.GameId   = gameId;
                    ret.IsShared = shared;
                }
                // This is an old style shared deck file, we need to convert it now, for posterity sake.
                if (ret.IsShared)
                {
                    ret.IsShared = false;
                    ret.Save(game, path);
                }
                deck = ret;
                return(deck);
            }
            catch (UserMessageException)
            {
                throw;
            }
            catch (FormatException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("The deck {0} is corrupt.", path);
            }
            catch (NullReferenceException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("The deck {0} is corrupt.", path);
            }
            catch (XmlException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("The deck {0} is corrupt.", path);
            }
            catch (FileNotFoundException)
            {
                throw new UserMessageException("Could not save deck to {0}, could not file the file.", path);
            }
            catch (IOException e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("Could not load deck from {0}, {1}", path, e.Message);
            }
            catch (Exception e)
            {
                Log.Error(String.Format("Problem loading deck from path {0}", path), e);
                throw new UserMessageException("Could not load deck from {0}, there was an unspecified problem.", path);
            }
            return(ret);
        }
 public static Section AddHtml(this Section section, string html)
 {
     return(section.Add(html, new HtmlConverter()));
 }
Example #46
0
        private void RenderSection(int depth, Graphics g, RectangleF rect, Section section, bool visible, float lastVisibleHeight)
        {
            float start = 0.0f;

            float[] minwidths  = new float[section.subsections.Count];
            float[] widths     = new float[section.subsections.Count];
            float   maxwidth   = 0.0f;
            float   totalwidth = 0.0f;

            for (int i = 0; i < section.subsections.Count; i++)
            {
                // initial widths are minwidth, used to 'proportionally' size sections.
                // all that matters here is the relative proportions and that it's >= minwidth,
                // it gets sized up or down to fit later.
                minwidths[i] = MinSectionSize(g, section.subsections[i]);
                widths[i]    = minwidths[i];

                maxwidth    = Math.Max(maxwidth, minwidths[i]);
                totalwidth += widths[i];
            }

            float scale = rect.Width / totalwidth;

            // if we have space free, scale everything up the same
            if (totalwidth < rect.Width)
            {
                for (int i = 0; i < section.subsections.Count; i++)
                {
                    widths[i] *= scale;
                }
            }
            else
            {
                // scale everything down to fit (this will reduce some below minwidth)
                for (int i = 0; i < section.subsections.Count; i++)
                {
                    widths[i] *= scale;
                }

                // search for sections that are > their min width, and skim off the top.
                for (int i = 0; i < section.subsections.Count; i++)
                {
                    // found a section that's too small
                    if (widths[i] < minwidths[i])
                    {
                        // we try and skim an equal amount off every section, so the scaling
                        // is nice and uniform rather than left-focussed
                        float missing = minwidths[i] - widths[i];
                        float share   = missing / (float)(section.subsections.Count - 1);

                        bool slack = false;

                        // keep going trying to find some slack and skimming it off
                        int iters = 0;
                        do
                        {
                            slack = false;
                            iters++;
                            if (iters == 10)
                            {
                                break;
                            }
                            for (int j = 0; j < section.subsections.Count;)
                            {
                                // ignore current section
                                if (i == j)
                                {
                                    j++;
                                    continue;
                                }

                                // if this section has free space
                                if (widths[j] > minwidths[j])
                                {
                                    float avail = widths[j] - minwidths[j];

                                    // skim off up as much as is available, up to the share per section
                                    float delta = Math.Max(0.1f, Math.Min(avail, share));
                                    widths[i] += delta;
                                    widths[j] -= delta;
                                    missing   -= delta;

                                    // if we didn't skim off our share, recalculate how much we'll need to
                                    // skim off each, and start again
                                    if (avail < share)
                                    {
                                        share = missing / (float)(section.subsections.Count - 1);
                                        j     = 0;
                                        continue;
                                    }

                                    slack = true;
                                }

                                j++;
                            }
                            // keep going while there are sections with slack, and we need to make some up.
                            // ie. if we find all our missing space then we can finish, but also if we haven't
                            // found enough but there's nothing to give, we also give up.
                        } while (slack && missing > 0.0f);
                    }
                }
            }

            for (int i = 0; i < section.subsections.Count; i++)
            {
                widths[i] /= rect.Width;
            }

            var clipRect = rect;

            clipRect.Height -= pipRadius * 6;

            for (int i = 0; i < section.subsections.Count; i++)
            {
                var s = section.subsections[i];
                if (s.Name.Length > 0)
                {
                    var col     = depth % 2 == 0 ? lightBack : darkBack;
                    var textcol = Color.Black;

                    if (s.color.A > 0)
                    {
                        col     = s.color;
                        textcol = s.textcolor;
                    }

                    g.Clip = new Region(clipRect);
                    var childRect = DrawBar(g, col, textcol, rect, start, widths[i], (s.Expanded ? "- " : "+ ") + s.Name, visible);
                    g.ResetClip();

                    RenderSection(depth + 1, g, childRect, s, visible && s.Expanded, visible ? childRect.Top : lastVisibleHeight);

                    var backRect = GetSubrect(childRect, 0.0f, 1.0f);
                    backRect.Y     += barBorder / 2;
                    backRect.Height = barHeight;

                    LinearGradientBrush brush = new LinearGradientBrush(new PointF(0, backRect.Y),
                                                                        new PointF(0, backRect.Y + backRect.Height + 1),
                                                                        Color.FromArgb(255, darkBack), Color.FromArgb(0, darkBack));

                    if (visible && s.Expanded && (s.subsections == null || s.subsections.Count == 0))
                    {
                        g.Clip = new Region(clipRect);
                        g.FillRectangle(brush, backRect);
                        g.ResetClip();
                    }

                    brush.Dispose();

                    s.lastRect        = childRect;
                    s.lastRect.Y      = rect.Y;
                    s.lastRect.Height = childRect.Y - rect.Y;

                    if (!visible)
                    {
                        s.lastRect.Height = 0;
                    }
                }
                else
                {
                    var backRect = GetSubrect(rect, start, widths[i]);
                    backRect.Y     += barBorder / 2;
                    backRect.Height = barHeight;

                    LinearGradientBrush brush = new LinearGradientBrush(new PointF(0, backRect.Y),
                                                                        new PointF(0, backRect.Y + backRect.Height + 1),
                                                                        Color.FromArgb(255, darkBack), Color.FromArgb(0, darkBack));

                    if (visible)
                    {
                        g.Clip = new Region(clipRect);
                        g.FillRectangle(brush, backRect);
                        g.ResetClip();
                    }

                    brush.Dispose();

                    int highlight = -1;

                    var highlightBarRect = rect;
                    highlightBarRect.Y      = highlightBarRect.Bottom - pipRadius * 4;
                    highlightBarRect.Height = pipRadius * 2;

                    if (s.draws != null)
                    {
                        for (int d = 0; d < s.draws.Count; d++)
                        {
                            if (m_History != null)
                            {
                                foreach (var u in m_History)
                                {
                                    if (u.eventID == s.draws[d].eventID)
                                    {
                                        var barcol = Color.Black;

                                        int type = 2;

                                        DrawPip(g, barcol, highlightBarRect, type, d, s.draws.Count, start, widths[i], "");
                                    }
                                }
                            }
                            else if (m_HighlightUsage != null)
                            {
                                foreach (var u in m_HighlightUsage)
                                {
                                    if ((u.eventID == s.draws[d].eventID) ||
                                        (u.eventID < s.draws[d].eventID && s.draws[d].events.Length > 0 && u.eventID >= s.draws[d].events[0].eventID))
                                    {
                                        var barcol = Color.Black;

                                        int type = 2;

                                        if (u.usage == ResourceUsage.Barrier)
                                        {
                                            type = 6;
                                        }

                                        DrawPip(g, barcol, highlightBarRect, type, d, s.draws.Count, start, widths[i], "");
                                    }
                                }
                            }

                            s.lastUsage[d]   = false;
                            s.lastVisible[d] = visible;
                        }

                        for (int d = 0; d < s.draws.Count; d++)
                        {
                            if (m_History != null)
                            {
                                foreach (var u in m_History)
                                {
                                    if (u.eventID == s.draws[d].eventID)
                                    {
                                        if (u.EventPassed())
                                        {
                                            DrawPip(g, Color.Lime, highlightBarRect, 1, d, s.draws.Count, start, widths[i], "");
                                            MarkWrite(s.draws[d].eventID);
                                        }
                                        else
                                        {
                                            DrawPip(g, Color.Crimson, highlightBarRect, 1, d, s.draws.Count, start, widths[i], "");
                                            MarkRead(s.draws[d].eventID);
                                        }

                                        s.lastUsage[d] = true;
                                    }
                                }
                            }
                            else if (m_HighlightUsage != null)
                            {
                                foreach (var u in m_HighlightUsage)
                                {
                                    if ((u.eventID == s.draws[d].eventID) ||
                                        (u.eventID < s.draws[d].eventID && s.draws[d].events.Length > 0 && u.eventID >= s.draws[d].events[0].eventID))
                                    {
                                        // read/write
                                        if (
                                            ((int)u.usage >= (int)ResourceUsage.VS_RWResource &&
                                             (int)u.usage <= (int)ResourceUsage.CS_RWResource) ||
                                            u.usage == ResourceUsage.GenMips ||
                                            u.usage == ResourceUsage.Copy ||
                                            u.usage == ResourceUsage.Resolve)
                                        {
                                            DrawPip(g, Color.Orchid, highlightBarRect, 3, d, s.draws.Count, start, widths[i], "");
                                            DrawPip(g, Color.Lime, highlightBarRect, 4, d, s.draws.Count, start, widths[i], "");
                                            MarkWrite(s.draws[d].eventID);
                                        }
                                        // write
                                        else if (u.usage == ResourceUsage.SO ||
                                                 u.usage == ResourceUsage.DepthStencilTarget ||
                                                 u.usage == ResourceUsage.ColourTarget ||
                                                 u.usage == ResourceUsage.CopyDst ||
                                                 u.usage == ResourceUsage.ResolveDst)
                                        {
                                            DrawPip(g, Color.Orchid, highlightBarRect, 1, d, s.draws.Count, start, widths[i], "");
                                            MarkWrite(s.draws[d].eventID);
                                        }
                                        // clear
                                        else if (u.usage == ResourceUsage.Clear)
                                        {
                                            DrawPip(g, Color.Silver, highlightBarRect, 1, d, s.draws.Count, start, widths[i], "");
                                            MarkWrite(s.draws[d].eventID);
                                        }
                                        // barrier
                                        else if (u.usage == ResourceUsage.Barrier)
                                        {
                                            DrawPip(g, Color.Tomato, highlightBarRect, 5, d, s.draws.Count, start, widths[i], "");
                                            MarkWrite(s.draws[d].eventID);
                                        }
                                        // read
                                        else
                                        {
                                            DrawPip(g, Color.Lime, highlightBarRect, 1, d, s.draws.Count, start, widths[i], "");
                                            MarkRead(s.draws[d].eventID);
                                        }

                                        s.lastUsage[d] = true;
                                    }
                                }
                            }
                        }

                        for (int d = 0; d < s.draws.Count; d++)
                        {
                            if (s.draws[d].eventID == m_Core.CurEvent)
                            {
                                highlight = d;
                            }

                            if (visible)
                            {
                                g.Clip = new Region(clipRect);

                                if (s.draws[d].eventID != m_Core.CurEvent)
                                {
                                    s.lastPoss[d] = DrawPip(g, Color.Blue, rect, 0, d, s.draws.Count, start, widths[i], s.draws[d].name);
                                }

                                g.ResetClip();
                            }
                            else
                            {
                                s.lastPoss[d] = DrawPip(g, Color.Blue, rect, 999, d, s.draws.Count, start, widths[i], s.draws[d].name);
                            }
                        }
                    }

                    if (highlight >= 0)
                    {
                        var subRect = GetSubrect(rect, start, widths[i]);
                        subRect.X     += pipRadius;
                        subRect.Y     += pipPaddingY;
                        subRect.Width -= pipRadius * 2;
                        subRect.Height = pipRadius * 2;

                        float delta = (float)(highlight + 1) / (float)(s.draws.Count + 1);

                        m_CurrentMarker = new PointF(subRect.X + delta * Math.Max(0, subRect.Width), lastVisibleHeight);
                    }

                    if (highlight >= 0 && visible && s.draws != null)
                    {
                        g.Clip = new Region(clipRect);

                        s.lastPoss[highlight] = DrawPip(g, Color.LightGreen, rect, 0, highlight, s.draws.Count, start, widths[i], s.draws[highlight].name);

                        g.ResetClip();
                    }

                    s.lastRect = backRect;

                    if (!visible)
                    {
                        s.lastRect.Height = 0;
                    }
                }

                start += widths[i];
            }
        }
Example #47
0
        public ActionResult Edit([Bind(Include = "ID,Course,Semester,IsOnline,RoomReq,SectionCapacity,Program,TimeRange")] Section section, FormCollection form, string[] TimeRanges)
        {
            if (ModelState.IsValid)
            {
                //formcollection for dropdown
                section.Semester = form["SemesterDropDown"];
                section.RoomReq  = form["RoomReqDropDown"];
                section.Program  = form["DepartmentDropDown"];

                //if statements for TimeRange combination
                int count = TimeRanges.Count();
                if (count == 1 && TimeRanges.Contains("1"))
                {
                    section.TimeRange        = "1";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 1 && TimeRanges.Contains("2"))
                {
                    section.TimeRange        = "2";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM";
                }
                else if (count == 1 && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "3";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 1 && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "4";
                    ViewBag.TimeRangeDisplay = "Late, 75 min, 5- 6:30";
                }
                else if (count == 1 && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "5";
                    ViewBag.TimeRangeDisplay = "Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 1 && TimeRanges.Contains("6"))
                {
                    section.TimeRange        = "6";
                    ViewBag.TimeRangeDisplay = "All";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("2"))
                {
                    section.TimeRange        = "12";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "13";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "14";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "15";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "123";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "124";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "125";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "134";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "135";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "145";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "1234";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "1235";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "1245";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("3") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "1345";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("2") && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "23";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 2 && TimeRanges.Contains("2") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "24";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 2 && TimeRanges.Contains("2") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "25";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "234";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5 - 6:30";
                }
                else if (count == 3 && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "235";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("2") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "245";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR Late, 75 min, 5 - 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "2345";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5 - 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "34";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 2 && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "35";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("3") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "345";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "45";
                    ViewBag.TimeRangeDisplay = "Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else
                {
                    section.TimeRange        = "6";
                    ViewBag.TimeRangeDisplay = "All";
                }

                db.Entry(section).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(section));
        }
Example #48
0
        private void FindDraw(Point p, Section s,
                              ref FetchDrawcall left, ref float dleft, ref bool uleft,
                              ref FetchDrawcall right, ref float dright, ref bool uright)
        {
            if (s == null)
            {
                return;
            }

            var rect = s.lastRect;

            rect.Y      = 0;
            rect.Height = 10000;

            if (s.subsections != null)
            {
                foreach (var sub in s.subsections)
                {
                    FindDraw(p, sub, ref left, ref dleft, ref uleft, ref right, ref dright, ref uright);

                    if (left != null && right != null)
                    {
                        return;
                    }
                }
            }

            if (rect.Contains(p))
            {
                if (s.draws == null || s.draws.Count == 0)
                {
                    return;
                }

                for (int i = 0; i < s.lastPoss.Count; i++)
                {
                    if (s.lastVisible[i])
                    {
                        if (s.lastPoss[i] <= p.X)
                        {
                            if (
                                // not found left
                                left == null ||
                                // this left is closer and as usage-y, or we don't have a usage-y one yet
                                (s.lastPoss[i] > dleft && s.lastUsage[i] == uleft) ||
                                // this left is WAY closer
                                (s.lastPoss[i] > dleft + 20.0f) ||
                                // this left is more usage-y
                                (s.lastUsage[i] && !uleft)
                                )
                            {
                                dleft = s.lastPoss[i];
                                uleft = s.lastUsage[i];
                                left  = s.draws[i];
                            }
                        }

                        if (s.lastPoss[i] > p.X)
                        {
                            if (
                                // not found right
                                right == null ||
                                // this right is closer and as usage-y, or we don't have a usage-y one yet
                                (s.lastPoss[i] < dright && s.lastUsage[i] == uright) ||
                                // this right is WAY closer
                                (s.lastPoss[i] < dright - 20.0f) ||
                                // this right is more usage-y
                                (s.lastUsage[i] && !uright)
                                )
                            {
                                dright = s.lastPoss[i];
                                uright = s.lastUsage[i];
                                right  = s.draws[i];
                            }
                        }
                    }
                }

                if (left != null && right != null)
                {
                    return;
                }
            }
        }
Example #49
0
        public ActionResult Create([Bind(Include = "ID,Course,SectionNumbers,Semester,IsOnline,RoomReq,SectionCapacity,Program,TimeRange")] Section section, FormCollection form, string[] TimeRanges)
        {
            if (ModelState.IsValid)
            {
                //FormCollection from dropdown
                section.Semester = form["SemesterDropDown"];
                section.RoomReq  = form["RoomReqDropDown"];
                section.Program  = form["DepartmentDropDown"];
                //section.SectionNumbers = form["SectionNumbers"];

                //if statements for TimeRange combination. this is good:)
                int count = TimeRanges.Count();
                if (count == 1 && TimeRanges.Contains("1"))
                {
                    section.TimeRange        = "1";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 1 && TimeRanges.Contains("2"))
                {
                    section.TimeRange        = "2";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM";
                }
                else if (count == 1 && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "3";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 1 && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "4";
                    ViewBag.TimeRangeDisplay = "Late, 75 min, 5- 6:30";
                }
                else if (count == 1 && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "5";
                    ViewBag.TimeRangeDisplay = "Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 1 && TimeRanges.Contains("6"))
                {
                    section.TimeRange        = "6";
                    ViewBag.TimeRangeDisplay = "All";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("2"))
                {
                    section.TimeRange        = "12";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "13";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "14";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 2 && TimeRanges.Contains("1") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "15";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "123";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "124";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "125";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "134";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "135";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("1") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "145";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "1234";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "1235";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("2") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "1245";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR Under Grad MW, 75 min, 2 PM - 3:30 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("1") && TimeRanges.Contains("3") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "1345";
                    ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("2") && TimeRanges.Contains("3"))
                {
                    section.TimeRange        = "23";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM";
                }
                else if (count == 2 && TimeRanges.Contains("2") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "24";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 2 && TimeRanges.Contains("2") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "25";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "234";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5 - 6:30";
                }
                else if (count == 3 && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "235";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("2") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "245";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR Late, 75 min, 5 - 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 4 && TimeRanges.Contains("2") && TimeRanges.Contains("3") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "2345";
                    ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM OR MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5 - 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("3") && TimeRanges.Contains("4"))
                {
                    section.TimeRange        = "34";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30";
                }
                else if (count == 2 && TimeRanges.Contains("3") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "35";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 3 && TimeRanges.Contains("3") && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "345";
                    ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM OR Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else if (count == 2 && TimeRanges.Contains("4") && TimeRanges.Contains("5"))
                {
                    section.TimeRange        = "45";
                    ViewBag.TimeRangeDisplay = "Late, 75 min, 5- 6:30 OR Under Grad TR, 75 min, 8 AM - 3:30 PM";
                }
                else
                {
                    section.TimeRange        = "6";
                    ViewBag.TimeRangeDisplay = "All";
                }
                //section.TimeRange = form["TimeDropDown"];
                //switch (section.TimeRange)
                //{
                //    case "1":
                //        ViewBag.TimeRangeDisplay = "Grad MW/TR, 75 min, 8 AM - 3:30 PM";
                //        break;
                //    case "2":
                //        ViewBag.TimeRangeDisplay = "Under Grad MW, 75 min, 2 PM - 3:30 PM";
                //        break;
                //    case "3":
                //        ViewBag.TimeRangeDisplay = "MWF Early, 50 min, 8 AM - 1 PM";
                //        break;
                //    case "4":
                //        ViewBag.TimeRangeDisplay = "Late, 75 min, 5- 6:30";
                //        break;
                //    case "5":
                //        ViewBag.TimeRangeDisplay = "Under Grad TR, 75 min, 8 AM - 3:30 PM";
                //        break;
                //    default:
                //        ViewBag.TimeRangeDisplay = "All";
                //        break;
                //}
                db.Sections.Add(section);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(section));
        }
Example #50
0
        public Document CreateDocument()
        {
            document = new Document();

            DefineStyles();

            foreach (Student student in students)
            {
                Section section = document.AddSection();
                section.PageSetup.TopMargin   = "3.0cm";
                section.PageSetup.LeftMargin  = "1.5cm";
                section.PageSetup.RightMargin = "1.5cm";

                Table table = new Table();
                table.Borders.Width = 0;
                table.AddColumn(Unit.FromInch(5));
                table.AddColumn(Unit.FromInch(2));

                Row       row       = table.AddRow();
                Cell      cell      = row.Cells[0];
                Paragraph paragraph = cell.AddParagraph();
                paragraph.Style = "NameStyle";
                paragraph.AddFormattedText(student.FirstName + " " + student.LastName);
                cell      = row.Cells[1];
                paragraph = cell.AddParagraph();
                paragraph.Format.Alignment = ParagraphAlignment.Right;
                paragraph.AddFormattedText(student.Gender);

                row       = table.AddRow();
                cell      = row.Cells[0];
                paragraph = cell.AddParagraph();
                paragraph.AddFormattedText(student.Email);
                cell      = row.Cells[1];
                paragraph = cell.AddParagraph();
                paragraph.Format.Alignment = ParagraphAlignment.Right;
                paragraph.AddFormattedText(student.Ethnicity + "\n\n");

                row       = table.AddRow();
                cell      = row.Cells[0];
                paragraph = cell.AddParagraph();
                paragraph.AddFormattedText("");
                cell      = row.Cells[1];
                paragraph = cell.AddParagraph();
                paragraph.Format.Alignment = ParagraphAlignment.Right;
                paragraph.AddFormattedText("Two Years in US HS:  " + student.USHS + "\n\n\n\n");


                document.LastSection.Add(table);

                table = new Table();
                table.Borders.Width = 0;
                table.AddColumn(Unit.FromInch(4.5));
                table.AddColumn(Unit.FromInch(1.5));
                table.AddColumn(Unit.FromInch(1.5));

                row       = table.AddRow();
                cell      = row.Cells[0];
                paragraph = cell.AddParagraph();
                paragraph.Format.Font.Bold = true;
                paragraph.AddFormattedText("PROJECT PREFERENCES:\n\n");
                cell      = row.Cells[1];
                paragraph = cell.AddParagraph();
                paragraph.Format.Font.Bold = true;
                paragraph.AddFormattedText("EXPERIENCE:\n\n");

                string[] experienceTypes = new string[] { "Electronics", "Crafting", "Programming", "CAD", "Prototyping" };

                for (int i = 1; i <= 5; i++)
                {
                    row       = table.AddRow();
                    cell      = row.Cells[0];
                    paragraph = cell.AddParagraph();
                    paragraph.AddFormattedText("  " + i.ToString() + ".     " + student.Preference(i) + "\n\n");
                    cell      = row.Cells[1];
                    paragraph = cell.AddParagraph();
                    paragraph.Format.Font.Bold = true;
                    paragraph.AddFormattedText(experienceTypes[i - 1] + "\n\n");
                    cell      = row.Cells[2];
                    paragraph = cell.AddParagraph();
                    string expOutput;
                    switch (i)
                    {
                    case 1:
                        expOutput = student.Electronics;
                        break;

                    case 2:
                        expOutput = student.Crafting;
                        break;

                    case 3:
                        expOutput = student.Programming;
                        break;

                    case 4:
                        expOutput = student.CAD;
                        break;

                    case 5:
                        expOutput = student.Prototyping;
                        break;

                    default:
                        expOutput = "";
                        break;
                    }
                    paragraph.AddFormattedText(expOutput);
                }

                document.LastSection.Add(table);

                table = new Table();
                table.Borders.Width = 0;
                table.AddColumn(Unit.FromInch(2));
                table.AddColumn(Unit.FromInch(1));
                row       = table.AddRow();
                cell      = row.Cells[0];
                paragraph = cell.AddParagraph();
                paragraph.Format.Font.Bold = true;
                paragraph.Format.Alignment = ParagraphAlignment.Right;
                paragraph.AddFormattedText("\n\nAP Credits:  ");
                cell      = row.Cells[1];
                paragraph = cell.AddParagraph();
                paragraph.AddFormattedText("\n\n" + student.APCredits);

                document.LastSection.Add(table);
            }

            return(document);
        }
Example #51
0
        /// <summary>
        /// Метод генерирует полис.
        /// </summary>
        /// <param name="policy">Экземпляр Insurance.BL.Models.Policy</param>
        /// <param name="user">Экземпляр Insurance.BL.Models.User</param>
        /// <returns>Имя сгенерированного полиса.</returns>
        public Document GeneratePolicy(User user, Policy policy, Stream stream)
        {
            var      encoding = Encoding.UTF8;
            var      p        = new PdfGenerator();
            Document document = new Document();
            Section  section  = document.AddSection();

            p.Styles(document);

            //ЗАГОЛОВОК
            Paragraph paragraph = section.AddParagraph();

            paragraph.Format.LeftIndent = 120;
            paragraph.AddFormattedText("СТРАХОВОЙ ПОЛИС", "Title");
            paragraph.AddFormattedText("\nКОМПЛЕКСНОГО АВТОМОБИЛЬНОГО" +
                                       "\nСТРАХОВАНИЯ, КРОМЕ ОТВЕТСТВЕННОСТИ", "Normal");

            //ТАБЛИЦА С ДАТОЙ СРОКА ДЕЙСТВИЯ ПОЛИСА
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            Table tablePolicyDate = section.AddTable();

            tablePolicyDate.AddColumn(296);
            tablePolicyDate.Borders.Width = 1.5;
            tablePolicyDate.TopPadding    = 4;
            tablePolicyDate.BottomPadding = 4;
            Row row = tablePolicyDate.AddRow();

            tablePolicyDate.Rows.LeftIndent = 180;
            var text = p.GetFormattedPolicyDateText(policy.PolicyDate);

            row.Style = "Text";
            row.Cells[0].AddParagraph(text);

            //ТАБЛИЦА С ИМЕНЕМ КЛИЕНТА
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            Table dateInsuranceCase = section.AddTable();

            dateInsuranceCase.AddColumn(480);
            dateInsuranceCase.Borders.Width = 1.5;
            dateInsuranceCase.TopPadding    = 4;
            dateInsuranceCase.BottomPadding = 4;
            row                   = dateInsuranceCase.AddRow();
            row.Style             = "Text";
            row.VerticalAlignment = VerticalAlignment.Center;
            row.Cells[0].AddParagraph("Страхователь (фамилия имя отчество)");
            row       = dateInsuranceCase.AddRow();
            row.Style = "Text";
            row.Cells[0].AddParagraph(user.Name);

            //ТАБЛИЦА С ПАРАМЕТРАМИ АВТОМОБИЛЯ.
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph("Характеристики транспортного средства:");
            Table carData = section.AddTable();

            //Строка с наименованием.
            carData.AddColumn(120);
            carData.AddColumn(120);
            carData.AddColumn(120);
            carData.AddColumn(120);
            row = carData.AddRow();
            carData.Borders.Width = 1.5;
            carData.TopPadding    = 4;
            carData.BottomPadding = 4;
            row.Style             = "Text";
            row.Cells[0].AddParagraph(
                "Номер" +
                "\nавтомобиля");
            row.Cells[1].AddParagraph(
                "Модель" +
                "\nавтомобиля");
            row.Cells[2].AddParagraph(
                "Год производства" +
                "\nавтомобиля");
            row.Cells[3].AddParagraph(
                "Мощность двигателя" +
                "\nавтомобиля");

            //Строка со значениями.
            row = carData.AddRow();
            row.VerticalAlignment = VerticalAlignment.Center;
            row.Cells[0].AddParagraph(policy.Car.CarNumber);
            row.Cells[1].AddParagraph(policy.Car.Model);
            row.Cells[2].AddParagraph(policy.Car.ManufacturedYear.ToString());
            row.Cells[3].AddParagraph(string.Format("{0} л.с.", policy.Car.EnginePower));

            //СТРАХОВАЯ ПРЕМИЯ
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph(
                "Автомобиль застрахован по программе все включено (угон\\хищение, полная потеря, повреждение)." +
                "\nСумма страховой премии:");
            Table cost = section.AddTable();

            cost.AddColumn(200);
            row = cost.AddRow();
            cost.Borders.Width    = 1.5;
            cost.TopPadding       = 4;
            cost.BottomPadding    = 4;
            row.Style             = "Title";
            row.VerticalAlignment = VerticalAlignment.Center;
            row.Cells[0].AddParagraph(string.Format("{0:C}", policy.Cost));

            //НОМЕР ПОЛИСА
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            section.AddParagraph();
            paragraph = section.AddParagraph();
            paragraph.Format.Alignment = ParagraphAlignment.Center;
            paragraph.AddFormattedText(string.Format("Полис № {0}", policy.PolicyId));

            //Сохранение и рендер полиса
            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true, PdfFontEmbedding.Always);

            pdfRenderer.Document = document;
            pdfRenderer.RenderDocument();
            pdfRenderer.PdfDocument.Save(stream);

            return(document);
        }
Example #52
0
        // GET: Sections/Edit/5
        public ActionResult Edit(int?id)
        {
            //SEMESTER DROPDOWN
            List <SelectListItem> semesterDropDown = new List <SelectListItem>();

            semesterDropDown.Add(new SelectListItem {
                Text = "Semester", Value = "Semester", Disabled = true
            });
            semesterDropDown.Add(new SelectListItem {
                Text = "Fall", Value = "Fall"
            });
            semesterDropDown.Add(new SelectListItem {
                Text = "Spring", Value = "Spring"
            });
            semesterDropDown.Add(new SelectListItem {
                Text = "Summer", Value = "Summer"
            });

            //DEPARTMENT DROPDOWN
            List <SelectListItem> departmentDropDown = new List <SelectListItem>();

            departmentDropDown.Add(new SelectListItem {
                Text = "DEPT", Value = "DEPT", Disabled = true
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "OM", Value = "OM"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "MIS", Value = "MIS"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "ST", Value = "ST"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "MBA", Value = "MBA"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "AC", Value = "AC"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "MGT", Value = "MGT"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "MKT", Value = "MKT"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "LGS", Value = "LGS"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "FI", Value = "FI"
            });
            departmentDropDown.Add(new SelectListItem {
                Text = "EC", Value = "EC"
            });

            //DEPARTMENT DROPDOWN
            List <SelectListItem> roomReqDropDown = new List <SelectListItem>();

            roomReqDropDown.Add(new SelectListItem {
                Text = "Requirements", Value = "Requirements", Disabled = true
            });
            roomReqDropDown.Add(new SelectListItem {
                Text = "N/A", Value = "N/A"
            });
            roomReqDropDown.Add(new SelectListItem {
                Text = "Capstone", Value = "Capstone"
            });
            roomReqDropDown.Add(new SelectListItem {
                Text = "Lab", Value = "Lab"
            });
            roomReqDropDown.Add(new SelectListItem {
                Text = "Computer", Value = "Computer"
            });
            roomReqDropDown.Add(new SelectListItem {
                Text = "Mass Lecture", Value = "Mass Lecture"
            });


            //TIME RANGE DROPDOWN
            //List<SelectListItem> timeDropDown = new List<SelectListItem>();
            //timeDropDown.Add(new SelectListItem { Text = "Grad MW/TR, 75 min, 8 AM - 3:30 PM", Value = "1" });
            //timeDropDown.Add(new SelectListItem { Text = "Under Grad MW, 75 min, 2 PM - 3:30 PM", Value = "2" });
            //timeDropDown.Add(new SelectListItem { Text = "MWF Early, 50 min, 8 AM - 1 PM", Value = "3" });
            //timeDropDown.Add(new SelectListItem { Text = "Late, 75 min, 5- 6:30", Value = "4" });
            //timeDropDown.Add(new SelectListItem { Text = "Under Grad TR, 75 min, 8 AM - 3:30 PM", Value = "5" });
            //timeDropDown.Add(new SelectListItem { Text = "All", Value = "6" });



            ViewBag.SemesterDropDown   = semesterDropDown;
            ViewBag.DepartmentDropDown = departmentDropDown;
            ViewBag.RoomReqDropDown    = roomReqDropDown;
            //ViewBag.TimeDropDown = timeDropDown;

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Section section = db.Sections.Find(id);

            //var check1 = "6";
            //if(section.TimeRange == MWF Early, 50 min, 8 AM - 1 PM)
            //{
            //   check="3"
            //}



            if (section == null)
            {
                return(HttpNotFound());
            }

            return(View(section));
        }
Example #53
0
        public void Given_A_Section_With_ContentList_Should_Use_Recursion_To_Traverse_Data(Section section, string[] expected)
        {
            // Assert

            // Act
            var result = SectionHelper.GetSectionContentList(section);

            // Assert
            result.Should().BeEquivalentTo(expected);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            // If was send true to Profile.EnableUpdatesOnAccessTokenChange method
            // this notification will be called after the user is logged in and
            // after the AccessToken is gotten
            Profile.Notifications.ObserveDidChange((sender, e) => {
                if (e.NewProfile == null)
                {
                    return;
                }

                LoggedIn(e.NewProfile.UserId);
            });

            loginButton = new LoginButton(new CGRect(48, 0, 218, 46))
            {
                LoginBehavior = LoginBehavior.Browser
            };

            // Handle actions once the user is logged in
            loginButton.Completed += (sender, e) => {
                if (e.Error != null)
                {
                    ShowMessageBox("Ups", e.Error.Description, "Ok", null, null);
                    return;
                }
                if (e.Result.IsCancelled)
                {
                    ShowMessageBox("Ups", "The user cancelled the request", "Ok", null, null);
                    return;
                }
            };

            // Handle actions once the user is logged out
            loginButton.LoggedOut += (sender, e) => {
                LoggedOut();
            };

            // This permission is set by default
            chkPublicProfile         = new CustomCheckboxElement("Public Profile", true);
            chkPublicProfile.Enabled = false;

            // Add or remove all the permissions that you want to ask
            readSection = new Section("Ask Read Permissions")
            {
                chkPublicProfile,
                new CustomCheckboxElement("Email", () => CheckReadPermission("email")),
                new CustomCheckboxElement("About Me", () => CheckReadPermission("user_about_me")),
                new CustomCheckboxElement("Birthday", () => CheckReadPermission("user_birthday")),
                new CustomCheckboxElement("Hometown", () => CheckReadPermission("user_hometown")),
                new CustomCheckboxElement("Friendlists", () => CheckReadPermission("read_custom_friendlists")),
                new CustomCheckboxElement("Managed Groups", () => CheckReadPermission("user_managed_groups"))
            };

            // The user image profile is set automatically once is logged in
            pictureView = new ProfilePictureView(new CGRect(48, 0, 220, 220));

            // Add the initial sections
            Root = new RootElement("Facebook iOS Sample")
            {
                readSection,
                new Section()
                {
                    new UIViewElement("", loginButton, true)
                    {
                        Flags = UIViewElement.CellFlags.DisableSelection | UIViewElement.CellFlags.Transparent,
                    }
                }
            };

            // If the user is already logged in, remove the read section and add the actions sections
            if (AccessToken.CurrentAccessToken != null)
            {
                LoggedIn(AccessToken.CurrentAccessToken.UserID);
            }
        }
Example #55
0
        public Section GetSection(SectionStyle style, bool isDamaged = false, int maxTries = 0)
        {
            var cardSpaces     = 3;
            var formationTypes = new List <FormationType>()
            {
                FormationType.SUIT_RUN,
                FormationType.SAME_RANK,
                FormationType.SAME_SUIT,
                FormationType.RUN,
                FormationType.SUM
            };

            switch (style)
            {
            case SectionStyle.RightPit:
                cardSpaces     = 3;
                formationTypes = isDamaged ?
                                 new List <FormationType>()
                {
                    FormationType.RUN, FormationType.SUM
                } :
                new List <FormationType>()
                {
                    FormationType.LOW_SUM
                };
                break;

            case SectionStyle.LeftPit:
                formationTypes = isDamaged ?
                                 new List <FormationType>()
                {
                    FormationType.RUN, FormationType.SUM
                } :
                new List <FormationType>()
                {
                    FormationType.SUM
                };
                break;

            case SectionStyle.LeftTower:
            case SectionStyle.RightTower:
                if (isDamaged)
                {
                    cardSpaces     = 2;
                    formationTypes = new List <FormationType>()
                    {
                        FormationType.SAME_RANK,
                        FormationType.SUM,
                    };
                }
                else
                {
                    cardSpaces = 4;
                }
                break;

            case SectionStyle.LeftWall:
            case SectionStyle.RightWall:
                if (isDamaged)
                {
                    formationTypes = new List <FormationType>()
                    {
                        FormationType.SAME_SUIT,
                        FormationType.SUM,
                    };
                }
                break;

            case SectionStyle.Gate:
                if (isDamaged)
                {
                    cardSpaces     = 4;
                    formationTypes = new List <FormationType>()
                    {
                        FormationType.LOW_SUM
                    };
                }
                else
                {
                    cardSpaces = 2;
                }
                break;
            }

            var section = new Section()
            {
                Style     = style,
                Name      = style.ToString("F"),
                IsDamaged = isDamaged,
                Spaces    = cardSpaces,
                Types     = formationTypes,
                MaxTries  = maxTries,
            };

            return(section);
        }
        public PE32(string path)
        {
            GruntyOS.IO.BinaryReader br = new GruntyOS.IO.BinaryReader(new GruntyOS.IO.FileStream(path, "r"));
            int  p         = 0;
            uint address   = 0;
            uint data_addr = 0;
            uint ib        = 0;

            for (int i = 0; i < (int)br.BaseStream.Data.Length; i++)
            {
                p = br.BaseStream.Position;
                if (br.ReadByte() == (byte)'P' && br.ReadByte() == (byte)'E')
                {
                    break;
                }
            }
            br.BaseStream.Position = p;
            Console.WriteLine("Start: " + p.ToString());
            byte[] hdr = new byte[(sizeof(PeHeader))];
            for (int i = 0; i < sizeof(PeHeader); i++)
            {
                hdr[i] = br.ReadByte();
            }

            fixed(byte *ptr = hdr)
            {
                PeHeader *header = (PeHeader *)ptr;

                Console.WriteLine(header->mMachine.ToString());
                byte[] ohdr = new byte[header->mSizeOfOptionalHeader];

                for (int i = 0; i < header->mSizeOfOptionalHeader; i++)
                {
                    ohdr[i] = br.ReadByte();
                }

                fixed(byte *ptr2 = ohdr)
                {
                    Pe32OptionalHeader *opt = (Pe32OptionalHeader *)ptr2;

                    Console.WriteLine(opt->mBaseOfCode.ToString());
                    byte[] tmp = new byte[40];
                    address   = opt->mBaseOfCode;
                    data_addr = opt->mBaseOfData;
                    ib        = opt->mImageBase;
                    for (int s = 0; s < header->mNumberOfSections; s++)
                    {
                        fixed(byte *ptr3 = tmp)
                        {
                            for (int i = 0; i < 40; i++)
                            {
                                tmp[i] = br.ReadByte();
                            }
                            SectionHeader *sec  = (SectionHeader *)ptr3;
                            string         name = "";

                            for (int c = 0; sec->Name[c] != 0; c++)
                            {
                                name += ((char)sec->Name[c]).ToString();
                            }
                            Section section = new Section();

                            section.Name            = name;
                            section.Address         = (uint)sec->PointerToRawData;
                            section.RelocationCount = (uint)sec->NumberOfRelocations;
                            section.RelocationPtr   = (uint)sec->PointerToRelocations;
                            section.Size            = (uint)sec->SizeOfRawData;
                            Console.WriteLine(((int)(uint)sec->VirtualAddress).ToString());
                            sections.Add(section);
                        }
                    }
                }

                for (int i = 0; i < sections.Count; i++)
                {
                    if (sections[i].Name == ".text")
                    {
                        text = new byte[sections[i].Size];
                        br.BaseStream.Position = (int)(uint)sections[i].Address;
                        for (int b = 0; b < (int)(uint)sections[i].Size; b++)
                        {
                            text[b] = br.ReadByte();
                        }
                    }
                    else if (sections[i].Name == ".data")
                    {
                        data = new byte[sections[i].Size];
                        br.BaseStream.Position = (int)(uint)sections[i].Address;
                        for (int b = 0; b < (int)(uint)sections[i].Size; b++)
                        {
                            data[b] = br.ReadByte();
                        }
                    }
                }
            }

            // We do not have paging working and I an to lazy to relocate this
            // so we are just loading this were the PE header tells us to
            // may be bad, because we 'could' be overwritting something
            // in RAM. Im not sure.... Lets hope not
            byte *dptr = (byte *)ib + address;

            for (int i = 0; i < text.Length; i++)
            {
                dptr[i] = text[i];
            }
            dptr = (byte *)ib + data_addr;
            for (int i = 0; i < data.Length; i++)
            {
                dptr[i] = data[i];
            }
            Caller cl = new Caller();

            cl.CallCode(ib + address); // Jump!!!!!
        }
Example #57
0
    protected override void DrawGUI(int windowId)
    {
        if (!IsLoggedIn)
        {
            return;                      // attempt draw nothing if not logged in
        }
        if (isFetching)
        {
            GUI.Label(new Rect(this.bounds.width / 2f - 256, this.bounds.height / 2f - 32, 512, 64), "Fetching friends...", "StatusNormal");
            return;
        }

        if (friends == null)
        {
            GUI.Label(new Rect(this.bounds.width / 2f - 256, this.bounds.height / 2f - 32, 512, 64), "Error loading friends...", "StatusError");
            return;
        }
        float heightSoFar = 0;
        Rect  currentRect = new Rect(interColumnSeprators, heightSoFar, playerIDColumnWidth, divideHeight);

        if (currentSection == Section.Normal)
        {
            GUI.Box(new Rect(0, 0, contentBounds.width, divideHeight), new GUIContent(""), "DefaultSeparationBar");
            GUI.Label(currentRect, "PLAYERID", "DefaultSeparationBarText");
            currentRect.x += interColumnSeprators + playerIDColumnWidth;
            GUI.Label(currentRect, "NAME", "DefaultSeparationBarText");
            currentRect.x += interColumnSeprators + messageColumnWidth;
            GUI.Label(currentRect, "LEVEL", "DefaultSeparationBarText");
            currentRect.x          += interColumnSeprators + levelColumnWidth;
            currentRect.x           = interColumnSeprators;
            currentRect.y          += divideHeight;
            currentRect.height      = sectionHeight;
            ScrollViewContentHeight = Mathf.Max(contentBounds.height, friendsDict.Count * (entryBounds.height + entrySpacing));
            foreach (KeyValuePair <string, Roar.DomainObjects.Friend> f in friendsDict)
            {
                currentRect.width = playerIDColumnWidth;
                GUI.Label(currentRect, string.Format(playerIdFormatString, f.Value.player_id), playerIdFormat);
                currentRect.x    += interColumnSeprators + playerIDColumnWidth;
                currentRect.width = playerNameColumnWidth;
                GUI.Label(currentRect, string.Format(nameFormatString, f.Value.name), nameFormat);
                currentRect.x    += interColumnSeprators + playerNameColumnWidth;
                currentRect.width = levelColumnWidth;
                GUI.Label(currentRect, string.Format(levelFormatString, f.Value.level), levelFormat);
                currentRect.x += levelColumnWidth + interColumnSeprators;

                if (GUI.Button(currentRect, "Delete", "DefaultButton"))
                {
                    networkActionInProgress = true;
                    friends.RemoveFriend(f.Value.player_id, DefaultRoar.Instance.PlayerId(), OnRoarFriendsRemove);
                }
                currentRect.x  = interColumnSeprators;
                currentRect.y += sectionHeight;
            }

            currentRect.width = contentBounds.width;
            GUI.Label(currentRect, statusString, "DefaultSmallStatusText");

            GUI.Box(new Rect(0, contentBounds.height - footerSpacing, contentBounds.width, footerSpacing), new GUIContent(""), "DefaultFooterStyle");
            currentRect.x      = interColumnSeprators;
            currentRect.y      = contentBounds.height - footerSpacing / 2 - buttonHeight / 2;
            currentRect.width  = buttonWidth;
            currentRect.height = buttonHeight;

            if (GUI.Button(currentRect, "Invite Friend", "DefaultButton"))
            {
                statusString   = "";
                currentSection = Section.SendingInvite;
                drawSubheading = true;
                subheaderName  = "Invite Friends";
            }

            currentRect.x += buttonWidth + interColumnSeprators;

            if (GUI.Button(currentRect, "Check Invites", "DefaultButton"))
            {
                statusString   = "";
                currentSection = Section.AcceptInvites;
                FetchAcceptable();
                drawSubheading = true;
                subheaderName  = "Pending Invites";
            }
        }
        if (currentSection == Section.AcceptInvites)
        {
            GUI.Box(new Rect(0, 0, contentBounds.width, divideHeight), new GUIContent(""), "DefaultSeparationBar");
            GUI.Label(currentRect, "PLAYERID", "DefaultSeparationBarText");
            currentRect.x += interColumnSeprators + playerIDColumnWidth;
            GUI.Label(currentRect, "NAME", "DefaultSeparationBarText");
            currentRect.x += interColumnSeprators + messageColumnWidth;
            GUI.Label(currentRect, "LEVEL", "DefaultSeparationBarText");
            currentRect.x          += interColumnSeprators + levelColumnWidth;
            currentRect.x           = interColumnSeprators;
            currentRect.y          += divideHeight;
            currentRect.height      = sectionHeight;
            ScrollViewContentHeight = Mathf.Max(contentBounds.height, friendsDict.Count * (entryBounds.height + entrySpacing));
            if (friendsInviteList != null)
            {
                foreach (Roar.DomainObjects.FriendInvite f in friendsInviteList)
                {
                    currentRect.width = playerIDColumnWidth;
                    GUI.Label(currentRect, f.player_id, playerIdFormat);
                    currentRect.x    += interColumnSeprators + playerIDColumnWidth;
                    currentRect.width = playerNameColumnWidth;
                    GUI.Label(currentRect, f.player_name, nameFormat);
                    currentRect.x    += interColumnSeprators + playerNameColumnWidth;
                    currentRect.width = messageColumnWidth;
                    GUI.Label(currentRect, f.message, levelFormat);

                    currentRect.x     += interColumnSeprators + messageColumnWidth;
                    currentRect.width  = buttonWidth;
                    currentRect.height = buttonHeight;

                    if (GUI.Button(currentRect, "Accept", buttonFormat))
                    {
                        inviteManipulated       = f;
                        networkActionInProgress = true;
                        friends.AcceptFriendInvite(f.player_id, f.invite_id, OnRoarFriendsAccept);
                    }
                    currentRect.x += interColumnSeprators + buttonWidth;
                    if (GUI.Button(currentRect, "Decline", buttonFormat))
                    {
                        inviteManipulated = f;
                        friends.DeclineFriendInvite(f.invite_id, OnRoarFriendsDeclineInvite);
                    }
                    currentRect.y += sectionHeight;
                }
            }

            currentRect.width = contentBounds.width;
            GUI.Label(currentRect, statusString, "DefaultSmallStatusText");

            GUI.Box(new Rect(0, contentBounds.height - footerSpacing, contentBounds.width, footerSpacing), new GUIContent(""), "DefaultFooterStyle");
            currentRect.x      = interColumnSeprators;
            currentRect.y      = contentBounds.height - footerSpacing / 2 - buttonHeight / 2;
            currentRect.width  = buttonWidth;
            currentRect.height = buttonHeight;

            if (GUI.Button(currentRect, "Back", "DefaultButton"))
            {
                Fetch();
                statusString   = "";
                currentSection = Section.Normal;
                drawSubheading = false;
                subheaderName  = "Invite Friends";
            }
        }

        if (currentSection == Section.SendingInvite)
        {
            currentRect.y     += verticalSeparators;
            currentRect.width  = contentBounds.width;
            currentRect.height = divideHeight;
            currentRect.x      = interColumnSeprators;
            GUI.Label(currentRect, statusString, "DefaultSmallStatusText");
            currentRect.y += divideHeight;

            currentRect.x      = interColumnSeprators;
            currentRect.width  = labelWidth;
            currentRect.height = labelHeight;
            GUI.Label(currentRect, "To: (PlayerID)");
            currentRect.x     += labelWidth + interColumnSeprators;
            currentRect.width  = contentBounds.width - currentRect.x - interColumnSeprators - selectButtonWidth;
            currentRect.height = textBoxHeight;
            playerIdToSendTo   = GUI.TextField(currentRect, playerIdToSendTo, "DefaultTextArea");
            currentRect.x     += contentBounds.width - currentRect.x - interColumnSeprators - selectButtonWidth;
            currentRect.width  = selectButtonWidth;
            if (GUI.Button(currentRect, "?", "DefaultButton"))
            {
                Debug.Log("going");
                System.Action <string> act = (pid) => {
                    playerIdToSendTo = pid;
                };
                GameObject.Find("/PlayerSelectionWidget").SendMessage("setCallbackAndEnable", act);
            }
            currentRect.y     += labelHeight + verticalSeparators;
            currentRect.x      = interColumnSeprators;
            currentRect.width  = labelWidth;
            currentRect.height = labelHeight;
            GUI.Label(currentRect, "Message: ", "DefaultLabel");
            currentRect.x     += labelWidth + interColumnSeprators;
            currentRect.width  = contentBounds.width - currentRect.x - interColumnSeprators;
            currentRect.height = messageBoxHeight;
            messageToSend      = GUI.TextArea(currentRect, messageToSend, "DefaultBigMessageBox");

            currentRect.y     += messageBoxHeight + verticalSeparators;
            currentRect.x      = interColumnSeprators;
            currentRect.width  = buttonWidth;
            currentRect.height = buttonHeight;

            if (GUI.Button(currentRect, "Send", "DefaultButton"))
            {
                friends.InviteFriend(playerIdToSendTo, DefaultRoar.Instance.PlayerId(), OnRoarFriendsSendInvite);
            }

            currentRect.x += buttonWidth + interColumnSeprators;
            if (GUI.Button(currentRect, "Back", "DefaultButton"))
            {
                statusString   = "";
                drawSubheading = false;
                currentSection = Section.Normal;
            }

            currentRect.x  = interColumnSeprators;
            currentRect.y += buttonHeight + verticalSeparators;
        }
    }
 public ReadAllStudentBySectionBetweenDatesCommand(DateTime initDate, DateTime endDate, Section section)
 {
     this.initDate = initDate;
     this.endDate  = endDate;
     this.section  = section;
 }
        public Pubnub_MessagingSub(string channelName, string cipher, bool enableSSL, Pubnub pubnub)
            : base(UITableViewStyle.Grouped, null)
        {
            Channel     = channelName;
            Ssl         = enableSSL;
            Cipher      = cipher;
            this.pubnub = pubnub;

            string strSsl = "";

            if (Ssl)
            {
                strSsl = "SSL,";
            }

            string strCip = "";

            if (!String.IsNullOrWhiteSpace(Cipher))
            {
                strCip = "Cipher";
            }

            string head = String.Format("{0} {1}", strSsl, strCip);

            Section secAction = new Section();

            bool bIphone = true;

            int viewHeight = 70;

            secAction.HeaderView = CreateHeaderView(viewHeight);

            secOutput = new Section("Output");

            root = new RootElement(head)
            {
                secAction,
                secOutput
            };

            Root = root;
            dvc  = new DialogViewController(root, true);
            var tap = new UITapGestureRecognizer();

            tap.AddTarget(() => {
                dvc.View.EndEditing(true);
            });
            dvc.View.AddGestureRecognizer(tap);

            tap.CancelsTouchesInView = false;
            dvc.NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, delegate {
                InvokeInBackground(() => {
                    pubnub.EndPendingRequests();
                });
                AppDelegate.navigation.PopToRootViewController(true);
            });
            Menu         = new SlideoutNavigationController();
            Menu.TopView = dvc;

            Menu.MenuViewLeft = new LeftNavController(Menu, this);

            AppDelegate.navigation.PushViewController(Menu, true);
            Menu.ShowMenuLeft();
            newChannels.Text = Channel;
        }
Example #60
0
 public INTERNAL_TextContainerSection(Section parent) :
     base(parent)
 {
 }