Пример #1
1
 public static SqlBinary IconTile(SqlBinary image, SqlInt32 zoom, SqlDouble Lon, SqlDouble Lat, SqlInt32 xTile, SqlInt32 yTile, SqlDouble scale)
 {
     SqlBinary result = null;
     using (Icon2TileRendering paster = new Icon2TileRendering())
     {
         using (MemoryStream ms = new MemoryStream())
         {
             ms.Write(image.Value, 0, image.Length);
             SetBeginPosition(ms);
             paster.PasteFromStreamScaledImageToTile((int)zoom, (double)Lon, (double)Lat, (int)xTile, (int)yTile, (double)scale, ms);
             result = paster.GetBytes();
         }
     }
     return result;
 }
 public static SqlDouble DetermineCompressionRate(SqlBinary originalEncodedValue, SqlString decodedValue)
 {
     int decodedValueLength = decodedValue.ToString().Length;
     int encodedValueLength = originalEncodedValue.Value.Length;
     double rate = (double)encodedValueLength / (double)decodedValueLength;
     return new SqlDouble(rate);
 }
Пример #3
0
        public static void FailConvertToBoolean(byte[] data)
        {
            var type = PrimitiveTypes.Binary();
            var binary = new SqlBinary(data);

            Assert.Throws<InvalidCastException>(() => type.CastTo(binary, PrimitiveTypes.Boolean()));
        }
Пример #4
0
 public static IEnumerable DetRefPosCov(SqlInt64 refPosStart, SqlBinary refSeq, SqlInt64 sreadPosStart, SqlInt64 sreadPosEnd,
     SqlString misMNuc, SqlString indel)
 {
     ArrayList result = new ArrayList();
     // The following contains plus one because of length-determination:
     int sreadSeqLength = (int)(sreadPosEnd.Value - sreadPosStart.Value) + 1;
     List<long> deletionPositions = DetermineDelPositions(sreadPosStart.Value, indel.Value);
     long actRefPos = sreadPosStart.Value;
     int refIndex = 0;
     while (refIndex < sreadSeqLength)
     {
         if (deletionPositions.Contains(actRefPos))
         {
             result.Add(new RefPosCoverage
             {
                 refPos = actRefPos,
                 coverage = 0
             });
         }
         else
         {
             result.Add(new RefPosCoverage
             {
                 refPos = actRefPos,
                 coverage = 1
             });
         }
         refIndex++;
         actRefPos++;
     }
     return result;
 }
Пример #5
0
 public static SqlBinary MergePHkeys(SqlBinary oldPHkeys, SqlInt16 newSnap, SqlInt32 newPHkey)
 {
     SqlIntArray keyArray = new SqlIntArray(oldPHkeys);
     int[] keys = keyArray.ToArray();
     keys[(short) newSnap] = (int) newPHkey;
     return SqlIntArray.FromArray(keys).ToSqlBuffer();
 }
Пример #6
0
 public static SqlBinary MergeSlots(SqlBinary oldSlots, SqlInt16 newSnap, SqlInt16 newSlot)
 {
     //short[] slots = oldSlots.ToArray();
     SqlSmallIntArray slotArray = new SqlSmallIntArray(oldSlots);
     short[] slots = slotArray.ToArray();
     slots[(short) newSnap] = (short) newSlot;
     return SqlSmallIntArray.FromArray(slots).ToSqlBuffer();
 }
Пример #7
0
        public void GetRawValue()
        {
            SqlType type = new SqlBinary(data, 10, ParameterDirection.Input);
            Assert.AreEqual(data, type.GetRawValue());

            type = new SqlBinary(null, 10, ParameterDirection.Input);
            Assert.Null(type.GetRawValue());
        }
Пример #8
0
 public static SqlBinary binFromBase64CLR(SqlString toDecode)
 {
     SqlBinary result = null;
     if (!toDecode.IsNull) {
         byte[] DecodedBytes = System.Convert.FromBase64String(toDecode.ToString());
         result = new SqlBinary(DecodedBytes);
     }
     return result;
 }
Пример #9
0
 public static SqlString binToBase64CLR(SqlBinary toEncode)
 {
     SqlString returnValue = null;
       if (!toEncode.IsNull) {
      byte[] toEncodeAsBytes = toEncode.Value;
      returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
       }
       return returnValue;
 }
Пример #10
0
    public static void AddToFilterFillRow(Object obj, out SqlInt16 snap, out SqlInt32 outPHKey, out SqlBinary finalFilter, out SqlInt32 hashFunctions, out SqlInt32 expectedCap)
    {
        object[] row = (object[])obj;
            finalFilter = new SqlBinary((byte[])row[2]);
            snap = new SqlInt16((short) row[0]);// (SqlInt16)row[10];
            outPHKey = new SqlInt32((int) row[1]);

            hashFunctions = new SqlInt32((int)row[3]);
            expectedCap = new SqlInt32((int)row[4]);
    }
 public static IEnumerable ObtainMismatchAndInDelBin(SqlBinary refSeq, SqlInt64 refPosStart, SqlBinary sreadSeq, SqlInt64 sreadPosStart,
     SqlString insPos, SqlString delPos)
 {
     Dictionary<int, int> insOffsetLen = DetermineOffsetLen(insPos);
     Dictionary<int, int> delOffsetLen = DetermineOffsetLen(delPos);
     string decodedRelatedRefSeqBlock = BinaryNucleotideCodecUtil.DetermineDecodedRelatedRefSeqBlock(sreadSeq.Length, sreadPosStart.Value,
         refPosStart.Value, refSeq.Value);
     string decodedSreadSeq = BinaryNucleotideCodecUtil.DetermineDecodedSeq(sreadSeq.Value);
     return DetermineMismatchInDelRow(insOffsetLen, delOffsetLen, decodedRelatedRefSeqBlock, decodedSreadSeq);
 }
        private static bool IsCompareToValue(SqlBinary bo) {
            if (IsComparison(bo.NodeType)
                && bo.Left.NodeType == SqlNodeType.MethodCall
                && bo.Right.NodeType == SqlNodeType.Value) {
                SqlMethodCall call = (SqlMethodCall)bo.Left;
                return IsCompareToMethod(call) || IsCompareMethod(call);
            }

            return false;
        }
