public DataLink(DataRecord parent, DataField parentLinkField, Type childType, string childField) { ParentRecord = parent; ParentField = parentLinkField; ChildRecordType = childType; ChildFieldName = childField; Validate(); }
/// <summary> /// /// </summary> /// <param name="df"></param> public void Add(DataField df) { if (!df.IsBytesVolatile) { throw new ArgumentException("dataField.IsBytesVolatile must be true"); } this.DataFieldManager.DataFields.Add(df); }
/// <summary> /// Records information for a line split /// </summary> /// <param name="parentLine">The line that may be getting split</param> /// <param name="field">The tag of the item that should be attached to the line split info</param> /// <param name="dataId">The ID for the section (null if there is no split)</param> /// <returns>True if a line split was recorded, false if the <paramref name="splitSection"/> is null.</returns> internal bool AddLineSplit(LineFeature parentLine, DataField field, string dataId) { if (dataId == null) return false; InternalIdValue id = new InternalIdValue(dataId); AddFeatureDescription(field, new FeatureStub(Creator, id, parentLine.EntityType, null)); return true; }
/// <summary> /// Initializes a new instance of the <see cref="ForwardFeatureRef"/> class. /// </summary> /// <param name="referenceFrom">The object that makes the forward-reference (not null).</param> /// <param name="field">The ID of the persistent field.</param> /// <param name="iid">The internal ID that has been persisted for the field (relating to a feature /// that has not been created yet).</param> /// <exception cref="ArgumentNullException">If <paramref name="referenceFrom"/> is not defined.</exception> internal ForwardFeatureRef(IFeatureRef referenceFrom, DataField field, InternalIdValue iid) : base(field) { if (referenceFrom == null) throw new ArgumentNullException(); ReferenceFrom = referenceFrom; InternalId = iid; }
internal void FromDataField(DataField df) { this.SetAllNull(); if (df.Name != null) this.Name = df.Name.Value; if (df.Field != null) this.Field = df.Field.Value; if (df.Subtotal != null) this.Subtotal = df.Subtotal.Value; if (df.ShowDataAs != null) this.ShowDataAs = df.ShowDataAs.Value; if (df.BaseField != null) this.BaseField = df.BaseField.Value; if (df.BaseItem != null) this.BaseItem = df.BaseItem.Value; if (df.NumberFormatId != null) this.NumberFormatId = df.NumberFormatId.Value; }
/// <summary> /// Initializes a new instance of the <see cref="ForwardFeatureRefArray"/> class. /// </summary> /// <param name="referenceFrom">The object that makes the forward-reference (not null).</param> /// <param name="field">The ID of the persistent array field.</param> /// <param name="items">The items that need to be resolved.</param> /// <exception cref="ArgumentNullException">If <paramref name="referenceFrom"/> is not defined.</exception> internal ForwardFeatureRefArray(IFeatureRefArray referenceFrom, DataField field, ForwardRefArrayItem[] items) : base(field) { if (referenceFrom == null || items == null) throw new ArgumentNullException(); if (items.Length == 0) throw new ArgumentException(); ReferenceFrom = referenceFrom; Items = items; }
public void Initialize() { this._dataField = new DataField(); this._dataField2 = new DataField(); this._textBox = new TextBox(); this._textBox.SetBinding(TextBox.TextProperty, new Binding("StringProperty") { Mode = BindingMode.TwoWay }); this._dataField.Content = this._textBox; TextBox textBox2 = new TextBox(); textBox2.SetBinding(TextBox.TextProperty, new Binding("IntProperty") { Mode = BindingMode.TwoWay }); this._dataField2.Content = textBox2; }
/// <summary> /// Used to create editable datafields. /// </summary> /// <param name="field"></param> /// <param name="userId"></param> public DataFieldDto(DataField field, int? userId) { Name = field.Name; Description = field.Description; FieldType = (DataType) Enum.Parse(typeof (DataType), field.FieldType.ToString()); if (field.TypeInfo != null) { TypeInfo = field.TypeInfo.Select(s => s.Value).ToArray(); } if (userId != null) { Data = field.UserData.First(u => u.UserId == userId).Data.Select(s => s.Value).ToArray(); } }
public void comboBox_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && (sender as ComboBox).DroppedDown == false) { //setup Element DataTemplate dataTemplate = new DataTemplate(); dataTemplate.idProperty = lastId; Output output = new Output(); DataField dataField = new DataField(); dataTemplate.addTemplateElement(output); dataTemplate.addTemplateElement(dataField); lastId++; //Setup control Panel elementContainer = new Panel(); Label elementTitle = new Label(); Label elementValues = new Label(); if ((sender as ComboBox).SelectedItem != null) { string value = (sender as ComboBox).Text; int split = value.IndexOf(':') + 2; elementTitle.Text = value.Substring(split, value.Length - split); } Label label = new Label(); if ((sender as ComboBox).SelectedItem != null) { string value = (sender as ComboBox).SelectedItem.ToString(); int split = value.IndexOf(':') + 2; label.Text = value.Substring(split, value.Length - split); } else { string value = (sender as ComboBox).Text; int split = value.IndexOf(':') + 2; label.Text = value.Substring(split, value.Length - split); } label.AutoSize = true; makeControlMove(label); setActiveControl(label); (sender as ComboBox).DoDragDrop(label, DragDropEffects.All); } }
//////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 21JUN2009 James Shen Initial Creation //////////////////////////////////////////////////////////////////////////// /** * constructor. */ public TabularData(BinaryReader reader, long offset, long size, DataField[] fields, StringData stringData, StringIndex stringIndex) : base(reader, offset, size) { this._fields = fields; this._stringData = stringData; this._stringIndex = stringIndex; int numberOfField = fields.Length; _recordSize = 0; for (int i = 0; i < numberOfField; i++) { switch (fields[i].GetFieldType()) { case DataField.TYPE_CHAR://char _recordSize += 4; break; case DataField.TYPE_INTEGER://int _recordSize += 4; break; case DataField.TYPE_SMALLINT://shot _recordSize += 2; break; case DataField.TYPE_FLOAT://float _recordSize += 8; break; case DataField.TYPE_DECIMAL://float _recordSize += 8; break; case DataField.TYPE_DATE://date _recordSize += 4; break; case DataField.TYPE_LOGICAL://bool _recordSize += 1; break; } } }
public void ApplyFeatureRefArray(DataField field, ForwardRefArrayItem[] featureRefs) { throw new NotImplementedException(); }
public MultiplayerView(LauncherWindow window) { Window = window; this.MinWidth = 250; MultiplayerLabel = new Label("Multiplayer") { Font = Font.WithSize(16), TextAlignment = Alignment.Center }; ServerIPEntry = new TextEntry() { PlaceholderText = "Server IP", Text = UserSettings.Local.LastIP }; ConnectButton = new Button("Connect"); BackButton = new Button("Back"); ServerListView = new ListView() { MinHeight = 200, SelectionMode = SelectionMode.Single }; AddServerButton = new Button("Add server"); RemoveServerButton = new Button("Remove") { Sensitive = false }; ServerCreationBox = new VBox() { Visible = false }; NewServerLabel = new Label("Add new server:") { TextAlignment = Alignment.Center }; NewServerName = new TextEntry() { PlaceholderText = "Name" }; NewServerAddress = new TextEntry() { PlaceholderText = "Address" }; CommitAddNewServer = new Button("Add server"); CancelAddNewServer = new Button("Cancel"); var iconField = new DataField <Image>(); var nameField = new DataField <string>(); var playersField = new DataField <string>(); ServerListStore = new ListStore(iconField, nameField, playersField); ServerListView.DataSource = ServerListStore; ServerListView.HeadersVisible = false; ServerListView.Columns.Add(new ListViewColumn("Icon", new ImageCellView { ImageField = iconField })); ServerListView.Columns.Add(new ListViewColumn("Name", new TextCellView { TextField = nameField })); ServerListView.Columns.Add(new ListViewColumn("Players", new TextCellView { TextField = playersField })); ServerIPEntry.KeyReleased += (sender, e) => { if (e.Key == Key.Return || e.Key == Key.NumPadEnter) { ConnectButton_Clicked(sender, e); } }; BackButton.Clicked += (sender, e) => { Window.InteractionBox.Remove(this); Window.InteractionBox.PackEnd(Window.MainMenuView); }; ConnectButton.Clicked += ConnectButton_Clicked; ServerListView.SelectionChanged += (sender, e) => { RemoveServerButton.Sensitive = ServerListView.SelectedRow != -1; ServerIPEntry.Sensitive = ServerListView.SelectedRow == -1; }; AddServerButton.Clicked += (sender, e) => { AddServerButton.Sensitive = false; RemoveServerButton.Sensitive = false; ConnectButton.Sensitive = false; ServerListView.Sensitive = false; ServerIPEntry.Sensitive = false; ServerCreationBox.Visible = true; }; CancelAddNewServer.Clicked += (sender, e) => { AddServerButton.Sensitive = true; RemoveServerButton.Sensitive = true; ConnectButton.Sensitive = true; ServerListView.Sensitive = true; ServerIPEntry.Sensitive = true; ServerCreationBox.Visible = false; }; RemoveServerButton.Clicked += (sender, e) => { var server = UserSettings.Local.FavoriteServers[ServerListView.SelectedRow]; ServerListStore.RemoveRow(ServerListView.SelectedRow); UserSettings.Local.FavoriteServers = UserSettings.Local.FavoriteServers.Where( s => s.Name != server.Name && s.Address != server.Address).ToArray(); UserSettings.Local.Save(); }; CommitAddNewServer.Clicked += (sender, e) => { var server = new FavoriteServer { Name = NewServerName.Text, Address = NewServerAddress.Text }; var row = ServerListStore.AddRow(); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TrueCraft.Launcher.Content.default-server-icon.png")) ServerListStore.SetValue(row, iconField, Image.FromStream(stream)); ServerListStore.SetValue(row, nameField, server.Name); ServerListStore.SetValue(row, playersField, "TODO/50"); UserSettings.Local.FavoriteServers = UserSettings.Local.FavoriteServers.Concat(new[] { server }).ToArray(); UserSettings.Local.Save(); AddServerButton.Sensitive = true; RemoveServerButton.Sensitive = true; ConnectButton.Sensitive = true; ServerListView.Sensitive = true; ServerIPEntry.Sensitive = true; ServerCreationBox.Visible = false; }; foreach (var server in UserSettings.Local.FavoriteServers) { var row = ServerListStore.AddRow(); using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TrueCraft.Launcher.Content.default-server-icon.png")) ServerListStore.SetValue(row, iconField, Image.FromStream(stream)); ServerListStore.SetValue(row, nameField, server.Name); ServerListStore.SetValue(row, playersField, "TODO/50"); } var addServerHBox = new HBox(); AddServerButton.WidthRequest = RemoveServerButton.WidthRequest = 0.5; addServerHBox.PackStart(AddServerButton, true); addServerHBox.PackStart(RemoveServerButton, true); var commitHBox = new HBox(); CancelAddNewServer.WidthRequest = CommitAddNewServer.WidthRequest = 0.5; commitHBox.PackStart(CommitAddNewServer, true); commitHBox.PackStart(CancelAddNewServer, true); ServerCreationBox.PackStart(NewServerLabel); ServerCreationBox.PackStart(NewServerName); ServerCreationBox.PackStart(NewServerAddress); ServerCreationBox.PackStart(commitHBox); this.PackEnd(BackButton); this.PackEnd(ConnectButton); this.PackStart(MultiplayerLabel); this.PackStart(ServerIPEntry); this.PackStart(ServerListView); this.PackStart(addServerHBox); this.PackStart(ServerCreationBox); }
public void TestPropertyLevelValidationWithTwoErrors() { DataField textField = null; DataField comboBoxField = null; ValidationSummary validationSummary = null; this.AddToPanelAndWaitForLoad(); this.EnqueueCallback(() => { textField = this.DataForm.Fields[2]; comboBoxField = this.DataForm.Fields[4]; validationSummary = this.GetTemplatePart <ValidationSummary>("ValidationSummary"); Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.IsTrue(comboBoxField.IsValid); this.DataForm.BeginEdit(); }); this.EnqueueDelay(100); this.EnqueueCallback(() => { textField = this.DataForm.Fields[2]; comboBoxField = this.DataForm.Fields[4]; this.GetInputControls(); SetValue(this.textBox, string.Empty); this.CommitAllFields(); Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsFalse(textField.IsValid); Assert.IsTrue(comboBoxField.IsValid); Assert.AreEqual(1, validationSummary.Errors.Count); Assert.AreEqual(this.textBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("StringProperty is required.", validationSummary.Errors[0].Message); this.comboBox.SelectedItem = 8; this.CommitAllFields(); Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsFalse(textField.IsValid); Assert.IsFalse(comboBoxField.IsValid); Assert.AreEqual(2, validationSummary.Errors.Count); Assert.AreEqual(this.textBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("StringProperty is required.", validationSummary.Errors[0].Message); Assert.AreEqual(this.comboBox, validationSummary.Errors[1].Sources[0].Control); Assert.AreEqual("IntProperty must be between 0 and 7.", validationSummary.Errors[1].Message); SetValue(this.textBox, "test string 1"); this.CommitAllFields(); Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.IsFalse(comboBoxField.IsValid); Assert.AreEqual(1, validationSummary.Errors.Count); Assert.AreEqual(this.comboBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("IntProperty must be between 0 and 7.", validationSummary.Errors[0].Message); this.comboBox.SelectedItem = 0; this.CommitAllFields(); Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.IsTrue(comboBoxField.IsValid); Assert.AreEqual(0, validationSummary.Errors.Count); }); this.EnqueueTestComplete(); }
public Array GetColumn(DataField field) { return(_data[field]); }
protected bool Equals(DataField other) { return string.Equals(Id, other.Id); }
public static CoreDataField ConvertWFDataFieldToCoreDataField(DataField df) { CoreDataField retVal = new CoreDataField(); retVal.Name = df.Name; retVal.Value = df.Value; return retVal; }
/// <summary> /// Initializes a new instance of the <see cref="UpdateItem<T>"/> class. /// </summary> /// <param name="field">The tag that identifies the item.</param> /// <param name="value">The value associated with the item.</param> internal UpdateItem(DataField field, object value) { m_Field = field; m_Value = value; }
/// <summary> /// Gets the sections. /// </summary> /// <param name="source">The source.</param> /// <returns></returns> private Sections GetSections(string source) { source = StripTags(source); Sections data = new Sections(); data.dataFields = new ArrayList(); data.minFields = 0; data.optionalData = false; data.dataTags = 0; MatchTagCollection tags = HtmlString.TagList(source); bool isOptionalTag = false; bool zTag = false; for (int i = 0; i < tags.Count; i++) { MatchTag tag = tags[i]; // check if tag + data is optional / regex zTag = false; if (char.ToUpper(tag.TagName[0]) == 'Z') { zTag = true; isOptionalTag = true; if (tag.IsClose) { isOptionalTag = false; } //i++; //if (i < tags.Count) // tag = tags[i]; //else // break; } // Check if tag is one of interest if (_template.Tags.IndexOf(char.ToUpper(tag.TagName[0])) != -1) { DataField section; if (!zTag) { // Add tag to array of fields section = new DataField(); section.optional = isOptionalTag; section.htmlTag = tag; section.hasData = false; section.source = tag.FullTag; if (section.source.IndexOf("<#") != -1 || section.source.IndexOf("<*") != -1) { section.hasData = true; if (isOptionalTag) { data.optionalData = true; } section.dataElements = GetElements(section.source); data.dataTags += section.dataElements.Count; } data.dataFields.Add(section); if (!isOptionalTag) { data.minFields++; } } // Add data between this tag and the next to field array int start = tag.Index + tag.Length; int end; if (i + 1 < tags.Count) { tag = tags[i + 1]; zTag = false; if (char.ToUpper(tag.TagName[0]) == 'Z') { zTag = true; isOptionalTag = true; if (tag.IsClose) { isOptionalTag = false; } } // start = tag.Index + tag.Length; // i++; // if (i + 1 < tags.Count) // tag = tags[i + 1]; // else // break; //} end = tag.Index; } else { end = source.Length; } if (!zTag) { section = new DataField(); section.optional = isOptionalTag; section.htmlTag = null; section.source = HtmlString.Decode(source.Substring(start, end - start)); section.hasData = false; if (section.source.IndexOf("<#") != -1 || section.source.IndexOf("<*") != -1) { section.hasData = true; if (isOptionalTag) { data.optionalData = true; } section.dataElements = GetElements(section.source); data.dataTags += section.dataElements.Count; } data.dataFields.Add(section); if (!isOptionalTag) { data.minFields++; } } } } return data; }
public SingleplayerView(LauncherWindow window) { Worlds.Local = new Worlds(); Worlds.Local.Load(); Window = window; this.MinWidth = 250; SingleplayerLabel = new Label("Singleplayer") { Font = Font.WithSize(16), TextAlignment = Alignment.Center }; WorldListView = new ListView { MinHeight = 200, SelectionMode = SelectionMode.Single }; CreateWorldButton = new Button("New world"); DeleteWorldButton = new Button("Delete") { Sensitive = false }; PlayButton = new Button("Play") { Sensitive = false }; BackButton = new Button("Back"); CreateWorldBox = new VBox() { Visible = false }; NewWorldName = new TextEntry() { PlaceholderText = "Name" }; NewWorldSeed = new TextEntry() { PlaceholderText = "Seed (optional)" }; NewWorldCommit = new Button("Create") { Sensitive = false }; NewWorldCancel = new Button("Cancel"); NameField = new DataField <string>(); WorldListStore = new ListStore(NameField); WorldListView.DataSource = WorldListStore; WorldListView.HeadersVisible = false; WorldListView.Columns.Add(new ListViewColumn("Name", new TextCellView { TextField = NameField, Editable = false })); ProgressLabel = new Label("Loading world...") { Visible = false }; ProgressBar = new ProgressBar() { Visible = false, Indeterminate = true, Fraction = 0 }; BackButton.Clicked += (sender, e) => { Window.MainContainer.Remove(this); Window.MainContainer.PackEnd(Window.MainMenuView); }; CreateWorldButton.Clicked += (sender, e) => { CreateWorldBox.Visible = true; }; NewWorldCancel.Clicked += (sender, e) => { CreateWorldBox.Visible = false; }; NewWorldName.Changed += (sender, e) => { NewWorldCommit.Sensitive = !string.IsNullOrEmpty(NewWorldName.Text); }; NewWorldCommit.Clicked += NewWorldCommit_Clicked; WorldListView.SelectionChanged += (sender, e) => { PlayButton.Sensitive = DeleteWorldButton.Sensitive = WorldListView.SelectedRow != -1; }; PlayButton.Clicked += PlayButton_Clicked; DeleteWorldButton.Clicked += (sender, e) => { var world = Worlds.Local.Saves[WorldListView.SelectedRow]; WorldListStore.RemoveRow(WorldListView.SelectedRow); Worlds.Local.Saves = Worlds.Local.Saves.Where(s => s != world).ToArray(); Directory.Delete(world.BaseDirectory, true); }; foreach (var world in Worlds.Local.Saves) { var row = WorldListStore.AddRow(); WorldListStore.SetValue(row, NameField, world.Name); } var createDeleteHbox = new HBox(); CreateWorldButton.WidthRequest = DeleteWorldButton.WidthRequest = 0.5; createDeleteHbox.PackStart(CreateWorldButton, true); createDeleteHbox.PackStart(DeleteWorldButton, true); CreateWorldBox.PackStart(NewWorldName); CreateWorldBox.PackStart(NewWorldSeed); var newWorldHbox = new HBox(); NewWorldCommit.WidthRequest = NewWorldCancel.WidthRequest = 0.5; newWorldHbox.PackStart(NewWorldCommit, true); newWorldHbox.PackStart(NewWorldCancel, true); CreateWorldBox.PackStart(newWorldHbox); this.PackStart(SingleplayerLabel); this.PackStart(WorldListView); this.PackStart(createDeleteHbox); this.PackStart(PlayButton); this.PackStart(CreateWorldBox); this.PackStart(ProgressLabel); this.PackStart(ProgressBar); this.PackEnd(BackButton); }
private void ProcessCalc() { AnalystField firstOutputField = null; int barsNeeded = Math.Abs(Analyst.DetermineMinTimeSlice()); IndentLevel = 2; AddLine("if( _inputCount>0 && CurrentBar>=" + barsNeeded + " )"); AddLine("{"); IndentIn(); AddLine("double[] input = new double[_inputCount];"); AddLine("double[] output = new double[_outputCount];"); int idx = 0; foreach (AnalystField field in Analyst.Script.Normalize .NormalizedFields) { if (field.Input) { String str; DataField df = Analyst.Script .FindDataField(field.Name); switch (field.Action) { case NormalizationAction.PassThrough: str = EngineArray.Replace(df.Source, "##", "" + (-field.TimeSlice)); AddLine("input[" + idx + "]=" + str + ";"); idx++; break; case NormalizationAction.Normalize: str = EngineArray.Replace(df.Source, "##", "" + (-field.TimeSlice)); AddLine("input[" + idx + "]=Norm(" + str + "," + field.NormalizedHigh + "," + field.NormalizedLow + "," + field.ActualHigh + "," + field.ActualLow + ");"); idx++; break; case NormalizationAction.Ignore: break; default: throw new AnalystCodeGenerationError( "Can't generate Ninjascript code, unsupported normalizatoin action: " + field.Action.ToString()); } } if (field.Output) { if (firstOutputField == null) { firstOutputField = field; } } } if (firstOutputField != null) { AddLine("Compute(input,output);"); AddLine("Output.Set(DeNorm(output[0]" + "," + firstOutputField.NormalizedHigh + "," + firstOutputField.NormalizedLow + "," + firstOutputField.ActualHigh + "," + firstOutputField.ActualLow + "));"); IndentOut(); } AddLine("}"); IndentLevel = 2; }
public static void FillDataGrid(DataGrid grid, PropertyList columns, DataContent[] rows) { DataTable dtab = new DataTable(); DataRow drow; int colNumber = 0; if (columns != null) { colNumber = columns.Size(); dtab.Columns.Add("_UIUTilsNo_", typeof(int)); for (IEnumerator i = columns.GetEnumerator(); i.MoveNext();) { DataInfo info = columns.Info(); if (info != null) { DataField f = columns.Info().GetField((String)i.Current); dtab.Columns.Add(f.getFieldTitle(), typeof(Object) /*f.getFieldType().ToImplType()*/); } else { dtab.Columns.Add((String)i.Current, typeof(Object)); } } for (int i = 0; i < rows.Length; i++) { drow = dtab.NewRow(); int col = 0; drow[col++] = i + 1; for (IEnumerator e = columns.GetEnumerator(); e.MoveNext();) { Object o = rows[i].GetProperty((String)e.Current); if (o == null) { o = DBNull.Value; } drow[col++] = o; } dtab.Rows.Add(drow); } } else if (rows != null && rows.Length > 0) { ICollection cols = rows[0].KeySet(); dtab.Columns.Add("No", typeof(int)); for (IEnumerator i = cols.GetEnumerator(); i.MoveNext();) { dtab.Columns.Add((String)i.Current, typeof(Object)); colNumber++; } for (int i = 0; i < rows.Length; i++) { drow = dtab.NewRow(); int col = 0; drow[col++] = i + 1; for (IEnumerator e = cols.GetEnumerator(); e.MoveNext();) { Object o = rows[i].GetProperty((String)e.Current); if (o == null) { o = DBNull.Value; } drow[col++] = o; } dtab.Rows.Add(drow); } } int x = -1; if (colNumber > 0) { x = (grid.ClientSize.Width - 40) / colNumber; if (x > 0) { grid.PreferredColumnWidth = x; } } grid.DataSource = dtab; grid.TableStyles.Clear(); grid.TableStyles.Add(new DataGridTableStyle()); GridColumnStylesCollection gcsColl = grid.TableStyles[0].GridColumnStyles; ArrayList a = new ArrayList(); for (int i = 0; i < gcsColl.Count; i++) { if (x > 0) { gcsColl[i].Width = x; gcsColl[i].NullText = ""; } a.Add(gcsColl[i]); } gcsColl.Clear(); UserTextBoxColumn u = new UserTextBoxColumn(); u.HeaderText = ""; u.MappingName = "_UIUTilsNo_"; u.Width = 30; gcsColl.Add(u); for (int i = 1; i < a.Count; i++) { gcsColl.Add((DataGridColumnStyle)a[i]); } /* * for (int i = 0; i < gcsColl.Count; i++) * { * if (gcsColl[i].GetType() == typeof (DataGridTextBoxColumn)) * { * DataGridTextBoxColumn textColumn = (DataGridTextBoxColumn) gcsColl[i]; * if (textColumn.HeaderText == "No") * { * textColumn.Width = 30; * textColumn.TextBox.BackColor=Color.Red; * //textColumn.HeaderText = "new header text"; * break; * } * } * }*/ if (dtab.Rows.Count > 0) { grid.CurrentRowIndex = 0; grid.Select(0); } grid.RowHeadersVisible = false; grid.RowHeaderWidth = 1; //grid.Focus(); }
private static Task <T[]> GenerateLoader <T>(RememberingParquetReader reader, DataField column) { return(new Task <T[]>(() => LoadColumn <T>(reader, column).Result)); }
private static Task <T[]> LoadColumn <T>(RememberingParquetReader reader, DataField column) { return(Task.FromResult(reader.LoadColumn <T>(column))); }
//////////////////////////////////////////////////////////////////////////// //--------------------------------- REVISIONS ------------------------------ // Date Name Tracking # Description // --------- ------------------- ------------- ---------------------- // 21JUN2009 James Shen Initial Creation //////////////////////////////////////////////////////////////////////////// /** * constructor. */ public Header(BinaryReader reader, long offset, long size) : base(reader, offset, size) { if (!IsJavaFormat()) { throw new IOException("Invalid map file format!"); } DataReader.Seek(reader, 0); FileVersion = DataReader.ReadString(reader); DataReader.Seek(reader, 16); FileFormat = DataReader.ReadString(reader); DataReader.Seek(reader, 32); DominantType = DataReader.ReadString(reader); DataReader.Seek(reader, 48); RecordCount = DataReader.ReadInt(reader); int minX, minY, maxX, maxY; minX = DataReader.ReadInt(reader); minY = DataReader.ReadInt(reader); maxX = DataReader.ReadInt(reader); maxY = DataReader.ReadInt(reader); MapBounds.X = minX / DOUBLE_PRECISION; MapBounds.Y = minY / DOUBLE_PRECISION; MapBounds.Width = (maxX - minX) / DOUBLE_PRECISION; MapBounds.Height = (maxY - minY) / DOUBLE_PRECISION; IndexOffset = DataReader.ReadInt(reader); IndexLength = DataReader.ReadInt(reader); RtreeIndexOffset = DataReader.ReadInt(reader); RtreeIndexLength = DataReader.ReadInt(reader); StringIndexOffset = DataReader.ReadInt(reader); StringIndexLength = DataReader.ReadInt(reader); StringDataOffset = DataReader.ReadInt(reader); StringDataLength = DataReader.ReadInt(reader); GeoDataOffset = DataReader.ReadInt(reader); GeoDataLength = DataReader.ReadInt(reader); TabularDataOffset = DataReader.ReadInt(reader); TabularDataLength = DataReader.ReadInt(reader); NumberOfFields = DataReader.ReadInt(reader); Fields = new DataField[NumberOfFields]; for (int i = 0; i < NumberOfFields; i++) { string fieldName = DataReader.ReadString(reader); byte fieldType = reader.ReadByte(); int fieldWidth = DataReader.ReadInt(reader); short fieldPrecision = DataReader.ReadShort(reader); Fields[i] = new DataField(fieldName, fieldType, fieldWidth, fieldPrecision); } this._size = (NumberOfFields + 1) * 256; }
public static Dictionary <uint, string> GetAttributes(DataField field, BaseFile baseFile) { int currentIndex = 0; if (field.Tag == "ATTF" || field.Tag == "ATTV" || field.Tag == "NATF") { LexicalLevel lexicalLevel = field.Tag == "ATTF" || field.Tag == "ATTV" ? baseFile.ATTFLexicalLevel : baseFile.NATFLexicalLevel; Dictionary <uint, string> values = new Dictionary <uint, string>(); uint key = 0; while (currentIndex < field.Bytes.Length && field.Bytes[currentIndex] != DataField.FieldTerminator) { foreach (SubFieldDefinition subFieldDefinition in field.FieldDescription.SubFieldDefinitions) { if (subFieldDefinition.FormatTypeCode == FormatTypeCode.CharacterData) { var sb = new StringBuilder(); if (subFieldDefinition.SubFieldWidth == 0) { if (lexicalLevel == LexicalLevel.ISO10646) { while (currentIndex < field.Bytes.Length && field.Bytes[currentIndex] != DataField.UnitTerminator) { sb.Append(BitConverter.ToChar(field.Bytes, currentIndex)); currentIndex += 2; } } else if (lexicalLevel == LexicalLevel.ISO8859) { System.Text.Encoding iso8859 = System.Text.Encoding.GetEncoding("iso-8859-1"); int startIndex = currentIndex; while (currentIndex < field.Bytes.Length && field.Bytes[currentIndex] != DataField.UnitTerminator) { currentIndex++; } string val = iso8859.GetString(field.Bytes, startIndex, currentIndex - startIndex); //string val2 = Encoding.GetEncoding(1252).GetString(field.Bytes, startIndex, currentIndex - startIndex); sb.Append(val); currentIndex++; } else { while (currentIndex < field.Bytes.Length && field.Bytes[currentIndex] != DataField.UnitTerminator) { sb.Append((char)field.Bytes[currentIndex]); currentIndex++; } //Consume the Terminator currentIndex++; } } else { for (int i = 0; i < subFieldDefinition.SubFieldWidth; i++) { sb.Append((char)field.Bytes[currentIndex]); currentIndex++; } } var s = sb.ToString(); if (!field.SubFields.ContainsKey(subFieldDefinition.Tag)) { field.SubFields.Add(subFieldDefinition.Tag, s); } if (!values.ContainsKey(key)) { values.Add(key, s); } else { // Attributes Error: declared key is missing } } else if (subFieldDefinition.FormatTypeCode == FormatTypeCode.LsofBinaryForm) { switch (subFieldDefinition.BinaryFormSubType) { case ExtendedBinaryForm.IntegerSigned: if (subFieldDefinition.BinaryFormPrecision != 4) { throw new NotImplementedException("Only handle Signed Ints of 4 bytes"); } int signedValue = 0; for (int i = 0; i < subFieldDefinition.BinaryFormPrecision; i++) { int tempVal = field.Bytes[currentIndex++]; for (int j = 0; j < i; j++) { tempVal = tempVal << 8; } signedValue += tempVal; } field.SubFields.Add(subFieldDefinition.Tag, signedValue); break; case ExtendedBinaryForm.IntegerUnsigned: if (subFieldDefinition.BinaryFormPrecision > 4) { throw new NotImplementedException("Only handle unsigned Ints 4 bytes or less"); } UInt32 unsignedValue = 0; for (int i = 0; i < subFieldDefinition.BinaryFormPrecision; i++) { UInt32 tempVal = field.Bytes[currentIndex++]; for (int j = 0; j < i; j++) { tempVal = tempVal << 8; } unsignedValue += tempVal; } if (!field.SubFields.ContainsKey(subFieldDefinition.Tag)) { field.SubFields.Add(subFieldDefinition.Tag, unsignedValue); } key = unsignedValue; break; default: throw new NotImplementedException("Unhandled LsofBinaryForm"); } } else if (subFieldDefinition.FormatTypeCode == FormatTypeCode.ExplicitPoint) { if (subFieldDefinition.SubFieldWidth == 0) { throw new Exception("Expected a subfield width for Explicit Point Type"); } var tempSb = new StringBuilder(); for (int i = 0; i < subFieldDefinition.SubFieldWidth; i++) { tempSb.Append((char)field.Bytes[currentIndex]); currentIndex++; } double value = 0; value = Double.Parse(tempSb.ToString(), CultureInfo.InvariantCulture); field.SubFields.Add(subFieldDefinition.Tag, value); } else if (subFieldDefinition.FormatTypeCode == FormatTypeCode.BitStringData) { if (subFieldDefinition.SubFieldWidth == 0) { throw new Exception("Expected a subfield width for Bit String Data"); } //divide by 8 and round up int bytesToRead = (subFieldDefinition.SubFieldWidth + (8 - 1)) / 8; byte[] newByteArray = new byte[bytesToRead]; for (int i = 0; i < bytesToRead; i++) { newByteArray[i] = field.Bytes[currentIndex]; currentIndex++; } field.SubFields.Add(subFieldDefinition.Tag, newByteArray); } else { throw new Exception("Unhandled subField type :" + subFieldDefinition.FormatTypeCode); } //if (field.Bytes[field.Bytes.Length - 1] != DataField.FieldTerminator) throw new Exception("Expected Field Terminator"); } } return(values); } return(null); }
public DbField(DataField field) { StrongField = field; }
/// <summary> /// Default constructor (for serialization mechanism). /// </summary> public UpdateItem() { m_Field = DataField.Empty; m_Value = null; }
/// <summary> /// Replaces a <see cref="DataField" />'s <see cref="TextBox" /> control with another control /// and updates the bindings. /// </summary> /// <param name="field">The <see cref="DataField"/> whose <see cref="TextBox"/> will be replaced.</param> /// <param name="newControl">The new control you're going to set as <see cref="DataField.Content" />.</param> /// <param name="dataBindingProperty">The control's property that will be used for data binding.</param> public static void ReplaceTextBox(this DataField field, FrameworkElement newControl, DependencyProperty dataBindingProperty) { field.ReplaceTextBox(newControl, dataBindingProperty, binding => { }); }
/// <summary> /// /// </summary> /// <param name="datafieldnode"></param> /// <returns></returns> private static DataField CreateDataField(XmlNode datafieldnode) { string name = string.Empty; string factor = string.Empty; object[] convertArgs = null; int begin = 0; int length = 0; IBytesConverter ibc = null; bool iscrc = false; bool isMatchCheck = false; byte[] bytes = null; bool littleEndian = true; bool isLazy = false; string str = string.Empty; XmlElement el = datafieldnode as XmlElement; name = GetAttribute(el, DeviceDefineNodeNames.DataFieldName); str = GetAttribute(el, DeviceDefineNodeNames.Begin); begin = int.Parse(str); str = GetAttribute(el, DeviceDefineNodeNames.Length); length = int.Parse(str); if (HasBytesConverterChildNode(datafieldnode)) { XmlNode bytesConverterNode = datafieldnode.SelectSingleNode( DeviceDefineNodeNames.BytesConverter); BytesConverterConfig cfg = CreateBytesConverterConfig(bytesConverterNode); ibc = GetBytesConverter(cfg); } else { // converter // str = GetAttribute(el, DeviceDefineNodeNames.Converter, true); if (str == null || str.Length == 0) { str = "Xdgk.Communi.OriginalConverter"; } // // factor = GetAttribute(el, DeviceDefineNodeNames.Factor, true); if (factor != null && factor.Length > 0) { try { float n = Convert.ToSingle(factor); convertArgs = new object[] { n }; } catch (FormatException formatEx) { string s = string.Format("Invalid Factor '{0}'", factor); throw new ConfigException(s, formatEx); } } ibc = GetBytesConvert(str, convertArgs); } // // str = GetAttribute(el, DeviceDefineNodeNames.LittleEndian, true); if (str.Length > 0) { littleEndian = bool.Parse(str); } ibc.IsLittleEndian = littleEndian; str = GetAttribute(el, DeviceDefineNodeNames.Bytes, true); if (str != null && str.Length > 0) { bytes = HexStringConverter.Default.ConvertToBytes(str); } str = GetAttribute(el, DeviceDefineNodeNames.Crc, true); if (str != null && str.Length > 0) { iscrc = bool.Parse(str); } str = GetAttribute(el, DeviceDefineNodeNames.MatchCheck, true); if (str != null && str.Length > 0) { isMatchCheck = bool.Parse(str); } str = GetAttribute(el, DeviceDefineNodeNames.Lazy, true); if (str != null && str.Length > 0) { isLazy = bool.Parse(str); } DataField df = new DataField(name, begin, length, (IBytesConverter)ibc); df.IsMatchCheck = isMatchCheck; if (bytes != null) df.Bytes = bytes; if (df.IsMatchCheck && (df.Bytes == null || df.Bytes.Length == 0)) { throw new Exception("must set bytes while matchCheck == true"); } df.IsCRC = iscrc; df.IsLazy = isLazy; return df; }
public static CustomButton CreateCustomButton(ValueDataField field, ICommand command, double fontSize, bool isWfDesignMode) { var hotkey = field.Value.To(Key.None); var hotkey2 = Key.None; string svalue; if (DataField.TryGetFieldProperties(field, ValueDataFieldConstants.HotKey2, isWfDesignMode, out svalue)) { hotkey2 = svalue.To(Key.None); } var button = new CustomButton { Text = field.Caption, HorizontalContentAlignment = HorizontalAlignment.Left, HotKey = hotkey, HotKey2 = hotkey2, Command = command, CommandParameter = field, IsEnabled = field.IsEnabled.HasValue && field.IsEnabled.Value, Visibility = field.Visible ? Visibility.Visible : Visibility.Collapsed, }; if (DataField.TryGetFieldProperties(field, ValueDataFieldConstants.SuffixText, isWfDesignMode, out svalue)) { button.SuffixText = svalue; } bool isNotMenuButton; if (DataField.TryGetFieldProperties(field, ValueDataFieldConstants.IsNotMenuButton, isWfDesignMode, out isNotMenuButton)) { button.IsNotMenuButton = isNotMenuButton; } bool transferHotKeyToControls; if (DataField.TryGetFieldProperties(field, ValueDataFieldConstants.TransferHotKeyToControls, isWfDesignMode, out transferHotKeyToControls)) { button.TransferHotKeyToControls = transferHotKeyToControls; } ICommand icommand; if (DataField.TryGetFieldProperties(field, ValueDataFieldConstants.Command, isWfDesignMode, out icommand)) { button.Command = icommand; } if (fontSize > 0) { button.FontSize = fontSize; } if (field.SetFocus) { button.BackgroundFocus(); } return(button); }
internal DataField ToDataField() { DataField df = new DataField(); if (this.Name != null && this.Name.Length > 0) df.Name = this.Name; df.Field = this.Field; if (this.Subtotal != DataConsolidateFunctionValues.Sum) df.Subtotal = this.Subtotal; if (this.ShowDataAs != ShowDataAsValues.Normal) df.ShowDataAs = this.ShowDataAs; if (this.BaseField != -1) df.BaseField = this.BaseField; if (this.BaseItem != 1048832) df.BaseItem = this.BaseItem; if (this.NumberFormatId != null) df.NumberFormatId = this.NumberFormatId.Value; return df; }
public void String_is_always_nullable() { var se = new DataField <string>("id"); Assert.True(se.HasNulls); }
public void TestPropertyLevelValidationWithTextChanged() { DataField textField = null; ValidationSummary validationSummary = null; this.AddToPanelAndWaitForLoad(); this.EnqueueCallback(() => { textField = this.DataForm.Fields[2]; validationSummary = this.GetTemplatePart <ValidationSummary>("ValidationSummary"); this.ExpectContentLoaded(); this.DataForm.BeginEdit(); }); this.WaitForContentLoaded(); this.EnqueueCallback(() => { textField = this.DataForm.Fields[2]; this.GetInputControls(); SetValue(this.textBox, string.Empty); this.CommitAllFields(); Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsFalse(textField.IsValid); Assert.AreEqual(1, validationSummary.Errors.Count); Assert.AreEqual(this.textBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("StringProperty is required.", validationSummary.Errors[0].Message); this.ExpectTextChangedOnTextBox(); SetValue(this.textBox, "test string 1"); }); this.WaitForTextChanged(); this.EnqueueCallback(() => { Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.AreEqual(0, validationSummary.Errors.Count); this.ExpectTextChangedOnTextBox(); SetValue(this.textBox, string.Empty); }); this.WaitForTextChanged(); this.EnqueueCallback(() => { Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsFalse(textField.IsValid); Assert.AreEqual(1, validationSummary.Errors.Count); Assert.AreEqual(this.textBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("StringProperty is required.", validationSummary.Errors[0].Message); this.ExpectTextChangedOnTextBox(); SetValue(this.textBox, "test string 1"); }); this.WaitForTextChanged(); this.EnqueueCallback(() => { Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.AreEqual(0, validationSummary.Errors.Count); this.ExpectTextChangedOnTextBox(); SetValue(this.textBox, string.Empty); }); this.EnqueueTestComplete(); }
public void Datetime_is_not_nullable_by_default() { var se = new DataField <DateTime>("id"); Assert.False(se.HasNulls); }
/// <summary> /// Obtains update items for a revised version of this face (for later use with <see cref="ExchangeData"/>). /// </summary> /// <param name="field">The tag that identifies this face</param> /// <param name="sections">The distances that will be used for the revised version of this face</param> /// <returns>The item representing the change (may be subsequently supplied to the <see cref="ExchangeData"/> method).</returns> internal UpdateItem GetUpdateItem(DataField field, Distance[] sections) { if (sections.Length != m_Sections.Count) throw new ArgumentException(); // Just package up every supplied section (even those that have not changed) return new UpdateItem(field, sections); }
private void ChangeField(DataField field) { if (!IsSourceValid()) { return; } _isLimit = false; switch (Source.UseStrategyType) { case MRUseStrategyTypeSysEnum.WHERE: { switch (Source.UseStrategy) { case MRUseStrategySysEnum.TE_FULL: case MRUseStrategySysEnum.TE_PARTIAL: _requirement = false; SetParam(field, null, false); break; case MRUseStrategySysEnum.TE_COMPLETE_MIN: case MRUseStrategySysEnum.TE_COMPLETE_MAX: _requirement = true; _isLimit = true; SetParam(field, null, true); break; case MRUseStrategySysEnum.SUPPLYAREA: _requirement = true; SetParam(field, null, true); break; case MRUseStrategySysEnum.OWNER: _requirement = true; SetParam(field, "MANDANT_MANDANTID", true); break; case MRUseStrategySysEnum.RESERVFULLTE: _requirement = true; SetParam(field, "ENUM_MR_TE", true); break; default: throw new DeveloperException("Неизвестная стратегия '{0}'.", Source.MRUseStrategy); } break; } case MRUseStrategyTypeSysEnum.ORDER: { switch (Source.UseStrategy) { case MRUseStrategySysEnum.COUNT_BEST: case MRUseStrategySysEnum.COUNT_MAX: case MRUseStrategySysEnum.COUNT_MIN: case MRUseStrategySysEnum.COUNT_MAX_PLACE: case MRUseStrategySysEnum.COUNT_MIN_PLACE: case MRUseStrategySysEnum.TE_FULL: case MRUseStrategySysEnum.TE_PARTIAL: case MRUseStrategySysEnum.FEFO: case MRUseStrategySysEnum.LEFO: case MRUseStrategySysEnum.PLACESORTPICK: case MRUseStrategySysEnum.MULTIPLICITY_BEST: _requirement = false; SetParam(field, null, false); break; case MRUseStrategySysEnum.FIFO: case MRUseStrategySysEnum.LIFO: _requirement = true; SetParam(field, "ENUM_ART_FIFO", true); break; case MRUseStrategySysEnum.SUPPLYAREA: _requirement = true; SetParam(field, null, true); break; default: throw new DeveloperException("Неизвестная стратегия '{0}'.", Source.MRUseStrategy); } break; } case MRUseStrategyTypeSysEnum.ACTION: { switch (Source.UseStrategy) { case MRUseStrategySysEnum.ROUND_IGNORE: case MRUseStrategySysEnum.ROUND_FIX: case MRUseStrategySysEnum.ROUND_DOWN: case MRUseStrategySysEnum.ROUND_UP: _requirement = false; SetParam(field, null, false); break; default: throw new DeveloperException("Неизвестная стратегия '{0}'.", Source.MRUseStrategy); } break; } default: throw new DeveloperException("Неизвестный тип стратегии '{0}'.", Source.MRUseStrategyType); } }
private void processDataField(CoreDataField dfToProcess, DataField wfdf, CoreDataField dfThatMocksWFDF, out bool needsUpdate, out bool breakFromLoop) { string checkText = dfToProcess.Check; needsUpdate = false; breakFromLoop = false; try { //Two modes, one setting and getting, one getting only, which does not need wfDataField if (checkText.Length == 0 || checkText.Equals("set")) { if (wfdf == null) { throw new WfdfNullReferenceException("Cannot set df in this mode"); } wfdf.Value = dfToProcess.Value; needsUpdate = true; } else if (checkText.StartsWith("check:", StringComparison.OrdinalIgnoreCase)) { string[] partsOfCheck = checkText.Split(new char[] { ':' }); string whatToCheck = partsOfCheck[1]; if (dfThatMocksWFDF == null) { throw new DddfNullReferenceException("cannot check df in this mode"); } if (!AssertValue(dfThatMocksWFDF, whatToCheck, dfToProcess)) { FailTest("Assert Failed", TestResultStage.ActivityExecutionError, currentProcess, currentActivity); breakFromLoop = true; } } else if (checkText.StartsWith("store:", StringComparison.OrdinalIgnoreCase)) { string[] partsOfCheck = checkText.Split(new char[] { ':' }); string keyToStoreAgainst = partsOfCheck[1]; //will add if it doesn't exist and overwrite if it does exist //I want this behaviour .... for now!!! Change to .Add() if you want to throw an error if it exists if (dfThatMocksWFDF == null) { throw new DddfNullReferenceException("Cannot store df in this mode"); } dataFieldDictionary[keyToStoreAgainst] = dfThatMocksWFDF.Value.ToString(); string debugMessage = String.Format("keyToStoreAgainst '{0}' set to value:{1}", keyToStoreAgainst, dfThatMocksWFDF.Value.ToString()); SendResult(new TestResultArgs(currentProcess, currentActivity, TestResultStage.DebugMessage, debugMessage) ); } else if (checkText.StartsWith("setToVariable", StringComparison.OrdinalIgnoreCase)) { if (!this.AutoActionTasks) { if (dataFieldDictionary.ContainsKey(dfToProcess.Value.ToString())) { if (wfdf == null) { throw new WfdfNullReferenceException("Cannot set df in this mode"); } wfdf.Value = dataFieldDictionary[dfToProcess.Value.ToString()]; string debugMessage = String.Format("wfdf.Value '{0}' dfdictkey: {1} set to value:{2}", wfdf.Value, dfToProcess.Name, dataFieldDictionary[dfToProcess.Value.ToString()]); SendResult(new TestResultArgs(currentProcess, currentActivity, TestResultStage.DebugMessage, debugMessage)); } else { string err = string.Format("Problem setting datafield. configured to set from temp variable, but temp variable name does not exist varName:{0} dfvalue:{1}", dfToProcess.Name, dfToProcess.Value); FailTest(err, TestResultStage.ActivityExecutionError, currentProcess, currentActivity); } } else { //Do not set Datafields in this mode. Allow the UI to do it. } } else { throw new NotImplementedException(string.Format("only catering for checking 'set', '', 'check:?', 'store:?' but got '{0}'", dfToProcess.Check)); } } catch (NullReferenceException ex) { string methodProperties = string.Format("mode: '{0}' p:{1}, a:{2}", checkText, currentProcess.ToString(), currentActivity.Name); if (ex is WfdfNullReferenceException) { throw new ArgumentException("cannot set workflow datafield in this activity mode " + methodProperties, ex); } else if (ex is DddfNullReferenceException) { throw new ArgumentException("cannot lookup workflow values in this activity mode" + methodProperties, ex); } else { throw ex; } } }
/// <summary> /// This method adds all the databases in the current project /// to the DataManager (DM). /// </summary> /// <param name="currentProject"></param> public void AddDatabases(ref Project currentProject) { // Make sure the CurrentProject is set; I think this changed and now the CurrentProject // is created earlier. if ((CurrentProject == null) || (!CurrentProject.Equals(currentProject))) { // this has to be set before the DataManager can be created this.CurrentProject = currentProject; } // locals Database database = null; List <Enumeration> enumerations = null; List <DTNDatabase> databases = null; // If the currentProject object exists if (NullHelper.Exists(currentProject)) { // set the databases databases = currentProject.Databases; // if the current project has enumerations if (ListHelper.HasOneOrMoreItems(currentProject.Enumerations)) { // get a list of enumerations enumerations = new List <Enumeration>(); // if the enumrations exist foreach (Enumeration enumeration in currentProject.Enumerations) { // add thsi enumerations enumerations.Add(enumeration); } } } // if databases exists if ((ListHelper.HasOneOrMoreItems(databases)) && (DataManager != null)) { // loop through each database foreach (DTNDatabase db in databases) { // convert to DataJuggler.Net.Sql database database = ConvertSQLDatabase(db, enumerations); // if the database exists if (database != null) { // If the database has Serializable selected if (db.Serializable) { // Serialize each table foreach (DataTable table in database.Tables) { // Set serializable on the table table.Serializable = true; } } // if there are one or more tables in the current Project if (ListHelper.HasOneOrMoreItems(CurrentProject.Tables)) { // iterate the tables foreach (DTNTable table in CurrentProject.Tables) { // attempt to find this table in this database DataTable dataTable = database.Tables.FirstOrDefault(x => x.Name == table.TableName); // If the dataTable object exists if (NullHelper.Exists(dataTable)) { // Store the tableId in dataTable so a save performs an update and not a duplicate insert dataTable.TableId = table.TableId; // Set the value for Exclude in the dataTable dataTable.Exclude = table.Exclude; dataTable.CreateBindingCallback = table.CreateBindingCallback; // if this table has one or more fields if (ListHelper.HasOneOrMoreItems(table.Fields)) { // iterate the fields foreach (DTNField field in table.Fields) { // We now must find the field in this DataTable DataField dataField = dataTable.Fields.FirstOrDefault(x => x.FieldName == field.FieldName); // If the dataField object exists if (NullHelper.Exists(dataField)) { // Store the FieldId, which is not really mapped, but when the field is converted // back to a DTNField, this FieldId is converted if present. dataField.FieldId = field.FieldId; // set Exclude dataField.Exclude = field.Exclude; } } } } } } // Add this database this.DataManager.Databases.Add(database); } } // now we must recreate the currentProject.Tables to match the database if ((DataManager != null) && (DataManager.Databases != null) && (DataManager.Databases.Count > 0) && (DataManager.Databases[0].Tables.Count > 0)) { // create the currentTables List <DTNTable> currentTables = new List <DTNTable>(); // iterate the databases foreach (Database db in DataManager.Databases) { // attempt to find the database DTNDatabase dtnDatabase = currentProject.Databases.FirstOrDefault(x => x.DatabaseName == db.Name); // If the dtnDatabase object exists if (NullHelper.Exists(dtnDatabase)) { // iterate the tables foreach (DataTable table in db.Tables) { // create the table DTNTable dtnTable = DataConverter.ConvertDataTable(table, currentProject, dtnDatabase); // We must check if we have an existing table already with this name that is excluded DTNTable existingTable = CurrentProject.Tables.FirstOrDefault(x => x.TableName == table.Name); // if the table exists if (NullHelper.Exists(dtnTable)) { // if the existingTable was found if (NullHelper.Exists(existingTable)) { // Update the value for exclude dtnTable.Exclude = existingTable.Exclude; dtnTable.CreateBindingCallback = existingTable.CreateBindingCallback; } // Add this table currentTables.Add(dtnTable); } } } } // Now set the CurrentProject.Tables back currentProject.Tables = currentTables; } } }
public void ReplaceDirectContent() { DataFormApp_DirectContent dataFormApp = new DataFormApp_DirectContent(); dataFormApp.dataForm.CurrentItem = new DataClass(); this.DataFormAppBase = dataFormApp; ContentPresenter contentPresenter = null; this.AddToPanelAndWaitForLoad(); this.EnqueueCallback(() => { contentPresenter = this.GetTemplatePart<ContentPresenter>("ContentPresenter"); TextBox textBox = contentPresenter.Content as TextBox; Assert.IsNotNull(textBox); Assert.AreEqual(dataFormApp.dataForm.Content, textBox); this.ExpectContentLoaded(); textBox = new TextBox(); textBox.SetBinding(TextBox.TextProperty, new Binding("Age") { Mode = BindingMode.TwoWay }); DataField dataField = new DataField() { Label = "Age", PropertyPath = "Age", Content = textBox }; StackPanel stackPanel = new StackPanel(); stackPanel.Children.Add(dataField); dataFormApp.dataForm.Content = stackPanel; }); this.WaitForContentLoaded(); this.EnqueueCallback(() => { Assert.AreEqual(DataFormMode.ReadOnly, dataFormApp.dataForm.Mode); contentPresenter = this.GetTemplatePart<ContentPresenter>("ContentPresenter"); StackPanel stackPanel = contentPresenter.Content as StackPanel; Assert.IsNotNull(stackPanel); Assert.AreEqual(dataFormApp.dataForm.Content, stackPanel); }); this.EnqueueTestComplete(); }
public ComboBoxes() { HBox box = new HBox(); ComboBox c = new ComboBox(); c.Items.Add("One"); c.Items.Add("Two"); c.Items.Add("Three"); c.SelectedIndex = 1; box.PackStart(c); Label la = new Label(); box.PackStart(la); c.SelectionChanged += delegate { la.Text = "Selected: " + (string)c.SelectedItem; }; PackStart(box); box = new HBox(); ComboBox c2 = new ComboBox(); box.PackStart(c2); Button b = new Button("Fill combo (should grow)"); box.PackStart(b); b.Clicked += delegate { for (int n = 0; n < 10; n++) { c2.Items.Add("Item " + new string ('#', n)); } }; PackStart(box); // Combo with custom labels box = new HBox(); ComboBox c3 = new ComboBox(); c3.Items.Add(0, "Combo with custom labels"); c3.Items.Add(1, "One"); c3.Items.Add(2, "Two"); c3.Items.Add(3, "Three"); c3.Items.Add(ItemSeparator.Instance); c3.Items.Add(4, "Maybe more"); var la3 = new Label(); box.PackStart(c3); box.PackStart(la3); c3.SelectionChanged += delegate { la3.Text = string.Format("Selected item: {0} with label {1}", c3.SelectedItem, c3.SelectedText); }; PackStart(box); box = new HBox(); var c4 = new ComboBoxEntry(); var la4 = new Label(); box.PackStart(c4); box.PackStart(la4); c4.Items.Add(1, "One"); c4.Items.Add(2, "Two"); c4.Items.Add(3, "Three"); c4.TextEntry.PlaceholderText = "This is an entry"; c4.TextEntry.Changed += delegate { la4.Text = "Selected text: " + c4.TextEntry.Text; }; PackStart(box); var c5 = new ComboBoxEntry(); c5.TextEntry.TextAlignment = Alignment.Center; c5.TextEntry.Text = "centered text"; PackStart(c5); // A complex combobox // Three data fields var imgField = new DataField <Image> (); var textField = new DataField <string> (); var descField = new DataField <string> (); ComboBox cbox = new ComboBox(); ListStore store = new ListStore(textField, imgField, descField); cbox.ItemsSource = store; var r = store.AddRow(); store.SetValue(r, textField, "Information"); store.SetValue(r, descField, "Icons are duplicated on purpose"); store.SetValue(r, imgField, StockIcons.Information); r = store.AddRow(); store.SetValue(r, textField, "Error"); store.SetValue(r, descField, "Another item"); store.SetValue(r, imgField, StockIcons.Error); r = store.AddRow(); store.SetValue(r, textField, "Warning"); store.SetValue(r, descField, "A third item"); store.SetValue(r, imgField, StockIcons.Warning); // Four views to show three data fields cbox.Views.Add(new ImageCellView(imgField)); cbox.Views.Add(new TextCellView(textField)); cbox.Views.Add(new ImageCellView(imgField)); cbox.Views.Add(new TextCellView(descField)); cbox.SelectedIndex = 0; PackStart(cbox); }
public void ApplyFeatureRefArray(DataField field, ForwardRefArrayItem[] featureRefs) { Debug.Assert(field == DataField.Delete); foreach (var item in featureRefs) { if (item.ArrayIndex < 0 || item.ArrayIndex >= m_Deletions.Count) throw new IndexOutOfRangeException(); m_Deletions[item.ArrayIndex] = item.Feature; // As DeserializationFactory.Deactivate... LineFeature line = (item.Feature as LineFeature); if (line != null) line.RemoveTopology(); item.Feature.IsInactive = true; } }
private void FocusControl(DataLink link, DataSet dataSet, DataField field) { Focus(); }
internal void AddFeatureStub(DataField field, FeatureStub stub) { if (stub != null) AddFeatureDescription(field, stub); }
/// <summary> /// Perform the analysis. /// </summary> /// <param name="target">The Encog analyst object to analyze.</param> public void Process(EncogAnalyst target) { int count = 0; CSVFormat csvFormat = ConvertStringConst .ConvertToCSVFormat(_format); var csv = new ReadCSV(_filename, _headers, csvFormat); // pass one, calculate the min/max while (csv.Next()) { if (_fields == null) { GenerateFields(csv); } for (int i = 0; i < csv.ColumnCount; i++) { if (_fields != null) { _fields[i].Analyze1(csv.Get(i)); } } count++; } if (count == 0) { throw new AnalystError("Can't analyze file, it is empty."); } if (_fields != null) { foreach (AnalyzedField field in _fields) { field.CompletePass1(); } } csv.Close(); // pass two, standard deviation csv = new ReadCSV(_filename, _headers, csvFormat); while (csv.Next()) { for (int i = 0; i < csv.ColumnCount; i++) { if (_fields != null) { _fields[i].Analyze2(csv.Get(i)); } } } if (_fields != null) { foreach (AnalyzedField field in _fields) { field.CompletePass2(); } } csv.Close(); String str = _script.Properties.GetPropertyString( ScriptProperties.SetupConfigAllowedClasses) ?? ""; bool allowInt = str.Contains("int"); bool allowReal = str.Contains("real") || str.Contains("double"); bool allowString = str.Contains("string"); // remove any classes that did not qualify foreach (AnalyzedField field in _fields) { if (field.Class) { if (!allowInt && field.Integer) { field.Class = false; } if (!allowString && (!field.Integer && !field.Real)) { field.Class = false; } if (!allowReal && field.Real && !field.Integer) { field.Class = false; } } } // merge with existing if ((target.Script.Fields != null) && (_fields.Length == target.Script.Fields.Length)) { for (int i = 0; i < _fields.Length; i++) { // copy the old field name _fields[i].Name = target.Script.Fields[i].Name; if (_fields[i].Class) { IList <AnalystClassItem> t = _fields[i].AnalyzedClassMembers; IList <AnalystClassItem> s = target.Script.Fields[i].ClassMembers; if (s.Count == t.Count) { for (int j = 0; j < s.Count; j++) { if (t[j].Code.Equals(s[j].Code)) { t[j].Name = s[j].Name; } } } } } } // now copy the fields var df = new DataField[_fields.Length]; for (int i_4 = 0; i_4 < df.Length; i_4++) { df[i_4] = _fields[i_4].FinalizeField(); } target.Script.Fields = df; }
private void ChangeFields() { DataField Temp = new DataField(); Color cTemp = new Color(); if (DRAG[0].Teacher == DROP[1].Teacher && DRAG[1].Teacher == DROP[0].Teacher && DRAG[1].Group == DROP[1].Group) { int Key0 = DRAG[0].Key, Key1 = DROP[0].Key, Key2 = DRAG[1].Key, Key3 = DROP[1].Key; Temp = DRAG[0]; cTemp = VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor; VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor = VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor; DRAG[0] = DROP[0]; VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor = cTemp; DROP[0] = Temp; SqlString = "UPDATE HorarioMaterias SET Hora='" + DRAG[0].Hour + "',Dia='" + DRAG[0].Day + "',PosicionFila=" + DRAG[0].Row + ",PosicionColumna=" + DRAG[0].Column + " Where ClaveHM=" + Key0 + ""; DataBaseUtilities.OpenConnection(PathDataBase); DataBaseUtilities.ExecuteNonSql(SqlString); SqlString = "UPDATE HorarioMaterias SET Hora='" + DROP[0].Hour + "',Dia='" + DROP[0].Day + "',PosicionFila=" + DROP[0].Row + ",PosicionColumna=" + DROP[0].Column + " Where ClaveHM=" + Key1 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); DataBaseUtilities.OpenConnection(PathDataBase); SqlString = "UPDATE HorarioMaterias SET Hora='" + DROP[1].Hour + "',Dia='" + DROP[1].Day + "',PosicionFila=" + DROP[1].Row + ",PosicionColumna=" + DROP[1].Column + " Where ClaveHM=" + Key2 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); DataBaseUtilities.OpenConnection(PathDataBase); SqlString = "UPDATE HorarioMaterias SET Hora='" + DRAG[1].Hour + "',Dia='" + DRAG[1].Day + "',PosicionFila=" + DRAG[1].Row + ",PosicionColumna=" + DRAG[1].Column + " Where ClaveHM=" + Key3 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); } //Si DRAG[1] y DROP[1] no son iguales a los maestro que vas a mover //En duda else if (DRAG[1].Teacher != null && DROP[1].Teacher != null) { int Key0 = DRAG[0].Key, Key1 = DROP[0].Key, Key2 = DRAG[1].Key, Key3 = DROP[1].Key; Temp = DRAG[0]; cTemp = VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor; VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor = VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor; DRAG[0] = DROP[0]; VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor = cTemp; DROP[0] = Temp; SqlString = "UPDATE HorarioMaterias SET Hora='" + DRAG[0].Hour + "',Dia='" + DRAG[0].Day + "',PosicionFila=" + DRAG[0].Row + ",PosicionColumna=" + DRAG[0].Column + " Where ClaveHM=" + Key0 + ""; DataBaseUtilities.OpenConnection(PathDataBase); DataBaseUtilities.ExecuteNonSql(SqlString); SqlString = "UPDATE HorarioMaterias SET Hora='" + DROP[0].Hour + "',Dia='" + DROP[0].Day + "',PosicionFila=" + DROP[0].Row + ",PosicionColumna=" + DROP[0].Column + " Where ClaveHM=" + Key1 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); DataBaseUtilities.OpenConnection(PathDataBase); DROP[1] = FindBlankSpace(DROP[1]); SqlString = "UPDATE HorarioMaterias SET Hora='" + DataSchedule[DROP[1].Row][DROP[1].Column].Hour + "',Dia='" + DataSchedule[DROP[1].Row][DROP[1].Column].Day + "',PosicionFila=" + DROP[1].Row + ",PosicionColumna=" + DROP[1].Column + " Where ClaveHM=" + Key2 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); DataBaseUtilities.OpenConnection(PathDataBase); DRAG[1] = FindBlankSpace(DRAG[1]); SqlString = "UPDATE HorarioMaterias SET Hora='" + DataSchedule[DRAG[1].Row][DRAG[1].Column].Hour + "',Dia='" + DataSchedule[DRAG[1].Row][DRAG[1].Column].Day + "',PosicionFila=" + DRAG[1].Row + ",PosicionColumna=" + DRAG[1].Column + " Where ClaveHM=" + Key3 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); } //Si no hay maestros en otros horarios en los campos que se van a cambiar else if (DRAG[1].Teacher == null && DROP[1].Teacher == null) { int Key0 = DRAG[0].Key, Key1 = DROP[0].Key; Temp = DRAG[0]; cTemp = VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor; VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor = VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor; DRAG[0] = DROP[0]; VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor = cTemp; DROP[0] = Temp; SqlString = "UPDATE HorarioMaterias SET Hora='" + DRAG[0].Hour + "',Dia='" + DRAG[0].Day + "',PosicionFila=" + DRAG[0].Row + ",PosicionColumna=" + DRAG[0].Column + " Where ClaveHM=" + Key0 + ""; DataBaseUtilities.OpenConnection(PathDataBase); DataBaseUtilities.ExecuteNonSql(SqlString); SqlString = "UPDATE HorarioMaterias SET Hora='" + DROP[0].Hour + "',Dia='" + DROP[0].Day + "',PosicionFila=" + DROP[0].Row + ",PosicionColumna=" + DROP[0].Column + " Where ClaveHM=" + Key1 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); } //Si solo el DRAG[1] no tiene maestro = en otro lado else if (DRAG[1].Teacher == null) { int Key0 = DRAG[0].Key, Key1 = DROP[0].Key, Key2 = DROP[1].Key; Temp = DRAG[0]; cTemp = VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor; VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor = VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor; DRAG[0] = DROP[0]; VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor = cTemp; DROP[0] = Temp; SqlString = "UPDATE HorarioMaterias SET Hora='" + DRAG[0].Hour + "',Dia='" + DRAG[0].Day + "',PosicionFila=" + DRAG[0].Row + ",PosicionColumna=" + DRAG[0].Column + " Where ClaveHM=" + Key0 + ""; DataBaseUtilities.OpenConnection(PathDataBase); DataBaseUtilities.ExecuteNonSql(SqlString); SqlString = "UPDATE HorarioMaterias SET Hora='" + DROP[0].Hour + "',Dia='" + DROP[0].Day + "',PosicionFila=" + DROP[0].Row + ",PosicionColumna=" + DROP[0].Column + " Where ClaveHM=" + Key1 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); DROP[1] = FindBlankSpace(DROP[1]); DataBaseUtilities.OpenConnection(PathDataBase); SqlString = "UPDATE HorarioMaterias SET Hora='" + DataSchedule[DROP[1].Row][DROP[1].Column].Hour + "',Dia='" + DataSchedule[DROP[1].Row][DROP[1].Column].Day + "',PosicionFila=" + DROP[1].Row + ",PosicionColumna=" + DROP[1].Column + " Where ClaveHM=" + Key2 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); } //Si solo el DROP[1] no tiene maestro = en otro lado else if (DROP[1].Teacher == null) { int Key0 = DRAG[0].Key, Key1 = DROP[0].Key, Key2 = DRAG[1].Key; Temp = DRAG[0]; cTemp = VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor; VisualSchedule[DRAG[0].Row][DRAG[0].Column].BackColor = VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor; DRAG[0] = DROP[0]; VisualSchedule[DROP[0].Row][DROP[0].Column].BackColor = cTemp; DROP[0] = Temp; SqlString = "UPDATE HorarioMaterias SET Hora='" + DRAG[0].Hour + "',Dia='" + DRAG[0].Day + "',PosicionFila=" + DRAG[0].Row + ",PosicionColumna=" + DRAG[0].Column + " Where ClaveHM=" + Key0 + ""; DataBaseUtilities.OpenConnection(PathDataBase); DataBaseUtilities.ExecuteNonSql(SqlString); SqlString = "UPDATE HorarioMaterias SET Hora='" + DROP[0].Hour + "',Dia='" + DROP[0].Day + "',PosicionFila=" + DROP[0].Row + ",PosicionColumna=" + DROP[0].Column + " Where ClaveHM=" + Key1 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); DRAG[1] = FindBlankSpace(DRAG[1]); DataBaseUtilities.OpenConnection(PathDataBase); SqlString = "UPDATE HorarioMaterias SET Hora='" + DataSchedule[DRAG[1].Row][DRAG[1].Column].Hour + "',Dia='" + DataSchedule[DRAG[1].Row][DRAG[1].Column].Day + "',PosicionFila=" + DRAG[1].Row + ",PosicionColumna=" + DRAG[1].Column + " Where ClaveHM=" + Key2 + ""; DataBaseUtilities.ExecuteNonSql(SqlString); DataBaseUtilities.CloseConnection(); } }
public async Task <IActionResult> UpsertDataField(DataField field) { return(await ExecuteRepositoryAction(() => _datasetRepository.UpsertDataField(field), $"Unable to create data field {field.AsJson()}")); }
/// <summary> /// Ensures that a persistent field has been associated with a spatial feature. /// </summary> /// <param name="field">A tag associated with the item</param> /// <param name="feature">The feature to assign to the field (not null).</param> /// <returns> /// True if a matching field was processed. False if the field is not known to this /// class (may be known to another class in the type hierarchy). /// </returns> public bool ApplyFeatureRef(DataField field, Feature feature) { if (field == DataField.From) { m_From = (PointFeature)feature; return true; } return false; }
/// <summary>创建一个新的流程实例 (create a new process instance )</summary> /// <param name="workflowProcessId">流程定义ID</param> /// <param name="creatorId">创建人ID</param> /// <param name="parentProcessInstanceId">父流程实例ID</param> /// <param name="parentTaskInstanceId">父任务实例ID</param> protected IProcessInstance _createProcessInstance(String workflowProcessId, String creatorId, String parentProcessInstanceId, String parentTaskInstanceId) { String wfprocessId = workflowProcessId; WorkflowDefinition workflowDef = RuntimeContext.DefinitionService.GetTheLatestVersionOfWorkflowDefinition(wfprocessId); WorkflowProcess wfProcess = workflowDef.getWorkflowProcess(); if (wfProcess == null) { throw new Exception("Workflow process NOT found,id=[" + wfprocessId + "]"); } IProcessInstance processInstance = (IProcessInstance)this.execute( new WorkflowSessionIProcessInstanceCreateProcessInstance(creatorId, wfProcess, workflowDef, parentProcessInstanceId, parentTaskInstanceId)); // 初始化流程变量 processInstance.ProcessInstanceVariables = new Dictionary <String, Object>(); List <DataField> datafields = wfProcess.DataFields; for (int i = 0; datafields != null && i < datafields.Count; i++) { DataField df = datafields[i]; if (df.DataType == DataTypeEnum.STRING) { if (df.InitialValue != null) { processInstance.setProcessInstanceVariable(df.Name, df.InitialValue); } else { processInstance.setProcessInstanceVariable(df.Name, ""); } } else if (df.DataType == DataTypeEnum.INTEGER) { if (df.InitialValue != null) { try { int intValue = int.Parse(df.InitialValue); processInstance.setProcessInstanceVariable(df.Name, intValue); } catch { } } else { processInstance.setProcessInstanceVariable(df.Name, 0); } } else if (df.DataType == DataTypeEnum.LONG) { if (df.InitialValue != null) { try { long longValue = long.Parse(df.InitialValue); processInstance.setProcessInstanceVariable(df.Name, longValue); } catch { } } else { processInstance.setProcessInstanceVariable(df.Name, (long)0); } } else if (df.DataType == DataTypeEnum.FLOAT) { if (df.InitialValue != null) { float floatValue = float.Parse(df.InitialValue); processInstance.setProcessInstanceVariable(df.Name, floatValue); } else { processInstance.setProcessInstanceVariable(df.Name, (float)0); } } else if (df.DataType == DataTypeEnum.DOUBLE) { if (df.InitialValue != null) { Double doubleValue = Double.Parse(df.InitialValue); processInstance.setProcessInstanceVariable(df.Name, doubleValue); } else { processInstance.setProcessInstanceVariable(df.Name, (Double)0); } } else if (df.DataType == DataTypeEnum.BOOLEAN) { if (df.InitialValue != null) { Boolean booleanValue = Boolean.Parse(df.InitialValue); processInstance.setProcessInstanceVariable(df.Name, booleanValue); } else { processInstance.setProcessInstanceVariable(df.Name, false); } } else if (df.DataType == DataTypeEnum.DATETIME) { // TODO 需要完善一下 if (df.InitialValue != null && df.DataPattern != null) { try { DateTime dateTmp = DateTime.Parse(df.InitialValue); processInstance.setProcessInstanceVariable(df.Name, dateTmp); } catch { processInstance.setProcessInstanceVariable(df.Name, null); } } else { processInstance.setProcessInstanceVariable(df.Name, null); } } } return(processInstance); }
// Generates content of pivotTablePart1. private void GeneratePivotTablePart1Content(PivotTablePart pivotTablePart1) { PivotTableDefinition pivotTableDefinition1 = new PivotTableDefinition() { Name = "PivotTable1", CacheId = (UInt32Value)2U, ApplyNumberFormats = false, ApplyBorderFormats = false, ApplyFontFormats = false, ApplyPatternFormats = false, ApplyAlignmentFormats = false, ApplyWidthHeightFormats = true, DataCaption = "Values", UpdatedVersion = 4, MinRefreshableVersion = 3, UseAutoFormatting = true, ItemPrintTitles = true, CreatedVersion = 4, Indent = (UInt32Value)0U, Outline = true, OutlineData = true, MultipleFieldFilters = false }; Location location1 = new Location() { Reference = "A1:B5", FirstHeaderRow = (UInt32Value)1U, FirstDataRow = (UInt32Value)1U, FirstDataColumn = (UInt32Value)1U }; PivotFields pivotFields1 = new PivotFields() { Count = (UInt32Value)2U }; PivotField pivotField1 = new PivotField() { Axis = PivotTableAxisValues.AxisRow, ShowAll = false }; Items items1 = new Items() { Count = (UInt32Value)4U }; Item item1 = new Item() { Index = (UInt32Value)0U }; Item item2 = new Item() { Index = (UInt32Value)1U }; Item item3 = new Item() { Index = (UInt32Value)2U }; Item item4 = new Item() { ItemType = ItemValues.Default }; items1.Append(item1); items1.Append(item2); items1.Append(item3); items1.Append(item4); pivotField1.Append(items1); PivotField pivotField2 = new PivotField() { DataField = true, ShowAll = false }; pivotFields1.Append(pivotField1); pivotFields1.Append(pivotField2); RowFields rowFields1 = new RowFields() { Count = (UInt32Value)1U }; Field field1 = new Field() { Index = 0 }; rowFields1.Append(field1); RowItems rowItems1 = new RowItems() { Count = (UInt32Value)4U }; RowItem rowItem1 = new RowItem(); MemberPropertyIndex memberPropertyIndex1 = new MemberPropertyIndex(); rowItem1.Append(memberPropertyIndex1); RowItem rowItem2 = new RowItem(); MemberPropertyIndex memberPropertyIndex2 = new MemberPropertyIndex() { Val = 1 }; rowItem2.Append(memberPropertyIndex2); RowItem rowItem3 = new RowItem(); MemberPropertyIndex memberPropertyIndex3 = new MemberPropertyIndex() { Val = 2 }; rowItem3.Append(memberPropertyIndex3); RowItem rowItem4 = new RowItem() { ItemType = ItemValues.Grand }; MemberPropertyIndex memberPropertyIndex4 = new MemberPropertyIndex(); rowItem4.Append(memberPropertyIndex4); rowItems1.Append(rowItem1); rowItems1.Append(rowItem2); rowItems1.Append(rowItem3); rowItems1.Append(rowItem4); ColumnItems columnItems1 = new ColumnItems() { Count = (UInt32Value)1U }; RowItem rowItem5 = new RowItem(); columnItems1.Append(rowItem5); DataFields dataFields1 = new DataFields() { Count = (UInt32Value)1U }; DataField dataField1 = new DataField() { Name = "Sum of score", Field = (UInt32Value)1U, BaseField = 0, BaseItem = (UInt32Value)0U }; dataFields1.Append(dataField1); PivotTableStyle pivotTableStyle1 = new PivotTableStyle() { Name = "PivotStyleMedium9", ShowRowHeaders = true, ShowColumnHeaders = true, ShowRowStripes = false, ShowColumnStripes = false, ShowLastColumn = true }; PivotTableDefinitionExtensionList pivotTableDefinitionExtensionList1 = new PivotTableDefinitionExtensionList(); pivotTableDefinition1.Append(location1); pivotTableDefinition1.Append(pivotFields1); pivotTableDefinition1.Append(rowFields1); pivotTableDefinition1.Append(rowItems1); pivotTableDefinition1.Append(columnItems1); pivotTableDefinition1.Append(dataFields1); pivotTableDefinition1.Append(pivotTableStyle1); pivotTableDefinition1.Append(pivotTableDefinitionExtensionList1); pivotTablePart1.PivotTableDefinition = pivotTableDefinition1; }
void linkField_DataBinding(object sender, EventArgs e) { var linkField = (HyperLink)sender; var context = DataBinder.GetDataItem(linkField.NamingContainer); var boundFieldValue = (DataBinder.Eval(context, DataField) == null)?"":(DataBinder.Eval(context, DataField)).ToString(); if (DisplayField == null) { linkField.Text = ""; } else { linkField.Text = CffGenGridViewCommon.FormatDataColumn(this._columnType, (DataBinder.Eval(context, DisplayField) == null) ? "" : (DataBinder.Eval(context, DisplayField)).ToString()); } string strRowIndex = ((System.Web.UI.WebControls.GridViewRow)(((System.Web.UI.Control)(linkField)).DataItemContainer)).RowIndex.ToString(); Cff.SaferTrader.Core.LinkHelper.SetRowIndex(strRowIndex); linkField.CssClass = this._cssStyle; //link helpers - careful when modifying as this needs to coincide with production version (ref: mariper) if (DataField.ToUpper().IndexOf("CUSTOMER") >= 0 || DataField.ToUpper().IndexOf("CUSTID") >= 0 || DataField.ToUpper().IndexOf("CUSTOMERID") >= 0) { if (string.IsNullOrEmpty(boundFieldValue)) { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToDashboardForCustomer; } else { if (SessionWrapper.Instance.Get != null) { if (SessionWrapper.Instance.Get.Scope == Scope.AllClientsScope) { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToDashboardForGivenCustomerId(boundFieldValue, (int?)DataBinder.Eval(context, "ClientId")); } else { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToDashboardForGivenCustomerId(boundFieldValue); } } } } else if (DataField.ToUpper().IndexOf("CLIENT") >= 0) { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToDashboardForAGivenClientId(boundFieldValue); } else if (DataField.ToUpper().IndexOf("CLIENTID") >= 0) { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToDashboardForAGivenClientId(boundFieldValue); } else if ((DataField.ToUpper().IndexOf("BATCH") >= 0) || (DataField.ToUpper().IndexOf("BATCHNUMBER") >= 0)) { string strCustID = ""; string strClientID = ""; try { strClientID = (DataBinder.Eval(context, "ClientId") == null) ? "" : DataBinder.Eval(context, "ClientId").ToString(); } catch (Exception) { } try { strCustID = (DataBinder.Eval(context, "CustomerId") == null) ? "" : DataBinder.Eval(context, "CustomerId").ToString(); } catch (Exception) { } bool doHyperLink = (_isReversed)?false:true; if (!string.IsNullOrEmpty(_boundFilterField)) { if (_boundFilterFieldValue == ((DataBinder.Eval(context, _boundFilterField) == null) ? "" : (DataBinder.Eval(context, _boundFilterField)).ToString())) { doHyperLink = _onOff; } //todo:: assign necessary filtering if arrayed filter fields } if (doHyperLink) { if (string.IsNullOrEmpty(boundFieldValue)) { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToInvoiceBatchesForClient; } else { linkField.NavigateUrl = Cff.SaferTrader.Core.LinkHelper.NavigateUrlFormatToInvoiceBatchesForClientWBatchID(boundFieldValue, strCustID, strClientID); } linkField.Style.Add(HtmlTextWriterStyle.TextDecoration, "underline"); linkField.ToolTip = "Click to View Batch"; linkField.Attributes.Add("title", "Click to View Batch"); this._navigateUrl = linkField.NavigateUrl; } else { //disable hyperlink linkField.Style.Add(HtmlTextWriterStyle.TextDecoration, "none"); linkField.Style.Add(HtmlTextWriterStyle.Color, "black"); } } }
private void FillDragDrop() { SqlString = @"Select ClaveHM,Materia,Grupo From HorarioMaterias Where Dia='" + DROP[0].Day + "' AND Hora='" + DROP[0].Hour + "' AND Maestro='" + DRAG[0].Teacher + "' AND Grupo<>'" + DRAG[0].Group + "'"; DataBaseUtilities.OpenConnection(PathDataBase); OleDbDataReader dr = DataBaseUtilities.ExecuteSql(SqlString); if (dr.Read()) { DROP[1].Key = Convert.ToInt32(dr["ClaveHM"]); DROP[1].Subject = dr["Materia"].ToString(); DROP[1].Group = dr["Grupo"].ToString(); DROP[1].Teacher = DRAG[0].Teacher; } else { DROP[1] = new DataField(null, null, null, null, -1, -1, -1, null, null); } DataBaseUtilities.CloseConnection(); SqlString = @"Select ClaveHM,Materia,Grupo From HorarioMaterias Where Dia='" + DRAG[0].Day + "' AND Hora='" + DRAG[0].Hour + "' AND Maestro='" + DROP[0].Teacher + "' AND Grupo<>'" + DROP[0].Group + "'"; DataBaseUtilities.OpenConnection(PathDataBase); dr = DataBaseUtilities.ExecuteSql(SqlString); if (dr.Read()) { DRAG[1].Key = Convert.ToInt32(dr["ClaveHM"]); DRAG[1].Subject = dr["Materia"].ToString(); DRAG[1].Group = dr["Grupo"].ToString(); DRAG[1].Teacher = DROP[0].Teacher; } else { DRAG[1] = new DataField(null, null, null, null, -1, -1, -1, null, null); } DataBaseUtilities.CloseConnection(); }
public void TestPropertyLevelValidation() { DataField textField = null; ValidationSummary validationSummary = null; this.AddToPanelAndWaitForLoad(); this.EnqueueCallback(() => { textField = this.DataForm.Fields[2]; validationSummary = this.GetTemplatePart <ValidationSummary>("ValidationSummary"); Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); this.ExpectContentLoaded(); this.DataForm.BeginEdit(); }); this.WaitForContentLoaded(); this.EnqueueCallback(() => { textField = this.DataForm.Fields[2]; this.GetInputControls(); SetValue(this.textBox, string.Empty); this.CommitAllFields(); Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsFalse(textField.IsValid); Assert.AreEqual(1, validationSummary.Errors.Count); Assert.AreEqual(this.textBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("StringProperty is required.", validationSummary.Errors[0].Message); SetValue(this.textBox, "test string 1"); this.CommitAllFields(); Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.AreEqual(0, validationSummary.Errors.Count); SetValue(this.textBox, "abcdefghijklmnopqrstuvwxyz"); this.CommitAllFields(); Assert.IsFalse(this.DataForm.IsItemValid); Assert.IsFalse(textField.IsValid); Assert.AreEqual(1, validationSummary.Errors.Count); Assert.AreEqual(this.textBox, validationSummary.Errors[0].Sources[0].Control); Assert.AreEqual("StringProperty must be at most 20 characters.", validationSummary.Errors[0].Message); SetValue(this.textBox, "test string 1"); this.CommitAllFields(); Assert.IsTrue(this.DataForm.IsItemValid); Assert.IsTrue(textField.IsValid); Assert.AreEqual(0, validationSummary.Errors.Count); this.ExpectEditEnded(); this.DataForm.CommitEdit(true /* exitEditingMode */); }); this.WaitForEditEnded(); this.EnqueueCallback(() => { Assert.IsFalse(this.DataForm.IsEditing); }); this.EnqueueTestComplete(); }
// <Summary> // This method is used to export a DataField object to xml. // </Summary> public string ExportDataField(DataField dataField, int indent = 0) { // initial value string dataFieldXml = ""; // locals string indentString = TextHelper.Indent(indent); string indentString2 = TextHelper.Indent(indent + 2); // If the dataField object exists if (NullHelper.Exists(dataField)) { // Create a StringBuilder StringBuilder sb = new StringBuilder(); // if the FieldName contains the word error if (dataField.FieldName.Contains("Error")) { // Write out only the error only sb.Append(indentString); sb.Append("<Error>" + dataField.FieldName + "</Error>" + Environment.NewLine); } else { // Write out each property // Append the indentString sb.Append(indentString); // Write the open dataField node sb.Append("<DataField>" + Environment.NewLine); // Write out the value for DataType sb.Append(indentString2); sb.Append("<DataType>" + dataField.DataType + "</DataType>" + Environment.NewLine); // Write out the value for DBDataType sb.Append(indentString2); sb.Append("<DBDataType>" + dataField.DBDataType + "</DBDataType>" + Environment.NewLine); // Write out the value for DBFieldName sb.Append(indentString2); sb.Append("<DBFieldName>" + dataField.DBFieldName + "</DBFieldName>" + Environment.NewLine); // Write out the value for DecimalPlaces sb.Append(indentString2); sb.Append("<DecimalPlaces>" + dataField.DecimalPlaces + "</DecimalPlaces>" + Environment.NewLine); // Write out the value for DefaultValue sb.Append(indentString2); sb.Append("<DefaultValue>" + dataField.DefaultValue + "</DefaultValue>" + Environment.NewLine); // Write out the value for EnumDataTypeName sb.Append(indentString2); sb.Append("<EnumDataTypeName>" + dataField.EnumDataTypeName + "</EnumDataTypeName>" + Environment.NewLine); // Write out the value for FieldName sb.Append(indentString2); sb.Append("<FieldName>" + dataField.FieldName + "</FieldName>" + Environment.NewLine); // Write out the value for FieldOrdinal sb.Append(indentString2); sb.Append("<FieldOrdinal>" + dataField.FieldOrdinal + "</FieldOrdinal>" + Environment.NewLine); // Write out the value for HasDefault sb.Append(indentString2); sb.Append("<HasDefault>" + dataField.HasDefault + "</HasDefault>" + Environment.NewLine); // Write out the value for Index sb.Append(indentString2); sb.Append("<Index>" + dataField.Index + "</Index>" + Environment.NewLine); // Write out the value for IsAutoIncrement sb.Append(indentString2); sb.Append("<IsAutoIncrement>" + dataField.IsAutoIncrement + "</IsAutoIncrement>" + Environment.NewLine); // Write out the value for IsEnumeration sb.Append(indentString2); sb.Append("<IsEnumeration>" + dataField.IsEnumeration + "</IsEnumeration>" + Environment.NewLine); // Write out the value for IsNullable sb.Append(indentString2); sb.Append("<IsNullable>" + dataField.IsNullable + "</IsNullable>" + Environment.NewLine); // Write out the value for IsReadOnly sb.Append(indentString2); sb.Append("<IsReadOnly>" + dataField.IsReadOnly + "</IsReadOnly>" + Environment.NewLine); // Write out the value for Loading sb.Append(indentString2); sb.Append("<Loading>" + dataField.Loading + "</Loading>" + Environment.NewLine); // Write out the value for Precision sb.Append(indentString2); sb.Append("<Precision>" + dataField.Precision + "</Precision>" + Environment.NewLine); // Write out the value for PrimaryKey sb.Append(indentString2); sb.Append("<PrimaryKey>" + dataField.PrimaryKey + "</PrimaryKey>" + Environment.NewLine); // Write out the value for Required sb.Append(indentString2); sb.Append("<Required>" + dataField.Required + "</Required>" + Environment.NewLine); // Write out the value for Scale sb.Append(indentString2); sb.Append("<Scale>" + dataField.Scale + "</Scale>" + Environment.NewLine); // Write out the value for Scope sb.Append(indentString2); sb.Append("<Scope>" + dataField.Scope + "</Scope>" + Environment.NewLine); // Write out the value for Size sb.Append(indentString2); sb.Append("<Size>" + dataField.Size + "</Size>" + Environment.NewLine); // Append the indentString sb.Append(indentString); // Write out the close dataField node sb.Append("</DataField>" + Environment.NewLine); } // set the return value dataFieldXml = sb.ToString(); } // return value return(dataFieldXml); }
// Generates content of pivotTablePart private static void GeneratePivotTablePartContent(PivotTablePart pivotTablePart1, IXLPivotTable pt) { var pivotTableDefinition = new PivotTableDefinition { Name = pt.Name, CacheId = 0U, DataCaption = "Values", MergeItem = GetBooleanValue(pt.MergeAndCenterWithLabels, true), Indent = Convert.ToUInt32(pt.RowLabelIndent), PageOverThenDown = (pt.FilterAreaOrder == XLFilterAreaOrder.OverThenDown), PageWrap = Convert.ToUInt32(pt.FilterFieldsPageWrap), ShowError = String.IsNullOrEmpty(pt.ErrorValueReplacement), UseAutoFormatting = GetBooleanValue(pt.AutofitColumns, true), PreserveFormatting = GetBooleanValue(pt.PreserveCellFormatting, true), RowGrandTotals = GetBooleanValue(pt.ShowGrandTotalsRows, true), ColumnGrandTotals = GetBooleanValue(pt.ShowGrandTotalsColumns, true), SubtotalHiddenItems = GetBooleanValue(pt.FilteredItemsInSubtotals, true), MultipleFieldFilters = GetBooleanValue(pt.AllowMultipleFilters, true), CustomListSort = GetBooleanValue(pt.UseCustomListsForSorting, true), ShowDrill = GetBooleanValue(pt.ShowExpandCollapseButtons, true), ShowDataTips = GetBooleanValue(pt.ShowContextualTooltips, true), ShowMemberPropertyTips = GetBooleanValue(pt.ShowPropertiesInTooltips, true), ShowHeaders = GetBooleanValue(pt.DisplayCaptionsAndDropdowns, true), GridDropZones = GetBooleanValue(pt.ClassicPivotTableLayout, true), ShowEmptyRow = GetBooleanValue(pt.ShowEmptyItemsOnRows, true), ShowEmptyColumn = GetBooleanValue(pt.ShowEmptyItemsOnColumns, true), ShowItems = GetBooleanValue(pt.DisplayItemLabels, true), FieldListSortAscending = GetBooleanValue(pt.SortFieldsAtoZ, true), PrintDrill = GetBooleanValue(pt.PrintExpandCollapsedButtons, true), ItemPrintTitles = GetBooleanValue(pt.RepeatRowLabels, true), FieldPrintTitles = GetBooleanValue(pt.PrintTitles, true), EnableDrill = GetBooleanValue(pt.EnableShowDetails, true) }; if (pt.EmptyCellReplacement != null) { pivotTableDefinition.ShowMissing = true; pivotTableDefinition.MissingCaption = pt.EmptyCellReplacement; } else { pivotTableDefinition.ShowMissing = false; } if (pt.ErrorValueReplacement != null) { pivotTableDefinition.ShowError = true; pivotTableDefinition.ErrorCaption = pt.ErrorValueReplacement; } else { pivotTableDefinition.ShowError = false; } var location = new Location { Reference = pt.TargetCell.Address.ToString(), FirstHeaderRow = 1U, FirstDataRow = 1U, FirstDataColumn = 1U }; var rowFields = new RowFields(); var columnFields = new ColumnFields(); var rowItems = new RowItems(); var columnItems = new ColumnItems(); var pageFields = new PageFields {Count = (uint)pt.ReportFilters.Count()}; var pivotFields = new PivotFields {Count = Convert.ToUInt32(pt.SourceRange.ColumnCount())}; foreach (var xlpf in pt.Fields) { var pf = new PivotField {ShowAll = false, Name = xlpf.CustomName}; if (pt.RowLabels.FirstOrDefault(p => p.SourceName == xlpf.SourceName) != null) { pf.Axis = PivotTableAxisValues.AxisRow; var f = new Field {Index = pt.Fields.IndexOf(xlpf)}; rowFields.AppendChild(f); for (var i = 0; i < xlpf.SharedStrings.Count; i++) { var rowItem = new RowItem(); rowItem.AppendChild(new MemberPropertyIndex {Val = i}); rowItems.AppendChild(rowItem); } var rowItemTotal = new RowItem {ItemType = ItemValues.Grand}; rowItemTotal.AppendChild(new MemberPropertyIndex()); rowItems.AppendChild(rowItemTotal); } else if (pt.ColumnLabels.FirstOrDefault(p => p.SourceName == xlpf.SourceName) != null) { pf.Axis = PivotTableAxisValues.AxisColumn; var f = new Field {Index = pt.Fields.IndexOf(xlpf)}; columnFields.AppendChild(f); for (var i = 0; i < xlpf.SharedStrings.Count; i++) { var rowItem = new RowItem(); rowItem.AppendChild(new MemberPropertyIndex {Val = i}); columnItems.AppendChild(rowItem); } var rowItemTotal = new RowItem {ItemType = ItemValues.Grand}; rowItemTotal.AppendChild(new MemberPropertyIndex()); columnItems.AppendChild(rowItemTotal); } else if (pt.ReportFilters.FirstOrDefault(p => p.SourceName == xlpf.SourceName) != null) { location.ColumnsPerPage = 1; location.RowPageCount = 1; pf.Axis = PivotTableAxisValues.AxisPage; pageFields.AppendChild(new PageField {Hierarchy = -1, Field = pt.Fields.IndexOf(xlpf)}); } else if (pt.Values.FirstOrDefault(p => p.CustomName == xlpf.SourceName) != null) { pf.DataField = true; } var fieldItems = new Items(); if (xlpf.SharedStrings.Count > 0) { for (uint i = 0; i < xlpf.SharedStrings.Count; i++) { fieldItems.AppendChild(new Item {Index = i}); } } if (xlpf.Subtotals.Count > 0) { foreach (var subtotal in xlpf.Subtotals) { var itemSubtotal = new Item(); switch (subtotal) { case XLSubtotalFunction.Average: pf.AverageSubTotal = true; itemSubtotal.ItemType = ItemValues.Average; break; case XLSubtotalFunction.Count: pf.CountASubtotal = true; itemSubtotal.ItemType = ItemValues.CountA; break; case XLSubtotalFunction.CountNumbers: pf.CountSubtotal = true; itemSubtotal.ItemType = ItemValues.Count; break; case XLSubtotalFunction.Maximum: pf.MaxSubtotal = true; itemSubtotal.ItemType = ItemValues.Maximum; break; case XLSubtotalFunction.Minimum: pf.MinSubtotal = true; itemSubtotal.ItemType = ItemValues.Minimum; break; case XLSubtotalFunction.PopulationStandardDeviation: pf.ApplyStandardDeviationPInSubtotal = true; itemSubtotal.ItemType = ItemValues.StandardDeviationP; break; case XLSubtotalFunction.PopulationVariance: pf.ApplyVariancePInSubtotal = true; itemSubtotal.ItemType = ItemValues.VarianceP; break; case XLSubtotalFunction.Product: pf.ApplyProductInSubtotal = true; itemSubtotal.ItemType = ItemValues.Product; break; case XLSubtotalFunction.StandardDeviation: pf.ApplyStandardDeviationInSubtotal = true; itemSubtotal.ItemType = ItemValues.StandardDeviation; break; case XLSubtotalFunction.Sum: pf.SumSubtotal = true; itemSubtotal.ItemType = ItemValues.Sum; break; case XLSubtotalFunction.Variance: pf.ApplyVarianceInSubtotal = true; itemSubtotal.ItemType = ItemValues.Variance; break; } fieldItems.AppendChild(itemSubtotal); } } else { fieldItems.AppendChild(new Item {ItemType = ItemValues.Default}); } pf.AppendChild(fieldItems); pivotFields.AppendChild(pf); } pivotTableDefinition.AppendChild(location); pivotTableDefinition.AppendChild(pivotFields); if (pt.RowLabels.Any()) { pivotTableDefinition.AppendChild(rowFields); } else { rowItems.AppendChild(new RowItem()); } pivotTableDefinition.AppendChild(rowItems); if (!pt.ColumnLabels.Any()) { columnItems.AppendChild(new RowItem()); pivotTableDefinition.AppendChild(columnItems); } else { pivotTableDefinition.AppendChild(columnFields); pivotTableDefinition.AppendChild(columnItems); } if (pt.ReportFilters.Any()) { pivotTableDefinition.AppendChild(pageFields); } var dataFields = new DataFields(); foreach (var value in pt.Values) { var sourceColumn = pt.SourceRange.Columns().FirstOrDefault(c => c.Cell(1).Value.ToString() == value.SourceName); if (sourceColumn == null) continue; var df = new DataField { Name = value.SourceName, Field = (UInt32)sourceColumn.ColumnNumber() - 1, Subtotal = value.SummaryFormula.ToOpenXml(), ShowDataAs = value.Calculation.ToOpenXml(), NumberFormatId = (UInt32)value.NumberFormat.NumberFormatId }; if (!String.IsNullOrEmpty(value.BaseField)) { var baseField = pt.SourceRange.Columns().FirstOrDefault(c => c.Cell(1).Value.ToString() == value.BaseField); if (baseField != null) df.BaseField = baseField.ColumnNumber() - 1; } else { df.BaseField = 0; } if (value.CalculationItem == XLPivotCalculationItem.Previous) df.BaseItem = 1048828U; else if (value.CalculationItem == XLPivotCalculationItem.Next) df.BaseItem = 1048829U; else df.BaseItem = 0U; dataFields.AppendChild(df); } pivotTableDefinition.AppendChild(dataFields); pivotTableDefinition.AppendChild(new PivotTableStyle { Name = Enum.GetName(typeof (XLPivotTableTheme), pt.Theme), ShowRowHeaders = pt.ShowRowHeaders, ShowColumnHeaders = pt.ShowColumnHeaders, ShowRowStripes = pt.ShowRowStripes, ShowColumnStripes = pt.ShowColumnStripes }); #region Excel 2010 Features var pivotTableDefinitionExtensionList = new PivotTableDefinitionExtensionList(); var pivotTableDefinitionExtension = new PivotTableDefinitionExtension {Uri = "{962EF5D1-5CA2-4c93-8EF4-DBF5C05439D2}"}; pivotTableDefinitionExtension.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); var pivotTableDefinition2 = new DocumentFormat.OpenXml.Office2010.Excel.PivotTableDefinition {EnableEdit = pt.EnableCellEditing, HideValuesRow = !pt.ShowValuesRow}; pivotTableDefinition2.AddNamespaceDeclaration("xm", "http://schemas.microsoft.com/office/excel/2006/main"); pivotTableDefinitionExtension.AppendChild(pivotTableDefinition2); pivotTableDefinitionExtensionList.AppendChild(pivotTableDefinitionExtension); pivotTableDefinition.AppendChild(pivotTableDefinitionExtensionList); #endregion pivotTablePart1.PivotTableDefinition = pivotTableDefinition; }
/// <summary> /// This method is used to parse a list of 'DataField' objects. /// </summary> /// <param name="XmlNode">The XmlNode to be parsed.</param> /// <returns>A list of 'DataField' objects.</returns> public List <DataField> ParseDataFields(XmlNode xmlNode, List <DataField> dataFields = null) { // locals DataField dataField = null; bool cancel = false; // if the xmlNode exists if (xmlNode != null) { // get the full name for this node string fullName = xmlNode.GetFullName(); // if this is the new collection line if (fullName == "Database.StoredProcedures.StoredProcedure.ReturnSetSchema") { // Raise event Parsing is starting. cancel = Parsing(xmlNode); // If not cancelled if (!cancel) { // create the return collection dataFields = new List <DataField>(); } } // if this is the new object line and the return collection exists else if ((fullName == "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField") && (dataFields != null)) { // Create a new object dataField = new DataField(); // Perform pre parse operations cancel = Parsing(xmlNode, ref dataField); // If not cancelled if (!cancel) { // parse this object dataField = ParseDataField(ref dataField, xmlNode); } // Perform post parse operations cancel = Parsed(xmlNode, ref dataField); // If not cancelled if (!cancel) { // Add this object to the return value dataFields.Add(dataField); } } // if there are ChildNodes if (xmlNode.HasChildNodes) { // iterate the child nodes foreach (XmlNode childNode in xmlNode.ChildNodes) { // self call this method for each childNode dataFields = ParseDataFields(childNode, dataFields); } } } // return value return(dataFields); }
/// <summary> /// Ensures that a persistent field has been associated with a spatial feature. /// </summary> /// <param name="field">A tag associated with the item</param> /// <param name="feature">The feature to assign to the field (not null).</param> /// <returns> /// True if a matching field was processed. False if the field is not known to this /// class (may be known to another class in the type hierarchy). /// </returns> public bool ApplyFeatureRef(DataField field, Feature feature) { switch (field) { case DataField.Backsight: m_Backsight = (PointFeature)feature; return true; case DataField.From: m_From = (PointFeature)feature; return true; } return false; }
/// <summary> /// This method is used to parse DataField objects. /// </summary> public DataField ParseDataField(ref DataField dataField, XmlNode xmlNode) { // if the dataField object exists and the xmlNode exists if ((dataField != null) && (xmlNode != null)) { // get the full name of this node string fullName = xmlNode.GetFullName(); // Check the name of this node to see if it is mapped to a property switch (fullName) { case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.DataType": // Set the value for dataField.DataType // Select the default value of this enum dataField.DataType = EnumHelper.GetEnumValue<DataJuggler.Net.DataManager+DataTypeEnum>(xmlNode.FormattedNodeValue, DataJuggler.Net.DataManager+DataTypeEnum); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.DBDataType": // Set the value for dataField.DBDataType dataField.DBDataType = xmlNode.FormattedNodeValue; // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.DBFieldName": // Set the value for dataField.DBFieldName dataField.DBFieldName = xmlNode.FormattedNodeValue; // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.DecimalPlaces": // Set the value for dataField.DecimalPlaces dataField.DecimalPlaces = NumericHelper.ParseInteger(xmlNode.FormattedNodeValue, 0, -1); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.DefaultValue": // Set the value for dataField.DefaultValue dataField.DefaultValue = xmlNode.FormattedNodeValue; // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.EnumDataTypeName": // Set the value for dataField.EnumDataTypeName dataField.EnumDataTypeName = xmlNode.FormattedNodeValue; // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.FieldName": // Set the value for dataField.FieldName dataField.FieldName = xmlNode.FormattedNodeValue; // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.FieldOrdinal": // Set the value for dataField.FieldOrdinal dataField.FieldOrdinal = NumericHelper.ParseInteger(xmlNode.FormattedNodeValue, 0, -1); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.HasDefault": // Set the value for dataField.HasDefault dataField.HasDefault = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Index": // Set the value for dataField.Index dataField.Index = NumericHelper.ParseInteger(xmlNode.FormattedNodeValue, 0, -1); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.IsAutoIncrement": // Set the value for dataField.IsAutoIncrement dataField.IsAutoIncrement = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.IsEnumeration": // Set the value for dataField.IsEnumeration dataField.IsEnumeration = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.IsNullable": // Set the value for dataField.IsNullable dataField.IsNullable = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.IsReadOnly": // Set the value for dataField.IsReadOnly dataField.IsReadOnly = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Loading": // Set the value for dataField.Loading dataField.Loading = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Precision": // Set the value for dataField.Precision dataField.Precision = NumericHelper.ParseInteger(xmlNode.FormattedNodeValue, 0, -1); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.PrimaryKey": // Set the value for dataField.PrimaryKey dataField.PrimaryKey = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Required": // Set the value for dataField.Required dataField.Required = BooleanHelper.ParseBoolean(xmlNode.FormattedNodeValue, false, false); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Scale": // Set the value for dataField.Scale dataField.Scale = NumericHelper.ParseInteger(xmlNode.FormattedNodeValue, 0, -1); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Scope": // Set the value for dataField.Scope // Select the default value of this enum dataField.Scope = EnumHelper.GetEnumValue<DataJuggler.Net.DataManager+Scope>(xmlNode.FormattedNodeValue, DataJuggler.Net.DataManager+Scope); // required break; case "Database.StoredProcedures.StoredProcedure.ReturnSetSchema.DataField.Size": // Set the value for dataField.Size dataField.Size = NumericHelper.ParseInteger(xmlNode.FormattedNodeValue, 0, -1); // required break; } // if there are ChildNodes if (xmlNode.HasChildNodes) { // iterate the child nodes foreach (XmlNode childNode in xmlNode.ChildNodes) { // append to this DataField dataField = ParseDataField(ref dataField, childNode); } } } // return value return(dataField); }