Пример #1
0
 public void Convert_ToBoolean_Success()
 {
     var value = SqlNumber.One;
     var b = new SqlBoolean();
     Assert.DoesNotThrow(() => b = (SqlBoolean)Convert.ChangeType(value, typeof(SqlBoolean)));
     Assert.IsTrue(b);
 }
Пример #2
0
        public void CastToNumber(bool value, int expected)
        {
            var type = PrimitiveTypes.Boolean();
            var boolean = new SqlBoolean(value);

            var casted = type.CastTo(boolean, PrimitiveTypes.Numeric());

            Assert.IsInstanceOf<SqlNumber>(casted);
            Assert.AreEqual(expected, ((SqlNumber)casted).ToInt32());
        }
Пример #3
0
        public void String_Convert_BooleanFalse()
        {
            const string s = "false";
            var sqlString = new SqlString(s);

            var b = new SqlBoolean();
            Assert.DoesNotThrow(() => b = (SqlBoolean)Convert.ChangeType(sqlString, typeof(SqlBoolean)));
            Assert.IsFalse(b.IsNull);
            Assert.AreEqual(SqlBoolean.False, b);
        }
Пример #4
0
        public void CastToString(SqlTypeCode typeCode, bool value, string expected)
        {
            var type = PrimitiveTypes.Boolean(typeCode);

            var boolean = new SqlBoolean(value);

            var casted = type.CastTo(boolean, PrimitiveTypes.String());

            Assert.IsInstanceOf<SqlString>(casted);
            Assert.AreEqual(expected, casted.ToString());
        }
Пример #5
0
        public void CastToBinary(bool value, byte expected)
        {
            var type = PrimitiveTypes.Boolean();
            var boolean = new SqlBoolean(value);

            var casted = type.CastTo(boolean, PrimitiveTypes.Binary());

            var expectedArray = new[] {expected};

            Assert.IsInstanceOf<SqlBinary>(casted);
            Assert.AreEqual(expectedArray, ((SqlBinary)casted).ToByteArray());
        }
Пример #6
0
        public void Compare_NotEqual()
        {
            var value1 = SqlBoolean.False;
            var value2 = new SqlBoolean(true);

            Assert.IsFalse(value1.IsNull);
            Assert.IsFalse(value2.IsNull);

            Assert.IsTrue(value1.IsComparableTo(value2));

            int i = -2;
            Assert.DoesNotThrow(() => i = value1.CompareTo(value2));
            Assert.AreEqual(-1, i);
        }
Пример #7
0
        public void BooleanNegate(bool a, bool expected)
        {
            var exp1 = SqlExpression.Constant(Field.Boolean(a));
            var negExp = SqlExpression.Negate(exp1);

            SqlExpression resultExp = null;
            Assert.DoesNotThrow(() => resultExp = negExp.Evaluate());
            Assert.IsNotNull(resultExp);
            Assert.IsInstanceOf<SqlConstantExpression>(resultExp);

            var constExp = (SqlConstantExpression)resultExp;
            Assert.IsNotNull(constExp.Value.Value);
            Assert.IsInstanceOf<BooleanType>(constExp.Value.Type);
            Assert.IsInstanceOf<SqlBoolean>(constExp.Value.Value);

            var actual = ((SqlBoolean)constExp.Value.Value);
            var expectedResult = new SqlBoolean(expected);
            Assert.AreEqual(expectedResult, actual);
        }
Пример #8
0
        public void BooleanOr(bool a, bool b, bool expected)
        {
            var exp1 = SqlExpression.Constant(DataObject.Boolean(new SqlBoolean(a)));
            var exp2 = SqlExpression.Constant(DataObject.Boolean(new SqlBoolean(b)));
            var orExp = SqlExpression.Or(exp1, exp2);

            SqlExpression resultExp = null;
            Assert.DoesNotThrow(() => resultExp = orExp.Evaluate());
            Assert.IsNotNull(resultExp);
            Assert.IsInstanceOf<SqlConstantExpression>(resultExp);

            var constExp = (SqlConstantExpression)resultExp;
            Assert.IsNotNull(constExp.Value.Value);
            Assert.IsInstanceOf<BooleanType>(constExp.Value.Type);
            Assert.IsInstanceOf<SqlBoolean>(constExp.Value.Value);

            var actual = ((SqlBoolean)constExp.Value.Value);
            var expectedResult = new SqlBoolean(expected);
            Assert.AreEqual(expectedResult, actual);
        }
Пример #9
0
        /**
         * Compares two instances of SqlBoolean to determine if they are equal.
         * @param x A SqlBoolean instance
         * @param y A SqlBoolean instance
         * @return A SqlBoolean that is True if the two instances are not equal or False if the two instances are equal.
         * If either instance of SqlDouble is null, the Value of the SqlBoolean will be Null.
         */
        public static SqlBoolean NotEquals(SqlBoolean x, SqlBoolean y)
        {
            if (x.IsNull || y.IsNull)
                return SqlBoolean.Null;

            return new SqlBoolean(x._value != y._value);
        }
Пример #10
0
 // Helper method to Compare methods and operators.
 // Returns 0 if x == y
 //         1 if x > y
 //        -1 if x < y
 private static int Compare(SqlBoolean x, SqlBoolean y)
 {
     if (x == y)
     {
         return 0;
     }
     if (x.IsTrue && y.IsFalse)
     {
         return 1;
     }
     if (x.IsFalse && y.IsTrue)
     {
         return -1;
     }
     return 0;
 }
Пример #11
0
 public static void SendMessage(SqlString HostName, SqlInt32 Port, SqlString Message, out SqlBoolean Result)
 {
     using (var udpClient = new UdpClient())
     {
         try
         {
             udpClient.Connect(HostName.Value, Port.Value);
             var sendBytes = UTF8.GetBytes(Message.Value);
             udpClient.Send(sendBytes, sendBytes.Length);
             udpClient.Close();
         }
         catch
         {
             Result = false;
             return;
         }
         Result = true;
     }
 }
Пример #12
0
        // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2.
        //          With these types the values should be used directly as CLR types instead of being converted to a SqlValue
        internal static object GetSqlValueFromComVariant(object comVal)
        {
            object sqlVal = null;

            if ((null != comVal) && (DBNull.Value != comVal))
            {
                if (comVal is float)
                {
                    sqlVal = new SqlSingle((float)comVal);
                }
                else if (comVal is string)
                {
                    sqlVal = new SqlString((string)comVal);
                }
                else if (comVal is double)
                {
                    sqlVal = new SqlDouble((double)comVal);
                }
                else if (comVal is byte[])
                {
                    sqlVal = new SqlBinary((byte[])comVal);
                }
                else if (comVal is char)
                {
                    sqlVal = new SqlString(((char)comVal).ToString());
                }
                else if (comVal is char[])
                {
                    sqlVal = new SqlChars((char[])comVal);
                }
                else if (comVal is System.Guid)
                {
                    sqlVal = new SqlGuid((Guid)comVal);
                }
                else if (comVal is bool)
                {
                    sqlVal = new SqlBoolean((bool)comVal);
                }
                else if (comVal is byte)
                {
                    sqlVal = new SqlByte((byte)comVal);
                }
                else if (comVal is short)
                {
                    sqlVal = new SqlInt16((short)comVal);
                }
                else if (comVal is int)
                {
                    sqlVal = new SqlInt32((int)comVal);
                }
                else if (comVal is long)
                {
                    sqlVal = new SqlInt64((long)comVal);
                }
                else if (comVal is decimal)
                {
                    sqlVal = new SqlDecimal((decimal)comVal);
                }
                else if (comVal is DateTime)
                {
                    // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method.
                    sqlVal = new SqlDateTime((DateTime)comVal);
                }
                else if (comVal is XmlReader)
                {
                    sqlVal = new SqlXml((XmlReader)comVal);
                }
                else if (comVal is TimeSpan || comVal is DateTimeOffset)
                {
                    sqlVal = comVal;
                }
#if DEBUG
                else
                {
                    Debug.Fail("unknown SqlType class stored in sqlVal");
                }
#endif
            }
            return(sqlVal);
        }