Пример #13
0
 public void Accumulate(SqlBinary Value)
 {
     // ��������� ����� ������ � ����������
     using (MemoryStream ms = new MemoryStream())
     {
         ms.Write(Value.Value, 0, Value.Length);
         ms.Seek(0, SeekOrigin.Begin);
         ms.Position = 0;
         PasteFromStreamImageToTile( ms);
     }
 }
Пример #14
0
    public static SqlBoolean SaveToFolderByZoomXY8bpp(SqlBinary image, SqlString rootFolderPath, SqlInt32 Zoom, SqlInt32 X, SqlInt32 Y)
    {
        SqlBoolean result = false;
          using (MemoryStream ms = new MemoryStream())
          {
              ms.Write(image.Value, 0, image.Length);
              SetBeginPosition(ms);

              using (var bitmap = new Bitmap(ms))
              {
                  if (bitmap == null) throw new Exception("Не удалось инициализировать объект Bitmap из Stream");
                  var quantizer = new WuQuantizer();
                  if (quantizer == null) throw new Exception("Не удалось инициализировать объект WuQuantizer");
                  using (var quantized = quantizer.QuantizeImage(bitmap))
                  {
                      if (quantized == null) throw new Exception("Не удалось инициализировать объект Image с помощью экземпляра WuQuantizer");
                      //try
                      //{
                      string zoomFolder = string.Format(@"{0}/{1}", rootFolderPath, Zoom);
                      CheckFolderExistsCreate(zoomFolder);
                      string xFolder = string.Format(@"{0}/{1}", zoomFolder, X);
                      CheckFolderExistsCreate(xFolder);
                      quantized.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);

                      //using (MemoryStream msquant = new MemoryStream())
                      //{
                      //    quantized.Save(msquant, ImageFormat.Png);
                      //    SetBeginPosition(msquant);
                      //    using (Icon2TileRendering renderer = new Icon2TileRendering(msquant))
                      //    {
                      //        renderer.SaveToPngFile((string) rootFolderPath, Zoom.ToString(), X.ToString(), Y.ToString());
                      //        result = true;
                      //    }
                      //}
                      //Image i2 = new Bitmap(quantized);
                      //CheckFolder((string)rootFolderPath, Zoom.ToString(), X.ToString(), Y.ToString())
                      //;
                      //i2.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);

                          //var img = ImageToStreamToImage(quantized);
                          //img.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);
                          //quantized.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);
                      //}
                      //catch (System.Exception ex)
                      //{
                      //    throw new Exception(string.Format("SaveToFolderByZoomXY8bpp {0}", ex.Message));
                      //}

                  }
              }
          }
          // Put your code here
        return result;
    }
        internal override SqlExpression VisitBinaryOperator(SqlBinary bo) {
            if (bo.NodeType.IsBinaryOperatorExpectingPredicateOperands()) {
                bo.Left = this.VisitPredicate(bo.Left);
                bo.Right = this.VisitPredicate(bo.Right);
            } else {
                bo.Left = this.VisitExpression(bo.Left);
                bo.Right = this.VisitExpression(bo.Right);
            }

            return bo;
        }
Пример #16
0
 public void Accumulate(SqlBinary Value, SqlInt32 PixelX, SqlInt32 PixelY)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         ms.Write(Value.Value, 0, Value.Length);
         ms.Seek(0, SeekOrigin.Begin);
         ms.Position = 0;
         //iconizer.PasteFromStreamImageToTileByXY((int)PixelX, (int)PixelY, ms);
         PasteFromStreamImageToTileByXY((int)PixelX, (int)PixelY, ms);
     }
 }
Пример #17
0
        public static SqlGeometry FromWkb(SqlBinary source)
        {
            if (source.IsNull)
                return SqlGeometry.Null;

            SqlGeometry geometry;
            if (!SqlGeometry.TryParse(source.ToByteArray(), out geometry))
                return SqlGeometry.Null;

            return geometry;
        }
Пример #18
0
 public static void FileWrite(string FileName, SqlBinary Text)
 {
     BinaryWriter binaryWriter = new BinaryWriter(File.Create(FileName));
     try
     {
         binaryWriter.Write(Text.Value);
     }
     finally
     {
         binaryWriter.Close();
     }
 }
Пример #19
0
        public void CreateMetaData()
        {
            Assert.Throws<TypeCannotBeUsedAsAClrTypeException>(() => SqlBinary.GetTypeHandler().CreateMetaData(null));

            SqlTypeHandler col = new SqlBinary(data, null, ParameterDirection.Input);
            Assert.Throws<TypePropertiesMustBeSetExplicitlyException>(() => col.CreateMetaData("Test"));

            col = new SqlBinary(data, 10, ParameterDirection.Input);
            var meta = col.CreateMetaData("Test");
            Assert.AreEqual(SqlDbType.Binary, meta.SqlDbType);
            Assert.AreEqual(10, meta.MaxLength);
            Assert.AreEqual("Test", meta.Name);
        }
Пример #20
0
        public static void ConvertToBoolean(byte[] data, bool? expectedResult)
        {
            var type = PrimitiveTypes.Binary();
            var binary = new SqlBinary(data);

            var result = type.CastTo(binary, PrimitiveTypes.Boolean());

            Assert.IsNotNull(result);
            Assert.IsInstanceOf<SqlBoolean>(result);

            var boolean = (SqlBoolean) result;

            Assert.AreEqual(expectedResult, (bool?)boolean);
        }
