Пример #1
0
        public void TestIndexByte()
        {
            using (var validDocsBitmap = new UnmanagedLib.BitVector(Pool))
            {
                validDocsBitmap.EnsureCapacity(1);
                validDocsBitmap.ChangeAll(true);

                using (var data = new ColumnData<byte>(DbType.Byte, Pool))
                {
                    data.EnsureCapacity(4);

                    data.DataArray.GetBlock(0)[0] = 1;
                    data.DataArray.GetBlock(0)[1] = 3;
                    data.DataArray.GetBlock(0)[2] = 0;
                    data.DataArray.GetBlock(0)[3] = 255;

                    data.NotNulls.Set(0);
                    data.NotNulls.Set(1);
                    data.NotNulls.Set(2);
                    data.NotNulls.Clear(3);

                    var index = new SortIndex();
                    index.Update(data, validDocsBitmap, 4);

                    Assert.AreEqual(4, index.OrderData.Length);

                    // expected resulting order: 3, 2, 0, 1
                    // item 3 goes on top because it is marked as NULL
                    Assert.AreEqual(3, index.OrderData[0]);
                    Assert.AreEqual(2, index.OrderData[1]);
                    Assert.AreEqual(0, index.OrderData[2]);
                    Assert.AreEqual(1, index.OrderData[3]);
                }
            }
        }
Пример #2
0
		public ColumnData Parse(Column column)
		{
			var ret = new ColumnData();
			ret.Name = column.Name;
			ret.DatabaseTypeName = column.DataType.ToString();
			ret.IsInPrimaryKey = column.InPrimaryKey;
			return ret;
		}
Пример #3
0
        public ColumnSettings(LiveSplitState state, string columnName, IList<ColumnSettings> columnsList)
        {
            InitializeComponent();

            Data = new ColumnData(columnName, ColumnType.Delta, "Current Comparison", "Current Timing Method");

            CurrentState = state;
            ColumnsList = columnsList; 
        }
Пример #4
0
		private long GetData (ColumnData column, BlobHandle blob, int length, object buffer, int bufferOffset)
		{
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "ManagedCommand.GetData()");

			Future future = new Future (Service.GetData,
				blob.current_page,
				length,
				blob.current_position,
				blob.keyId,
				blob.fragNo,
				blob.dirPage,
				blob.pages,
				blob.tag == BoxTag.DV_BLOB_WIDE_HANDLE ? 1 : 0,
				blob.timeStamp);

			object result = null;
			try
			{
				connection.futures.Add (future);
				future.SendRequest (connection.Session, timeout);
				result = future.GetResult (connection.Session, connection.futures);
			}
			finally
			{
				connection.futures.Remove (future);
			}

			if (!(result is object[]))
				return 0;

			object[] results = (object[]) result;
			if (results[0] is int && (AnswerTag) results[0] == AnswerTag.QA_ERROR)
			{
				errors.AddServerError ((string) results[1], null, (string) results[2]);
				Diagnostics.HandleResult (CLI.ReturnCode.SQL_ERROR, this, connection.OuterConnection);
			}

			int startOffset = column.lobOffset;
			for (int i = 0; i < results.Length; i++)
			{
				if (results[i] is int[])
				{
					int[] array = (int[]) results[i];
					blob.current_page = array[1];
					blob.current_position = array[2];
					continue;
				}
				else if (results[i] is string)
				{
					string s = (string) results[i];
					if (buffer is char[])
					{
						char[] chars = s.ToCharArray ();
						char[] charBuffer = (char[]) buffer;

						Debug.WriteLineIf (Switch.Enabled, "do chars");
						Debug.WriteLineIf (Switch.Enabled, "buffer length: " + 
						    (charBuffer == null ? "no" : charBuffer.Length.ToString ()));
						Debug.WriteLineIf (Switch.Enabled, "buffer offset: " + bufferOffset);
						Debug.WriteLineIf (Switch.Enabled, "data length: " + chars.Length);
						Debug.WriteLineIf (Switch.Enabled, "length: " + length);

						if (charBuffer != null)
						{
							int copyLength = length < chars.Length ? length : chars.Length;
							Array.Copy (chars, 0, charBuffer, bufferOffset, copyLength);
						}
						column.lobOffset += chars.Length;
						bufferOffset += chars.Length;
						length -= chars.Length;
					}
					else
					{
						byte[] bytes = Encoding.GetEncoding ("iso-8859-1").GetBytes (s);
						byte[] byteBuffer = (byte[]) buffer;

						Debug.WriteLineIf (Switch.Enabled, "do bytes");
						Debug.WriteLineIf (Switch.Enabled, "buffer length: " + 
						    (byteBuffer == null ? "no" : byteBuffer.Length.ToString ()));
						Debug.WriteLineIf (Switch.Enabled, "buffer offset: " + bufferOffset);
						Debug.WriteLineIf (Switch.Enabled, "data length: " + bytes.Length);
						Debug.WriteLineIf (Switch.Enabled, "length: " + length);

						if (byteBuffer != null)
						{
							int copyLength = length < bytes.Length ? length : bytes.Length;
							Array.Copy (bytes, 0, byteBuffer, bufferOffset, copyLength);
						}
						column.lobOffset += bytes.Length;
						bufferOffset += bytes.Length;
						length -= bytes.Length;
					}
				}
			}
			return column.lobOffset - startOffset;
		}
Пример #5
0
        public void SetSettings(XmlNode node)
        {
            var     element = (XmlElement)node;
            Version version = SettingsHelper.ParseVersion(element["Version"]);

            CurrentSplitTopColor    = SettingsHelper.ParseColor(element["CurrentSplitTopColor"]);
            CurrentSplitBottomColor = SettingsHelper.ParseColor(element["CurrentSplitBottomColor"]);
            VisualSplitCount        = SettingsHelper.ParseInt(element["VisualSplitCount"]);
            SplitPreviewCount       = SettingsHelper.ParseInt(element["SplitPreviewCount"]);
            DisplayIcons            = SettingsHelper.ParseBool(element["DisplayIcons"]);
            ShowThinSeparators      = SettingsHelper.ParseBool(element["ShowThinSeparators"]);
            AlwaysShowLastSplit     = SettingsHelper.ParseBool(element["AlwaysShowLastSplit"]);
            SplitWidth             = SettingsHelper.ParseFloat(element["SplitWidth"]);
            AutomaticAbbreviations = SettingsHelper.ParseBool(element["AutomaticAbbreviations"], false);
            ShowColumnLabels       = SettingsHelper.ParseBool(element["ShowColumnLabels"], false);
            LabelsColor            = SettingsHelper.ParseColor(element["LabelsColor"], Color.FromArgb(255, 255, 255));
            OverrideTimesColor     = SettingsHelper.ParseBool(element["OverrideTimesColor"], false);
            BeforeTimesColor       = SettingsHelper.ParseColor(element["BeforeTimesColor"], Color.FromArgb(255, 255, 255));
            CurrentTimesColor      = SettingsHelper.ParseColor(element["CurrentTimesColor"], Color.FromArgb(255, 255, 255));
            AfterTimesColor        = SettingsHelper.ParseColor(element["AfterTimesColor"], Color.FromArgb(255, 255, 255));
            SplitHeight            = SettingsHelper.ParseFloat(element["SplitHeight"], 6);
            SplitGradientString    = SettingsHelper.ParseString(element["CurrentSplitGradient"], GradientType.Vertical.ToString());
            BackgroundColor        = SettingsHelper.ParseColor(element["BackgroundColor"], Color.Transparent);
            BackgroundColor2       = SettingsHelper.ParseColor(element["BackgroundColor2"], Color.Transparent);
            GradientString         = SettingsHelper.ParseString(element["BackgroundGradient"], ExtendedGradientType.Plain.ToString());
            SeparatorLastSplit     = SettingsHelper.ParseBool(element["SeparatorLastSplit"], true);
            DropDecimals           = SettingsHelper.ParseBool(element["DropDecimals"], true);
            DeltasAccuracy         = SettingsHelper.ParseEnum(element["DeltasAccuracy"], TimeAccuracy.Tenths);
            OverrideDeltasColor    = SettingsHelper.ParseBool(element["OverrideDeltasColor"], false);
            DeltasColor            = SettingsHelper.ParseColor(element["DeltasColor"], Color.FromArgb(255, 255, 255));
            Display2Rows           = SettingsHelper.ParseBool(element["Display2Rows"], false);
            SplitTimesAccuracy     = SettingsHelper.ParseEnum(element["SplitTimesAccuracy"], TimeAccuracy.Seconds);
            ShowBlankSplits        = SettingsHelper.ParseBool(element["ShowBlankSplits"], true);
            LockLastSplit          = SettingsHelper.ParseBool(element["LockLastSplit"], false);
            IconSize    = SettingsHelper.ParseFloat(element["IconSize"], 24f);
            IconShadows = SettingsHelper.ParseBool(element["IconShadows"], true);

            if (version >= new Version(1, 5))
            {
                var columnsElement = element["Columns"];
                ColumnsList.Clear();
                foreach (var child in columnsElement.ChildNodes)
                {
                    var columnData = ColumnData.FromXml((XmlNode)child);
                    ColumnsList.Add(new ColumnSettings(CurrentState, columnData.Name, ColumnsList)
                    {
                        Data = columnData
                    });
                }
            }
            else
            {
                ColumnsList.Clear();
                var comparison = SettingsHelper.ParseString(element["Comparison"]);
                if (SettingsHelper.ParseBool(element["ShowSplitTimes"]))
                {
                    ColumnsList.Add(new ColumnSettings(CurrentState, "+/-", ColumnsList)
                    {
                        Data = new ColumnData("+/-", ColumnType.Delta, comparison, "Current Timing Method")
                    });
                    ColumnsList.Add(new ColumnSettings(CurrentState, "Time", ColumnsList)
                    {
                        Data = new ColumnData("Time", ColumnType.SplitTime, comparison, "Current Timing Method")
                    });
                }
                else
                {
                    ColumnsList.Add(new ColumnSettings(CurrentState, "+/-", ColumnsList)
                    {
                        Data = new ColumnData("+/-", ColumnType.DeltaorSplitTime, comparison, "Current Timing Method")
                    });
                }
            }
            if (version >= new Version(1, 3))
            {
                BeforeNamesColor  = SettingsHelper.ParseColor(element["BeforeNamesColor"]);
                CurrentNamesColor = SettingsHelper.ParseColor(element["CurrentNamesColor"]);
                AfterNamesColor   = SettingsHelper.ParseColor(element["AfterNamesColor"]);
                OverrideTextColor = SettingsHelper.ParseBool(element["OverrideTextColor"]);
            }
            else
            {
                if (version >= new Version(1, 2))
                {
                    BeforeNamesColor = CurrentNamesColor = AfterNamesColor = SettingsHelper.ParseColor(element["SplitNamesColor"]);
                }
                else
                {
                    BeforeNamesColor  = Color.FromArgb(255, 255, 255);
                    CurrentNamesColor = Color.FromArgb(255, 255, 255);
                    AfterNamesColor   = Color.FromArgb(255, 255, 255);
                }
                OverrideTextColor = !SettingsHelper.ParseBool(element["UseTextColor"], true);
            }
        }
Пример #6
0
		public object GetColumnData (int i, ColumnData[] columns)
		{
		        Debug.WriteLineIf (CLI.FnTrace.Enabled, "ManagedCommand.GetColumnData"); 
			Debug.Assert (currentRow != null);
			ColumnData column = columns[i];
			object data = currentRow[i + 1];
			if (data is BlobHandle)
			{
				BlobHandle blob = (BlobHandle) data;

				column.lobOffset = 0;
				column.lobLength = blob.length;

				if (column.columnType.GetType() == typeof(DataTypeChar) ||
					column.columnType.GetType() == typeof(DataTypeWide))
				{
					char[] chars = new char[blob.length];
					GetData (column, blob, blob.length, chars, 0);
					data = new String (chars);
				}
				else
				{
					byte[] bytes = new byte[blob.length];
					GetData (column, blob, blob.length, bytes, 0);
					data = bytes;
				}
			}
			else
			{
				Debug.Assert (column.bufferType != null);
				if (data is DateTimeMarshaler)
                                  data = ((IConvertData)data).ConvertData(typeof(DateTime));
				else
				data = column.bufferType.ConvertValue (data);
			}
			return data;
		}
Пример #7
0
		public long GetChars (int i, ColumnData[] columns, long fieldOffset,
			char[] buffer, int bufferOffset, int length)
		{
			ColumnData column = columns[i];
			object data = currentRow[i + 1];
			if (data is BlobHandle)
			{
				BlobHandle blob = (BlobHandle) data;
				if (buffer == null)
					return blob.length < fieldOffset ? 0 : blob.length - fieldOffset;
				if (fieldOffset < column.lobOffset)
				{
					blob.Rewind ();
					column.lobOffset = 0;
				}
				if (fieldOffset > column.lobOffset)
				{
					GetData (column, blob, (int) (fieldOffset - column.lobOffset), null, 0);
					if (fieldOffset > column.lobOffset)
						return 0;
				}
				return GetData (column, blob, length, buffer, bufferOffset);
			}
			else
			{
				char[] chars = ((string) data).ToCharArray ();
				if (buffer == null)
					return chars.Length < fieldOffset ? 0 : chars.Length - fieldOffset;
				if (length > (chars.Length - fieldOffset))
					length = (int) (chars.Length - fieldOffset);
				Array.Copy (chars, (int) fieldOffset, buffer, bufferOffset, length);
				return length;
			}
		}
Пример #8
0
 public ColumnDisplayData(ColumnData data, String Caption)
 {
     _data = data;
     _caption = Caption;
 }
Пример #9
0
        private FrameworkElementFactory CreateDefaultElement(ColumnData cd)
        {
            FrameworkElementFactory stackElement = this.CreateStackPanelElement(cd);

            return(stackElement);
        }