Пример #13
0
 public static SqlBoolean op_Equality(SqlBoolean x, SqlBoolean y)
 {
     return Equals(x, y);
 }
Пример #14
0
 public static SqlBoolean op_BitwiseAnd(SqlBoolean x, SqlBoolean y)
 {
     return And(x, y);
 }
Пример #15
0
    public static void ListsMembers_FillRow(object resultObj, out SqlString id, out SqlString email, out SqlString emailType, out SqlString status,
                                            out SqlString ipSignup, out SqlDateTime timestampSignup, out SqlString ipOpt, out SqlDateTime timestampOpt, out Int32 memberRating,
                                            out SqlString campaignId, out SqlDateTime timestamp, out SqlDateTime infoChanged, out Int32 webId, out Int32 leid, out SqlString listId,
                                            out SqlString listName, out SqlString language, out SqlBoolean isGmonkey)
    {
        MemberInfo memberInfo = (MemberInfo)resultObj;

        id              = memberInfo.Id;
        email           = memberInfo.Email;
        emailType       = memberInfo.EmailType;
        status          = memberInfo.Status;
        ipSignup        = memberInfo.IPSignup;
        timestampSignup = memberInfo.TimestampSignup ?? SqlDateTime.Null;
        ipOpt           = memberInfo.IPOptIn;
        timestampOpt    = memberInfo.TimestampOptIn ?? SqlDateTime.Null;
        memberRating    = memberInfo.MemberRating;
        campaignId      = memberInfo.CampaignId;
        timestamp       = memberInfo.Timestamp ?? SqlDateTime.Null;
        infoChanged     = memberInfo.InfoChanged ?? SqlDateTime.Null;
        webId           = memberInfo.WebId;
        leid            = memberInfo.LEId;
        listId          = memberInfo.ListId;
        listName        = memberInfo.ListName;
        language        = memberInfo.Language;
        isGmonkey       = memberInfo.IsGoldenMonkey ? SqlBoolean.True : SqlBoolean.False;
    }
Пример #16
0
    public static void ListsList_FillRow(object resultObj, out SqlString id, out SqlString name, out SqlDateTime dateCreated, out SqlBoolean emailTypeOption,
                                         out SqlBoolean useAwesomeBar, out SqlString defaultFromName, out SqlString defaultFromEmail, out SqlString defaultSubject, out SqlString defaultLanguage,
                                         out SqlDouble listRating, out SqlString subscriberUrlShort, out SqlString subscribeUrlLong, out SqlString beamerAddress, out SqlString visibility)
    {
        ListInfo listInfo = (ListInfo)resultObj;

        id                 = listInfo.Id;
        name               = listInfo.Name;
        dateCreated        = DateTime.Parse(listInfo.DateCreated);
        emailTypeOption    = listInfo.EmailTypeOption ? SqlBoolean.True : SqlBoolean.False;
        useAwesomeBar      = listInfo.UseAwesomebar ? SqlBoolean.True : SqlBoolean.False;
        defaultFromName    = listInfo.DefaultFromName;
        defaultFromEmail   = listInfo.DefaultFromEmail;
        defaultSubject     = listInfo.DefaultSubject;
        defaultLanguage    = listInfo.DefaultLanguage;
        listRating         = listInfo.ListRating;
        subscriberUrlShort = listInfo.SubscribeUrlShort;
        subscribeUrlLong   = listInfo.SubscribeUrlLong;
        beamerAddress      = listInfo.BeamerAddress;
        visibility         = listInfo.Visibility;
    }
Пример #17
0
    public static IEnumerable ListsInterestGroupings(SqlString apikey, SqlString list_id, SqlBoolean counts)
    {
        List <InterestGroupingRow> rows = new List <InterestGroupingRow>();

        MailChimpManager mc = new MailChimpManager(apikey.ToString());

        List <InterestGrouping> results = mc.GetListInterestGroupings(list_id.ToString(), counts.IsTrue);

        foreach (InterestGrouping grouping in results)
        {
            foreach (InterestGrouping.InnerGroup innerGroup in grouping.GroupNames)
            {
                InterestGroupingRow row = new InterestGroupingRow();
                row.Id           = grouping.Id;
                row.Name         = grouping.Name;
                row.GroupName    = innerGroup.Name;
                row.DisplayOrder = innerGroup.DisplayOrder;
                row.Subscribers  = innerGroup.Subscribers;
                rows.Add(row);
            }
        }

        return(rows);
    }
Пример #18
0
    public static void FillRowFromJson(Object token, out SqlString path, out SqlString value, out SqlString type, out SqlBoolean hasvalues, out SqlInt32 index)
    {
        JToken item = (JToken)token;

        path      = item.Path;
        type      = item.Type.ToString();
        hasvalues = item.HasValues;
        value     = item.ToString();
        index     = count;
        count++;
    }
Пример #19
0
 public override object FromStringValue(string xml)
 {
     return(SqlBoolean.Parse(xml));
 }
 /// <summary>
 /// Resets the values of all public members to their values in the database.
 /// </summary>
 protected override void SetRegisteredMembers()
 {
     this.SearchBidId      = (Guid)base.GetColumn("SearchBidId");
     this.SearchQuestionId = (Guid)base.GetColumn("SearchQuestionId");
     this.AnswerValue      = (SqlBoolean)base.GetColumn("AnswerValue");
 }
        public static void CreateActivity(SqlString url, SqlString username, SqlString password, SqlString token, SqlDateTime createdDT, SqlBoolean externalMessage, SqlString employeeId, SqlString actUrl, SqlString actTitle, SqlString actBody)
        {
            IChatterSoapService service = new ChatterSoapService(url.Value);

            service.AllowUntrustedConnection();
            service.Login(username.Value, password.Value, token.Value);

            service.CreateProfileActivity(employeeId.IsNull ? null : employeeId.Value, actUrl.IsNull ? null : actUrl.Value, actTitle.IsNull ? null : actTitle.Value, actBody.IsNull ? null : actBody.Value, createdDT.Value);
            if (externalMessage.IsTrue)
            {
                service.CreateExternalMessage(actUrl.IsNull ? null : actUrl.Value, actTitle.IsNull ? null : actTitle.Value, actBody.IsNull ? null : actBody.Value, employeeId.IsNull ? null : employeeId.Value);
            }
        }