Пример #21
0
 internal override SqlExpression VisitBinaryOperator(SqlBinary bo) {
     base.VisitBinaryOperator(bo);
     if (bo.NodeType.IsComparisonOperator() 
         && bo.Left.ClrType!=typeof(bool) && bo.Right.ClrType!=typeof(bool)) {
         // Strip unnecessary CONVERT calls. 
         if (bo.Left.NodeType == SqlNodeType.Convert) {
             var conv = (SqlUnary)bo.Left;
             if (CanDbConvert(conv.Operand.ClrType, bo.Right.ClrType) 
                 && conv.Operand.SqlType.ComparePrecedenceTo(bo.Right.SqlType) != 1) {
                 return VisitBinaryOperator(new SqlBinary(bo.NodeType, bo.ClrType, bo.SqlType, conv.Operand, bo.Right));
             }
         }
         if (bo.Right.NodeType == SqlNodeType.Convert) {
             var conv = (SqlUnary)bo.Right;
             if (CanDbConvert(conv.Operand.ClrType, bo.Left.ClrType)
                 && conv.Operand.SqlType.ComparePrecedenceTo(bo.Left.SqlType) != 1) {
                 return VisitBinaryOperator(new SqlBinary(bo.NodeType, bo.ClrType, bo.SqlType, bo.Left, conv.Operand));
             }
         }
     }
     if (bo.Right != null && bo.NodeType != SqlNodeType.Concat) {
         SqlExpression left = bo.Left;
         SqlExpression right = bo.Right;
         this.CoerceBinaryArgs(ref left, ref right);
         if (bo.Left != left || bo.Right != right) {
             bo = sql.Binary(bo.NodeType, left, right);
         }
         bo.SetSqlType(typeProvider.PredictTypeForBinary(bo.NodeType, left.SqlType, right.SqlType));
     }
     if (bo.NodeType.IsComparisonOperator()) {
         // When comparing a unicode value against a non-unicode column, 
         // we want retype the parameter as non-unicode.
         Func<SqlExpression, SqlExpression, bool> needsRetype = 
             (expr, val) => (val.NodeType == SqlNodeType.Value || val.NodeType == SqlNodeType.ClientParameter) && 
                            !(expr.NodeType == SqlNodeType.Value || expr.NodeType == SqlNodeType.ClientParameter) &&
                            val.SqlType.IsUnicodeType && !expr.SqlType.IsUnicodeType;
         SqlSimpleTypeExpression valueToRetype = null;
         if (needsRetype(bo.Left, bo.Right)) {
             valueToRetype = (SqlSimpleTypeExpression)bo.Right;
         } else if (needsRetype(bo.Right, bo.Left)) {
             valueToRetype = (SqlSimpleTypeExpression)bo.Left;
         }
         if(valueToRetype != null) {
             valueToRetype.SetSqlType(valueToRetype.SqlType.GetNonUnicodeEquivalent());
         }
     }
     return bo;
 }
Пример #22
0
    public static SqlBoolean SaveToFolderByZoomXY(SqlBinary image, SqlString rootFolderPath, SqlInt32 Zoom, SqlInt32 X, SqlInt32 Y)
    {
        SqlBoolean result = false;
        using (MemoryStream ms = new MemoryStream())
        {
            ms.Write(image.Value, 0, image.Length);
            SetBeginPosition(ms);

            using (Icon2TileRendering bitmap = new Icon2TileRendering(ms))
            {
                bitmap.SaveToPngFile((string)rootFolderPath, Zoom.ToString(), X.ToString(), Y.ToString());
                result = true;
            }
        }
        // Put your code here
        return result;
    }
Пример #23
0
    public static SqlBoolean SaveToFile(SqlBinary image, SqlString filePath, SqlString mimeType)
    {
        SqlBoolean result = false;
        using (MemoryStream ms = new MemoryStream())
        {
            ms.Write(image.Value, 0, image.Length);
            SetBeginPosition(ms);

            using (Icon2TileRendering bitmap = new Icon2TileRendering(ms))
            {
                 bitmap.SaveToFile((string)filePath,(string)mimeType);
                 result = true;
            }
        }
        // Put your code here
        return result;
    }
Пример #24
0
 internal override SqlExpression VisitBinaryOperator(SqlBinary bo)
 {
     if (bo.NodeType == SqlNodeType.EQ || bo.NodeType == SqlNodeType.NE ||
         bo.NodeType == SqlNodeType.EQ2V || bo.NodeType == SqlNodeType.NE2V ||
         bo.NodeType == SqlNodeType.GT || bo.NodeType == SqlNodeType.GE ||
         bo.NodeType == SqlNodeType.LT || bo.NodeType == SqlNodeType.LE)
     {
         if (!bo.Left.SqlType.SupportsComparison ||
             !bo.Right.SqlType.SupportsComparison)
         {
             throw Error.UnhandledStringTypeComparison();
         }
     }
     bo.Left  = this.VisitExpression(bo.Left);
     bo.Right = this.VisitExpression(bo.Right);
     return(bo);
 }
Пример #25
0
    public static SqlBoolean SaveToFile(SqlBinary image, SqlString filePath, SqlString mimeType)
    {
        SqlBoolean result = false;

        using (MemoryStream ms = new MemoryStream())
        {
            ms.Write(image.Value, 0, image.Length);
            SetBeginPosition(ms);

            using (Icon2TileRendering bitmap = new Icon2TileRendering(ms))
            {
                bitmap.SaveToFile((string)filePath, (string)mimeType);
                result = true;
            }
        }
        // Put your code here
        return(result);
    }
Пример #26
0
        public SqlBinaryTest()
        {
            byte[] b1 = new byte[2];
            byte[] b2 = new byte[3];
            byte[] b3 = new byte[2];

            b1[0] = 240;
            b1[1] = 15;
            b2[0] = 10;
            b2[1] = 10;
            b2[2] = 10;
            b3[0] = 240;
            b3[1] = 15;

            _test1 = new SqlBinary(b1);
            _test2 = new SqlBinary(b2);
            _test3 = new SqlBinary(b3);
        }
Пример #27
0
        internal override SqlSelect VisitSelect(SqlSelect select)
        {
            // DevDiv 179191
            if (@select.Where != null && @select.Where.NodeType == SqlNodeType.Coalesce)
            {
                SqlBinary bin = (SqlBinary)@select.Where;
                if (bin.Right.NodeType == SqlNodeType.Value)
                {
                    SqlValue value = (SqlValue)bin.Right;
                    if (value.Value != null && value.Value.GetType() == typeof(bool) && (bool)value.Value == false)
                    {
                        @select.Where = bin.Left;
                    }
                }
            }

            return(base.VisitSelect(@select));
        }