Пример #10
0
		public bool IsDBNull (int i, ColumnData[] columns)
		{
			if (dataBuffer == null)
				dataBuffer = new MemoryHandle (2048);

			ColumnData column = columns[i];
			BufferType type = column.bufferType;

			IntPtr length;
			CLI.ReturnCode rc = (CLI.ReturnCode) CLI.SQLGetData (
				hstmt,
				(ushort) (i + 1),
				(short) type.sqlCType,
				dataBuffer.Handle,
				(IntPtr) 0,
				out length);
			if (rc != CLI.ReturnCode.SQL_SUCCESS && rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
				Diagnostics.HandleResult (rc, this, outerCommand.Connection);

			// rewind so that another IsDBNull() won't get SQL_NO_DATA
			RewindData (columns);

			return (length == (IntPtr) (int) CLI.LengthCode.SQL_NULL_DATA);
		}
Пример #11
0
        private void SetColumnMetaData(object compilationColumns, int hiddenColumns)
        {
            Debug.WriteLineIf(CLI.FnTrace.Enabled, "ManagedCommand.SetColumnMetaData");
            object[] descriptions = null;
            if (compilationColumns is object[])
            {
                descriptions = (object[])compilationColumns;
            }

            if (descriptions == null || descriptions.Length == 0)
            {
                columns = null;
                return;
            }

            bool hasKeyColumns = false;

            columns = new ColumnData[descriptions.Length];
            for (int i = 0; i < columns.Length; i++)
            {
                object[] description = (object[])descriptions[i];

                ColumnData column = new ColumnData();
                columns[i] = column;

                ColumnFlags flags = (ColumnFlags)description[11];

                column.columnName = (string)description[0];
                column.columnType = DataTypeInfo.MapDvType((BoxTag)description[1]);
                if (0 != (flags & ColumnFlags.CDF_XMLTYPE))
                {
                    Debug.WriteLineIf(SqlXml.Switch.TraceVerbose,
                                      String.Format("Set XML type for {0}", column.columnName));
                    column.columnType = DataTypeInfo.Xml;
                }
                if (column.columnType == null)
                {
                    throw new SystemException("Unknown data type");
                }
                column.bufferType = column.columnType.bufferType;

                column.columnSize = column.columnType.GetFieldSize((int)description[3]);
                column.precision  = (short)column.columnSize;
                column.scale      = (short)((int)description[2]);
                column.IsLong     = column.columnType.isLong;
                column.IsNullable = (0 != (int)description[4]);

                CLI.Updatable updatable = (CLI.Updatable)(int) description[5];
                column.IsReadOnly = (updatable == CLI.Updatable.SQL_ATTR_READONLY);

                column.IsAutoIncrement = (0 != (flags & ColumnFlags.CDF_AUTOINCREMENT));
                column.IsKey           = (0 != (flags & ColumnFlags.CDF_KEY));
                if (column.IsKey)
                {
                    hasKeyColumns = true;
                }

                column.IsHidden     = (i >= (columns.Length - hiddenColumns));
                column.IsRowVersion = (column.columnType == DataTypeInfo.Timestamp);
                // TODO: check for unique columns as well.
                column.IsUnique = false;

                column.baseCatalogName = (string)Values.NullIfZero(description[7]);
                column.baseColumnName  = (string)Values.NullIfZero(description[8]);
                column.baseSchemaName  = (string)Values.NullIfZero(description[9]);
                column.baseTableName   = (string)Values.NullIfZero(description[10]);

                if (column.baseTableName == null || column.baseTableName == "")
                {
                    column.IsExpression = true;
                }
                else
                {
                    column.IsExpression = false;
                }
            }

            if (uniqueRows && !hasKeyColumns)
            {
                uniqueRows = false;
            }
        }
Пример #12
0
		public ColumnData[] GetColumnMetaData ()
		{
			int columnCount = GetResultColumns ();
			if (columnCount == 0)
				return null;

			ColumnData[] columns = new ColumnData[columnCount];

			MemoryHandle name = new MemoryHandle ((CLI.SQL_MAX_COLUMN_NAME_LEN + 1) * Platform.WideCharSize);
			try 
			{
				for (int i = 0; i < columnCount; i++)
				{
					CLI.ReturnCode rc;
					short length, dataType, decimalDigits, nullable;
					uint columnSize;
					IntPtr iVal;

					ColumnData column = new ColumnData ();
					columns[i] = column;

					rc = (CLI.ReturnCode) CLI.SQLDescribeCol (
						hstmt, (ushort) (i + 1),
						name.Handle, (short) name.Length, out length,
						out dataType, out columnSize, out decimalDigits, out nullable);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					length = (short) (length * Platform.WideCharSize);

					column.columnName = Platform.WideCharsToString (name.Handle, length);
					//System.Console.WriteLine ("name.Length: {0}, length: {1}, columnName: {2}", name.Length, length, column.columnName);
					    Debug.WriteLineIf (SqlXml.Switch.TraceVerbose, 
						String.Format ("SQLColAttribute col={0} data_type={1}", 
						  column.columnName, dataType));
					column.columnType = DataTypeInfo.MapSqlType ((CLI.SqlType) dataType);
					if (((CLI.SqlType)dataType) == CLI.SqlType.SQL_WLONGVARCHAR)
					  {
					    MemoryHandle bcolt = new MemoryHandle (
						(CLI.SQL_MAX_COLUMN_NAME_LEN + 1) * Platform.WideCharSize);
					    short blength;
					    IntPtr biVal;

					    Debug.WriteLineIf (SqlXml.Switch.TraceVerbose, 
						String.Format ("Calling SQLColAttribute for col {0}", 
						  column.columnName));
					    rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.DescriptorField.SQL_DESC_LOCAL_TYPE_NAME,
						bcolt.Handle, (short) bcolt.Length, out blength, out biVal);
					    Debug.WriteLineIf (SqlXml.Switch.TraceInfo, 
						String.Format (
						  "Calling SQLColAttribute for col {0} returned rc={1}", 
						  column.columnName, rc));
					    if (rc == CLI.ReturnCode.SQL_SUCCESS)
					      {
						String baseColumnType = Platform.WideCharsToString (
						    bcolt.Handle, blength);
						Debug.WriteLineIf (SqlXml.Switch.TraceInfo, 
						    String.Format (
						      "Calling SQLColAttribute for col {0} returned type={1}", 
						      column.columnName, baseColumnType));
						if (baseColumnType == "XMLType")
						  column.columnType = DataTypeInfo.Xml;
					      }
					  }
					  
					if (column.columnType == null)
						throw new SystemException ("Unknown data type");
					column.bufferType = column.columnType.bufferType;
					column.columnSize = column.columnType.GetFieldSize ((int) columnSize);
					column.precision = (short) column.columnSize;
					column.scale = decimalDigits;

					column.IsLong = column.columnType.isLong;
					column.IsNullable = nullable == 0 ? false : true;

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.ColumnAttribute.SQL_COLUMN_UPDATABLE,
						IntPtr.Zero, (short) 0, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					CLI.Updatable updatable = (CLI.Updatable) (int) iVal;
					column.IsReadOnly = (updatable == CLI.Updatable.SQL_ATTR_READONLY);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.ColumnAttribute.SQL_COLUMN_KEY,
						IntPtr.Zero, (short) 0, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.IsKey = (((int) iVal) != 0);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.ColumnAttribute.SQL_COLUMN_HIDDEN,
						IntPtr.Zero, (short) 0, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.IsHidden = (((int) iVal) != 0);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.ColumnAttribute.SQL_COLUMN_AUTO_INCREMENT,
						IntPtr.Zero, (short) 0, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.IsAutoIncrement = (((int) iVal) != 0);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.DescriptorField.SQL_DESC_ROWVER,
						IntPtr.Zero, (short) 0, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.IsRowVersion = (((int) iVal) != 0);

					// TODO: check for unique columns as well.
					column.IsUnique = false;

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.DescriptorField.SQL_DESC_BASE_COLUMN_NAME,
						name.Handle, (short) name.Length, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.baseColumnName = Platform.WideCharsToString (name.Handle, length);
					//System.Console.WriteLine ("name.Length: {0}, length: {1}, baseColumnName: {2}", name.Length, length, column.baseColumnName);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.DescriptorField.SQL_DESC_BASE_TABLE_NAME,
						name.Handle, (short) name.Length, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.baseTableName = Platform.WideCharsToString (name.Handle, length);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.DescriptorField.SQL_DESC_SCHEMA_NAME,
						name.Handle, (short) name.Length, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.baseSchemaName = Platform.WideCharsToString (name.Handle, length);

					rc = (CLI.ReturnCode) CLI.SQLColAttribute (
						hstmt, (ushort) (i + 1),
						(ushort) CLI.DescriptorField.SQL_DESC_CATALOG_NAME,
						name.Handle, (short) name.Length, out length, out iVal);
					if (rc != CLI.ReturnCode.SQL_SUCCESS)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);
					column.baseCatalogName = Platform.WideCharsToString (name.Handle, length);

					if (column.baseTableName == null || column.baseTableName == "")
						column.IsExpression = true;
					else
						column.IsExpression = false;
				}

				GC.KeepAlive (this);
			}
			finally
			{
				name.Dispose ();
			}

			return columns;
		}