Пример #22
0
        /**
         * Performs a bitwise XOR operation on the two specified SqlBoolean instances.
         * @param x A SqlBoolean instance
         * @param y A SqlBoolean instance
         * @return The result of the logical XOR operation.
         */
        public static SqlBoolean Xor(SqlBoolean x, SqlBoolean y)
        {
            if (x.IsNull || y.IsNull)
                return SqlBoolean.Null;

            if (x.IsTrue && y.IsTrue)
                return new SqlBoolean(false);

            if (x.IsTrue || y.IsTrue)
                return new SqlBoolean(true);

            return new SqlBoolean(false); // both args are False

        }
Пример #23
0
 public static bool op_True(SqlBoolean x)
 {
     return x.IsTrue;
 }
Пример #24
0
    public static void ListsMemberInterestGroupings_FillRow(object resultObj, out SqlInt32 id, out SqlString name, out SqlString group_names,
                                                            out SqlString group_interest_name, out SqlBoolean interested)
    {
        MemberInterestGroupRow row = (MemberInterestGroupRow)resultObj;

        id                  = row.Id ?? SqlInt32.Null;
        name                = row.Name;
        group_names         = row.GroupNames;
        group_interest_name = row.GroupInterestName;
        interested          = row.Interested;
    }
Пример #25
0
 public static SqlBoolean op_OnesComplement(SqlBoolean x)
 {
     return OnesComplement(x);
 }
Пример #26
0
    public static int ListsMergeVarUpdate(SqlString apikey, SqlString list_id, SqlString tag, SqlBoolean opt_req, SqlBoolean opt_public, SqlBoolean opt_show,
                                          SqlInt32 opt_order, SqlString opt_default_value, SqlString opt_helptext, SqlString opt_choices, SqlString opt_dateformat,
                                          SqlString opt_phoneformat, SqlString opt_defaultcountry)
    {
        try
        {
            MailChimpManager mc = new MailChimpManager(apikey.ToString());

            MergeVarItemResult result = mc.UpdateMergeVar(list_id.ToString(), tag.ToString(), new MergeVarOptions
            {
                Required       = opt_req.IsTrue,
                Public         = opt_public.IsTrue,
                Show           = opt_show.IsTrue,
                Order          = opt_order.Value,
                DefaultValue   = opt_default_value.ToString(),
                HelpText       = opt_helptext.ToString(),
                Choices        = opt_choices.ToString().Split(','),
                DateFormat     = opt_dateformat.ToString(),
                PhoneFormat    = opt_phoneformat.ToString(),
                DefaultCountry = opt_defaultcountry.ToString()
            });

            SqlDataRecord record = new SqlDataRecord(MergeVarResultsMetaData);
            record.SetString(0, result.Name);
            record.SetBoolean(1, result.Required);
            record.SetString(2, result.FieldType);
            record.SetBoolean(3, result.Public);
            record.SetBoolean(4, result.Show);
            record.SetInt32(5, result.Order);
            record.SetString(6, result.DefaultValue);
            record.SetString(7, result.HelpText);
            record.SetString(8, (result.Choices == null) ? string.Empty : string.Join(",", result.Choices));
            record.SetString(9, result.Size);
            record.SetString(10, result.Tag);
            record.SetInt32(11, result.Id);

            SqlContext.Pipe.Send(record);
        }
        catch (Exception ex)
        {
            SqlContext.Pipe.Send(ex.Message);
            SqlContext.Pipe.Send(ex.StackTrace);
            return(1);
        }
        return(0);
    }
Пример #27
0
        public void NumericIsNullTrue()
        {
            var exp1 = SqlExpression.Constant(DataObject.Number(SqlNumber.Null));
            var exp2 = SqlExpression.Constant(DataObject.Null());
            var orExp = SqlExpression.Is(exp1, exp2);

            SqlExpression resultExp = null;
            Assert.DoesNotThrow(() => resultExp = orExp.Evaluate());
            Assert.IsNotNull(resultExp);
            Assert.IsInstanceOf<SqlConstantExpression>(resultExp);

            var constExp = (SqlConstantExpression)resultExp;
            Assert.IsNotNull(constExp.Value.Value);
            Assert.IsInstanceOf<BooleanType>(constExp.Value.Type);
            Assert.IsInstanceOf<SqlBoolean>(constExp.Value.Value);

            var actual = ((SqlBoolean)constExp.Value.Value);
            var expectedResult = new SqlBoolean(true);
            Assert.AreEqual(expectedResult, actual);
        }
Пример #28
0
    public static void ListsMergeVars_FillRow(object resultObj, out SqlString name, out SqlBoolean req,
                                              out SqlString field_type, out SqlBoolean is_public, out SqlBoolean show, out SqlInt32 order, out SqlString default_value,
                                              out SqlString helptext, out SqlString size, out SqlString tag, out SqlString choices, out SqlInt32 id)
    {
        MergeVarItemResult itemResult = (MergeVarItemResult)resultObj;

        name          = itemResult.Name;
        req           = itemResult.Required ? SqlBoolean.True : SqlBoolean.False;
        field_type    = itemResult.FieldType;
        is_public     = itemResult.Public ? SqlBoolean.True : SqlBoolean.False;
        show          = itemResult.Show ? SqlBoolean.True : SqlBoolean.False;
        order         = itemResult.Order;
        default_value = itemResult.DefaultValue;
        helptext      = itemResult.HelpText;
        size          = itemResult.Size;
        tag           = itemResult.Tag;
        choices       = (itemResult.Choices == null) ? string.Empty : string.Join(",", itemResult.Choices);
        id            = itemResult.Id;
    }
Пример #29
0
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="PBoolean"/>
 /// structure using the supplied boolean value.
 /// </summary>
 /// <param name="value"></param>
 public PBoolean(bool value)
 {
     _sql      = value;
     ValueType = PValueType.Value;
 }
Пример #30
0
    public static int ListsSubscribe(SqlString apikey, SqlString list_id, SqlString email, SqlString euid, SqlString leid, SqlString email_type, SqlBoolean double_optin, SqlBoolean update_existing, SqlBoolean send_welcome)
    {
        try
        {
            MailChimpManager mc = new MailChimpManager(apikey.ToString());

            EmailParameter emailParam = new EmailParameter
            {
                Email = email.ToString(),
                EUId  = euid.ToString(),
                LEId  = leid.ToString()
            };

            EmailParameter result = mc.Subscribe(list_id.ToString(), emailParam, null, email_type.ToString(),
                                                 double_optin.IsTrue, update_existing.IsTrue, true, send_welcome.IsTrue);

            SqlDataRecord record = new SqlDataRecord(EmailParameterResultsMetaData);
            record.SetString(0, result.Email);
            record.SetString(1, result.EUId);
            record.SetString(2, result.LEId);

            SqlContext.Pipe.Send(record);
        }
        catch (Exception ex)
        {
            SqlContext.Pipe.Send(ex.Message);
            return(1);
        }
        return(0);
    }
Пример #31
0
        public void CreateFromByte()
        {
            var value = new SqlBoolean(1);
            Assert.IsNotNull(value);
            Assert.IsFalse(value.IsNull);
            Assert.AreEqual(true, (bool)value);

            value = new SqlBoolean(0);
            Assert.IsNotNull(value);
            Assert.IsFalse(value.IsNull);
            Assert.AreEqual(false, (bool)value);
        }