Пример #28
0
    public static SqlString ExtractHash([SqlFacet(MaxSize = -1)] SqlBinary source)
    {
        if (!source.IsNull)
        {
            byte[] _hash = MD5.Create().ComputeHash(source.Value);

            StringBuilder stringBuilder = new StringBuilder(_hash.Length);

            for (int i = 0; i < _hash.Length; i++)
            {
                stringBuilder.Append(_hash[i]);
            }

            return(stringBuilder.ToString());
        }

        return(null);
    }
Пример #29
0
        public static SqlBinary SQLSetBinaryFlag(int index, bool flag, SqlBinary sqlBinary)
        {
#if !DEBUG
            using (SqlConnection conn
                       = new SqlConnection("context connection=true"))
#endif
            {
#if !DEBUG
                conn.Open();
#endif
                if (!sqlBinary.IsNull)
                {
                    return(new SqlBinary(SetBinaryFlag(index, flag, sqlBinary.Value)));
                }

                return(new SqlBinary(SetBinaryFlag(index, flag)));
            }
        }
Пример #30
0
        public void GetReady()
        {
            byte [] b1 = new Byte [2];
            byte [] b2 = new Byte [3];
            byte [] b3 = new Byte [2];

            b1 [0] = 240;
            b1 [1] = 15;
            b2 [0] = 10;
            b2 [1] = 10;
            b2 [2] = 10;
            b3 [0] = 240;
            b3 [1] = 15;

            Test1 = new SqlBinary(b1);
            Test2 = new SqlBinary(b2);
            Test3 = new SqlBinary(b3);
        }
Пример #31
0
    public static SqlBoolean SaveToFolderByZoomXY(SqlBinary image, SqlString rootFolderPath, SqlInt32 Zoom, SqlInt32 X, SqlInt32 Y)
    {
        SqlBoolean result = false;

        using (MemoryStream ms = new MemoryStream())
        {
            ms.Write(image.Value, 0, image.Length);
            SetBeginPosition(ms);

            using (Icon2TileRendering bitmap = new Icon2TileRendering(ms))
            {
                bitmap.SaveToPngFile((string)rootFolderPath, Zoom.ToString(), X.ToString(), Y.ToString());
                result = true;
            }
        }
        // Put your code here
        return(result);
    }
Пример #32
0
 public static byte[] SelectBinarysOriOfFive(SqlBinary sourceBinary, int FIndex)
 {
     byte[] array = new byte[]
     {
         0,
         0,
         240,
         112,
         2,
         0,
         128
     };
     if (!sourceBinary.IsNull && sourceBinary.Length >= FIndex * 7)
     {
         Array.Copy(sourceBinary.Value, (FIndex - 1) * 7, array, 0, 7);
     }
     return(array);
 }
Пример #33
0
        public void WrapBytes()
        {
            byte[] bytes = new byte[10] {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 0
            };

            SqlBinary binary = SqlBinary.WrapBytes(bytes);

            Assert.Equal(bytes[5], binary[5]);

            // verify that changing the byte[] that was passed in also changes the value in the SqlBinary instance
            bytes[5] = 0xFF;
            Assert.Equal(bytes[5], binary[5]);

            SqlBinary nullBinary = SqlBinary.WrapBytes(null);

            Assert.True(nullBinary.IsNull);
        }
Пример #34
0
        public override void Visit(SqlBinary node)
        {
            switch (node.NodeType)
            {
            case SqlNodeType.DateTimeOffsetPlusInterval:
                DateTimeAddInterval(node.Left, node.Right).AcceptVisitor(this);
                return;

            case SqlNodeType.DateTimeOffsetMinusDateTimeOffset:
                DateTimeOffsetSubtractDateTimeOffset(node.Left, node.Right).AcceptVisitor(this);
                return;

            case SqlNodeType.DateTimeOffsetMinusInterval:
                DateTimeAddInterval(node.Left, -node.Right).AcceptVisitor(this);
                return;
            }
            base.Visit(node);
        }
Пример #35
0
    private void ProcessResults(WarehouseRowVersionQueryDelegate query)
    {
        SqlBinary binary;
        bool      moreDataAvailable = true;

        this.GetProcessingParameters(out binary);
        SqlBinary waterMark = binary;

        while (moreDataAvailable)
        {
            bool result = false;
            using (WarehouseResultDatabase database = new WarehouseResultDatabase())
            {
                result = query(database, waterMark);
            }
            moreDataAvailable = result;
        }
    }
Пример #36
0
        public ReadOnlyCollection <Errorable <TreeIDPathMapping> > retrieve(SqlCommand cmd, SqlDataReader dr, int expectedCapacity = 10)
        {
            List <Errorable <TreeIDPathMapping> > mappings = new List <Errorable <TreeIDPathMapping> >();

            // Read the TreeTreeReferences:
            while (dr.Read())
            {
                SqlBinary bid = dr.GetSqlBinary(0);

                TreeID?id   = bid.IsNull ? (TreeID?)null : (TreeID?)bid.Value;
                string path = dr.GetSqlString(1).Value;

                // TODO: use a function to parse the path and return an error accordingly.
                mappings.Add(new TreeIDPathMapping(new TreeTreePath(_rootid, (CanonicalTreePath)path), id));
            }

            return(new ReadOnlyCollection <Errorable <TreeIDPathMapping> >(mappings));
        }
Пример #37
0
    public static SqlInt32 BitCount(SqlBinary b)
    {
        BitArray bit   = new BitArray(b.Value);
        int      count = 0;



        for (int i = 0; i < bit.Length; i++)
        {
            if (bit[i])
            {
                count = count + 1;
            }
        }


        return(count);
    }
        public static void CastToString(string s, SqlTypeCode typeCode, int maxSize, string expected)
        {
            var type     = new SqlBinaryType(SqlTypeCode.Binary);
            var input    = (SqlString)s;
            var destType = new SqlCharacterType(typeCode, maxSize, null);

            var bytes  = input.ToByteArray();
            var binary = new SqlBinary(bytes);

            Assert.True(type.CanCastTo(binary, destType));

            var result = type.Cast(binary, destType);

            Assert.NotNull(result);
            Assert.IsType <SqlString>(result);

            Assert.Equal(expected, (SqlString)result);
        }
        public static void CastToNumber()
        {
            var type = new SqlBinaryType(SqlTypeCode.Binary);

            var value = new SqlBinary(new byte[] { 44, 95, 122, 0 });

            Assert.True(type.CanCastTo(value, PrimitiveTypes.Numeric(22, 4)));

            var result = type.Cast(value, PrimitiveTypes.Numeric(22, 4));

            Assert.NotNull(result);
            Assert.IsType <SqlNumber>(result);

            var number = (SqlNumber)result;

            Assert.False(number.CanBeInt32);
            Assert.Equal(74445.4656, (double)number);
        }