Пример #13
0
		public object GetColumnData (int i, ColumnData[] columns)
		{
			if (dataBuffer == null)
				dataBuffer = new MemoryHandle (2048);

			ColumnData column = columns[i];
			BufferType type = column.bufferType;
			object columnData;// = column.data;

			IntPtr length;
			CLI.ReturnCode rc = (CLI.ReturnCode) CLI.SQLGetData (
				hstmt,
				(ushort) (i + 1),
				(short) type.sqlCType,
				dataBuffer.Handle,
				(IntPtr) dataBuffer.Length,
				out length);
			if (rc != CLI.ReturnCode.SQL_SUCCESS && rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
				Diagnostics.HandleResult (rc, this, outerCommand.Connection);

			if (length == (IntPtr) (int) CLI.LengthCode.SQL_NULL_DATA)
				columnData = DBNull.Value;
			else if ((int) length <= (dataBuffer.Length - type.NullTermSize) && (int) length >= 0)
				columnData = type.NativeToManaged (dataBuffer.Handle, (int) length);
			else
			{
				column.lobOffset = 0;
				column.lobLength = (int) length;
				columnData = type.NativeSizeToManaged (column.lobLength);
				type.NativePartToManaged (dataBuffer.Handle, dataBuffer.Length - type.NullTermSize, columnData, ref column.lobOffset);
				for (;;)
				{
					rc = (CLI.ReturnCode) CLI.SQLGetData (
						hstmt,
						(ushort) (i + 1),
						(short) column.bufferType.sqlCType,
						dataBuffer.Handle,
						(IntPtr) dataBuffer.Length,
						out length);
					if (rc == CLI.ReturnCode.SQL_NO_DATA)
						break;
					if (rc != CLI.ReturnCode.SQL_SUCCESS && rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
						Diagnostics.HandleResult (rc, this, outerCommand.Connection);

					int copyLength = (int) length;
					if (copyLength > dataBuffer.Length - type.NullTermSize)
						copyLength = dataBuffer.Length - type.NullTermSize;
					type.NativePartToManaged (dataBuffer.Handle, copyLength, columnData, ref column.lobOffset);
				}
				if (column.columnType.GetType() == typeof(DataTypeChar) ||
					column.columnType.GetType() == typeof(DataTypeWide))
					columnData = new String ((char []) columnData);
			}

			GC.KeepAlive (this);
			return columnData;
		}
Пример #14
0
        private string GetTableName(ColumnData[] columns)
        {
            if (columns == null)
            {
                throw new InvalidOperationException("The SelectCommand has not generated a result set.");
            }

            int n = columns.Length;

            if (n < 1)
            {
                throw new InvalidOperationException("The SelectCommand has not generated a result set.");
            }

            string baseCatalogName = null;
            string baseSchemaName  = null;
            string baseTableName   = null;

            bool first = true;

            for (int i = 1; i < n; i++)
            {
                ColumnData c = columns[i];
                if (c.IsExpression)
                {
                    continue;
                }

                if (first)
                {
                    first           = false;
                    baseCatalogName = c.baseCatalogName;
                    baseSchemaName  = c.baseSchemaName;
                    baseTableName   = c.baseTableName;
                }
                else
                {
                    if (baseCatalogName != c.baseCatalogName ||
                        baseSchemaName != c.baseSchemaName ||
                        baseTableName != c.baseTableName)
                    {
                        throw new InvalidOperationException("The SelectCommand generated a result set not suitable for the command builder.");
                    }
                }
            }

            if (baseTableName == null || baseTableName == "")
            {
                throw new InvalidOperationException("The SelectCommand generated a result set not suitable for the command builder.");
            }

            StringBuilder tableName = new StringBuilder();

            if (baseCatalogName != null && baseCatalogName != "")
            {
                tableName.Append(QuotePrefix);
                tableName.Append(baseCatalogName);
                tableName.Append(QuoteSuffix);
                tableName.Append(".");
            }
            if (baseSchemaName != null && baseSchemaName != "")
            {
                tableName.Append(QuotePrefix);
                tableName.Append(baseSchemaName);
                tableName.Append(QuoteSuffix);
                tableName.Append(".");
            }
            tableName.Append(QuotePrefix);
            tableName.Append(baseTableName);
            tableName.Append(QuoteSuffix);
            return(tableName.ToString());
        }
Пример #15
0
        private VirtuosoCommand GetUpdateCommand(DataTableMapping mapping, DataRow row)
        {
            Debug.WriteLineIf(CLI.FnTrace.Enabled, "VirtuosoCommandBuilder.GetUpdateCommand()");
            VirtuosoCommand selectCommand = CollectInfo();
            VirtuosoCommand command       = updateCommand;

            if (command == null)
            {
                command = CreateCommand(selectCommand);
            }
            command.Parameters.Clear();

            StringBuilder text = new StringBuilder("update ");

            text.Append(tableName);
            text.Append(" set ");

            int n = columns.Length;

            for (int i = 0; i < n; i++)
            {
                ColumnData c = columns[i];
                if (c.IsAutoIncrement || c.IsRowVersion || c.IsHidden || c.IsExpression)
                {
                    continue;
                }

                if (i != 0)
                {
                    text.Append(", ");
                }
                text.Append(c.baseColumnName);
                text.Append(" = ?");

                AddParameter(command, c, DataRowVersion.Current, mapping, row);
            }

            text.Append(" where ");

            bool first = true;

            for (int i = 0; i < n; i++)
            {
                ColumnData c = columns[i];
                if (c.IsLong || c.IsHidden || c.IsExpression)
                {
                    continue;
                }

                if (first)
                {
                    first = false;
                }
                else
                {
                    text.Append(" and ");
                }

                text.Append("((? is null and ");
                text.Append(c.baseColumnName);
                text.Append(" is null) or (");
                text.Append(c.baseColumnName);
                text.Append(" = ?))");

                AddParameter(command, c, DataRowVersion.Original, mapping, row);
                AddParameter(command, c, DataRowVersion.Original, mapping, row);
            }

            command.CommandText      = text.ToString();
            command.CommandType      = CommandType.Text;
            command.UpdatedRowSource = UpdateRowSource.None;
            updateCommand            = command;
            return(command);
        }
Пример #16
0
        /// <summary>
        /// ListColumnData() - Retrieve a list of the Column Data
        /// </summary>
        /// <param name="cs">Connection String</param>
        /// <param name="schemaName">Schema Name</param>
        /// <param name="tableName">Table to retrieve info for</param>
        /// <returns>List of ColumnData objects for the requested table.</returns>
        public List <ColumnData> ListColumnData(string cs, string schemaName, string tableName)
        {
            List <ColumnData> colDataList = new List <ColumnData>();
            string            sqlCommand  = "SELECT ";

            sqlCommand += "s.column_id as ColumnId, ";
            sqlCommand += "s.name as ColumnName, ";
            sqlCommand += "sh.name + '.' + o.name as ObjectName, ";
            sqlCommand += "o.type_desc as ObjectType, ";
            sqlCommand += "t.name as DataType, ";
            sqlCommand += "CAST(s.max_length as int) as Length, ";
            sqlCommand += "CASE ";
            sqlCommand += "    WHEN t.name IN('char','varchar') THEN t.name + '(' + CASE WHEN s.max_length < 0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length) END + ')' ";
            sqlCommand += "    WHEN t.name IN('nvarchar','nchar') THEN t.name + '(' + CASE WHEN s.max_length < 0 then 'MAX' ELSE CONVERT(varchar(10),s.max_length / 2) END + ')' ";
            sqlCommand += "    WHEN t.name IN('numeric') THEN t.name + '(' + CONVERT(varchar(10), s.precision) + ',' + CONVERT(varchar(10), s.scale) + ')' ";
            sqlCommand += "    ELSE t.name ";
            sqlCommand += "END as SqlDataType, ";
            sqlCommand += "s.is_nullable IsNullable, ";
            sqlCommand += "( ";
            sqlCommand += "    CASE ";
            sqlCommand += "        WHEN ic.column_id IS NULL THEN '' ";
            sqlCommand += "        ELSE ' identity(' + ISNULL(CONVERT(varchar(10), ic.seed_value), '') + ',' + ISNULL(CONVERT(varchar(10), ic.increment_value), '') + ')=' + ISNULL(CONVERT(varchar(10), ic.last_value), 'null') ";
            sqlCommand += "    END + ";
            sqlCommand += "    CASE ";
            sqlCommand += "        WHEN sc.column_id IS NULL THEN '' ";
            sqlCommand += "        ELSE ' computed(' + ISNULL(sc.definition, '') + ')' ";
            sqlCommand += "    END + ";
            sqlCommand += "    CASE ";
            sqlCommand += "        WHEN cc.object_id IS NULL THEN '' ";
            sqlCommand += "        ELSE ' check(' + ISNULL(cc.definition, '') + ')' ";
            sqlCommand += "    END ";
            sqlCommand += ") as MiscInfo ";
            sqlCommand += "FROM sys.columns s ";
            sqlCommand += "INNER JOIN sys.types t ON s.system_type_id = t.user_type_id and t.is_user_defined = 0 ";
            sqlCommand += "INNER JOIN sys.objects o ON s.object_id = o.object_id ";
            sqlCommand += "INNER JOIN sys.schemas sh on o.schema_id = sh.schema_id ";
            sqlCommand += "LEFT OUTER JOIN sys.identity_columns ic ON s.object_id = ic.object_id AND s.column_id = ic.column_id ";
            sqlCommand += "LEFT OUTER JOIN sys.computed_columns sc ON s.object_id = sc.object_id AND s.column_id = sc.column_id ";
            sqlCommand += "LEFT OUTER JOIN sys.check_constraints cc ON s.object_id = cc.parent_object_id AND s.column_id = cc.parent_column_id ";
            sqlCommand += "WHERE sh.name = @SchemaName ";
            sqlCommand += "AND o.name = @TableName ";
            sqlCommand += "AND o.type_desc = 'USER_TABLE' ";
            sqlCommand += "ORDER BY sh.name + '.' + o.name, s.column_id";

            SqlConnection cn = new SqlConnection(cs);

            using (cn)
            {
                try
                {
                    SqlCommand cmd = new SqlCommand(sqlCommand, cn);
                    cmd.CommandType    = CommandType.Text;
                    cmd.CommandTimeout = 60;
                    cmd.Parameters.Add(new SqlParameter("SchemaName", schemaName));
                    cmd.Parameters.Add(new SqlParameter("TableName", tableName));

                    DataTable table = GetResultSet(cmd);
                    foreach (DataRow dr in table.Rows)
                    {
                        ColumnData colData = new ColumnData();
                        PopulateObject(dr, colData);
                        colDataList.Add(colData);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return(colDataList);
        }
Пример #17
0
        protected void UpdateColumn(LiveSplitState state, SimpleLabel label, ColumnData data)
        {
            var comparison = data.Comparison == "Current Comparison" ? state.CurrentComparison : data.Comparison;

            if (!state.Run.Comparisons.Contains(comparison))
            {
                comparison = state.CurrentComparison;
            }

            var timingMethod = state.CurrentTimingMethod;

            if (data.TimingMethod == "Real Time")
            {
                timingMethod = TimingMethod.RealTime;
            }
            else if (data.TimingMethod == "Game Time")
            {
                timingMethod = TimingMethod.GameTime;
            }

            var type = data.Type;

            var splitIndex = state.Run.IndexOf(Split);

            if (splitIndex < state.CurrentSplitIndex)
            {
                if (type == ColumnType.SplitTime || type == ColumnType.SegmentTime)
                {
                    label.ForeColor = Settings.OverrideTimesColor ? Settings.BeforeTimesColor : state.LayoutSettings.TextColor;

                    if (type == ColumnType.SplitTime)
                    {
                        label.Text = TimeFormatter.Format(Split.SplitTime[timingMethod]);
                    }
                    else //SegmentTime
                    {
                        var segmentTime = LiveSplitStateHelper.GetPreviousSegmentTime(state, splitIndex, timingMethod);
                        label.Text = TimeFormatter.Format(segmentTime);
                    }
                }

                if (type == ColumnType.DeltaorSplitTime || type == ColumnType.Delta)
                {
                    var deltaTime = Split.SplitTime[timingMethod] - Split.Comparisons[comparison][timingMethod];
                    var color     = LiveSplitStateHelper.GetSplitColor(state, deltaTime, splitIndex, true, true, comparison, timingMethod);
                    if (color == null)
                    {
                        color = Settings.OverrideTimesColor ? Settings.BeforeTimesColor : state.LayoutSettings.TextColor;
                    }
                    label.ForeColor = color.Value;

                    if (type == ColumnType.DeltaorSplitTime)
                    {
                        if (deltaTime != null)
                        {
                            label.Text = DeltaTimeFormatter.Format(deltaTime);
                        }
                        else
                        {
                            label.Text = TimeFormatter.Format(Split.SplitTime[timingMethod]);
                        }
                    }
                    else if (type == ColumnType.Delta)
                    {
                        label.Text = DeltaTimeFormatter.Format(deltaTime);
                    }
                }
                else if (type == ColumnType.SegmentDeltaorSegmentTime || type == ColumnType.SegmentDelta)
                {
                    var segmentDelta = LiveSplitStateHelper.GetPreviousSegmentDelta(state, splitIndex, comparison, timingMethod);
                    var color        = LiveSplitStateHelper.GetSplitColor(state, segmentDelta, splitIndex, false, true, comparison, timingMethod);
                    if (color == null)
                    {
                        color = Settings.OverrideTimesColor ? Settings.BeforeTimesColor : state.LayoutSettings.TextColor;
                    }
                    label.ForeColor = color.Value;

                    if (type == ColumnType.SegmentDeltaorSegmentTime)
                    {
                        if (segmentDelta != null)
                        {
                            label.Text = DeltaTimeFormatter.Format(segmentDelta);
                        }
                        else
                        {
                            label.Text = TimeFormatter.Format(LiveSplitStateHelper.GetPreviousSegmentTime(state, splitIndex, timingMethod));
                        }
                    }
                    else if (type == ColumnType.SegmentDelta)
                    {
                        label.Text = DeltaTimeFormatter.Format(segmentDelta);
                    }
                }
            }
            else
            {
                if (type == ColumnType.SplitTime || type == ColumnType.SegmentTime || type == ColumnType.DeltaorSplitTime || type == ColumnType.SegmentDeltaorSegmentTime)
                {
                    if (Split == state.CurrentSplit)
                    {
                        label.ForeColor = Settings.OverrideTimesColor ? Settings.CurrentTimesColor : state.LayoutSettings.TextColor;
                    }
                    else
                    {
                        label.ForeColor = Settings.OverrideTimesColor ? Settings.AfterTimesColor : state.LayoutSettings.TextColor;
                    }

                    if (type == ColumnType.SplitTime || type == ColumnType.DeltaorSplitTime)
                    {
                        label.Text = TimeFormatter.Format(Split.Comparisons[comparison][timingMethod]);
                    }
                    else //SegmentTime or SegmentTimeorSegmentDeltaTime
                    {
                        var previousTime = TimeSpan.Zero;
                        for (var index = splitIndex - 1; index >= 0; index--)
                        {
                            var comparisonTime = state.Run[index].Comparisons[comparison][timingMethod];
                            if (comparisonTime != null)
                            {
                                previousTime = comparisonTime.Value;
                                break;
                            }
                        }
                        label.Text = TimeFormatter.Format(Split.Comparisons[comparison][timingMethod] - previousTime);
                    }
                }

                //Live Delta
                var splitDelta = type == ColumnType.DeltaorSplitTime || type == ColumnType.Delta;
                var bestDelta  = LiveSplitStateHelper.CheckLiveDelta(state, splitDelta, comparison, timingMethod);
                if (bestDelta != null && Split == state.CurrentSplit &&
                    (type == ColumnType.DeltaorSplitTime || type == ColumnType.Delta || type == ColumnType.SegmentDeltaorSegmentTime || type == ColumnType.SegmentDelta))
                {
                    if (splitDelta) //DeltaorSplitTime or Delta
                    {
                        label.Text = DeltaTimeFormatter.Format(bestDelta);
                    }
                    else //SegmentDeltaorSegmentTime or SegmentDelta
                    {
                        label.Text = DeltaTimeFormatter.Format(LiveSplitStateHelper.GetLiveSegmentDelta(state, splitIndex, comparison, timingMethod));
                    }

                    label.ForeColor = Settings.OverrideDeltasColor ? Settings.DeltasColor : state.LayoutSettings.TextColor;
                }
                else if (type == ColumnType.Delta || type == ColumnType.SegmentDelta)
                {
                    label.Text = "";
                }
            }
        }
Пример #18
0
		public long GetChars (int i, ColumnData[] columns, long fieldOffset,
			char[] buffer, int bufferOffset, int length)
		{
			if (dataBuffer == null)
				dataBuffer = new MemoryHandle (2048);

			CLI.ReturnCode rc;
			IntPtr outlen;
			ColumnData column = columns[i];

			if (fieldOffset < column.lobOffset)
				RewindData (columns);

			while (fieldOffset > column.lobOffset)
			{
				int dataLength = (int) (fieldOffset - column.lobOffset) * Platform.WideCharSize + Platform.WideCharSize;
				if (dataLength > dataBuffer.Length)
					dataLength = dataBuffer.Length;

				rc = (CLI.ReturnCode) CLI.SQLGetData (
					hstmt,
					(ushort) (i + 1),
					(short) CLI.SqlCType.SQL_C_WCHAR,
					dataBuffer.Handle,
					(IntPtr) dataLength,
					out outlen);
				if (rc == CLI.ReturnCode.SQL_NO_DATA)
					return 0;
				if (rc != CLI.ReturnCode.SQL_SUCCESS || rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
					Diagnostics.HandleResult (rc, this, outerCommand.Connection);

				if (dataLength > (int) outlen)
					dataLength = (int) outlen;
				else
					dataLength -= Platform.WideCharSize;
				column.lobOffset += dataLength / Platform.WideCharSize;
			}

			if (buffer == null)
			{
				rc = (CLI.ReturnCode) CLI.SQLGetData (
					hstmt,
					(ushort) (i + 1),
					(short) CLI.SqlCType.SQL_C_WCHAR,
					dataBuffer.Handle,
					(IntPtr) 0,
					out outlen);
				if (rc == CLI.ReturnCode.SQL_NO_DATA)
					return 0;
				if (rc != CLI.ReturnCode.SQL_SUCCESS && rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
					Diagnostics.HandleResult (rc, this, outerCommand.Connection);
				return (long) outlen / Platform.WideCharSize;
			}

			int readLength = 0;
			while (length > readLength)
			{
				int dataLength = (length - readLength) * Platform.WideCharSize + Platform.WideCharSize;
				if (dataLength > dataBuffer.Length)
					dataLength = dataBuffer.Length;

				rc = (CLI.ReturnCode) CLI.SQLGetData (
					hstmt,
					(ushort) (i + 1),
					(short) CLI.SqlCType.SQL_C_WCHAR,
					dataBuffer.Handle,
					(IntPtr) dataLength,
					out outlen);
				if (rc == CLI.ReturnCode.SQL_NO_DATA)
					break;
				if (rc != CLI.ReturnCode.SQL_SUCCESS || rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
					Diagnostics.HandleResult (rc, this, outerCommand.Connection);

				if (dataLength > (int) outlen)
					dataLength = (int) outlen;
				else
					dataLength -= Platform.WideCharSize;

				char[] data = Platform.WideCharsToArray (dataBuffer.Handle, dataLength);
				Array.Copy (data, 0, buffer, bufferOffset, data.Length);
				column.lobOffset += data.Length;
				bufferOffset += data.Length;
				readLength += data.Length;
			}

			GC.KeepAlive (this);
			return readLength;
		}
Пример #19
0
        public long GetBytes(int i, ColumnData[] columns, long fieldOffset,
                             byte[] buffer, int bufferOffset, int length)
        {
            ColumnData column = columns[i];
            object     data   = currentRow[i + 1];

            if (data is BlobHandle)
            {
                BlobHandle blob = (BlobHandle)data;
                if (buffer == null)
                {
                    return(blob.length < fieldOffset ? 0 : blob.length - fieldOffset);
                }
                if (fieldOffset < column.lobOffset)
                {
                    blob.Rewind();
                    column.lobOffset = 0;
                }
                if (fieldOffset > column.lobOffset)
                {
                    GetData(column, blob, (int)(fieldOffset - column.lobOffset), null, 0);
                    if (fieldOffset > column.lobOffset)
                    {
                        return(0);
                    }
                }
                return(GetData(column, blob, length, buffer, bufferOffset));
            }
            else if (data is byte[])
            {
                byte[] bytes = (byte[])data;
                if (buffer == null)
                {
                    return(bytes.Length < fieldOffset ? 0 : bytes.Length - fieldOffset);
                }
                if (length > (bytes.Length - fieldOffset))
                {
                    length = (int)(bytes.Length - fieldOffset);
                }
                Array.Copy(bytes, (int)fieldOffset, buffer, bufferOffset, length);
                return(length);
            }
            else if (data is string)
            {
                string str = (string)data;
                if (buffer == null)
                {
                    return(str.Length < fieldOffset ? 0 : str.Length - fieldOffset);
                }
                if (length > (str.Length - fieldOffset))
                {
                    length = (int)(str.Length - fieldOffset);
                }
                BufferTypeBinary.ConvertStringToBytes(str, buffer,
                                                      bufferOffset, length,
                                                      (int)fieldOffset);
                return(length);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Пример #20
0
		public long GetBytes (int i, ColumnData[] columns, long fieldOffset,
			byte[] buffer, int bufferOffset, int length)
		{
			if (dataBuffer == null)
				dataBuffer = new MemoryHandle (2048);

			CLI.ReturnCode rc;
			IntPtr outlen;
			ColumnData column = columns[i];

			if (fieldOffset < column.lobOffset)
				RewindData (columns);

			while (fieldOffset > column.lobOffset)
			{
				int dataLength = (int) fieldOffset - column.lobOffset;
				if (dataLength > dataBuffer.Length)
					dataLength = dataBuffer.Length;

				rc = (CLI.ReturnCode) CLI.SQLGetData (
					hstmt,
					(ushort) (i + 1),
					(short) CLI.SqlCType.SQL_C_BINARY,
					dataBuffer.Handle,
					(IntPtr) dataLength,
					out outlen);
				if (rc == CLI.ReturnCode.SQL_NO_DATA)
					return 0;
				if (rc != CLI.ReturnCode.SQL_SUCCESS)
					Diagnostics.HandleResult (rc, this, outerCommand.Connection);

				if (dataLength > (int) outlen)
					dataLength = (int) outlen;
				column.lobOffset += dataLength;
			}

			if (buffer == null)
			{
				rc = (CLI.ReturnCode) CLI.SQLGetData (
					hstmt,
					(ushort) (i + 1),
					(short) CLI.SqlCType.SQL_C_BINARY,
					dataBuffer.Handle,
					(IntPtr) 0,
					out outlen);
				if (rc == CLI.ReturnCode.SQL_NO_DATA)
					return 0;
				if (rc != CLI.ReturnCode.SQL_SUCCESS && rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
					Diagnostics.HandleResult (rc, this, outerCommand.Connection);
				return (long) outlen;
			}

			int readLength = 0;
			while (length > readLength)
			{
				int dataLength = length - readLength;
				if (dataLength > dataBuffer.Length)
					dataLength = dataBuffer.Length;

				rc = (CLI.ReturnCode) CLI.SQLGetData (
					hstmt,
					(ushort) (i + 1),
					(short) CLI.SqlCType.SQL_C_BINARY,
					dataBuffer.Handle,
					(IntPtr) dataLength,
					out outlen);
				if (rc == CLI.ReturnCode.SQL_NO_DATA)
					break;
				if (rc != CLI.ReturnCode.SQL_SUCCESS || rc != CLI.ReturnCode.SQL_SUCCESS_WITH_INFO)
					Diagnostics.HandleResult (rc, this, outerCommand.Connection);

				if (dataLength > (int) outlen)
					dataLength = (int) outlen;
				column.lobOffset += dataLength;
				readLength += dataLength;

				Marshal.Copy (dataBuffer.Handle, buffer, bufferOffset, dataLength);
				bufferOffset += dataLength;
			}

			GC.KeepAlive (this);
			return readLength;
		}
Пример #21
0
        private void btnTestInsert_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cmbKensu.Text))
            {
                MessageBox.Show("挿入件数を指定して下さい。");
                return;
            }

            if (MessageBox.Show("ダミーデータを挿入しますか?", "確認", MessageBoxButtons.OKCancel) != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("キャンセルしました。");
                return;
            }

            lblTotalNum.Text = cmbKensu.Text;
            lblInsertedNum.Text = "0";

            long insertednum = 0;
            long kensu = 0;
            long.TryParse(cmbKensu.Text, out kensu);

            MySQLDAO.MySQLConString objConString = this.getObjConstring();

            List<string> colNames = new List<string>();
            Dictionary<string, string> colTypes = new Dictionary<string, string>();
            Dictionary<string, string> colVales = new Dictionary<string, string>();

            Dictionary<string, string> paramsByColumn = new Dictionary<string, string>();
            Dictionary<string, string> nullratiosByColumn = new Dictionary<string, string>();
            foreach (DataGridViewRow row in this.grid.Rows)
            {
                CustomDataMySQLTable c = row.DataBoundItem as CustomDataMySQLTable;
                if (c != null)
                {
                    string columnName = c.ColName;
                    string param = c.Val;
                    string nullratio = c.NullRatio;

                    paramsByColumn.Add(columnName, param);
                    nullratiosByColumn.Add(columnName, nullratio);

                }
            }

            ColumnData cold = new ColumnData(paramsByColumn, nullratiosByColumn);

            try
            {
                using (MySQLDAOContext con = new MySQLDAOContext(MySQLConString.getStaticConstring()))
                {
                    con.OpenConnection();
                    //con.BeginTransaction(IsolationLevel.RepeatableRead);
                    InsertDAO dao = new InsertDAO(con);

                    for (int l = 0; l < kensu; l++)
                    {

                        Dictionary<string, string> genedCols = cold.GenerateNext();

                        colNames.Clear();
                        colTypes.Clear();
                        colVales.Clear();
                        foreach (DataGridViewRow row in this.grid.Rows)
                        {
                            CustomDataMySQLTable c = row.DataBoundItem as CustomDataMySQLTable;
                            if (c != null)
                            {
                                string columnName = c.ColName;
                                string colVal = genedCols[columnName];
                                string colType = c.ColType;

                                colNames.Add(columnName);
                                colTypes.Add(columnName, colType);
                                colVales.Add(columnName, colVal);
                            }
                        }

                        try
                        {
                            dao.Insert(tbxTableName.Text, colNames, colTypes, colVales);
                            //con.CommitTransaction();
                        }
                        catch (Exception excp)
                        {
                            /*
                            MessageBox.Show(excp.Message);
                            MessageBox.Show("ロールバックします。");
                            con.RollbackTransaction();
                            con.CloseConnection();
                            return;
                             */
                            MySQLTableHelper.SetNext();
                            continue;
                        }

                        MySQLTableHelper.SetNext();
                        insertednum++;
                        lblInsertedNum.Text = insertednum.ToString();
                        System.Windows.Forms.Application.DoEvents();
                    }

                    con.CloseConnection();
                }

                MessageBox.Show(insertednum + "の挿入に成功しました。");
            }
            catch (Exception excp)
            {
                MessageBox.Show("エラーが発生しました。MySQLが起動しているかご確認下さい。");
                return;
            }
        }
Пример #22
0
		private void RewindData (ColumnData[] columns)
		{
			CLI.ReturnCode rc = (CLI.ReturnCode) CLI.SQLSetPos (hstmt, 1, (ushort) CLI.SetPosOp.SQL_POSITION, (ushort) CLI.LockOption.SQL_LOCK_NO_CHANGE);
			if (rc != CLI.ReturnCode.SQL_SUCCESS)
				Diagnostics.HandleResult (rc, this, outerCommand.Connection);
			GC.KeepAlive (this);

			for (int i = 0; i < columns.Length; i++)
				columns[i].lobOffset = 0;
		}
        /// <summary>
        /// Fill  the Database Data based on Information that`s extracted of SQL Server Selected Database
        /// in the Interface of the app
        /// </summary>
        /// <param name="customColumnsFileName"> Full path file for CustomMappings.xlsx file </param>
        private void GetDBData(string customColumnsFileName)
        {
            dbData.DatabaseName = currentDB;
            List <ManagedColumns> customInsertColumns = new List <ManagedColumns>();
            List <ManagedColumns> customUpdateColumns = new List <ManagedColumns>();
            List <ManagedColumns> customSelectColumns = new List <ManagedColumns>();

            if (File.Exists(customColumnsFileName) && customColumns)
            {
                DataTable configTbl = ReadExcelFile.getExcellToDtbl(customColumnsFileName);

                for (int i = 0; i < configTbl.Rows.Count; i++)
                {
                    if (configTbl.Rows[i][0].ToString() != string.Empty)
                    {
                        ManagedColumns managedInsertColumns = new ManagedColumns();
                        managedInsertColumns.ColumnName    = configTbl.Rows[i][0].ToString();
                        managedInsertColumns.ColumnValue   = configTbl.Rows[i][1].ToString();
                        managedInsertColumns.UsedForParam  = Convert.ToBoolean(int.Parse(configTbl.Rows[i][2].ToString()));
                        managedInsertColumns.UsedForColumn = Convert.ToBoolean(int.Parse(configTbl.Rows[i][3].ToString()));
                        customInsertColumns.Add(managedInsertColumns);
                        ManagedColumns managedUpdateColumns = new ManagedColumns();
                        managedUpdateColumns.ColumnName    = configTbl.Rows[i][0].ToString();
                        managedUpdateColumns.ColumnValue   = configTbl.Rows[i][1].ToString();
                        managedUpdateColumns.UsedForParam  = Convert.ToBoolean(int.Parse(configTbl.Rows[i][4].ToString()));
                        managedUpdateColumns.UsedForColumn = Convert.ToBoolean(int.Parse(configTbl.Rows[i][5].ToString()));
                        customUpdateColumns.Add(managedUpdateColumns);
                        ManagedColumns managedSelectColumns = new ManagedColumns();
                        managedSelectColumns.ColumnName    = configTbl.Rows[i][0].ToString();
                        managedSelectColumns.ColumnValue   = configTbl.Rows[i][1].ToString();
                        managedSelectColumns.UsedForParam  = Convert.ToBoolean(int.Parse(configTbl.Rows[i][6].ToString()));
                        managedSelectColumns.UsedForColumn = Convert.ToBoolean(int.Parse(configTbl.Rows[i][7].ToString()));
                        customSelectColumns.Add(managedSelectColumns);
                    }
                }
                dbData.ManagedInsertColumns = customInsertColumns;
                dbData.ManagedUpdateColumns = customUpdateColumns;
                dbData.ManagedSelectColumns = customSelectColumns;
            }
            else if (customColumns)
            {
                MessageBox.Show("File CustomColumsMappings.xlsx does not exist!\nNot found in the Application Configuration dir!");
            }

            int startvalue = 1;

            //1 RANK 2 tableName, 3 columnname, 4 primarikey chek, 5 columndatatype , 6 null , 7 IsFK
            procGenData = sqlConn.GetProcTablesData(serverAddress, serverUser, serverUserPassword, currentDB, configurationFolderPath, columnsDataSql);
            string            currentPrimaryKey         = string.Empty;
            string            currentPrimaryKeyDataType = string.Empty;
            List <ColumnData> currentColumns            = new List <ColumnData>();

            for (int i = 0; i < procGenData.Rows.Count; i++)
            {
                if ((startvalue == int.Parse(procGenData.Rows[i][0].ToString()) - 1) || ((i + 1) == procGenData.Rows.Count))
                {
                    TableData currentTbl = new TableData();
                    currentTbl.Columns            = currentColumns;
                    currentTbl.TableName          = procGenData.Rows[i - 1][1].ToString();
                    currentTbl.PrimaryKey         = currentPrimaryKey;
                    currentTbl.PrimaryKeyDataType = currentPrimaryKeyDataType;
                    dbData.Tables.Add(currentTbl);
                    currentColumns = new List <ColumnData>();
                    startvalue     = int.Parse(procGenData.Rows[i][0].ToString());
                }

                if (bool.Parse(procGenData.Rows[i][3].ToString()))
                {
                    currentPrimaryKey         = procGenData.Rows[i][2].ToString();
                    currentPrimaryKeyDataType = procGenData.Rows[i][4].ToString();
                }

                if (bool.Parse(procGenData.Rows[i][3].ToString()) == false)
                {
                    ColumnData currentColumn = new ColumnData();
                    currentColumn.ColumnName     = procGenData.Rows[i][2].ToString();
                    currentColumn.ColumnDataType = procGenData.Rows[i][4].ToString();
                    currentColumn.isNullable     = bool.Parse(procGenData.Rows[i][5].ToString());
                    currentColumn.isFK           = bool.Parse(procGenData.Rows[i][6].ToString());
                    currentColumns.Add(currentColumn);
                }
            }
        }
Пример #24
0
        public void SetSettings(XmlNode node)
        {
            var     element = (XmlElement)node;
            Version version;

            if (element["Version"] != null)
            {
                version = Version.Parse(element["Version"].InnerText);
            }
            else
            {
                version = new Version(1, 0, 0, 0);
            }
            CurrentSplitTopColor    = ParseColor(element["CurrentSplitTopColor"]);
            CurrentSplitBottomColor = ParseColor(element["CurrentSplitBottomColor"]);
            VisualSplitCount        = Int32.Parse(element["VisualSplitCount"].InnerText);
            SplitPreviewCount       = Int32.Parse(element["SplitPreviewCount"].InnerText);
            DisplayIcons            = Boolean.Parse(element["DisplayIcons"].InnerText);
            ShowThinSeparators      = Boolean.Parse(element["ShowThinSeparators"].InnerText);
            AlwaysShowLastSplit     = Boolean.Parse(element["AlwaysShowLastSplit"].InnerText);
            SplitWidth = Single.Parse(element["SplitWidth"].InnerText.Replace(',', '.'), CultureInfo.InvariantCulture);

            if (version >= new Version(1, 5))
            {
                HideIconsIfAllBlank = Boolean.Parse(element["HideIconsIfAllBlank"].InnerText);
                ShowColumnLabels    = Boolean.Parse(element["ShowColumnLabels"].InnerText);
                LabelsColor         = ParseColor(element["LabelsColor"]);
                var columnsElement = element["Columns"];
                ColumnsList.Clear();
                foreach (var child in columnsElement.ChildNodes)
                {
                    var columnData = ColumnData.FromXml((XmlNode)child);
                    ColumnsList.Add(new ColumnSettings(CurrentState, columnData.Name, ColumnsList)
                    {
                        Data = columnData
                    });
                }
            }
            else
            {
                HideIconsIfAllBlank = true;
                ShowColumnLabels    = false;
                LabelsColor         = Color.FromArgb(255, 255, 255);
                ColumnsList.Clear();
                var comparison = element["Comparison"].InnerText;
                if (Boolean.Parse(element["ShowSplitTimes"].InnerText))
                {
                    ColumnsList.Add(new ColumnSettings(CurrentState, "+/-", ColumnsList)
                    {
                        Data = new ColumnData("+/-", ColumnType.Delta, comparison, "Current Timing Method")
                    });
                    ColumnsList.Add(new ColumnSettings(CurrentState, "Time", ColumnsList)
                    {
                        Data = new ColumnData("Time", ColumnType.SplitTime, comparison, "Current Timing Method")
                    });
                }
                else
                {
                    ColumnsList.Add(new ColumnSettings(CurrentState, "+/-", ColumnsList)
                    {
                        Data = new ColumnData("+/-", ColumnType.DeltaorSplitTime, comparison, "Current Timing Method")
                    });
                }
            }
            if (version >= new Version(1, 3))
            {
                OverrideTimesColor  = Boolean.Parse(element["OverrideTimesColor"].InnerText);
                BeforeTimesColor    = ParseColor(element["BeforeTimesColor"]);
                CurrentTimesColor   = ParseColor(element["CurrentTimesColor"]);
                AfterTimesColor     = ParseColor(element["AfterTimesColor"]);
                BeforeNamesColor    = ParseColor(element["BeforeNamesColor"]);
                CurrentNamesColor   = ParseColor(element["CurrentNamesColor"]);
                AfterNamesColor     = ParseColor(element["AfterNamesColor"]);
                SplitHeight         = Single.Parse(element["SplitHeight"].InnerText.Replace(',', '.'), CultureInfo.InvariantCulture);
                SplitGradientString = element["CurrentSplitGradient"].InnerText;
                BackgroundColor     = ParseColor(element["BackgroundColor"]);
                BackgroundColor2    = ParseColor(element["BackgroundColor2"]);
                GradientString      = element["BackgroundGradient"].InnerText;
                SeparatorLastSplit  = Boolean.Parse(element["SeparatorLastSplit"].InnerText);
                DropDecimals        = Boolean.Parse(element["DropDecimals"].InnerText);
                DeltasAccuracy      = ParseEnum <TimeAccuracy>(element["DeltasAccuracy"]);
                OverrideDeltasColor = Boolean.Parse(element["OverrideDeltasColor"].InnerText);
                DeltasColor         = ParseColor(element["DeltasColor"]);
                Display2Rows        = Boolean.Parse(element["Display2Rows"].InnerText);
            }
            else
            {
                if (version >= new Version(1, 2))
                {
                    BeforeNamesColor = CurrentNamesColor = AfterNamesColor = ParseColor(element["SplitNamesColor"]);
                }
                else
                {
                    BeforeNamesColor  = Color.FromArgb(255, 255, 255);
                    CurrentNamesColor = Color.FromArgb(255, 255, 255);
                    AfterNamesColor   = Color.FromArgb(255, 255, 255);
                }
                BeforeTimesColor     = Color.FromArgb(255, 255, 255);
                CurrentTimesColor    = Color.FromArgb(255, 255, 255);
                AfterTimesColor      = Color.FromArgb(255, 255, 255);
                OverrideTimesColor   = false;
                SplitHeight          = 6;
                CurrentSplitGradient = GradientType.Vertical;
                BackgroundColor      = Color.Transparent;
                BackgroundColor2     = Color.Transparent;
                BackgroundGradient   = ExtendedGradientType.Plain;
                SeparatorLastSplit   = true;
                DropDecimals         = true;
                DeltasAccuracy       = TimeAccuracy.Tenths;
                OverrideDeltasColor  = false;
                DeltasColor          = Color.FromArgb(255, 255, 255);
                Display2Rows         = false;
            }
            if (version >= new Version(1, 2))
            {
                SplitTimesAccuracy = ParseEnum <TimeAccuracy>(element["SplitTimesAccuracy"]);
                if (version >= new Version(1, 3))
                {
                    OverrideTextColor = Boolean.Parse(element["OverrideTextColor"].InnerText);
                }
                else
                {
                    OverrideTextColor = !Boolean.Parse(element["UseTextColor"].InnerText);
                }
                ShowBlankSplits = Boolean.Parse(element["ShowBlankSplits"].InnerText);
                LockLastSplit   = Boolean.Parse(element["LockLastSplit"].InnerText);
                IconSize        = Single.Parse(element["IconSize"].InnerText.Replace(',', '.'), CultureInfo.InvariantCulture);
                IconShadows     = Boolean.Parse(element["IconShadows"].InnerText);
            }
            else
            {
                SplitTimesAccuracy = TimeAccuracy.Seconds;
                OverrideTextColor  = false;
                ShowBlankSplits    = true;
                LockLastSplit      = false;
                IconSize           = 24f;
                IconShadows        = true;
            }
        }
Пример #25
0
        private object GetColumnData(int i)
        {
            ColumnData column = columns[i];
            Type       type   = column.columnType.bufferType.type;

            if (column.data == null)
            {
                column.data = innerCommand.GetColumnData(i, columns);
            }
            if (column.data != null && !Convert.IsDBNull(column.data) && type != column.data.GetType())
            {
                if (column.data is IConvertData)
                {
                    return(((IConvertData)column.data).ConvertData(type));
                }
                else if (column.data is IConvertible)
                {
                    switch (column.data.GetType().FullName)
                    {
                    case "System.Int32":
                    case "System.Single":
                    case "System.Double":
                    case "System.Decimal":
                    case "System.DateTime":
                    case "OpenLink.Data.Virtuoso.VirtuosoDateTime":
                    case "System.DateTimeOffset":
                    case "OpenLink.Data.Virtuoso.VirtuosoDateTimeOffset":
                    case "System.TimeSpan":
                    case "OpenLink.Data.Virtuoso.VirtuosoTimeSpan":
                        return(column.data);

                    default:
                        return(Convert.ChangeType(column.data, type));
                    }
                }
                else if (column.data is SqlExtendedString)
                {
                    return(column.data);
                }
                else if (column.data is SqlRdfBox)
                {
                    return(column.data);
                }
                else
                {
                    switch (column.data.GetType().FullName)
                    {
                    case "System.DateTime":
                    case "OpenLink.Data.Virtuoso.VirtuosoDateTime":
                    case "System.DateTimeOffset":
                    case "OpenLink.Data.Virtuoso.VirtuosoDateTimeOffset":
                    case "System.TimeSpan":
                    case "OpenLink.Data.Virtuoso.VirtuosoTimeSpan":
                    case "System.Byte[]":
                        return(column.data);

                    default:
                        return(column.data.ToString());
                    }
                }
            }
            else
            {
                return(column.data);
            }
        }
Пример #26
0
        public void configure(Net7.Tables table)
        {
            if (!m_table.Equals(table))
            {
                // Clear the previous search results
                guiSearchCriteriaTbl.Items.Clear();
                guiResultTbl.Items.Clear();
                guiResultLbl.Text = "";
            }

            m_table = table;
            ColumnData.ColumnDataInfo[] fields = null;
            switch (m_table)
            {
            case Net7.Tables.effects:
                m_columns = new Enum[] { Net7.Table_effects._effect_id, Net7.Table_effects._description, Net7.Table_effects._base_asset_id };
                fields    = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_effects>(true);
                break;

            case Net7.Tables.factions:
                m_columns = new Enum[] { Net7.Table_factions._faction_id, Net7.Table_factions._name };
                fields    = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_factions>(true);
                break;

            case Net7.Tables.item_base:
                m_columns = new Enum[] { Net7.Table_item_base._id,
                                         Net7.Table_item_base._name,
                                         Net7.Table_item_base._category,
                                         Net7.Table_item_base._sub_category,
                                         Net7.Table_item_base._level,
                                         Net7.Table_item_base._status };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_item_base>(true);
                break;

            case Net7.Tables.missions:
                m_columns = new Enum[] { Net7.Table_missions._mission_id,
                                         Net7.Table_missions._mission_name,
                                         Net7.Table_missions._mission_type,
                                         Net7.Table_missions._mission_key };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_missions>(true);
                break;

            case Net7.Tables.mob_base:
                m_columns = new Enum[] { Net7.Table_mob_base._mob_id,
                                         Net7.Table_mob_base._name };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_mob_base>(true);
                break;

            case Net7.Tables.starbase_npcs:
                m_columns = new Enum[] { Net7.Table_starbase_npcs._npc_Id,
                                         Net7.Table_starbase_npcs._first_name,
                                         Net7.Table_starbase_npcs._last_name };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_starbase_npcs>(true);
                break;

            case Net7.Tables.sectors:
                m_columns = new Enum[] { Net7.Table_sectors._sector_id,
                                         Net7.Table_sectors._name };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_sectors>(true);
                break;

            case Net7.Tables.sector_objects:
                m_columns = new Enum[] { Net7.Table_sector_objects._sector_object_id,
                                         Net7.Table_sector_objects._name,
                                         Net7.Table_sector_objects._base_asset_id,
                                         Net7.Table_sector_objects._sector_id };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_sector_objects>(true);
                break;

            case Net7.Tables.skills:
                m_columns = new Enum[] { Net7.Table_skills._skill_id,
                                         Net7.Table_skills._name };
                fields = CommonTools.Enumeration.ToColumnDataInfo <Net7.Table_skills>(true);
                break;

            default:
                throw (new Exception("DlgSearch.configure() does not handle the table " + table.ToString()));
            }

            guiResultTbl.Columns.Clear();
            m_adjustedColumnWidths = false;

            ColumnHeader columnHeader;

            for (int columnIndex = 0; columnIndex < m_columns.Length; columnIndex++)
            {
                columnHeader = new ColumnHeader();
                columnHeader.DisplayIndex = columnIndex;
                columnHeader.Text         = ColumnData.GetName(m_columns[columnIndex]);
                columnHeader.Width        = -2;
                guiResultTbl.Columns.Add(columnHeader);
            }

            m_dlgSearchCriteria = new DlgSearchCriteria();
            m_dlgSearchCriteria.configure(fields);
        }
Пример #27
0
		public bool IsDBNull (int i, ColumnData[] columns)
		{
			Debug.Assert (currentRow != null);
			return Convert.IsDBNull (currentRow[i + 1]);
		}
Пример #28
0
        private void onSearchClick(object sender, EventArgs e)
        {
            String        query         = "";
            List <String> sqlParameters = new List <String>();
            List <String> sqlValues     = new List <String>();
            int           parameterId   = 0;

            foreach (SearchCriteria searchCriteria in this.guiSearchCriteriaTbl.Items)
            {
                if (query.Length != 0)
                {
                    query += " AND ";
                }
                query += searchCriteria.getQuery() + parameterId.ToString();
                sqlParameters.Add(searchCriteria.sqlParameter + parameterId.ToString());
                sqlValues.Add(searchCriteria.sqlValue);
                parameterId++;
            }

            if (query.Length != 0)
            {
                String select = "";
                foreach (Enum column in m_columns)
                {
                    if (select.Length == 0)
                    {
                        select = DB.SELECT;
                    }
                    else
                    {
                        select += ",";
                    }
                    select += ColumnData.GetName(column);
                }
                query = select
                        + DB.FROM
                        + m_table.ToString()
                        + DB.WHERE
                        + query;

                DataTable dataTable = DB.Instance.executeQuery(query, sqlParameters.ToArray(), sqlValues.ToArray());
                guiResultTbl.Items.Clear();
                guiResultLbl.Text = dataTable.Rows.Count.ToString() + " items";

                ListViewItem  listViewItem;
                List <String> rowData = new List <string>();
                foreach (DataRow dataRow in dataTable.Rows)
                {
                    rowData.Clear();
                    for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
                    {
                        rowData.Add(dataRow[columnIndex].ToString());
                    }

                    listViewItem = new ListViewItem(rowData.ToArray());
                    guiResultTbl.Items.Add(listViewItem);
                }

                if (m_adjustedColumnWidths == false)
                {
                    List <int> columnWidth = new List <int>();
                    m_adjustedColumnWidths = true;
                    foreach (ColumnHeader columnHeader in guiResultTbl.Columns)
                    {
                        columnHeader.Width = -2;
                        columnWidth.Add(columnHeader.Width);
                    }
                }
            }
        }
Пример #29
0
		public long GetBytes (int i, ColumnData[] columns, long fieldOffset,
			byte[] buffer, int bufferOffset, int length)
		{
			ColumnData column = columns[i];
			object data = currentRow[i + 1];
			if (data is BlobHandle)
			{
				BlobHandle blob = (BlobHandle) data;
				if (buffer == null)
					return blob.length < fieldOffset ? 0 : blob.length - fieldOffset;
				if (fieldOffset < column.lobOffset)
				{
					blob.Rewind ();
					column.lobOffset = 0;
				}
				if (fieldOffset > column.lobOffset)
				{
					GetData (column, blob, (int) (fieldOffset - column.lobOffset), null, 0);
					if (fieldOffset > column.lobOffset)
						return 0;
				}
				return GetData (column, blob, length, buffer, bufferOffset);
			}
			else if (data is byte[])
			{
				byte[] bytes = (byte[]) data;
				if (buffer == null)
					return bytes.Length < fieldOffset ? 0 : bytes.Length - fieldOffset;
				if (length > (bytes.Length - fieldOffset))
					length = (int) (bytes.Length - fieldOffset);
				Array.Copy (bytes, (int) fieldOffset, buffer, bufferOffset, length);
				return length;
			}
			else if (data is string)
			{
				string str = (string) data;
				if (buffer == null)
					return str.Length < fieldOffset ? 0 : str.Length - fieldOffset;
				if (length > (str.Length - fieldOffset))
					length = (int) (str.Length - fieldOffset);
				BufferTypeBinary.ConvertStringToBytes (str, buffer, 
				    bufferOffset, length,
				    (int) fieldOffset);
				return length;
			}
			else
			  throw new NotSupportedException ();
		}
Пример #30
0
        public static IndexArchitecture RetrieveIndexArchitecture(
            this MetadataManager metadataManager,
            string tableName,
            string schema,
            Index index,
            MetadataDbContext dbContext)
        {
            var pagesMetadata = dbContext
                                .GetDataPagesMetadata(tableName, schema)
                                .Where((item) => item.IndexID == index.IndexID);
            var indexPagesMetadata = pagesMetadata
                                     .Where((item) => item.PageType.GetDatabasePageType() == DatabasePage.Type.Index);
            var dataPagesMetadata = pagesMetadata
                                    .Where((item) => item.PageType.GetDatabasePageType() == DatabasePage.Type.Data);

            if (index.IndexType == IndexType.Clustered)
            {
                var pagefileIndexpagePairs = indexPagesMetadata
                                             .Select((item) =>
                {
                    return(new IndexPage()
                    {
                        PageID = item.PageID,
                        FileID = item.FileID,
                        IndexID = item.IndexID,
                        TableObjectID = item.ObjectID,
                        NextPageID = item.NextPagePageID,
                        PrevPageID = item.PreviousPagePageID
                    });
                })
                                             .ToDictionary((keySelector) => keySelector.GetDatabasePageUniqueKey());
                var indexPages = new List <IndexPage>();

                foreach (var pagefileIndexpagePair in pagefileIndexpagePairs)
                {
                    var indexPage = pagefileIndexpagePair.Value;
                    if (indexPage.NextPageID.GetValueOrDefault() > 0)
                    {
                        indexPage.NextPage = pagefileIndexpagePairs[indexPage.GetDatabasePageUniqueKey()];
                    }
                    if (indexPage.PrevPageID.GetValueOrDefault() > 0)
                    {
                        indexPage.PrevPage = pagefileIndexpagePairs[indexPage.GetDatabasePageUniqueKey()];
                    }
                    indexPages.Add(indexPage);
                }

                var pagefileDatapagePairs = dataPagesMetadata
                                            .Select((item) =>
                {
                    return(new DataPage()
                    {
                        PageID = item.PageID,
                        FileID = item.FileID,
                        IndexID = item.IndexID,
                        TableObjectID = item.ObjectID,
                        NextPageID = item.NextPagePageID,
                        PrevPageID = item.PreviousPagePageID
                    });
                })
                                            .ToDictionary((keySelector) => keySelector.GetDatabasePageUniqueKey());
                var dataPages = new List <DataPage>();

                foreach (var pagefileDatapagePair in pagefileDatapagePairs)
                {
                    var dataPage = pagefileDatapagePair.Value;
                    if (dataPage.NextPageID.GetValueOrDefault() > 0)
                    {
                        dataPage.NextPage = pagefileDatapagePairs[dataPage.GetDatabasePageUniqueKey()];
                    }
                    if (dataPage.PrevPageID.GetValueOrDefault() > 0)
                    {
                        dataPage.PrevPage = pagefileDatapagePairs[dataPage.GetDatabasePageUniqueKey()];
                    }
                    dataPages.Add(dataPage);
                }

                foreach (var indexPage in indexPages)
                {
                    var indexPageMetadata = dbContext.GetIndexPageIntermediateMetadata(indexPage.FileID, indexPage.PageID);

                    var childrenPages = new List <DatabasePage>();
                    indexPageMetadata.ForEach((item) =>
                    {
                        var childrenPageKey = item.GetDatabasePageUniqueKey();
                        if (pagefileIndexpagePairs.ContainsKey(childrenPageKey))
                        {
                            childrenPages.Add(pagefileIndexpagePairs[childrenPageKey]);
                        }
                        if (pagefileDatapagePairs.ContainsKey(childrenPageKey))
                        {
                            childrenPages.Add(pagefileDatapagePairs[childrenPageKey]);
                        }
                    });
                    indexPage.Children = childrenPages;
                }

                var tableColumns = new HashSet <string>();
                dbContext
                .GetColumnMetadata()
                .Where((item) => item.TableObjectID == index.TableObjectID)
                .ToList()
                .ForEach((item) =>
                {
                    tableColumns.Add(item.ColumnName);
                });

                var rowDatas    = new List <RowData>();
                var columnDatas = new List <ColumnData>();
                foreach (var dataPage in dataPages)
                {
                    var datapageMetadata = dbContext.GetDataPageMetadata(dataPage.FileID, dataPage.PageID);

                    datapageMetadata.ForEach((item) =>
                    {
                        if (item.Field == "KeyHashValue")
                        {
                            var rowData = new RowData()
                            {
                                ColumnDatas  = columnDatas,
                                KeyHashValue = item.Value
                            };
                            rowDatas.Add(rowData);
                            columnDatas = new List <ColumnData>();
                        }
                        else if (tableColumns.Contains(item.Field))
                        {
                            var columnData = new ColumnData()
                            {
                                ColumnName    = item.Field,
                                RawColumnData = item.Value
                            };
                            columnDatas.Add(columnData);
                        }
                    });

                    dataPage.RowDatas = rowDatas;
                }

                var indexPagesSet = new HashSet <IndexPage>();
                indexPages.ForEach((item) =>
                {
                    indexPagesSet.Add(item);
                });
                var dataPagesSet = new HashSet <DataPage>();
                dataPages.ForEach((item) =>
                {
                    dataPagesSet.Add(item);
                });

                return(new ClusteredIndexArchitecture()
                {
                    IndexPages = indexPagesSet,
                    DataPages = dataPagesSet
                });
            }
            else if (index.IndexType == IndexType.Heap)
            {
                return(null);
            }
            else if (index.IndexType == IndexType.NonClustered)
            {
                return(null);
            }
            else
            {
                throw new Exception();
            }
        }
Пример #31
0
		private void SetColumnMetaData (object compilationColumns, int hiddenColumns)
		{
		  Debug.WriteLineIf (CLI.FnTrace.Enabled, "ManagedCommand.SetColumnMetaData");
			object[] descriptions = null;
			if (compilationColumns is object[])
				descriptions = (object[]) compilationColumns;

			if (descriptions == null || descriptions.Length == 0)
			{
				columns = null;
				return;
			}

			bool hasKeyColumns = false;

			columns = new ColumnData[descriptions.Length];
			for (int i = 0; i < columns.Length; i++)
			{
				object[] description = (object[]) descriptions[i];

				ColumnData column = new ColumnData ();
				columns[i] = column;

				ColumnFlags flags = (ColumnFlags) description[11];

				column.columnName = (string) description[0];
				column.columnType = DataTypeInfo.MapDvType ((BoxTag) description[1]);
				if (0 != (flags & ColumnFlags.CDF_XMLTYPE))
				  {
				    Debug.WriteLineIf (SqlXml.Switch.TraceVerbose,
					String.Format ("Set XML type for {0}", column.columnName));
				    column.columnType = DataTypeInfo.Xml;
				  }
				if (column.columnType == null)
					throw new SystemException ("Unknown data type");
				column.bufferType = column.columnType.bufferType;

				column.columnSize = column.columnType.GetFieldSize ((int) description[3]);
				column.precision = (short) column.columnSize;
				column.scale = (short) ((int) description[2]);
				column.IsLong = column.columnType.isLong;
				column.IsNullable = (0 != (int) description[4]);

				CLI.Updatable updatable = (CLI.Updatable) (int) description[5];
				column.IsReadOnly = (updatable == CLI.Updatable.SQL_ATTR_READONLY);

				column.IsAutoIncrement = (0 != (flags & ColumnFlags.CDF_AUTOINCREMENT));
				column.IsKey = (0 != (flags & ColumnFlags.CDF_KEY));
				if (column.IsKey)
					hasKeyColumns = true;

				column.IsHidden = (i >= (columns.Length - hiddenColumns));
				column.IsRowVersion = (column.columnType == DataTypeInfo.Timestamp);
				// TODO: check for unique columns as well.
				column.IsUnique = false;

				column.baseCatalogName = (string) Values.NullIfZero (description[7]);
				column.baseColumnName = (string) Values.NullIfZero (description[8]);
				column.baseSchemaName = (string) Values.NullIfZero (description[9]);
				column.baseTableName = (string) Values.NullIfZero (description[10]);

				if (column.baseTableName == null || column.baseTableName == "")
					column.IsExpression = true;
				else
					column.IsExpression = false;
			}

			if (uniqueRows && !hasKeyColumns)
				uniqueRows = false;
		}
Пример #32
0
        /// <summary>
        ///   <para>
        ///     Validate the display the value of the field contained within DataBinding</para>
        /// </summary>
        /// <returns>
        ///     <para>The data validation result.</para>
        /// </returns>
        public DataValidation.Result validField(Boolean newRecord, DataBinding dataBinding, DataRow dataRow)
        {
            DataValidation.Result dataValidationResult = null;
            switch ((Net7.Table_item_manufacture)dataBinding.enumeration)
            {
            case Net7.Table_item_manufacture._item_id:
            {
                if (newRecord)
                {
                    // Store the item ID
                    String itemIdColumnName          = ColumnData.GetName(Net7.Table_item_base._id);
                    String itemId                    = dataRow[itemIdColumnName].ToString();
                    String manufacturingIdColumnName = ColumnData.GetName(Net7.Table_item_manufacture._item_id);
                    dataRow[manufacturingIdColumnName] = itemId;
                }
            }
            break;

            case Net7.Table_item_manufacture._comp_1:
            case Net7.Table_item_manufacture._comp_2:
            case Net7.Table_item_manufacture._comp_3:
            case Net7.Table_item_manufacture._comp_4:
            case Net7.Table_item_manufacture._comp_5:
            case Net7.Table_item_manufacture._comp_6:
            {
                int    componentIndex = getComponentIndexFromEnum((Net7.Table_item_manufacture)dataBinding.enumeration);
                String componentId    = m_listComponentFields[componentIndex].getFields().m_field.Text;
                if (componentIndex == 0)
                {
                    dataValidationResult = componentId.Equals(UnspecifiedComponentId)
                                                   ? null
                                                   : DataValidation.isInTable(componentId,
                                                                              Net7.Tables.item_manufacture.ToString(),
                                                                              Database.getQueryItem(componentId));
                }
                else if (componentIndex > 0)
                {
                    // Valid to be unspecified otherwise must be in the item table
                    dataValidationResult = componentId.Equals(UnspecifiedComponentId)
                                                   ? null
                                                   : DataValidation.isInTable(componentId,
                                                                              "Items",
                                                                              Database.getQueryItem(componentId));
                    if (dataValidationResult == null || dataValidationResult.isValid())
                    {
                        // Previous component must be specified
                        String previousComponentId = m_listComponentFields[componentIndex - 1].getFields().m_field.Text;
                        if (!componentId.Equals(UnspecifiedComponentId) && previousComponentId.Equals(UnspecifiedComponentId))
                        {
                            if (dataValidationResult == null)
                            {
                                dataValidationResult = new DataValidation.Result();
                            }
                            dataValidationResult.setMessage("You must define the previous component before specifying this one");
                        }
                    }
                }
            }
            break;
            }
            return(dataValidationResult);
        }
Пример #33
0
        public FileResult AjaxFinancialExportData(string queryString)
        {
            //每页显示条数:
            SalesStatisticsReportQueryFilter getQueryEntity = SerializationUtility.JsonDeserialize2 <SalesStatisticsReportQueryFilter>(queryString);

            getQueryEntity.C1SysNo    = getQueryEntity.Category.C1SysNo == 0 ? null : getQueryEntity.Category.C1SysNo;
            getQueryEntity.C2SysNo    = getQueryEntity.Category.C2SysNo == 0 ? null : getQueryEntity.Category.C2SysNo;
            getQueryEntity.C3SysNo    = getQueryEntity.Category.C3SysNo == 0 ? null : getQueryEntity.Category.C3SysNo;
            getQueryEntity.SortFields = "B.ProductID DESC";

            int MerchantSysNo = UserAuthHelper.GetCurrentUser().SellerSysNo;

            getQueryEntity.VendorSysNoList = new List <int>();
            getQueryEntity.VendorSysNoList.Add(MerchantSysNo);
            getQueryEntity.SOStatusList = new List <int>();
            if (getQueryEntity.SOStatus.HasValue)
            {
                getQueryEntity.SOStatusList.Add(getQueryEntity.SOStatus.Value);
            }

            getQueryEntity.PageSize  = 10000000;
            getQueryEntity.PageIndex = 0;


            SalesStatisticsReport result = FinancialReportService.SalesStatisticsReportQuery(getQueryEntity);


            List <DataTable> dataTableList = new List <DataTable>();

            if (result.SalesStatisticsResult.ResultList.Count <= 0)
            {
                throw new BusinessException("无数据可导出!!!");
            }


            DataTable newDt = ToDataTableTow(result.SalesStatisticsResult.ResultList);

            dataTableList.Add(newDt);

            List <ColumnData> columndatalist = new List <ColumnData>();
            ColumnData        columndata     = null;

            columndata = new ColumnData()
            {
                FieldName = "ProductID", Width = 20, Title = "商品ID"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductName", Width = 30, Title = "商品名称"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "C1Name", Width = 15, Title = "一级分类"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "C2Name", Width = 15, Title = "二级分类"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "C3Name", Width = 15, Title = "三级分类", ValueFormat = ""
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "BeginDate", Width = 20, Title = "开始时间"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "EndDate", Width = 20, Title = "结束时间"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "BrandName", Width = 20, Title = "品牌"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "VendorName", Width = 20, Title = "供应商"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "StockName", Width = 20, Title = "仓库"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "BMCode", Width = 20, Title = "BM编号"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductProperty1", Width = 20, Title = "属性1"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductProperty2", Width = 20, Title = "属性2"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "Quantity", Width = 20, Title = "数量"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductCost", Width = 20, Title = "销售成本"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductPriceAmount", Width = 20, Title = "销售金额"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "PromotionDiscountAmount", Width = 20, Title = "优惠金额"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductSaleAmount", Width = 20, Title = "实际销售金额"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "PayTypeName", Width = 20, Title = "支付方式"
            };
            columndatalist.Add(columndata);
            columndata = new ColumnData()
            {
                FieldName = "ProductGrossMargin", Width = 20, Title = "商品毛利"
            };
            columndatalist.Add(columndata);
            List <List <ColumnData> > columnList = new List <List <ColumnData> >();

            columnList.Add(columndatalist);
            //步骤5:调用生成Excel的公共方法,返回

            /*例如:
             * IFileExport excelExport = new ExcelFileExporter();
             * byte[] excelByte = excelExport.CreateFile(dataTableList, columnList, null, out fileName, "测试导出Excel");
             * return File(new MemoryStream(excelByte), "application/ms-excel", fileName);
             */
            string      fileName    = "";
            IFileExport excelExport = new ExcelFileExporter();

            byte[] excelByte = excelExport.CreateFile(dataTableList, columnList, null, out fileName, "销售统计报表");
            return(File(new MemoryStream(excelByte), "application/ms-excel", fileName));
        }
Пример #34
0
        public bool Parse(string FileName)
        {
            // Load the provided file into a line buffer
            try
            {
                using (StreamReader sr = new StreamReader(FileName))
                {
                    //csv's are often tiny so just read it all into ram in one blob operation
                    string file = sr.ReadToEnd();
                    if (file.Length < 20)
                    {
                        Console.WriteLine("csv too short");
                        return(false);
                    }
                    file = file.Replace("\r", "\n");

                    string[] lines = file.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    if (lines.Length < 2)
                    {
                        Console.WriteLine("Not enough rows in csv");
                        return(false);
                    }
                    Console.WriteLine("CSV Header Row ~> %s", lines[0]);
                    string[] headings = lines[0].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    parsedColumns = new List <ColumnData> {
                    };
                    foreach (string header in headings)
                    {
                        ColumnData c = new ColumnData
                        {
                            ColumnName = header,
                            cells      = new List <string> {
                            },
                            ColumnTag  = EXIFReWriter.EXIFTag.Ignored
                        };
                        var colName = c.ColumnName.ToLower();
                        if ((colName.Contains("file") || colName.Contains("image")) && !colName.Contains("gps"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.FileName;
                        }
                        else if (colName.Contains("latitude") && !colName.Contains("ref"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.GPSLatitude;
                        }
                        else if (colName.Contains("longitude") && !colName.Contains("ref"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.GPSLongitude;
                        }
                        else if ((colName.Contains("altitude") || colName.Contains("height")) && !colName.Contains("ref"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.GPSAltitude;
                        }
                        else if ((colName.Contains("altitude") || colName.Contains("height")) && colName.Contains("ref"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.GPSAltitudeReference;
                        }
                        else if (colName.Contains("date"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.DateTime;
                        }
                        else if (colName.Contains("comment"))
                        {
                            c.ColumnTag = EXIFReWriter.EXIFTag.UserComment;
                        }
                        parsedColumns.Add(c);
                    }

                    Console.WriteLine("Parsing %d Lines", lines.Length - 1);
                    for (int i = 1; i < lines.Length; i++)
                    {
                        //Split line into columns, and assign all of these out
                        var lineCols = lines[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        int column   = 0;
                        for (; column < lineCols.Length && column < parsedColumns.Count; column++)
                        {
                            parsedColumns[column].cells.Add(lineCols[column].Trim());
                        }
                        //Add any blank filling
                        for (; column < parsedColumns.Count; column++)
                        {
                            Console.WriteLine("Passing Column %d on line %d", column, i);
                            parsedColumns[column].cells.Add("");
                        }
                        //Check for non-labelled columns
                        for (; column < lineCols.Length; column++)
                        {
                            ColumnData c = new ColumnData
                            {
                                ColumnName = "Unknown " + column.ToString(),
                                cells      = new List <string> {
                                }
                            };
                            parsedColumns.Add(c);
                        }
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The File could not be read:");
                Console.WriteLine(e.Message);
                return(false);
            }
            // Read first line as headings
            // Read all subsequent lines as data for said headings
        }
Пример #35
0
        public void RunThread()
        {
            List <string> list = new List <string>();

            #region TechSOFT Banner


            //list.Add("");
            //list.Add("");
            //list.Add("\t\t**********************************************");
            //list.Add("\t\t*          ASTRA Pro Release 18.0            *");
            //list.Add("\t\t*      TechSOFT Engineering Services         *");
            //list.Add("\t\t*                                            *");
            //list.Add("\t\t*      DESIGN OF RCC PILE FOUNDATION         *");
            //list.Add("\t\t*                                            *");
            //list.Add("\t\t**********************************************");
            //list.Add("\t\t----------------------------------------------");
            //list.Add("\t\tTHIS RESULT CREATED ON " + System.DateTime.Now.ToString("dd.MM.yyyy  AT HH:mm:ss") + " ");
            //list.Add("\t\t----------------------------------------------");
            //list.Add("");

            #endregion



            int c    = 0;
            int step = 1;


            string ColumnNos = "";

            //int c = 0;
            for (int i = 0; i < dgv_columns.RowCount; i++)
            {
                try
                {
                    c = 1;
                    ColumnData cd = new ColumnData();
                    cd.IsSelect = (bool)dgv_columns[c++, i].Value;
                    if (cd.IsSelect)
                    {
                        Set_Grid_Color(i, false, false);
                        Pile_Design.ColumnNo = dgv_columns[c++, i].Value.ToString(); c++;

                        if (MessageBox.Show("Process Design Pile Foundation " + Pile_Design.ColumnNo + " \n\nDou you want to continue ?", "ASTRA", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            break;
                        }
                        //Pile_Design.Continuous_ColumnMembers = dgv_columns[c++, i].Value.ToString();
                        Pile_Design.D = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        //Pile_Design.PL = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.LPC = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.BPC = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.DPC = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.d1  = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.d2  = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.d3  = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.P   = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Pile_Design.AM  = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);

                        //Pile_Design.Mx = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0);


                        list.AddRange(Pile_Design.Design_Program_Loop(i + 1).ToArray());

                        dgv_columns[c, i].Value = Pile_Design.IS_DESIGN_OK ? " OK" : "NOT OK";
                        Set_Grid_Color(i, true, Pile_Design.IS_DESIGN_OK);
                        Add_Foundation_BOQ(Pile_Design.BOQ);
                    }
                }
                catch (Exception exx) { }
            }



            #region End of Report
            list.Add("");
            list.Add("---------------------------------------------------------------------------");
            list.Add("---------------------       END OF REPORT        --------------------------");
            list.Add("---------------------------------------------------------------------------");
            #endregion End of Report



            File.WriteAllLines(Pile_Design.Report_File, list.ToArray());
            //MessageBox.Show(this, "Report file created in file " + Pile_Design.Report_File);
            ////frmASTRAReport fap = new frmASTRAReport(Pile_Design.Report_File);
            ////fap.Owner = this;
            ////fap.Show();

            //frmASTRAReport.OpenReport(Pile_Design.Report_File, this);

            Save_Data();
        }
Пример #36
0
		public void InitialiseFromOb(ColumnData<object> ObIn)
		{
			try
			{
				ob = ObIn;
				int ColumnId;
				foreach (ColumnDef c in Table)
				{
					ColumnId = (int) c.ColumnEnum;
					ObInitialised[ColumnId] = true;
					ObAtInit[ColumnId] = Ob[ColumnId];
				}
			}catch(Exception ex)
			{
				throw new Exception(String.Format("ObIn is null:{0} Table is null:{1} ObInitialised is null:{2} ObAtInit is null{3}", ObIn == null, Table == null,  ObInitialised == null, ObAtInit == null), ex);
			}
		}
Пример #37
0
        private long GetData(ColumnData column, BlobHandle blob, int length, object buffer, int bufferOffset)
        {
            Debug.WriteLineIf(CLI.FnTrace.Enabled, "ManagedCommand.GetData()");

            Future future = new Future(Service.GetData,
                                       blob.current_page,
                                       length,
                                       blob.current_position,
                                       blob.keyId,
                                       blob.fragNo,
                                       blob.dirPage,
                                       blob.pages,
                                       blob.tag == BoxTag.DV_BLOB_WIDE_HANDLE ? 1 : 0,
                                       blob.timeStamp);

            object result = null;

            try
            {
                connection.futures.Add(future);
                future.SendRequest(connection.Session, timeout);
                result = future.GetResult(connection.Session, connection.futures);
            }
            finally
            {
                connection.futures.Remove(future);
            }

            if (!(result is object[]))
            {
                return(0);
            }

            object[] results = (object[])result;
            if (results[0] is int && (AnswerTag)results[0] == AnswerTag.QA_ERROR)
            {
                errors.AddServerError((string)results[1], null, (string)results[2]);
                Diagnostics.HandleResult(CLI.ReturnCode.SQL_ERROR, this, connection.OuterConnection);
            }

            int startOffset = column.lobOffset;

            for (int i = 0; i < results.Length; i++)
            {
                if (results[i] is int[])
                {
                    int[] array = (int[])results[i];
                    blob.current_page     = array[1];
                    blob.current_position = array[2];
                    continue;
                }
                else if (results[i] is string)
                {
                    string s = (string)results[i];
                    if (buffer is char[])
                    {
                        char[] chars      = s.ToCharArray();
                        char[] charBuffer = (char[])buffer;

                        Debug.WriteLineIf(Switch.Enabled, "do chars");
                        Debug.WriteLineIf(Switch.Enabled, "buffer length: " +
                                          (charBuffer == null ? "no" : charBuffer.Length.ToString()));
                        Debug.WriteLineIf(Switch.Enabled, "buffer offset: " + bufferOffset);
                        Debug.WriteLineIf(Switch.Enabled, "data length: " + chars.Length);
                        Debug.WriteLineIf(Switch.Enabled, "length: " + length);

                        if (charBuffer != null)
                        {
                            int copyLength = length < chars.Length ? length : chars.Length;
                            Array.Copy(chars, 0, charBuffer, bufferOffset, copyLength);
                        }
                        column.lobOffset += chars.Length;
                        bufferOffset     += chars.Length;
                        length           -= chars.Length;
                    }
                    else
                    {
                        byte[] bytes      = Encoding.GetEncoding("iso-8859-1").GetBytes(s);
                        byte[] byteBuffer = (byte[])buffer;

                        Debug.WriteLineIf(Switch.Enabled, "do bytes");
                        Debug.WriteLineIf(Switch.Enabled, "buffer length: " +
                                          (byteBuffer == null ? "no" : byteBuffer.Length.ToString()));
                        Debug.WriteLineIf(Switch.Enabled, "buffer offset: " + bufferOffset);
                        Debug.WriteLineIf(Switch.Enabled, "data length: " + bytes.Length);
                        Debug.WriteLineIf(Switch.Enabled, "length: " + length);

                        if (byteBuffer != null)
                        {
                            int copyLength = length < bytes.Length ? length : bytes.Length;
                            Array.Copy(bytes, 0, byteBuffer, bufferOffset, copyLength);
                        }
                        column.lobOffset += bytes.Length;
                        bufferOffset     += bytes.Length;
                        length           -= bytes.Length;
                    }
                }
            }
            return(column.lobOffset - startOffset);
        }
Пример #38
0
        private static List <ColumnData> GetColumnData4VerticalAlignment(UIElementCollection Children, Size finalSize)
        {
            List <ColumnData> columnDatas = new List <ColumnData>(Children.Count);

            int i = 0; int j = 0;

            foreach (UIElement child in Children)
            {
                if (columnDatas.Count - 1 < j)
                {
                    columnDatas.Add(new ColumnData());
                }
                var currentColumnData = columnDatas[j];
                currentColumnData.Column = j;

                var currentPoint0 = new Point();
                var currentPoint1 = new Point();

                if (i == 0)
                {
                    // first element of a column
                    currentPoint0.Y = 0.0;
                    currentPoint1.Y = child.DesiredSize.Height - 1;
                    currentPoint0.X = columnDatas.Take(j).Sum(rd => rd.MaxWidthInColumn);
                    currentPoint1.X = currentPoint0.X + child.DesiredSize.Width - 1;
                    currentColumnData.Point0s.Add(currentPoint0);
                    currentColumnData.Point1s.Add(currentPoint1);
                    currentColumnData.Children.Add(child);
                    currentColumnData.MaxWidthInColumn = Math.Max(child.DesiredSize.Width, currentColumnData.MaxWidthInColumn);
                    i++;
                }
                else if ((currentColumnData.Point1s[i - 1].Y + child.DesiredSize.Height) <= finalSize.Height)
                {
                    // append to existing column
                    currentPoint0.Y = currentColumnData.Point1s[i - 1].Y + 1;
                    currentPoint1.Y = currentPoint0.Y + child.DesiredSize.Height - 1;
                    currentPoint0.X = columnDatas.Take(j).Sum(rd => rd.MaxWidthInColumn);
                    currentPoint1.X = currentPoint0.X + child.DesiredSize.Width - 1;
                    currentColumnData.Point0s.Add(currentPoint0);
                    currentColumnData.Point1s.Add(currentPoint1);
                    currentColumnData.Children.Add(child);
                    currentColumnData.MaxWidthInColumn = Math.Max(child.DesiredSize.Width, currentColumnData.MaxWidthInColumn);
                    i++;
                }
                else
                {
                    // start new column
                    currentPoint0.Y = 0.0;
                    currentPoint1.Y = child.DesiredSize.Height - 1;
                    currentPoint0.X = columnDatas.Sum(rd => rd.MaxWidthInColumn);
                    currentPoint1.X = currentPoint0.X + child.DesiredSize.Width - 1;
                    var newColumnData = new ColumnData();
                    newColumnData.Point0s.Add(currentPoint0);
                    newColumnData.Point1s.Add(currentPoint1);
                    newColumnData.Children.Add(child);
                    newColumnData.MaxWidthInColumn = child.DesiredSize.Width;
                    columnDatas.Add(newColumnData);
                    i = 1;
                    j++;
                }
            }

            return(columnDatas);
        }
Пример #39
0
 private static int GetColumnOrder(ColumnData columnData)
 {
     return(columnData.ColumnOrderInformation.Order);
 }
Пример #40
0
        private void btnParse1_Click(object sender, EventArgs e)
        {
            string columnName = "col1";
            string param = tbxScript1.Text;

            MySQLDAO.MySQLConString objConString = this.getObjConstring();

            Dictionary<string, string> paramsByColumn = new Dictionary<string, string>();
            Dictionary<string, string> nullratiosByColumn = new Dictionary<string, string>();
            paramsByColumn.Add(columnName, param);
            nullratiosByColumn.Add(columnName, "");

            ColumnData cold = new ColumnData(paramsByColumn, nullratiosByColumn);

            //1
            Dictionary<string, string> genedCols = cold.GenerateNext();
            MessageBox.Show(genedCols[columnName]);

            MySQLTableHelper.SetNext();

            //2
            Dictionary<string, string> genedCols2 = cold.GenerateNext();
            MessageBox.Show(genedCols2[columnName]);

            MySQLTableHelper.SetNext();
        }
Пример #41
0
        public void RunThread()
        {
            List <string> list = new List <string>();

            #region TechSOFT Banner
            list.Add("");
            list.Add("");
            list.Add("\t\t**********************************************");
            list.Add("\t\t*          ASTRA Pro Release 18.0            *");
            list.Add("\t\t*      TechSOFT Engineering Services         *");
            list.Add("\t\t*                                            *");
            list.Add("\t\t*           DESIGN OF RCC COLUMN             *");
            list.Add("\t\t*                                            *");
            list.Add("\t\t**********************************************");
            list.Add("\t\t----------------------------------------------");
            list.Add("\t\tTHIS RESULT CREATED ON " + System.DateTime.Now.ToString("dd.MM.yyyy  AT HH:mm:ss") + " ");
            list.Add("\t\t----------------------------------------------");
            list.Add("");

            #endregion



            int c    = 0;
            int step = 1;


            string ColumnNos = "";

            Design_Summary = new List <string>();
            //int c = 0;
            for (int i = 0; i < dgv_columns.RowCount; i++)
            {
                try
                {
                    c = 0;
                    ColumnData cd = new ColumnData();
                    cd.IsSelect = (bool)dgv_columns[c++, i].Value;
                    if (cd.IsSelect)
                    {
                        Set_Grid_Color(i);

                        cd.ColumnNos = dgv_columns[c++, i].Value.ToString();
                        if (MessageBox.Show("Process Design Column " + cd.ColumnNos + " \n\nDo you want to continue ?", "ASTRA", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            break;
                        }
                        cd.Continuous_ColumnMembers = dgv_columns[c, i].Value.ToString(); c++;
                        cd.Breadth      = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Depth        = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Main_Bar_dia = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Bar_Nos      = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Tie_Bar_Dia  = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Pu           = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Mux          = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;
                        cd.Muy          = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0); c++;



                        //col_design.ColumnNos = All_Column_Data[i].Continuous_ColumnMembers;

                        col_design.Beam_Nos = cd.Continuous_ColumnMembers;
                        col_design.D        = cd.Depth * 1000;
                        col_design.b        = cd.Breadth * 1000;
                        col_design.bar_dia  = cd.Main_Bar_dia;
                        col_design.bar_nos  = cd.Bar_Nos;
                        col_design.tie_dia  = cd.Tie_Bar_Dia;
                        col_design.Pu       = cd.Pu;
                        col_design.Mux      = cd.Mux;
                        col_design.Muy      = cd.Muy;

                        //col_design.All_Column_Data.Clear();
                        col_design.Col_Data = cd;

                        if (Design_Summary == null)
                        {
                            Design_Summary = new List <string>();
                        }

                        Design_Summary.Add(string.Format(""));
                        list.AddRange(col_design.Design_Program_Loop(i + 1).ToArray());

                        Design_Summary.Add(string.Format("------------------------------------------------"));
                        Design_Summary.Add(string.Format("COLUMN = {0}", cd.ColumnNos));
                        Design_Summary.Add(string.Format("CONTINUOUS MEMBERS = {0}", cd.Continuous_ColumnMembers));
                        Design_Summary.AddRange(col_design.Design_Summary.ToArray());
                        Design_Summary.Add(string.Format("------------------------------------------------"));



                        Set_Grid_Color(i, true, col_design.IS_DESIGN_OK);

                        dgv_columns[c, i].Value = col_design.IS_DESIGN_OK ? " OK " : "NOT OK";

                        Add_Column_BOQ(col_design.BOQ);
                    }
                }
                catch (Exception exx) { }
            }



            #region End of Report
            list.Add("");
            list.Add("---------------------------------------------------------------------------");
            list.Add("---------------------       END OF REPORT        --------------------------");
            list.Add("---------------------------------------------------------------------------");
            #endregion End of Report

            Save_Data();

            File.WriteAllLines(col_design.Report_File, list.ToArray());


            string des_sum = Path.Combine(Path.GetDirectoryName(col_design.Get_Report_File(1)), "COLUMN_DESIGN_SUMMARY.TXT");
            File.WriteAllLines(des_sum, Design_Summary.ToArray());



            MessageBox.Show(this, "Report file created in file " + col_design.Report_File);

            frmASTRAReport fap = new frmASTRAReport(col_design.Report_File);
            fap.Owner = this;
            fap.ShowDialog();
        }
Пример #42
0
        public void RunThread()
        {
            List <string> list = new List <string>();

            #region TechSOFT Banner
            list.Add("");
            list.Add("");
            list.Add("\t\t**********************************************");
            list.Add("\t\t*          ASTRA Pro Release 18.0            *");
            list.Add("\t\t*      TechSOFT Engineering Services         *");
            list.Add("\t\t*                                            *");
            list.Add("\t\t*      DESIGN OF ISOLATED FOUNDATION         *");
            list.Add("\t\t*                                            *");
            list.Add("\t\t**********************************************");
            list.Add("\t\t----------------------------------------------");
            list.Add("\t\tTHIS RESULT CREATED ON " + System.DateTime.Now.ToString("dd.MM.yyyy  AT HH:mm:ss") + " ");
            list.Add("\t\t----------------------------------------------");
            list.Add("");

            #endregion



            int c    = 0;
            int step = 1;


            string ColumnNos = "";

            Design_Summary = new List <string>();
            //int c = 0;
            for (int i = 0; i < dgv_columns.RowCount; i++)
            {
                try
                {
                    c = 1;
                    ColumnData cd = new ColumnData();
                    cd.IsSelect = (bool)dgv_columns[c++, i].Value;
                    if (cd.IsSelect)
                    {
                        Set_Grid_Color(i, false, Foot_Des.IS_DESIGN_OK);

                        Foot_Des.ColumnNo = dgv_columns[c++, i].Value.ToString(); c++;
                        //Foot_Des.Continuous_ColumnMembers = dgv_columns[c++, i].Value.ToString();
                        Foot_Des.C1 = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Foot_Des.C2 = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);

                        Foot_Des.l = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Foot_Des.b = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);

                        Foot_Des.P1 = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Foot_Des.P2 = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Foot_Des.ph = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);

                        Foot_Des.bar_dia = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Foot_Des.P       = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);
                        Foot_Des.Mx      = MyStrings.StringToDouble(dgv_columns[c++, i].Value.ToString(), 0.0);

                        //Foot_Des.Mx = MyStrings.StringToDouble(dgv_columns[c, i].Value.ToString(), 0.0);

                        list.AddRange(Foot_Des.Design_Program_Loop(i + 1).ToArray());
                        Design_Summary.Add(string.Format("------------------------------------------------"));
                        //Design_Summary.Add(string.Format("FOUNDATION = {0}, ELEVATION = {1} M", Foot_Des.F));
                        Design_Summary.Add(string.Format("FOUNDATION = {0}", Foot_Des.ColumnNo));
                        //Design_Summary.Add(string.Format("CONTINUOUS MEMBERS = {0}", cd.Continuous_ColumnMembers));
                        Design_Summary.AddRange(Foot_Des.Design_Summary.ToArray());
                        Design_Summary.Add(string.Format("------------------------------------------------"));


                        #region End of Report
                        list.Add("");
                        #endregion End of Report

                        dgv_columns[c, i].Value = Foot_Des.IS_DESIGN_OK ? " OK" : "NOT OK";
                        Set_Grid_Color(i, true, Foot_Des.IS_DESIGN_OK);

                        Add_Foundation_BOQ(Foot_Des.BOQ);
                    }
                }
                catch (Exception exx) { }
            }



            #region End of Report
            list.Add("");
            list.Add("---------------------------------------------------------------------------");
            list.Add("---------------------       END OF REPORT        --------------------------");
            list.Add("---------------------------------------------------------------------------");
            #endregion End of Report



            File.WriteAllLines(Foot_Des.Report_File, list.ToArray());

            string des_sum = Path.Combine(Path.GetDirectoryName(Foot_Des.Get_Report_File(1)), "FOUNDATION_DESIGN_SUMMARY.TXT");
            File.WriteAllLines(des_sum, Design_Summary.ToArray());
        }
Пример #43
0
 public ColumnDisplayData(ColumnData data)
     : this(data, "")
 {
 }
Пример #44
0
        public void SetSettings(XmlNode node)
        {
            var     element = (XmlElement)node;
            Version version = SettingsHelper.ParseVersion(element["Version"]);

            VisualSplitCount       = SettingsHelper.ParseInt(element["VisualSplitCount"]);
            SplitPreviewCount      = SettingsHelper.ParseInt(element["SplitPreviewCount"]);
            ShowThinSeparators     = SettingsHelper.ParseBool(element["ShowThinSeparators"]);
            AlwaysShowLastSplit    = SettingsHelper.ParseBool(element["AlwaysShowLastSplit"]);
            SplitWidth             = SettingsHelper.ParseFloat(element["SplitWidth"]);
            AutomaticAbbreviations = SettingsHelper.ParseBool(element["AutomaticAbbreviations"], false);
            ShowColumnLabels       = SettingsHelper.ParseBool(element["ShowColumnLabels"], false);
            LabelsColor            = SettingsHelper.ParseColor(element["LabelsColor"], Color.FromArgb(255, 255, 255));
            OverrideTimesColor     = SettingsHelper.ParseBool(element["OverrideTimesColor"], false);
            BeforeTimesColor       = SettingsHelper.ParseColor(element["BeforeTimesColor"], Color.FromArgb(255, 255, 255));
            CurrentTimesColor      = SettingsHelper.ParseColor(element["CurrentTimesColor"], Color.FromArgb(255, 255, 255));
            AfterTimesColor        = SettingsHelper.ParseColor(element["AfterTimesColor"], Color.FromArgb(255, 255, 255));
            SplitHeight            = SettingsHelper.ParseFloat(element["SplitHeight"], 6);
            SeparatorLastSplit     = SettingsHelper.ParseBool(element["SeparatorLastSplit"], true);
            DropDecimals           = SettingsHelper.ParseBool(element["DropDecimals"], true);
            DeltasAccuracy         = SettingsHelper.ParseEnum(element["DeltasAccuracy"], TimeAccuracy.Tenths);
            OverrideDeltasColor    = SettingsHelper.ParseBool(element["OverrideDeltasColor"], false);
            DeltasColor            = SettingsHelper.ParseColor(element["DeltasColor"], Color.FromArgb(255, 255, 255));
            Display2Rows           = SettingsHelper.ParseBool(element["Display2Rows"], false);
            SplitTimesAccuracy     = SettingsHelper.ParseEnum(element["SplitTimesAccuracy"], TimeAccuracy.Seconds);
            ShowBlankSplits        = SettingsHelper.ParseBool(element["ShowBlankSplits"], true);
            LockLastSplit          = SettingsHelper.ParseBool(element["LockLastSplit"], false);
            SplitsLabel            = SettingsHelper.ParseString(element["SplitsLabel"], "Splits");

            //Title
            ShowTitle             = SettingsHelper.ParseBool(element["ShowTitle"], false);
            ShowGameName          = SettingsHelper.ParseBool(element["ShowGameName"], false);
            ShowCategoryName      = SettingsHelper.ParseBool(element["ShowCategoryName"], false);
            ShowFinishedRunsCount = SettingsHelper.ParseBool(element["ShowFinishedRunsCount"], false);
            ShowAttemptCount      = SettingsHelper.ParseBool(element["ShowAttemptCount"], false);
            DisplayGameIcon       = SettingsHelper.ParseBool(element["DisplayGameIcon"], false);
            CenterTitle           = SettingsHelper.ParseBool(element["CenterTitle"], false);
            ShowRegion            = SettingsHelper.ParseBool(element["ShowRegion"], false);
            ShowPlatform          = SettingsHelper.ParseBool(element["ShowPlatform"], false);
            ShowVariables         = SettingsHelper.ParseBool(element["ShowVariables"], false);

            if (version >= new Version(1, 5))
            {
                var columnsElement = element["Columns"];
                ColumnsList.Clear();
                foreach (var child in columnsElement.ChildNodes)
                {
                    var columnData = ColumnData.FromXml((XmlNode)child);
                    ColumnsList.Add(new ColumnSettings(CurrentState, columnData.Name, ColumnsList)
                    {
                        Data = columnData
                    });
                }
            }
            else
            {
                ColumnsList.Clear();
                var comparison = SettingsHelper.ParseString(element["Comparison"]);
                if (SettingsHelper.ParseBool(element["ShowSplitTimes"]))
                {
                    ColumnsList.Add(new ColumnSettings(CurrentState, "+/-", ColumnsList)
                    {
                        Data = new ColumnData("+/-", ColumnType.Delta, comparison, "Current Timing Method")
                    });
                    ColumnsList.Add(new ColumnSettings(CurrentState, "Time", ColumnsList)
                    {
                        Data = new ColumnData("Time", ColumnType.SplitTime, comparison, "Current Timing Method")
                    });
                }
                else
                {
                    ColumnsList.Add(new ColumnSettings(CurrentState, "+/-", ColumnsList)
                    {
                        Data = new ColumnData("+/-", ColumnType.DeltaorSplitTime, comparison, "Current Timing Method")
                    });
                }
            }
            if (version >= new Version(1, 3))
            {
                BeforeNamesColor  = SettingsHelper.ParseColor(element["BeforeNamesColor"]);
                CurrentNamesColor = SettingsHelper.ParseColor(element["CurrentNamesColor"]);
                AfterNamesColor   = SettingsHelper.ParseColor(element["AfterNamesColor"]);
                OverrideTextColor = SettingsHelper.ParseBool(element["OverrideTextColor"]);
            }
            else
            {
                if (version >= new Version(1, 2))
                {
                    BeforeNamesColor = CurrentNamesColor = AfterNamesColor = SettingsHelper.ParseColor(element["SplitNamesColor"]);
                }
                else
                {
                    BeforeNamesColor  = Color.FromArgb(255, 255, 255);
                    CurrentNamesColor = Color.FromArgb(255, 255, 255);
                    AfterNamesColor   = Color.FromArgb(255, 255, 255);
                }
                OverrideTextColor = !SettingsHelper.ParseBool(element["UseTextColor"], true);
            }
        }
Пример #45
0
        protected void UpdateColumn(LiveSplitState state, SimpleLabel label, ColumnData data)
        {
            var comparison = data.Comparison == "Current Comparison" ? state.CurrentComparison : data.Comparison;
            if (!state.Run.Comparisons.Contains(comparison))
                comparison = state.CurrentComparison;

            var timingMethod = state.CurrentTimingMethod;
            if (data.TimingMethod == "Real Time")
                timingMethod = TimingMethod.RealTime;
            else if (data.TimingMethod == "Game Time")
                timingMethod = TimingMethod.GameTime;

            var type = data.Type;

            var splitIndex = state.Run.IndexOf(Split);
            if (splitIndex < state.CurrentSplitIndex)
            {
                if (type == ColumnType.SplitTime || type == ColumnType.SegmentTime)
                {
                    label.ForeColor = Settings.OverrideTimesColor ? Settings.BeforeTimesColor : state.LayoutSettings.TextColor;

                    if (type == ColumnType.SplitTime)
                        label.Text = TimeFormatter.Format(Split.SplitTime[timingMethod]);

                    else //SegmentTime
                    {
                        var segmentTime = LiveSplitStateHelper.GetPreviousSegmentTime(state, splitIndex, comparison, timingMethod);
                        label.Text = TimeFormatter.Format(segmentTime);
                    }
                }
                
                if (type == ColumnType.DeltaorSplitTime || type == ColumnType.Delta)
                {
                    var deltaTime = Split.SplitTime[timingMethod] - Split.Comparisons[comparison][timingMethod];
                    var color = LiveSplitStateHelper.GetSplitColor(state, deltaTime, splitIndex, true, true, comparison, timingMethod);
                    if (color == null)
                        color = Settings.OverrideTimesColor ? Settings.BeforeTimesColor : state.LayoutSettings.TextColor;
                    label.ForeColor = color.Value;

                    if (type == ColumnType.DeltaorSplitTime)
                    {
                        if (deltaTime != null)
                            label.Text = DeltaTimeFormatter.Format(deltaTime);
                        else
                            label.Text = TimeFormatter.Format(Split.SplitTime[timingMethod]);
                    }

                    else if (type == ColumnType.Delta)
                        label.Text = DeltaTimeFormatter.Format(deltaTime);   
                }

                else if (type == ColumnType.SegmentDeltaorSegmentTime || type == ColumnType.SegmentDelta)
                {
                    var segmentDelta = LiveSplitStateHelper.GetPreviousSegmentDelta(state, splitIndex, comparison, timingMethod);
                    var color = LiveSplitStateHelper.GetSplitColor(state, segmentDelta, splitIndex, false, true, comparison, timingMethod);
                    if (color == null)
                        color = Settings.OverrideTimesColor ? Settings.BeforeTimesColor : state.LayoutSettings.TextColor;
                    label.ForeColor = color.Value;

                    if (type == ColumnType.SegmentDeltaorSegmentTime)
                    {
                        if (segmentDelta != null)
                            label.Text = DeltaTimeFormatter.Format(segmentDelta);
                        else
                            label.Text = TimeFormatter.Format(Split.SplitTime[timingMethod]);
                    }

                    else if (type == ColumnType.SegmentDelta)
                        label.Text = DeltaTimeFormatter.Format(segmentDelta);
                }               
            }
            else
            {
                if (type == ColumnType.SplitTime || type == ColumnType.SegmentTime || type == ColumnType.DeltaorSplitTime || type == ColumnType.SegmentDeltaorSegmentTime)
                {
                    if (Split == state.CurrentSplit)
                        label.ForeColor = Settings.OverrideTimesColor ? Settings.CurrentTimesColor : state.LayoutSettings.TextColor;
                    else
                        label.ForeColor = Settings.OverrideTimesColor ? Settings.AfterTimesColor : state.LayoutSettings.TextColor;

                    if (type == ColumnType.SplitTime || type == ColumnType.DeltaorSplitTime)
                        label.Text = TimeFormatter.Format(Split.Comparisons[comparison][timingMethod]);

                    else //SegmentTime or SegmentTimeorSegmentDeltaTime
                    {
                        var previousTime = splitIndex > 0 ? state.Run[splitIndex - 1].Comparisons[comparison][timingMethod] : TimeSpan.Zero;
                        label.Text = TimeFormatter.Format(Split.Comparisons[comparison][timingMethod] - previousTime);
                    }
                }

                //Live Delta
                var bestDelta = LiveSplitStateHelper.CheckLiveDelta(state, true, comparison, timingMethod);
                if (bestDelta != null && Split == state.CurrentSplit &&
                    (type == ColumnType.DeltaorSplitTime || type == ColumnType.Delta || type == ColumnType.SegmentDeltaorSegmentTime || type == ColumnType.SegmentDelta))
                {
                    if (type == ColumnType.DeltaorSplitTime || type == ColumnType.Delta)
                        label.Text = DeltaTimeFormatter.Format(bestDelta);

                    else if (type == ColumnType.SegmentDeltaorSegmentTime || type == ColumnType.SegmentDelta)
                        label.Text = DeltaTimeFormatter.Format(LiveSplitStateHelper.GetLiveSegmentDelta(state, splitIndex, comparison, timingMethod));

                    label.ForeColor = Settings.OverrideDeltasColor ? Settings.DeltasColor : state.LayoutSettings.TextColor;
                }
                else if (type == ColumnType.Delta || type == ColumnType.SegmentDelta)
                    label.Text = "";
            }
        }
Пример #46
0
            private void CalcColumnWidthes(MeasureData[] data, double widthConstrait)
            {
                var columnDefinitions = PanelContainer.ColumnDefinitions.ToArray();

                if (data.Length <= 0)
                {
                    return;
                }

                var columnData = new ColumnData[data[data.Length - 1].ColumnIndex + 1];

                for (int i = 0; i < columnData.Length; i++)
                {
                    columnData[i] = i < columnDefinitions.Length ?
                                    new ColumnData(columnDefinitions[i]) : new ColumnData();
                }

                foreach (MeasureData child in data
                         .Where(child => child.ColumnIndex >= columnDefinitions.Length))
                {
                    columnData[child.ColumnIndex].Minimum =
                        Math.Max(child.DesiredSize.Width, columnData[child.ColumnIndex].Minimum);
                }

                bool stretchAuto = !columnData.Any(column => column.Value.IsStar) &&
                                   PanelContainer.HorizontalContentAlignment == HorizontalAlignment.Stretch;

                foreach (ColumnData column in columnData)
                {
                    if (column.Value.IsAuto && stretchAuto)
                    {
                        column.Value = new GridLength(1, GridUnitType.Star);
                    }
                    else if (!column.IsStar)
                    {
                        column.ActualValue = column.IsAuto ? column.Minimum :
                                             Math.Min(column.Maximum, Math.Max(column.Minimum, column.Value.Value));
                        column.Final = true;
                    }
                }

                DistributeStarWidth(columnData, widthConstrait);

                double extraSpace       = Math.Max(0, widthConstrait - columnData.Sum(column => column.ActualValue));
                double accumulatedWidth = 0;

                foreach (ColumnData column in columnData)
                {
                    column.Offset = accumulatedWidth;
                    switch (PanelContainer.HorizontalContentAlignment)
                    {
                    case HorizontalAlignment.Center:
                        column.Offset += extraSpace / 2;
                        break;

                    case HorizontalAlignment.Right:
                        column.Offset += extraSpace;
                        break;
                    }
                    accumulatedWidth += column.ActualValue;
                }

                for (var i = 0; i < data.Length; i++)
                {
                    var rect = data[i].Rect;
                    rect.X     = columnData[data[i].ColumnIndex].Offset;
                    rect.Width = data[i].DesiredSize.Width;

                    switch (data[i].HorizontalAlignment)
                    {
                    case HorizontalAlignment.Center:
                        rect.X += (columnData[data[i].ColumnIndex].ActualValue - rect.Width) / 2;
                        break;

                    case HorizontalAlignment.Right:
                        rect.X += columnData[data[i].ColumnIndex].ActualValue - rect.Width;
                        break;

                    case HorizontalAlignment.Stretch:
                        rect.Width = columnData[data[i].ColumnIndex].ActualValue;
                        break;
                    }

                    data[i].Rect = rect;
                }
            }