Пример #32
0
    public static int ListsUnsubscribe(SqlString apikey, SqlString list_id, SqlString email, SqlString euid, SqlString leid, SqlBoolean delete_member, SqlBoolean send_goodbye, SqlBoolean send_notify)
    {
        try
        {
            MailChimpManager mc = new MailChimpManager(apikey.ToString());

            EmailParameter emailParam = new EmailParameter
            {
                Email = email.ToString(),
                EUId  = euid.ToString(),
                LEId  = leid.ToString()
            };

            UnsubscribeResult result = mc.Unsubscribe(list_id.ToString(), emailParam, delete_member.IsTrue, send_goodbye.IsTrue, send_notify.IsTrue);

            SqlDataRecord record = new SqlDataRecord(CompleteResultsMetaData);
            record.SetBoolean(0, result.Complete);

            SqlContext.Pipe.Send(record);
        }
        catch (Exception ex)
        {
            SqlContext.Pipe.Send(ex.Message);
            return(1);
        }
        return(0);
    }
Пример #33
0
        // One's Complement
        public static SqlBoolean operator ~(SqlBoolean x)
        {
            SqlBoolean b;
            if (x.IsTrue)
            {
                b = new SqlBoolean(false);
            }
            else
            {
                b = new SqlBoolean(true);
            }

            return b;
        }
Пример #34
0
        public static void AddInputEndpointToPersistentVM(
            SqlString certificateThumbprint,
            SqlGuid sgSubscriptionId,
            SqlString serviceName,
            SqlString deploymentSlots,
            SqlString vmName,
            SqlString EndpointName,
            SqlInt32 LocalPort,
            SqlBoolean EnableDirectServerReturn,
            SqlInt32 Port,
            SqlString Protocol,
            SqlString Vip,
            SqlBoolean fBlocking)
        {
            X509Certificate2 certificate = RetrieveCertificateInStore(certificateThumbprint.Value);

            Azure.Management.Deployment result = Azure.Internal.Management.GetDeployments(
                certificate,
                sgSubscriptionId.Value,
                serviceName.Value,
                deploymentSlots.Value);

            var vmToAdd = (ITPCfSQL.Azure.Management.PersistentVMRole)result.RoleList.FirstOrDefault(item => item.RoleName.Equals(vmName.Value, StringComparison.InvariantCultureIgnoreCase));

            if (vmToAdd == null)
            {
                throw new ArgumentException("No PersistentVMRole with name " + vmName.Value + " found in sgSubscriptionId = " +
                                            sgSubscriptionId.Value + ", serviceName = " + serviceName.Value + ", deploymentSlots = "
                                            + deploymentSlots.Value + ".");
            }

            ITPCfSQL.Azure.Management.DeploymentRoleConfigurationSetsConfigurationSetInputEndpoint[] driiesTemp = new
                                                                                                                  ITPCfSQL.Azure.Management.DeploymentRoleConfigurationSetsConfigurationSetInputEndpoint[vmToAdd.ConfigurationSets.ConfigurationSet.InputEndpoints.Length + 1];

            Array.Copy(vmToAdd.ConfigurationSets.ConfigurationSet.InputEndpoints, driiesTemp, vmToAdd.ConfigurationSets.ConfigurationSet.InputEndpoints.Length);

            driiesTemp[driiesTemp.Length - 1] = new ITPCfSQL.Azure.Management.DeploymentRoleConfigurationSetsConfigurationSetInputEndpoint()
            {
                Name      = EndpointName.Value,
                LocalPort = LocalPort.Value,
                EnableDirectServerReturn = EnableDirectServerReturn.Value,
                Port     = Port.Value,
                Protocol = Protocol.Value,
                Vip      = Vip.Value
            };

            vmToAdd.ConfigurationSets.ConfigurationSet.InputEndpoints = driiesTemp;

            var output = ITPCfSQL.Azure.Internal.Management.UpdatePersistentVMRole(
                certificate,
                sgSubscriptionId.Value,
                serviceName.Value,
                result.Name,
                vmToAdd);

            PushOperationStatus(
                certificate,
                sgSubscriptionId.Value,
                new Guid(output[ITPCfSQL.Azure.Internal.Constants.HEADER_REQUEST_ID]),
                fBlocking.IsNull ? false : fBlocking.Value);
        }
Пример #35
0
        /**
         * Performs a bitwise OR operation on the two specified SqlBoolean instances.
         * @param x A SqlBoolean instance
         * @param y A SqlBoolean instance
         * @return The result of the logical OR operation.
         */
        public static SqlBoolean Or(SqlBoolean x, SqlBoolean y)
        {
            if (x.IsNull || y.IsNull)
                return SqlBoolean.Null;

            bool res = x.IsTrue || y.IsTrue;
            return new SqlBoolean(res);
        }
Пример #36
0
 public SqlBooleanTest()
 {
     CultureInfo.CurrentCulture = new CultureInfo("en-US");
     _sqlTrue  = new SqlBoolean(true);
     _sqlFalse = new SqlBoolean(false);
 }
Пример #37
0
 public static SqlBoolean OnesComplement(SqlBoolean x)
 {
     if (x.IsNull)
     {
         throw new SqlNullValueException();
     }
     return new SqlBoolean(x._value == false);
 }
Пример #38
0
        public void GetXsdTypeTest()
        {
            XmlQualifiedName qualifiedName = SqlBoolean.GetXsdType(null);

            Assert.Equal("boolean", qualifiedName.Name);
        }
Пример #39
0
 public static bool op_Explicit(SqlBoolean x)
 {
     return x.Value;
 }
 public static void IsFalse(SqlBoolean sqlBoolean)
 {
     MST.Assert.IsFalse((bool)sqlBoolean);
 }
Пример #41
0
 public static bool op_False(SqlBoolean x)
 {
     return x.IsFalse;
 }