Пример #40
0
        public static byte[] GetMaxTimestamp(List <Entity> Entities)
        {
            byte[] currentMax = new byte[8] {
                0, 0, 0, 0, 0, 0, 0, 0
            };
            SqlBinary sqlCurrentMax = new SqlBinary(currentMax);
            SqlBinary sqlCurrent;

            foreach (Entity item in Entities)
            {
                sqlCurrent = new SqlBinary(item.Version);
                if (sqlCurrentMax.CompareTo(sqlCurrent) < 0)
                {
                    sqlCurrentMax = sqlCurrent;
                }
            }
            return(sqlCurrentMax.Value);
        }
        public static void CastToDate(string s, SqlTypeCode typeCode)
        {
            var type     = new SqlBinaryType(SqlTypeCode.Binary);
            var date     = SqlDateTime.Parse(s);
            var destType = new SqlDateTimeType(typeCode);

            var bytes  = date.ToByteArray();
            var binary = new SqlBinary(bytes);

            Assert.True(type.CanCastTo(binary, destType));

            var result = type.Cast(binary, destType);

            Assert.NotNull(result);
            Assert.IsType <SqlDateTime>(result);

            Assert.Equal(date, (SqlDateTime)result);
        }
Пример #42
0
        public override object GetEntity(Uri absoluteUri,
                                         string role, Type ofObjectToReturn)
        {
            string fileName = absoluteUri.Segments[absoluteUri.Segments.Length - 1];
            string key      = String.Format("{0}#{1}#{2}", m_portDirection, m_portName, fileName);

            if (Includes.ContainsKey(key))
            {
                return(new MemoryStream(Includes[key]));
            }
            else
            {
                object content = null;

                using (SqlConnection connection = new SqlConnection(BtsConnectionHelper.MgmtDBConnectionString))
                {
                    using (SqlCommand command = new SqlCommand(String.Format("SELECT cabContent FROM [adpl_sat] join [bts_{0}port] on [applicationId] = [nApplicationID] and [nvcName] = '{1}' where luid = concat(applicationId,':','{2}')", m_portDirection, m_portName, fileName), connection))
                    {
                        connection.Open();
                        content = command.ExecuteScalar();
                    }
                }

                if (content != null)
                {
                    SqlBinary    cabContent = new SqlBinary((byte[])content);
                    MemoryStream stream     = new MemoryStream(cabContent.Value);
                    byte[]       CabBytes   = null;

                    using (CabFile file = new CabFile(stream))
                    {
                        // file.EntryExtract += CabEntryExtract;
                        file.ExtractEntries();
                        CabBytes = file.Entries[0].Data;
                        Includes.Add(key, CabBytes);
                    }
                    //default utf-8, so the files must be in utf-8
                    return(new MemoryStream(CabBytes));
                }
            }


            throw new ArgumentException(String.Format("Resource file {0} could not be found in the same application as the {1} port {2}", fileName, m_portDirection, m_portName));
        }