Пример #42
0
        public static bool Process(string targetConnection,
                                   string repositoryConnection, int snapshotid,
                                   Database database,
                                   ref Dictionary <Sql.SqlObjectType, Dictionary <MetricMeasureType, uint> > metricsData)
        {
            bool isOk = true;


            Debug.Assert(!string.IsNullOrEmpty(targetConnection));
            Debug.Assert(!string.IsNullOrEmpty(repositoryConnection));
            Debug.Assert(database != null);
            Program.ImpersonationContext wi = Program.SetLocalImpersonationContext();
            try
            {
                //Do the main job
                uint      processedCertificatesCnt = 0;
                Stopwatch sw = new Stopwatch();
                sw.Start();
                using (SqlConnection target = new SqlConnection(targetConnection),
                       repository = new SqlConnection(repositoryConnection))
                {
                    // Open repository and target connections.
                    repository.Open();
                    Program.SetTargetSQLServerImpersonationContext();
                    target.Open();

                    var sqlServerVersion = Sql.SqlHelper.ParseVersion(target.ServerVersion);

                    // Use bulk copy object to write to repository.
                    using (SqlBulkCopy bcp = new SqlBulkCopy(repository))
                    {
                        bcp.DestinationTableName = CertificateTable.RepositoryTable;
                        bcp.BulkCopyTimeout      = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();


                        using (DataTable dataTable = CertificateTable.Create())
                        {
                            var query = CreateQuery(database, sqlServerVersion);
                            using (SqlDataReader rdr = Sql.SqlHelper.ExecuteReader(target, null,
                                                                                   CommandType.Text, query, null))
                            {
                                while (rdr.Read())
                                {
                                    // Retrieve the object information.

                                    SqlString   certName               = rdr.GetSqlString((int)DatabaseCertificateColumns.CertificateName);
                                    SqlInt32    certificateId          = rdr.IsDBNull((int)DatabaseCertificateColumns.CertificateId) ? SqlInt32.Null : rdr.GetSqlInt32((int)DatabaseCertificateColumns.CertificateId);
                                    SqlInt32    principalId            = rdr.IsDBNull((int)DatabaseCertificateColumns.PrincipalId) ? SqlInt32.Null : rdr.GetSqlInt32((int)DatabaseCertificateColumns.PrincipalId);
                                    SqlString   keyEncryptionType      = rdr.GetSqlString((int)DatabaseCertificateColumns.KeyEncryptionType);
                                    SqlString   keyEncryptionTypeDesc  = rdr.GetSqlString((int)DatabaseCertificateColumns.KeyEncryptionTypeDesc);
                                    SqlBoolean  isActiveForBeginDialog = rdr.GetSqlBoolean((int)DatabaseCertificateColumns.IsActiveForBeginDialog);
                                    SqlString   issuerName             = rdr.GetSqlString((int)DatabaseCertificateColumns.IssuerName);
                                    SqlString   certSerialNumber       = rdr.GetSqlString((int)DatabaseCertificateColumns.CertSerialNumber);
                                    var         sid               = rdr.GetSqlBinary((int)DatabaseCertificateColumns.Sid);
                                    SqlString   stringSid         = rdr.GetSqlString((int)DatabaseCertificateColumns.StringSid);
                                    SqlString   subject           = rdr.GetSqlString((int)DatabaseCertificateColumns.Subject);
                                    SqlDateTime expiryDate        = rdr.GetSqlDateTime((int)DatabaseCertificateColumns.ExpiryDate);
                                    SqlDateTime startDate         = rdr.GetSqlDateTime((int)DatabaseCertificateColumns.StartDate);
                                    var         thumbprint        = rdr.GetSqlBinary((int)DatabaseCertificateColumns.Thumbprint);
                                    SqlString   attestedBy        = rdr.GetSqlString((int)DatabaseCertificateColumns.AttestedBy);
                                    SqlDateTime keyLastBackupDate = rdr.IsDBNull((int)DatabaseCertificateColumns.KeyLastBackupDate) ? SqlDateTime.Null : rdr.GetSqlDateTime((int)DatabaseCertificateColumns.KeyLastBackupDate);



                                    // Update the datatable.
                                    var dataRow = dataTable.NewRow();
                                    dataRow[CertificateTable.SnapshotId]             = snapshotid;
                                    dataRow[CertificateTable.DbId]                   = database.DbId;
                                    dataRow[CertificateTable.CertificateName]        = certName;
                                    dataRow[CertificateTable.CertificateId]          = certificateId;
                                    dataRow[CertificateTable.PrincipalId]            = principalId;
                                    dataRow[CertificateTable.KeyEncryptionType]      = keyEncryptionType;
                                    dataRow[CertificateTable.KeyEncryptionTypeDesc]  = keyEncryptionTypeDesc;
                                    dataRow[CertificateTable.IsActiveForBeginDialog] = isActiveForBeginDialog;
                                    dataRow[CertificateTable.IssuerName]             = issuerName;
                                    dataRow[CertificateTable.CertSerialNumber]       = certSerialNumber;
                                    dataRow[CertificateTable.Sid]               = sid;
                                    dataRow[CertificateTable.StringSid]         = stringSid;
                                    dataRow[CertificateTable.Subject]           = subject;
                                    dataRow[CertificateTable.ExpiryDate]        = expiryDate;
                                    dataRow[CertificateTable.StartDate]         = startDate;
                                    dataRow[CertificateTable.Thumbprint]        = thumbprint;
                                    dataRow[CertificateTable.AttestedBy]        = attestedBy;
                                    dataRow[CertificateTable.KeyLastBackupDate] = keyLastBackupDate;
                                    processedCertificatesCnt++;
                                    dataTable.Rows.Add(dataRow);

                                    if (dataTable.Rows.Count > Constants.RowBatchSize)
                                    {
                                        bcp.WriteToServer(dataTable);
                                        dataTable.Clear();
                                    }
                                }
                                // Write any items still in the data table.
                                if (dataTable.Rows.Count > 0)
                                {
                                    bcp.WriteToServer(dataTable);
                                    dataTable.Clear();
                                }
                            }
                        }
                    }
                }


                sw.Stop();


                //ToDo: Check if we need this
                uint oldMetricCount = 0;
                uint oldMetricTime  = 0;
                // See if Schema is already in Metrics Dictionary
                // ----------------------------------------------
                Dictionary <MetricMeasureType, uint> de;
                if (metricsData.TryGetValue(SqlObjectType.Schema, out de))
                {
                    de.TryGetValue(MetricMeasureType.Count, out oldMetricCount);
                    de.TryGetValue(MetricMeasureType.Time, out oldMetricTime);
                }
                else
                {
                    de = new Dictionary <MetricMeasureType, uint>();
                }
                de[MetricMeasureType.Count]       = processedCertificatesCnt + oldMetricCount;
                de[MetricMeasureType.Time]        = (uint)sw.ElapsedMilliseconds + oldMetricTime;
                metricsData[SqlObjectType.Schema] = de;
            }
            catch (Exception ex)
            {
                _logX.loggerX.Error(ex.Message);
                string strMessage = "Processing certificates";
                _logX.loggerX.Error("ERROR - " + strMessage, ex);
                Sql.Database.CreateApplicationActivityEventInRepository(repositoryConnection,
                                                                        snapshotid,
                                                                        Collector.Constants.ActivityType_Error,
                                                                        Collector.Constants.ActivityEvent_Error,
                                                                        strMessage + ex.Message);
                AppLog.WriteAppEventError(SQLsecureEvent.ExErrExceptionRaised, SQLsecureCat.DlDataLoadCat,
                                          " SQL Server = " + new SqlConnectionStringBuilder(targetConnection).DataSource +
                                          strMessage, ex.Message);
                isOk = false;
            }
            finally
            {
                Program.RestoreImpersonationContext(wi);
            }
            return(isOk);
        }
Пример #43
0
 public static SqlBoolean op_BitwiseOr(SqlBoolean x, SqlBoolean y)
 {
     return Or(x, y);
 }
Пример #44
0
 public SqlInt16 GetShortValue(SqlByte index, SqlBoolean byteSwap, SqlBoolean wordSwap)
 {
     return(new DeviceSQL.Device.MODBUS.Data.EventArchiveRecord(Convert.ToUInt16(Index), Data.Value).GetShortValue(index.Value, byteSwap.Value));
 }