Пример #43
0
 public static void Load(SqlString fileName, out SqlBinary fileData, out SqlString result)
 {
     result   = new SqlString();//SqlString.Null!!!
     fileData = new SqlBinary();
     try
     {
         if (fileName.IsNull)
         {
             result = "Параметр <FileName> не может быть пустым (null)";
             return;
         }
         if (!System.IO.File.Exists(fileName.Value))
         {
             result = string.Format("Файл <{0}> не существует, или недостаточно прав для доступа к файлу", fileName.Value);
             return;
         }
         try
         {
             using (var fileStream = new System.IO.FileStream(fileName.Value, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
             {
                 int length = (int)fileStream.Length;
                 var buffer = new byte[length];
                 int count;
                 int sum = 0;
                 while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                 {
                     sum += count;  // sum is a buffer offset for next reading
                 }
                 fileData = new SqlBinary(buffer);
             }
         }
         catch (Exception e)
         {
             result = e.Message;
             return;
         }
         return;
     }
     catch (Exception e)
     {
         result = e.Message;
     }
 }
Пример #44
0
        public static bool SQLHasBinaryFlag(int index, SqlBinary sqlBinary)
        {
#if !DEBUG
            using (SqlConnection conn
                       = new SqlConnection("context connection=true"))
#endif
            {
#if !DEBUG
                conn.Open();
#endif

                if (!sqlBinary.IsNull)
                {
                    return(HasBinaryFlag(index, sqlBinary.Value));
                }

                return(false);
            }
        }
Пример #45
0
        public void Accumulate(SqlBinary value)
        {
            if (value.IsNull)
            {
                return;
            }

            var hash      = value.Value;
            var hv        = BitConverter.ToUInt64(hash, 0);
            var reg_index = hv & (m - 1);
            var bits      = hv >> p;
            var rank      = GetRank(bits);

            if (rank > _hash[reg_index])
            {
                _hash[reg_index] = rank;
            }
            // Put your code here
        }
Пример #46
0
        public static SqlBinary GetSqlBinary(this SqlDataReader rs, string columnName)
        {
            SqlBinary retVal = new SqlBinary(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });

            try
            {
                if (rs != null && rs[columnName] != DBNull.Value)
                {
                    byte[] buff = rs[columnName] as byte[];
                    retVal = new SqlBinary(buff);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Coulumn '{0}' in table '{1}' doesn't exist!\r\n{2}", columnName, rs.GetSchemaTable().TableName, ex.Message));
            }

            return(retVal);
        }
Пример #47
0
    /// <summary>
    /// FillRow method to populate the output table
    /// </summary>
    /// <param name="obj">Input AccountInfo</param>
    /// <param name="AccountType">Accoun type</param>
    /// <param name="NTAccount">NTAccount name</param>
    /// <param name="Context">Context of the account</param>
    /// <param name="SamAccountName">SAMAccount Name</param>
    /// <param name="Name">Account Name</param>
    /// <param name="DisplayName">Account Display Name</param>
    /// <param name="DistinguishedName">Account Distinguished Name</param>
    /// <param name="UserPrincipalName">User Principal Name</param>
    /// <param name="Sid">SID of the account</param>
    /// <param name="Guid">GUID of the account</param>
    /// <param name="Description">Account description</param>
    /// <param name="ParentNTAccount">Parent NTAccount name in case of group members</param>
    /// <param name="ParentSid">Parent Account SID in case of group members</param>
    public static void FillGroupMembers(object obj, out SqlString AccountType, out SqlString NTAccount, out SqlString Context, out SqlString SamAccountName, out SqlString Name, out SqlString DisplayName, out SqlString DistinguishedName,
                                        out SqlString UserPrincipalName, out SqlBinary Sid, out SqlGuid Guid, out SqlString Description, out SqlString ParentNTAccount, out SqlBinary ParentSid)
    {
        AccountInfo ai = (AccountInfo)obj;

        byte[] sidBuffer;

        AccountType       = ai.AccountType;
        NTAccount         = ai.NTAccount;
        Context           = ai.Context;
        SamAccountName    = ai.SamAccountName;
        Name              = ai.Name;;
        DisplayName       = ai.DisplayName;
        DistinguishedName = ai.DistinguishedName;
        UserPrincipalName = ai.UserPrincipalName;
        Description       = ai.Description;

        if (ai.Sid != null)
        {
            sidBuffer = new byte[ai.Sid.BinaryLength];
            ai.Sid.GetBinaryForm(sidBuffer, 0);
            Sid = new SqlBinary(sidBuffer);
        }
        else
        {
            Sid = SqlBinary.Null;
        }

        Guid = ai.Guid.HasValue ? ai.Guid.Value : SqlGuid.Null;

        ParentNTAccount = ai.ParentNTAccount == null ? SqlString.Null : ai.ParentNTAccount;

        if (ai.ParentSid != null)
        {
            sidBuffer = new byte[ai.ParentSid.BinaryLength];
            ai.ParentSid.GetBinaryForm(sidBuffer, 0);
            ParentSid = new SqlBinary(sidBuffer);
        }
        else
        {
            ParentSid = SqlBinary.Null;
        }
    }
Пример #48
0
        public void AddTest()
        {
            SqlLiteral <int> l1 = SqlDml.Literal(1);
            SqlLiteral <int> l2 = SqlDml.Literal(2);
            SqlBinary        b  = l1 + l2;

            Assert.AreEqual(b.NodeType, SqlNodeType.Add);

            b = b - ~l1;
            Assert.AreEqual(b.NodeType, SqlNodeType.Subtract);
            Assert.AreEqual(b.Right.NodeType, SqlNodeType.BitNot);

            SqlSelect s = SqlDml.Select();

            s.Columns.Add(1, "id");
            b = b / s;
            Assert.AreEqual(b.NodeType, SqlNodeType.Divide);
            Assert.AreEqual(b.Right.NodeType, SqlNodeType.SubSelect);

            SqlCast c = SqlDml.Cast(l1, SqlType.Decimal);

            Assert.AreEqual(c.NodeType, SqlNodeType.Cast);

            SqlFunctionCall l = SqlDml.CharLength(SqlDml.Literal("name"));

            b = c % l;
            Assert.AreEqual(b.NodeType, SqlNodeType.Modulo);
            Assert.AreEqual(b.Right.NodeType, SqlNodeType.FunctionCall);

            b = l1 * (-l2);
            Assert.AreEqual(b.NodeType, SqlNodeType.Multiply);
            Assert.AreEqual(b.Right.NodeType, SqlNodeType.Negate);

            SqlBatch    batch = SqlDml.Batch();
            SqlVariable v1    = SqlDml.Variable("v1", SqlType.Double);

            batch.Add(v1.Declare());
            batch.Add(SqlDml.Assign(v1, 1.0));
            s = SqlDml.Select();
            s.Columns.Add(b, "value");
            batch.Add(s);
        }
Пример #49
0
        internal override SqlExpression VisitBinaryOperator(SqlBinary bo)
        {
            //
            // Special case to allow DateTime CLR type to be passed as a paramater where
            // a SQL type TIME is expected. We do this only for the equality/inequality
            // comparisons.
            //
            switch (bo.NodeType)
            {
            case SqlNodeType.EQ:
            case SqlNodeType.EQ2V:
            case SqlNodeType.NE:
            case SqlNodeType.NE2V:
            {
                SqlDbType leftSqlDbType  = ((SqlType)(bo.Left.SqlType)).SqlDbType;
                SqlDbType rightSqlDbType = ((SqlType)(bo.Right.SqlType)).SqlDbType;
                if (leftSqlDbType == rightSqlDbType)
                {
                    break;
                }

                bool isLeftColRef  = bo.Left is SqlColumnRef;
                bool isRightColRef = bo.Right is SqlColumnRef;
                if (isLeftColRef == isRightColRef)
                {
                    break;
                }

                if (isLeftColRef && leftSqlDbType == SqlDbType.Time && bo.Right.ClrType == typeof(DateTime))
                {
                    this.timeProviderType = bo.Left.SqlType;
                }
                else if (isRightColRef && rightSqlDbType == SqlDbType.Time && bo.Left.ClrType == typeof(DateTime))
                {
                    this.timeProviderType = bo.Left.SqlType;
                }
                break;
            }
            }
            base.VisitBinaryOperator(bo);
            return(bo);
        }
Пример #50
0
 internal override SqlExpression VisitBinaryOperator(SqlBinary bo)
 {
     if (bo.NodeType == SqlNodeType.Coalesce)
     {
         sb.Append("IIF(");
         Visit(bo.Left);
         sb.Append(" IS NULL, ");
         Visit(bo.Right);
         sb.Append(", ");
         Visit(bo.Left);
         sb.Append(")");
         return(bo);
     }
     VisitWithParens(bo.Left, bo);
     sb.Append(" ");
     sb.Append(GetOperator(bo.NodeType));
     sb.Append(" ");
     VisitWithParens(bo.Right, bo);
     return(bo);
 }
 /// <summary>
 /// Replace equals and not equals:
 /// 
 /// | CASE XXX              |               CASE XXX                            CASE XXX             
 /// |   WHEN AAA THEN MMMM  | != RRRR  ===>    WHEN AAA THEN (MMMM != RRRR) ==>    WHEN AAA THEN true
 /// |   WHEN BBB THEN NNNN  |                  WHEN BBB THEN (NNNN != RRRR)        WHEN BBB THEN false
 /// |   etc.                |                  etc.                                etc.               
 /// |   ELSE OOOO           |                  ELSE (OOOO != RRRR)                 ELSE true
 /// | END                                   END                                 END
 /// 
 /// Where MMMM, NNNN and RRRR are constants. 
 /// </summary>
 internal override SqlExpression VisitBinaryOperator(SqlBinary bo) {
     switch (bo.NodeType) {
         case SqlNodeType.EQ:
         case SqlNodeType.NE:
         case SqlNodeType.EQ2V:
         case SqlNodeType.NE2V:
             if (bo.Left.NodeType == SqlNodeType.SimpleCase && 
                 bo.Right.NodeType == SqlNodeType.Value && 
                 AreCaseWhenValuesConstant((SqlSimpleCase)bo.Left)) {
                 return this.DistributeOperatorIntoCase(bo.NodeType, (SqlSimpleCase)bo.Left, bo.Right);
             } 
             else if (bo.Right.NodeType == SqlNodeType.SimpleCase && 
                 bo.Left.NodeType==SqlNodeType.Value &&
                 AreCaseWhenValuesConstant((SqlSimpleCase)bo.Right)) {
                 return this.DistributeOperatorIntoCase(bo.NodeType, (SqlSimpleCase)bo.Right, bo.Left);
             } 
             break;
     }
     return base.VisitBinaryOperator(bo);
 }
Пример #52
0
 public static IEnumerable DetNucDistr(SqlInt64 refPosStart, SqlBinary refSeq, SqlInt64 sreadPosStart, SqlInt64 sreadPosEnd,
     SqlString misMNuc, SqlString indel)
 {
     ArrayList result = new ArrayList();
     // The following is used because of triplet:
     string decodedRelatedRefSeqBlock = BinaryNucleotideCodecUtil.DetermineRefSeqBlockWithPrecAndSuccNucs(sreadPosStart.Value,
         sreadPosEnd.Value, refPosStart.Value, refSeq.Value);
     List<long> deletionPositions = DetermineDelPositions(sreadPosStart.Value, indel.Value);
     Dictionary<long, string> mutationPositions = DetermineMutPositions(sreadPosStart.Value, misMNuc.Value);
     long actRefPos = sreadPosStart.Value;
     // The refIndex is one-based because of triplet:
     int refIndex = 1;
     // The last element of decodedRelatedRefSeqBlock is not needed because it is only triplet:
     while (refIndex < decodedRelatedRefSeqBlock.Length - 1)
     {
         RecordActNucDetail(result, decodedRelatedRefSeqBlock, deletionPositions, mutationPositions, actRefPos, refIndex);
         refIndex++;
         actRefPos++;
     }
     return result;
 }
Пример #53
0
        public override void Visit(SqlBinary node)
        {
            switch (node.NodeType)
            {
            case SqlNodeType.DateTimePlusInterval:
                DateTimeAddInterval(node.Left, node.Right).AcceptVisitor(this);
                return;

            case SqlNodeType.DateTimeMinusDateTime:
                DateTimeSubtractDateTime(node.Left, node.Right).AcceptVisitor(this);
                return;

            case SqlNodeType.DateTimeMinusInterval:
                DateTimeAddInterval(node.Left, -node.Right).AcceptVisitor(this);
                return;

            default:
                base.Visit(node);
                return;
            }
        }
Пример #54
0
 // new constructor
 public FileResult(
     SqlBoolean success,
     SqlString message,
     SqlString code,
     SqlDecimal?size      = null,
     SqlDateTime?started  = null,
     SqlDateTime?finished = null,
     SqlString?filename   = null,
     SqlBinary?binary     = null
     )
 {
     this.Success  = success;
     this.Message  = message;
     this.Code     = code;
     this.Size     = size ?? 0;
     this.Started  = started ?? DateTime.Now;
     this.Finished = finished ?? DateTime.Now;
     this.FileName = filename ?? null;
     this.Binary   = binary ?? null;
     //if (finished.HasValue == false) { this.Finished = DateTime.Now; } else { this.Finished = (SqlDateTime)Finished; }
 }
Пример #55
0
        public static SqlBinary PatchImage(SqlBinary image, SqlInt32 maxSize)
        {
            SqlBinary result = new SqlBinary();

            if (image == null || image.IsNull)
            {
                return(result);
            }

            Image tmpImage = null;

            using (var ms = new MemoryStream((byte[])image))
            {
                tmpImage = new Bitmap(Image.FromStream(ms));  // http://csharp-tricks.blogspot.ch/2010/10/allgemeiner-fehler-in-gdi.html http://www.kerrywong.com/2007/11/15/understanding-a-generic-error-occurred-in-gdi-error/ https://support.microsoft.com/en-us/kb/814675
            }

            if (tmpImage == null)
            {
                return(result);
            }

            if (!tmpImage.RawFormat.Equals(ImageFormat.Jpeg))
            {
                tmpImage = _PatchImage_(tmpImage);
            }

            if (!maxSize.IsNull && maxSize != 0)
            {
                int maxOriginalSize = tmpImage.Width >= tmpImage.Height ? tmpImage.Width : tmpImage.Height;

                if (maxOriginalSize > maxSize)
                {
                    tmpImage = new Bitmap(tmpImage, GetNewImageSize(tmpImage.Size, tmpImage.Width >= tmpImage.Height ? (float)maxSize / tmpImage.Width : (float)maxSize / tmpImage.Height));
                }
            }

            result = new SqlBinary(ImageToByteArray(tmpImage));

            return(result);
        }
Пример #56
0
    public static SqlInt16 YearFromBinary(SqlBinary sql_binary)
    {
        // NULL in NULL out.
        if (sql_binary.IsNull) { return SqlInt16.Null; }

        // Get the input binary.
        var bytes = sql_binary.Value;

        // The string to be populated.
        string result;

        // Separate the year, month, and day as it's a regular date.
        var year = (bytes[0] << 4 | bytes[1] >> 4) - 1024;

        // When the binary does not have a year part:
        if (year == -1024)
        {
          return SqlInt16.Null;
        }

        return new SqlInt16((Int16)year);
    }
Пример #57
0
    public static SqlInt32 compareFilters(SqlBinary filter1, SqlBinary filter2, SqlInt32 numHashFunctions)
    {
        byte[] f1 = (byte[])filter1;
            byte[] f2 = (byte[])filter2;
            //int[] setBitsLookup = {0, 1, 1, 2, 1, 2, 6, 3, 1,};

            //int result = 0;
            //int index = 0;
            int max = (f1.Length < f2.Length) ? f1.Length : f2.Length;
            int collisions = 0;
            for (int i = 0; i < f1.Length; i++)
            {
                int andResult = f1[i] & f2[i];
                //int count;
                byte mask;
                int count;

                for (count = 0, mask = 0x80; mask != 0; mask >>=1)
                {
                    if ((andResult & mask) != 0) {
                        count++;
                    }
                }
                collisions += count;
            }

            //collisions = (collisions < (int)numHashFunctions) ? 0 : 1;
            return (SqlInt32) collisions;

        /*
            while (result == 0 && index < max)
            {
                result = (f1[index] & f2[index]);
                index++;
            }

            return (result == 0) ? 0 : 1;*/
    }
Пример #58
0
 public static SqlString DetDecRefSeq(SqlInt32 posRadius, SqlInt64 pos, SqlInt64 refPosStart, SqlBinary refSeq)
 {
     if (posRadius.Value > 128)
     {
         throw new InvalidExpressionException("The posRadius is too long. It should be less than 129.");
     }
     else if (posRadius.Value < 0)
     {
         throw new InvalidExpressionException("The posRadius should be non-negative.");
     }
     long relatedPosStartValue = pos.Value - posRadius.Value;
     long relatedPosEndValue = pos.Value + posRadius.Value - 1;
     int relatedByteSeqLength = posRadius.Value;
     // If the relatedPosStartValue is not aligned to the beginning of the given byte exactly
     // then the size of byte array should be increased:
     relatedByteSeqLength = (Math.Abs(relatedPosStartValue - refPosStart.Value) % 2 == 1)
         ? (relatedByteSeqLength + 1) : relatedByteSeqLength;
     string decodedRelatedRefSeqBlock = BinaryNucleotideCodecUtil.DetermineDecodedRelatedRefSeqBlock(relatedByteSeqLength,
         relatedPosStartValue, refPosStart.Value, refSeq.Value);
     decodedRelatedRefSeqBlock = BinaryNucleotideCodecUtil.ComplementSucceedingNuc(relatedPosEndValue, refPosStart.Value,
         refSeq.Value, decodedRelatedRefSeqBlock);
     return new SqlString(decodedRelatedRefSeqBlock);
 }
Пример #59
0
 internal override SqlExpression VisitBinaryOperator(SqlBinary bo) {
     switch (bo.NodeType) {
         case SqlNodeType.Coalesce:
             sb.Append("COALESCE(");
             this.Visit(bo.Left);
             sb.Append(",");
             this.Visit(bo.Right);
             sb.Append(")");
             break;
         default:
             this.VisitWithParens(bo.Left, bo);
             sb.Append(" ");
             sb.Append(GetOperator(bo.NodeType));
             sb.Append(" ");
             this.VisitWithParens(bo.Right, bo);
             break;
     }
     return bo;
 }
Пример #60
0
        public override ISqlObject CastTo(ISqlObject value, SqlType destType)
        {
            var n = (SqlNumber) value;
            var sqlType = destType.TypeCode;
            ISqlObject casted;

            switch (sqlType) {
                case (SqlTypeCode.Bit):
                case (SqlTypeCode.Boolean):
                    casted = new SqlBoolean(n.ToBoolean());
                    break;
                case (SqlTypeCode.TinyInt):
                case (SqlTypeCode.SmallInt):
                case (SqlTypeCode.Integer):
                    casted = new SqlNumber(n.ToInt32());
                    break;
                case (SqlTypeCode.BigInt):
                    casted = new SqlNumber(n.ToInt64());
                    break;
                case (SqlTypeCode.Float):
                case (SqlTypeCode.Real):
                case (SqlTypeCode.Double):
                    double d;
                    if (n.State == NumericState.NotANumber) {
                        casted = new SqlNumber(Double.NaN);
                    } else if (n.State == NumericState.PositiveInfinity) {
                        casted = new SqlNumber(Double.PositiveInfinity);
                    } else if (n.State == NumericState.NegativeInfinity) {
                        casted = new SqlNumber(Double.NegativeInfinity);
                    } else {
                        casted = new SqlNumber(n.ToDouble());
                    }

                    break;
                case (SqlTypeCode.Numeric):
                case (SqlTypeCode.Decimal):
                    casted = n;
                    break;
                case (SqlTypeCode.Char):
                    casted = new SqlString(n.ToString().PadRight(((StringType) destType).MaxSize));
                    break;
                case (SqlTypeCode.VarChar):
                case (SqlTypeCode.LongVarChar):
                case (SqlTypeCode.String):
                    casted = new SqlString(n.ToString());
                    break;
                case (SqlTypeCode.Date):
                case (SqlTypeCode.Time):
                case (SqlTypeCode.TimeStamp):
                    casted = ToDate(n.ToInt64());
                    break;
                case (SqlTypeCode.Blob):
                case (SqlTypeCode.Binary):
                case (SqlTypeCode.VarBinary):
                case (SqlTypeCode.LongVarBinary):
                    casted = new SqlBinary(n.ToByteArray());
                    break;
                case (SqlTypeCode.Null):
                    casted = SqlNull.Value;
                    break;
                default:
                    throw new InvalidCastException();
            }

            return casted;
        }