Пример #45
0
 public static SqlBoolean op_ExclusiveOr(SqlBoolean x, SqlBoolean y)
 {
     return Xor(x, y);
 }
Пример #46
0
        public SqlSingle GetFloatValue(SqlByte index, SqlBoolean byteSwap, SqlBoolean wordSwap)
        {
            var floatValue = new DeviceSQL.Device.MODBUS.Data.EventArchiveRecord(Convert.ToUInt16(Index), Data.Value).GetNullableFloatValue(index.Value, byteSwap.Value, wordSwap.Value);

            return(floatValue ?? SqlSingle.Null);
        }
Пример #47
0
 public static SqlBoolean op_Inequality(SqlBoolean x, SqlBoolean y)
 {
     return NotEquals(x, y);
 }
 public override void SetSqlBoolean(object o, int index, SqlBoolean value)
 {
     this[index].SetSqlBoolean(o, value);
 }
Пример #49
0
        public void StringLikesPattern(string input, string patern, bool expected)
        {
            var exp1 = SqlExpression.Constant(DataObject.String(patern));
            var exp2 = SqlExpression.Constant(DataObject.String(input));
            var likeExp = SqlExpression.Like(exp1, exp2);

            SqlExpression resultExp = null;
            Assert.DoesNotThrow(() => resultExp = likeExp.Evaluate());
            Assert.IsNotNull(resultExp);
            Assert.IsInstanceOf<SqlConstantExpression>(resultExp);

            var constExp = (SqlConstantExpression)resultExp;
            Assert.IsNotNull(constExp.Value.Value);
            Assert.IsInstanceOf<BooleanType>(constExp.Value.Type);
            Assert.IsInstanceOf<SqlBoolean>(constExp.Value.Value);

            var actual = ((SqlBoolean)constExp.Value.Value);
            var expectedResult = new SqlBoolean(expected);
            Assert.AreEqual(expectedResult, actual);
        }
Пример #50
0
        public static SqlBoolean InitialiseDeviceDetection(SqlString filename, SqlString properties, SqlInt32 expirySeconds, SqlBoolean memoryMode)
        {
            if (filename.IsNull || File.Exists(filename.Value) == false)
            {
                throw new FileNotFoundException(String.Format(
                                                    "Device data file '{0}' could not be found",
                                                    filename.Value));
            }

            // Dispose of the old providers dataset if not null.
            if (_provider != null)
            {
                _provider.DataSet.Dispose();
            }

            // Create the provider using the file provided.
            try
            {
                _provider = new Provider(
                    memoryMode.IsNull || memoryMode.Value == false ?
                    Factories.StreamFactory.Create(filename.Value) :
                    Factories.MemoryFactory.Create(filename.Value));
            }
            catch (Exception ex)
            {
                throw new MobileException(String.Format(
                                              "Could not create data set from file '{0}'. " +
                                              "Check the file is uncompressed and in the correct format.",
                                              filename.Value), ex);
            }

            if (_provider != null)
            {
                // Configure the caches.
                int cacheSize = 1000;
                _cacheUserAgent = new Cache <string, InternalResult>(
                    cacheSize,
                    new UserAgentCacheLoader());
                _cacheIdString = new Cache <string, InternalResult>(
                    cacheSize,
                    new StringIdCacheLoader());
                _cacheIdArray = new Cache <byte[], InternalResult>(
                    cacheSize,
                    new ByteArrayIdCacheLoad());

                // Set the properties that the functions should be returning.
                _numberOfProperties = 0;
                _requiredProperties.Clear();
                _dynamicProperties.Clear();
                if (properties.IsNull || String.IsNullOrEmpty(properties.Value))
                {
                    // Use all the available properties that the provider supports.
                    foreach (var component in _provider.DataSet.Components)
                    {
                        _requiredProperties.Add(component, component.Properties.ToList());
                        _numberOfProperties += component.Properties.Length;
                    }
                    _dynamicProperties.Add(DynamicProperties.Id);
                    _dynamicProperties.Add(DynamicProperties.Difference);
                    _dynamicProperties.Add(DynamicProperties.Method);
                }
                else
                {
                    // Get the array of properties that should be returned from the match where
                    // the property is contained in the providers data set.
                    foreach (var propertyName in properties.Value.Split(
                                 new string[] { " ", ",", "|", "\t" },
                                 StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).Distinct())
                    {
                        switch (propertyName)
                        {
                        case "Id":
                            _dynamicProperties.Add(DynamicProperties.Id);
                            _numberOfProperties++;
                            break;

                        case "Method":
                            _dynamicProperties.Add(DynamicProperties.Method);
                            _numberOfProperties++;
                            break;

                        case "Difference":
                            _dynamicProperties.Add(DynamicProperties.Difference);
                            _numberOfProperties++;
                            break;

                        default:
                            var property = _provider.DataSet.Properties[propertyName];
                            if (property != null)
                            {
                                if (_requiredProperties.ContainsKey(property.Component) == false)
                                {
                                    _requiredProperties.Add(property.Component, new List <Property>());
                                }
                                _requiredProperties[property.Component].Add(property);
                                _numberOfProperties++;
                            }
                            break;
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Пример #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PBoolean"/> structure using the supplied
 /// <see cref="System.Data.SqlTypes.SqlBoolean"/> value.
 /// </summary>
 public PBoolean(SqlBoolean value)
 {
     _sql      = value;
     ValueType = value.IsNull ? PValueType.Null : PValueType.Value;
 }
Пример #52
0
        public void SqlTypes_SqlBoolean()
        {
            NpgsqlParameter parameter;
            SqlBoolean value = new SqlBoolean(false);

#if NET_2_0
            parameter = new NpgsqlParameter ();
            parameter.NpgsqlValue = value;
            Assert.AreEqual (NpgsqlDbType.Bit, parameter.NpgsqlDbType, "#A:NpgsqlDbType");
            Assert.AreEqual (value, parameter.NpgsqlValue, "#A:NpgsqlValue");
            Assert.AreEqual (value, parameter.Value, "#A:Value");

            parameter = new NpgsqlParameter ();
            parameter.NpgsqlValue = SqlBoolean.Null;
            Assert.AreEqual (NpgsqlDbType.Bit, parameter.NpgsqlDbType, "#B:NpgsqlDbType");
            Assert.AreEqual (SqlBoolean.Null, parameter.NpgsqlValue, "#B:NpgsqlValue");
            Assert.AreEqual (SqlBoolean.Null, parameter.Value, "#B:Value");
#endif

            parameter = new NpgsqlParameter();
            parameter.Value = value;
            Assert.AreEqual(NpgsqlDbType.Bit, parameter.NpgsqlDbType, "#C:NpgsqlDbType");
#if NET_2_0
            Assert.AreEqual (value, parameter.NpgsqlValue, "#C:NpgsqlValue");
#endif
            Assert.AreEqual(value, parameter.Value, "#C:Value");
        }
Пример #53
0
        public override DataTable SelectOne()
        {
            SqlCommand cmdToExecute = new SqlCommand();

            cmdToExecute.CommandText = "dbo.[sp_tblCashVoucher_SelectOne]";
            cmdToExecute.CommandType = CommandType.StoredProcedure;
            DataTable      toReturn = new DataTable("tblCashVoucher");
            SqlDataAdapter adapter  = new SqlDataAdapter(cmdToExecute);

            // Use base class' connection object
            cmdToExecute.Connection = _mainConnection;

            try
            {
                cmdToExecute.Parameters.Add(new SqlParameter("@sstrSN", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _strSN));
                cmdToExecute.Parameters.Add(new SqlParameter("@iErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));

                if (_mainConnectionIsCreatedLocal)
                {
                    // Open connection.
                    _mainConnection.Open();
                }
                else
                {
                    if (_mainConnectionProvider.IsTransactionPending)
                    {
                        cmdToExecute.Transaction = _mainConnectionProvider.CurrentTransaction;
                    }
                }

                // Execute query.
                adapter.Fill(toReturn);
                _errorCode = (SqlInt32)cmdToExecute.Parameters["@iErrorCode"].Value;

                if (_errorCode != (int)LLBLError.AllOk)
                {
                    // Throw error.
                    throw new Exception("Stored Procedure 'sp_tblCashVoucher_SelectOne' reported the ErrorCode: " + _errorCode);
                }

                if (toReturn.Rows.Count > 0)
                {
                    _nCashVoucherID     = toReturn.Rows[0]["nCashVoucherID"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["nCashVoucherID"];
                    _strSN              = toReturn.Rows[0]["strSN"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strSN"];
                    _strDescription     = toReturn.Rows[0]["strDescription"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strDescription"];
                    _strDescription2    = toReturn.Rows[0]["strDescription2"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strDescription2"];
                    _nCreatedByID       = toReturn.Rows[0]["nCreatedByID"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["nCreatedByID"];
                    _dtCreatedDate      = toReturn.Rows[0]["dtCreatedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["dtCreatedDate"];
                    _strRedeemedByID    = toReturn.Rows[0]["strRedeemedByID"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strRedeemedByID"];
                    _dtRedeemedDate     = toReturn.Rows[0]["dtRedeemedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["dtRedeemedDate"];
                    _strRedeemedBranch  = toReturn.Rows[0]["strRedeemedBranch"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strRedeemedBranch"];
                    _nStatusID          = toReturn.Rows[0]["nStatusID"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["nStatusID"];
                    _dtStartDate        = toReturn.Rows[0]["dtStartDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["dtStartDate"];
                    _dtExpiryDate       = toReturn.Rows[0]["dtExpiryDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["dtExpiryDate"];
                    _dtPrintedDate      = toReturn.Rows[0]["dtPrintedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["dtPrintedDate"];
                    _strSoldToID        = toReturn.Rows[0]["strSoldToID"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strSoldToID"];
                    _dtSoldDate         = toReturn.Rows[0]["dtSoldDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["dtSoldDate"];
                    _strSoldBranch      = toReturn.Rows[0]["strSoldBranch"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strSoldBranch"];
                    _mValue             = toReturn.Rows[0]["mValue"] == System.DBNull.Value ? SqlMoney.Null : (Decimal)toReturn.Rows[0]["mValue"];
                    _strBranchCode      = toReturn.Rows[0]["strBranchCode"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strBranchCode"];
                    _nCashVoucherTypeID = toReturn.Rows[0]["nCashVoucherTypeID"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["nCashVoucherTypeID"];
                    _nCashVoucherTypeID = toReturn.Rows[0]["nCashVoucherTypeID"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["nCashVoucherTypeID"];
                    _nValidDuration     = toReturn.Rows[0]["nValidDuration"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["nValidDuration"];
                    _strDurationUnit    = toReturn.Rows[0]["strDurationUnit"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strDurationUnit"];
                    _fSell              = toReturn.Rows[0]["fSell"] == System.DBNull.Value ? SqlBoolean.Null : (bool)toReturn.Rows[0]["fSell"];
                    _strCategoryIDs     = toReturn.Rows[0]["strCategoryIDs"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strCategoryIDs"];
                }
                return(toReturn);
            }
            catch (Exception ex)
            {
                // some error occured. Bubble it to caller and encapsulate Exception object
                throw new Exception("TblCashVoucher::SelectOne::Error occured.", ex);
            }
            finally
            {
                if (_mainConnectionIsCreatedLocal)
                {
                    // Close connection.
                    _mainConnection.Close();
                }
                cmdToExecute.Dispose();
                adapter.Dispose();
            }
        }
        public override object Aggregate(int[] records, AggregateType kind)
        {
            bool flag = false;

            try
            {
                int       num;
                SqlDouble num2;
                SqlDouble num3;
                int       num4;
                int       num5;
                int       num6;
                int       num7;
                int       num8;
                int       num9;
                int       num10;
                int       num11;
                SqlDouble minValue;
                int       num13;
                SqlDouble maxValue;
                SqlDouble num15;
                int       num16;
                SqlDouble num17;
                SqlDouble num18;
                int[]     numArray;
                SqlDouble num19;
                int       num21;
                int[]     numArray2;
                int       num22;
                int[]     numArray3;
                switch (kind)
                {
                case AggregateType.Sum:
                    num18     = 0.0;
                    numArray3 = records;
                    num10     = 0;
                    goto Label_007F;

                case AggregateType.Mean:
                    num17     = 0.0;
                    num16     = 0;
                    numArray2 = records;
                    num9      = 0;
                    goto Label_00F8;

                case AggregateType.Min:
                    maxValue = SqlDouble.MaxValue;
                    num6     = 0;
                    goto Label_031B;

                case AggregateType.Max:
                    minValue = SqlDouble.MinValue;
                    num5     = 0;
                    goto Label_039A;

                case AggregateType.First:
                    if (records.Length <= 0)
                    {
                        return(null);
                    }
                    return(this.values[records[0]]);

                case AggregateType.Count:
                    num  = 0;
                    num4 = 0;
                    goto Label_03FF;

                case AggregateType.Var:
                case AggregateType.StDev:
                    num      = 0;
                    num2     = 0.0;
                    num19    = 0.0;
                    num3     = 0.0;
                    num15    = 0.0;
                    numArray = records;
                    num8     = 0;
                    goto Label_01EE;

                default:
                    goto Label_0424;
                }
Label_004B:
                num22 = numArray3[num10];
                if (!this.IsNull(num22))
                {
                    num18 += this.values[num22];
                    flag   = true;
                }
                num10++;
Label_007F:
                if (num10 < numArray3.Length)
                {
                    goto Label_004B;
                }
                if (flag)
                {
                    return(num18);
                }
                return(base.NullValue);

Label_00BE:
                num21 = numArray2[num9];
                if (!this.IsNull(num21))
                {
                    num17 += this.values[num21];
                    num16++;
                    flag = true;
                }
                num9++;
Label_00F8:
                if (num9 < numArray2.Length)
                {
                    goto Label_00BE;
                }
                if (flag)
                {
                    return(num17 / ((double)num16));
                }
                return(base.NullValue);

Label_0186:
                num7 = numArray[num8];
                if (!this.IsNull(num7))
                {
                    num3  += this.values[num7];
                    num15 += this.values[num7] * this.values[num7];
                    num++;
                }
                num8++;
Label_01EE:
                if (num8 < numArray.Length)
                {
                    goto Label_0186;
                }
                if (num <= 1)
                {
                    return(base.NullValue);
                }
                num2  = ((SqlDouble)(num * num15)) - (num3 * num3);
                num19 = num2 / (num3 * num3);
                bool x = num19 < 1E-15;
                if (!SqlBoolean.op_True(x))
                {
                }
                if (SqlBoolean.op_True(x | (num2 < 0.0)))
                {
                    num2 = 0.0;
                }
                else
                {
                    num2 /= (double)(num * (num - 1));
                }
                if (kind == AggregateType.StDev)
                {
                    return(Math.Sqrt(num2.Value));
                }
                return(num2);

Label_02CB:
                num13 = records[num6];
                if (!this.IsNull(num13))
                {
                    if (SqlDouble.LessThan(this.values[num13], maxValue).IsTrue)
                    {
                        maxValue = this.values[num13];
                    }
                    flag = true;
                }
                num6++;
Label_031B:
                if (num6 < records.Length)
                {
                    goto Label_02CB;
                }
                if (flag)
                {
                    return(maxValue);
                }
                return(base.NullValue);

Label_034A:
                num11 = records[num5];
                if (!this.IsNull(num11))
                {
                    if (SqlDouble.GreaterThan(this.values[num11], minValue).IsTrue)
                    {
                        minValue = this.values[num11];
                    }
                    flag = true;
                }
                num5++;
Label_039A:
                if (num5 < records.Length)
                {
                    goto Label_034A;
                }
                if (flag)
                {
                    return(minValue);
                }
                return(base.NullValue);

Label_03E9:
                if (!this.IsNull(records[num4]))
                {
                    num++;
                }
                num4++;
Label_03FF:
                if (num4 < records.Length)
                {
                    goto Label_03E9;
                }
                return(num);
            }
            catch (OverflowException)
            {
                throw ExprException.Overflow(typeof(SqlDouble));
            }
Label_0424:
            throw ExceptionBuilder.AggregateException(kind, base.DataType);
        }
Пример #55
0
 public static SqlBoolean Or(SqlBoolean x, SqlBoolean y)
 {
     return (x | y);
 }
Пример #56
0
 // Bitwise exclusive-OR (XOR)
 public static SqlBoolean Xor(SqlBoolean x, SqlBoolean y)
 {
     return (x ^ y);
 }
Пример #57
0
        public static void GetSkyline(SqlString strQuery, SqlString strOperators, SqlInt32 numberOfRecords,
                                      SqlInt32 sortType, SqlInt32 count, SqlInt32 dimension, SqlString algorithm, SqlBoolean hasIncomparable)
        {
            try
            {
                Type strategyType = Type.GetType("prefSQL.SQLSkyline." + algorithm.ToString());

                if (!typeof(SkylineStrategy).IsAssignableFrom(strategyType))
                {
                    throw new Exception("passed algorithm is not of type SkylineStrategy.");
                }

                var strategy = (SkylineStrategy)Activator.CreateInstance(strategyType);

                strategy.Provider                   = Helper.ProviderClr;
                strategy.ConnectionString           = Helper.CnnStringSqlclr;
                strategy.RecordAmountLimit          = numberOfRecords.Value;
                strategy.HasIncomparablePreferences = hasIncomparable.Value;
                strategy.SortType                   = sortType.Value;

                var skylineSample = new SkylineSampling
                {
                    SubsetCount      = count.Value,
                    SubsetDimension  = dimension.Value,
                    SelectedStrategy = strategy
                };

                DataTable     dataTableReturn    = skylineSample.GetSkylineTable(strQuery.ToString(), strOperators.ToString());
                SqlDataRecord dataRecordTemplate = skylineSample.DataRecordTemplateForStoredProcedure;

                //throw new Exception(dataTableReturn.Rows[0].Table.Columns.Count.ToString());

                if (SqlContext.Pipe != null)
                {
                    SqlContext.Pipe.SendResultsStart(dataRecordTemplate);

                    foreach (DataRow recSkyline in dataTableReturn.Rows)
                    {
                        for (var i = 0; i < recSkyline.Table.Columns.Count; i++)
                        {
                            dataRecordTemplate.SetValue(i, recSkyline[i]);
                        }
                        SqlContext.Pipe.SendResultsRow(dataRecordTemplate);
                    }
                    SqlContext.Pipe.SendResultsEnd();
                }
            }
            catch (Exception ex)
            {
                //Pack Errormessage in a SQL and return the result
                var strError = "Error in prefSQL_SkylineSampling: ";
                strError += ex.Message;

                if (SqlContext.Pipe != null)
                {
                    SqlContext.Pipe.Send(strError);
                }
            }
        }
Пример #58
0
 private PBoolean(PValueType type)
 {
     ValueType = type;
     _sql      = SqlBoolean.Null;
 }
Пример #59
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;
        }
Пример #60
0
    public static IEnumerable fnSystemFileCreate
    (
        SqlBinary inFileBinary,
        SqlString inSourceDirectory,
        SqlString inSourceFileName,
        SqlBoolean inOverwrite
    )
    {
        string formatMessage = string.Empty;

        // store the results in a list
        ArrayList resultCollection = new ArrayList();

        // logs the time the row had begun processing
        SqlDateTime startTime = DateTime.Now;

        // Complete file path
        string completePath = (string)inSourceDirectory + (string)inSourceFileName;

        // Check if the destination directory exists
        if (System.IO.Directory.Exists((string)inSourceDirectory) == false)
        {
            // Directory does not exist
            formatMessage = String.Format("Output directory {0} does not exist.  Please create this and try again.", (string)inSourceDirectory);
            resultCollection.Add(new FileResult(false, formatMessage, STATUS_CODES.FAILURE, null, startTime, DateTime.Now));
            return(resultCollection);
        }

        // Check if this file already exists
        if (System.IO.File.Exists(completePath) && inOverwrite == false)
        {
            // File already exists
            formatMessage = String.Format("Output file {0} already exists with no overwriting specified.  Please confirm overwrite and try again.", completePath);
            resultCollection.Add(new FileResult(false, formatMessage, STATUS_CODES.FAILURE, null, startTime, DateTime.Now));
            return(resultCollection);
        }

        // Create the file
        try
        {
            // binary to file operation
            if (!inFileBinary.IsNull)
            {
                long fsSize = 0;

                // otherwise convert the stream of bytes to a file
                FileStream fs = System.IO.File.Create(completePath);
                fs.Write(inFileBinary.Value, 0, inFileBinary.Value.Length);
                fsSize = fs.Length;
                fs.Close();

                // Update the success status
                formatMessage = String.Format("Varbinary data to disk file {0} created successfully.", completePath);
                resultCollection.Add(new FileResult(true, formatMessage, STATUS_CODES.SUCCESS, fsSize / 1024, startTime, DateTime.Now));
            }
        }
        catch (Exception ex)
        {
            formatMessage = String.Format("Unable to convert varbinary data to disk file {0}: {1}.\r\n{2}.", completePath, ex.Message, ex.StackTrace);
            resultCollection.Add(new FileResult(false, formatMessage, STATUS_CODES.FAILURE, null, startTime, DateTime.Now));
            return(resultCollection);
        }

        // All done
        return(resultCollection);
    }