示例#1
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;
 }
示例#2
0
 public static SqlString GetHttp(SqlString url)
 {
     if (url.IsNull) return SqlString.Null;
     var client = new WebClient();
     client.Encoding = Encoding.UTF8;
     return client.DownloadString(url.Value);
 }
示例#3
0
 public void String_Compare_Equal()
 {
     const string s = "Test string in UTF-16 LE";
     var sqlString1 = new SqlString(s);
     var sqlString2 = new SqlString(s);
     Assert.AreEqual(0, sqlString1.CompareTo(sqlString2));
 }
    public static void PR_GER_FileInfo(SqlString nom_Caminho)
    {

        FileInfo _file = new FileInfo(nom_Caminho.Value);

        List<SqlMetaData> colunas = new List<SqlMetaData>();
        //new SqlMetaData("stringcol", SqlDbType.NVarChar, 128)

        colunas.Add(new SqlMetaData("dat_Criacao", SqlDbType.DateTime));
        colunas.Add(new SqlMetaData("dat_UltimoAcesso", SqlDbType.DateTime));
        colunas.Add(new SqlMetaData("dat_UltimaEscrita", SqlDbType.DateTime));
        colunas.Add(new SqlMetaData("ind_Existe", SqlDbType.Bit));
        colunas.Add(new SqlMetaData("nom_Arquivo", SqlDbType.VarChar, 700));
        colunas.Add(new SqlMetaData("nom_Diretorio", SqlDbType.VarChar, 700));
        colunas.Add(new SqlMetaData("nom_Extensao", SqlDbType.VarChar, 700));

        colunas.Add(new SqlMetaData("val_Tamanho", SqlDbType.BigInt));

        SqlDataRecord record = new SqlDataRecord(colunas.ToArray());

        BindFile(_file, record);


        SqlContext.Pipe.Send(record);
    }
示例#5
0
		public SqlToken(SqlTokenType tokenType, SqlString sql, int sqlIndex, int length)
		{
			_tokenType = tokenType;
			_sql = sql;
			_sqlIndex = sqlIndex;
			_length = length;
		}
示例#6
0
    public static SqlBoolean RegExpCheck(SqlString source, [SqlFacet(MaxSize = 4000)] SqlString pattern)
    {
        if (source.IsNull || pattern.IsNull)
            return SqlBoolean.Null;

        return Regex.IsMatch(source.Value, pattern.Value);
    }
    public static void SampleWSPut(SqlString weburl, out SqlString returnval)
    {
        string url = Convert.ToString(weburl);
        string feedData = string.Empty;
        try {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream stream = null;
            StreamReader streamReader = null;

            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT"; // you have to change to
            //PUT/POST/GET/DELETE based on your scenerio…
            request.ContentLength = 0;
            response = (HttpWebResponse)request.GetResponse();
            stream = response.GetResponseStream();
            streamReader = new StreamReader(stream);
            feedData = streamReader.ReadToEnd();

            response.Close();
            stream.Dispose();
            streamReader.Dispose();

        } catch (Exception ex) {
            SqlContext.Pipe.Send(ex.Message.ToString());
        }
        returnval = feedData;
    }
    public static void FillRowFromSequencesAndExtraAndMissingNuc(object tableTypeObject, out SqlString mismatch, out SqlString indel)
    {
        var tableType = (MismatchInDelRow)tableTypeObject;

        mismatch = tableType.Mismatch;
        indel = tableType.Indel;
    }
    public static void SampleWSPost(SqlString weburl, out SqlString returnval)
    {
        string url = Convert.ToString(weburl);
        string feedData = string.Empty;
        try {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream stream = null;
            StreamReader streamReader = null;

            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            response = (HttpWebResponse)request.GetResponse();
            stream = response.GetResponseStream();
            streamReader = new StreamReader(stream);
            feedData = streamReader.ReadToEnd();
            response.Close();
            stream.Dispose();
            streamReader.Dispose();

        } catch (Exception ex) {
            SqlContext.Pipe.Send(ex.Message.ToString());
        }
        returnval = feedData;
    }
示例#10
0
 public static SqlString Or3(
     SqlString text0,
     SqlString text1,
     SqlString text2)
 {
     return OrSqlString(text0, text1, text2);
 }
 public static SqlDateTime ParamDateTimeTemp(SqlXml Xml, SqlString Name)
 {
     String ValueType;
       String Value = GetValueFromXMLAttribute(Xml, Name, out ValueType);
       if (Value == null) return new SqlDateTime();
       SqlDateTime Result;
       try
       {
     Result = new SqlDateTime(XmlConvert.ToDateTime(Value, XmlDateTimeSerializationMode.RoundtripKind));
       }
       catch (Exception Error)
       {
     throw new System.Exception("Error convert Param = \"" + Name.Value.ToString() + "\" Value = \"" + Value.ToString() + "\" to DateTime: " + Error.Message);
       }
       if (ValueType != null && ValueType != "")
       {
     // year, month, day, hour, minute, second
     switch (ValueType)
     {
       case "1": return Result.Value.Date.AddDays(1);
       default: return Result;
     }
       }
       return Result;
 }
    public static SqlString RegexReplace(SqlChars input, SqlString pattern, SqlChars replacement)
    {
        Regex regex = new Regex(pattern.Value, Options);

        return regex.Replace(new string(input.Value),new string(replacement.Value));
        ///return regex.IsMatch(new string(input.Value)); ///The SQL datatype here is a BIT
    }
示例#13
0
 public void Accumulate(SqlString value)
 {
     if (!value.IsNull)
     {
         this.intermediateResult.Append(value.Value).Append(", ");
     }
 }
示例#14
0
 public static SqlString Join2(
     SqlString separator,
     SqlString text0,
     SqlString text1)
 {
     return JoinString(separator, text0, text1);
 }
示例#15
0
 public static SqlString GetPinYin(SqlString word)
 {
     // 汉字 to 拼音首字母.
     string result = GetChineseSpell(word.ToString());
     // 返回.
     return new SqlString(result);
 }
示例#16
0
    public static object Lookup(object param, SqlString lookupQuery)
    {
        if (lookupQuery.IsNull || String.IsNullOrWhiteSpace(lookupQuery.Value))
            throw new ArgumentNullException("lookupQuery");

        var pparam = SqlValue.From(param);
        if (pparam == null || pparam.Value == null) return null;

        using (var conn = new SqlConnection("context connection=true"))
        using (var cmd = new SqlCommand(lookupQuery.Value, conn) { CommandType = CommandType.Text })
        {
            cmd.Parameters.Add(new SqlParameter("@value", pparam.Value));
            conn.Open();

            using (var reader = cmd.ExecuteReader())
            {
                if (reader.Read())
                {
                    var response = reader[0];
                    return response;
                }
            }

            conn.Close();
        }

        return null;
    }
示例#17
0
 public static SqlInt32 IsNucX(SqlInt64 posStart, SqlString misMNuc, SqlInt64 refPos, SqlString refNuc, SqlString countNuc)
 {
     SqlInt32 result;
     Dictionary<long, string> mutationPositions = new Dictionary<long, string>();
     string mutationPattern = @"[0-9]+ [ACGTN]+";
     MatchCollection matches = Regex.Matches(misMNuc.Value, mutationPattern);
     foreach (Match match in matches)
     {
         var foundMutation = match.Value;
         string[] foundMutParts = foundMutation.Split(' ');
         long mutStartPos = posStart.Value + Int32.Parse(foundMutParts[0]);
         var mutNuc = foundMutParts[1];
         mutationPositions.Add(mutStartPos, mutNuc);
     }
     string mutValue;
     if (mutationPositions.TryGetValue(refPos.Value, out mutValue))
     {
         result = new SqlInt32(countNuc.Value.Equals(mutValue) ? 1 : 0);
     }
     else
     {
         result = new SqlInt32(countNuc.Value.Equals(refNuc.Value) ? 1 : 0);
     }
     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);
 }
 public CompStrings(SqlString from, SqlString to, SqlString replace, SqlString tolerance, SqlString comp) {
     this.from = from.ToString();
     this.to = to.ToString();
     this.replace = replace.ToString();
     this.tolerance = tolerance.ToString();
     this.comp = comp.ToString();
 }
示例#20
0
 public static SqlString TakeNotNull2(
     SqlInt32 index,
     SqlString text0,
     SqlString text1)
 {
     return TakeNotNull(index, text0, text1);
 }
示例#21
0
 public static SqlChars RegexGroup( SqlChars input, SqlString pattern, SqlString name )
 {
     Regex regex = new Regex( pattern.Value, Options );
       Match match = regex.Match( new string( input.Value ) );
       return match.Success ?
         new SqlChars( match.Groups[name.Value].Value ) : SqlChars.Null;
 }
    public void Accumulate(SqlString StringValue,SqlString Delimiter)
    {
        if (!hasNull)
        {
            if (this.Delimiter == null)
            {
                this.Delimiter = Delimiter.Value;
            }

            if (!StringValue.IsNull)
            {
                if (StringValue.Value != null)
                {
                    intermediateResult.Add(StringValue.Value);
                }
                else
                {
                    hasNull = true;
                }
            }
            else
            {
                hasNull = true;
            }
        }
    }
示例#23
0
 public void Accumulate(SqlString Value)
 {
     if (!Value.IsNull)
     {
         sb.Append(Value).Append(", ");
     }
 }
示例#24
0
    public static void FillRowFromSeqStartEnd(object tableTypeObject, out SqlString substr, out SqlInt64 cnt)
    {
        var tableType = (SubstrCount)tableTypeObject;

        substr = tableType.Substr;
        cnt = tableType.Cnt;
    }
示例#25
0
 private static void DualFillRow(Object obj, ref SqlString item)
 {
     if (obj != null)
     {
         item = (string)obj;
     }
 }
示例#26
0
 public static SqlString UniqueList3(
     SqlString text0,
     SqlString text1,
     SqlString text2)
 {
     return UniqueList(text0, text1, text2);
 }
示例#27
0
文件: Function1.cs 项目: fatbudy/CSSM
 public static int GetParam(SqlString s)
 {
     // 在此处放置代码
     Regex _break_comp = new Regex(@"\{\d\}", RegexOptions.Compiled);
     return  _break_comp.Matches(s.ToString() ).Count;
     //return new SqlString("Hello");
 }
示例#28
0
 public static SqlString LookupText(SqlString param, SqlString lookupValues)
 {
     var found = LookupValue(param, lookupValues);
     return !String.IsNullOrWhiteSpace(found)
         ? new SqlString(found, param.LCID)
         : SqlString.Null;
 }
示例#29
0
文件: ToJson.cs 项目: jgcoding/J-SQL
 /// <summary>
 /// Accumulate the next value, not if the value is null
 /// </summary>
 /// <param name="itemValue"></param>
 public void Accumulate(SqlString itemKey, SqlString itemValue)
 {
     if (String.IsNullOrEmpty(itemKey.Value))
     {
         // don't process empty key-value pairs
         if (String.IsNullOrEmpty(itemValue.Value))
         {
             return;    
         }
         // this is a JObject token
         if (itemValue.Value.StartsWith("{@JObject", sc))
         {
             this.objType = "object";
             this.json.AppendFormat("{0},", FormatJsonValue(itemValue.Value));
         }
         // this is a JArray token
         else if (itemValue.Value.StartsWith("{@JArray", sc))
         {
             this.objType = "array";
             this.json.AppendFormat("{0},", FormatJsonValue(itemValue.Value));
         }
         // otherwise, handle simple arrays (non-key/value pairs)
         else
         {   
             this.objType = "array";
             this.json.AppendFormat("{0},", itemValue.Value.StartsWith("\"") ? itemValue.Value : FormatJsonValue(itemValue.Value));
         }
     }
     else/*handle key/value pairs*/
     {
         this.json.AppendFormat("\"{0}\":{1},", itemKey.Value, itemValue.Value.StartsWith("\"") ? itemValue.Value : FormatJsonValue(itemValue.Value));
     }
 }
示例#30
0
    public static SqlString RegExpSearch(SqlString source, [SqlFacet(MaxSize = 4000)] SqlString pattern)
    {
        if (source.IsNull || pattern.IsNull)
            return SqlString.Null;

        return Regex.Match(source.Value, pattern.Value).Value;
    }
示例#31
0
 public WhenParsingCommandText_ContainingAllClauses_SpecifyingClausesGroupBy()
 {
     this.sqlString = SqlString.Parse(
         "SELECT Column1, Column2, Column3 FROM Table WHERE Column1 = @p0 AND Column2 > @p1 GROUP BY Column3 ORDER BY Column2 DESC",
         Clauses.GroupBy);
 }
示例#32
0
 public WhenParsingEmptyCommandText()
 {
     this.sqlString = SqlString.Parse(
         string.Empty,
         Clauses.Select | Clauses.From | Clauses.Where | Clauses.GroupBy | Clauses.OrderBy);
 }
示例#33
0
 public WhenParsingCommandText_ContainingWhereWithoutGroupByOrOrderBy_SpecifyingClausesWhere()
 {
     this.sqlString = SqlString.Parse(
         "SELECT Column1, Column2, Column3 FROM Table WHERE Column1 = @p0 AND Column2 > @p1",
         Clauses.Where);
 }
示例#34
0
 public WhenParsingCommandText_ContainingWhereWithOrderByWithoutGroupBy_SpecifyingClausesFrom()
 {
     this.sqlString = SqlString.Parse(
         "SELECT Column1, Column2, Column3 FROM Table WHERE Column1 = @p0 AND Column2 > @p1 ORDER BY Column2 DESC",
         Clauses.From);
 }
示例#35
0
 public WhenParsingCommandText_ContainingOrderByWithoutWhereOrGroupBy_SpecifyingClausesFrom()
 {
     this.sqlString = SqlString.Parse(
         "SELECT Column1, Column2, Column3 FROM Table ORDER BY Column2 DESC",
         Clauses.From);
 }
示例#36
0
        /// <summary>
        /// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
        /// </summary>
        /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
        /// <remarks>
        /// Properties needed for this method:
        /// <UL>
        ///		 <LI>StrSizeCode</LI>
        /// </UL>
        /// Properties set after a succesful call of this method:
        /// <UL>
        ///		 <LI>ErrorCode</LI>
        ///		 <LI>StrSizeCode</LI>
        ///		 <LI>StrDescription</LI>
        /// </UL>
        /// Will fill all properties corresponding with a field in the table with the value of the row selected.
        /// </remarks>
        public override DataTable SelectOne()
        {
            SqlCommand cmdToExecute = new SqlCommand();

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

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

            try
            {
                cmdToExecute.Parameters.Add(new SqlParameter("@sstrSizeCode", SqlDbType.VarChar, 10, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _strSizeCode));
                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_tblSize_SelectOne' reported the ErrorCode: " + _errorCode);
                }

                if (toReturn.Rows.Count > 0)
                {
                    _strSizeCode    = (string)toReturn.Rows[0]["strSizeCode"];
                    _strDescription = toReturn.Rows[0]["strDescription"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["strDescription"];
                }
                return(toReturn);
            }
            catch (Exception ex)
            {
                // some error occured. Bubble it to caller and encapsulate Exception object
                throw new Exception("TblSize::SelectOne::Error occured.", ex);
            }
            finally
            {
                if (_mainConnectionIsCreatedLocal)
                {
                    // Close connection.
                    _mainConnection.Close();
                }
                cmdToExecute.Dispose();
                adapter.Dispose();
            }
        }
 public void RemoveUnusedCommandParameters(IDbCommand cmd, SqlString sqlString)
 {
     _innerDriver.RemoveUnusedCommandParameters(cmd, sqlString);
 }
 public override SqlString AppendIdentitySelectToInsert(SqlString insertString)
 {
     return(insertString.Append("\nselect @@identity"));
 }
 protected void InitProjection(SqlString projectionString, SqlString whereString, SqlString orderByString, SqlString groupByString, SqlString havingString, IDictionary <string, IFilter> enabledFilters, LockMode lockMode)
 {
     InitProjection(projectionString, whereString, orderByString, groupByString, havingString, enabledFilters, lockMode, Array.Empty <EntityProjection>());
 }
        private void InitStatementString(OuterJoinableAssociation rootAssociation, SqlString projection, SqlString condition, SqlString orderBy, SqlString groupBy, SqlString having, LockMode lockMode)
        {
            SqlString selectClause = projection;

            if (selectClause == null)
            {
                int joins = CountEntityPersisters(associations);

                Suffixes = BasicLoader.GenerateSuffixes(joins + 1);
                var suffix = Suffixes[joins];
                selectClause = new SqlString(GetSelectFragment(rootAssociation, suffix, null) + SelectString(associations));
            }

            JoinFragment ojf = MergeOuterJoins(associations);

            SqlSelectBuilder select = new SqlSelectBuilder(Factory)
                                      .SetLockMode(lockMode, alias)
                                      .SetSelectClause(selectClause)
                                      .SetFromClause(Dialect.AppendLockHint(lockMode, persister.FromTableFragment(alias)) + persister.FromJoinFragment(alias, true, true))
                                      .SetWhereClause(condition)
                                      .SetOuterJoins(ojf.ToFromFragmentString, ojf.ToWhereFragmentString + WhereFragment)
                                      .SetOrderByClause(OrderBy(associations, orderBy))
                                      .SetGroupByClause(groupBy)
                                      .SetHavingClause(having);

            if (Factory.Settings.IsCommentsEnabled)
            {
                select.SetComment(Comment);
            }

            SqlString = select.ToSqlString();
        }
        public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit)
        {
            SqlStringBuilder pagingBuilder = new SqlStringBuilder();

            pagingBuilder.Add(queryString);

            if (limit != null)
            {
                pagingBuilder.Add(" limit ");
                pagingBuilder.Add(limit);
            }

            if (offset != null)
            {
                pagingBuilder.Add(" offset ");
                pagingBuilder.Add(offset);
            }

            return(pagingBuilder.ToSqlString());
        }
 public override SqlString AddIdentifierOutParameterToInsert(SqlString insertString, string identifierColumnName, string parameterName)
 {
     return(insertString.Append(" returning ").Append(identifierColumnName));
 }
示例#43
0
        public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit)
        {
            var pagingBuilder = new SqlStringBuilder(queryString);

            pagingBuilder.Add(" limit ");

            if (offset != null)
            {
                pagingBuilder.Add(offset);
                pagingBuilder.Add(", ");
            }

            if (limit != null)
            {
                pagingBuilder.Add(limit);
            }
            else
            {
                pagingBuilder.Add(int.MaxValue.ToString());
            }

            return(pagingBuilder.ToSqlString());
        }
示例#44
0
 public StrRowString(int rowId, SqlString value)
 {
     RowId = rowId;
     Value = value;
 }
示例#45
0
        public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit)
        {
            // This does not support the Cache SQL 'DISTINCT BY (comma-list)' extensions,
            // but this extension is not supported through Hibernate anyway.
            int insertionPoint = queryString.StartsWithCaseInsensitive("select distinct") ? 15 : 6;

            return(new SqlStringBuilder(queryString.Length + 8)
                   .Add(queryString)
                   .Insert(insertionPoint, " TOP ? ")
                   .ToSqlString());
        }
示例#46
0
    public static void slog_loopback(
        String server,
        String dbname,
        out SqlInt64 logid,
        SqlString msgid,
        SqlInt32 errno,
        SqlByte severity,
        SqlInt32 logprocid,
        SqlString msgtext,
        SqlString errproc,
        SqlInt32 linenum,
        SqlString username,
        SqlString appname,
        SqlString hostname,
        SqlString p1,
        SqlString p2,
        SqlString p3,
        SqlString p4,
        SqlString p5,
        SqlString p6)
    {
        // A tip from Adam Machanic, see http://www.codemag.com/article/0705051
        // This matters in case there is a safe CLR assembly higher on the
        // call stack.
        SqlClientPermission scp = new SqlClientPermission(
            System.Security.Permissions.PermissionState.Unrestricted);

        scp.Assert();

        // Set up the connection string. Very important: Enlist must be false!
        SqlConnectionStringBuilder cstring = new SqlConnectionStringBuilder();

        cstring.DataSource         = server;
        cstring.InitialCatalog     = dbname;
        cstring.IntegratedSecurity = true;
        cstring.Enlist             = false;

        using (SqlConnection cnn = new SqlConnection(cstring.ConnectionString))
        {
            cnn.Open();

            // Set up the call and add all of the umpteen parameters.
            SqlCommand cmd = new SqlCommand("slog.log_insert_sp", cnn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@logid", SqlDbType.BigInt);
            cmd.Parameters["@logid"].Direction = ParameterDirection.Output;

            cmd.Parameters.Add("@msgid", SqlDbType.VarChar, 36);
            cmd.Parameters["@msgid"].Value = msgid;

            cmd.Parameters.Add("@errno", SqlDbType.Int);
            cmd.Parameters["@errno"].Value = errno;

            cmd.Parameters.Add("@severity", SqlDbType.TinyInt);
            cmd.Parameters["@severity"].Value = severity;

            cmd.Parameters.Add("@logprocid", SqlDbType.Int);
            cmd.Parameters["@logprocid"].Value = logprocid;

            cmd.Parameters.Add("@msgtext", SqlDbType.NVarChar, 2048);
            cmd.Parameters["@msgtext"].Value = msgtext;

            cmd.Parameters.Add("@errproc", SqlDbType.NVarChar, 128);
            cmd.Parameters["@errproc"].Value = errproc;

            cmd.Parameters.Add("@linenum", SqlDbType.Int);
            cmd.Parameters["@linenum"].Value = linenum;

            cmd.Parameters.Add("@username", SqlDbType.NVarChar, 128);
            cmd.Parameters["@username"].Value = username;

            cmd.Parameters.Add("@appname", SqlDbType.NVarChar, 128);
            cmd.Parameters["@appname"].Value = appname;

            cmd.Parameters.Add("@hostname", SqlDbType.NVarChar, 128);
            cmd.Parameters["@hostname"].Value = hostname;

            cmd.Parameters.Add("@p1", SqlDbType.NVarChar, 400);
            cmd.Parameters["@p1"].Value = p1;
            cmd.Parameters.Add("@p2", SqlDbType.NVarChar, 400);
            cmd.Parameters["@p2"].Value = p2;
            cmd.Parameters.Add("@p3", SqlDbType.NVarChar, 400);
            cmd.Parameters["@p3"].Value = p3;
            cmd.Parameters.Add("@p4", SqlDbType.NVarChar, 400);
            cmd.Parameters["@p4"].Value = p4;
            cmd.Parameters.Add("@p5", SqlDbType.NVarChar, 400);
            cmd.Parameters["@p5"].Value = p5;
            cmd.Parameters.Add("@p6", SqlDbType.NVarChar, 400);
            cmd.Parameters["@p6"].Value = p6;

            cmd.ExecuteNonQuery();

            // Get the output parameter.
            logid = new SqlInt64((Int64)cmd.Parameters["@logid"].Value);
        }
    }
示例#47
0
 private ISqlValue ToString(SqlString value, SqlType destType)
 {
     return(destType.NormalizeValue(value));
 }
示例#48
0
 public ForecastSalesRateCollectionKey(SqlString companyCode, SqlString customerNumber, SqlDateTime posWeekEndDateEnd)
 {
     CompanyCode     = companyCode;
     CustomerNumber  = customerNumber;
     POSSalesEndDate = posWeekEndDateEnd;
 }
示例#49
0
        public override SqlString GetLimitString(SqlString queryString, SqlString offset, SqlString limit)
        {
            // FIXME - This should use the ROWS syntax in Firebird to avoid problems with subqueries metioned here:
            // http://www.firebirdsql.org/refdocs/langrefupd20-select.html#langrefupd20-first-skip

            /*
             * "SELECT FIRST x [SKIP y] rest-of-sql-statement"
             */

            int insertIndex = GetAfterSelectInsertPoint(queryString);

            var limitFragment = new SqlStringBuilder();

            if (limit != null)
            {
                limitFragment.Add(" first ");
                limitFragment.Add(limit);
            }

            if (offset != null)
            {
                limitFragment.Add(" skip ");
                limitFragment.Add(offset);
            }

            return(queryString.Insert(insertIndex, limitFragment.ToSqlString()));
        }
示例#50
0
        public AdminENT SelectByUserNamePassword(SqlString UserName, SqlString Password)
        {
            using (SqlConnection objConn = new SqlConnection(ConnectionString))
            {
                objConn.Open();
                using (SqlCommand objCmd = objConn.CreateCommand())
                {
                    try
                    {
                        #region Prepare Command
                        objCmd.CommandType = CommandType.StoredProcedure;
                        objCmd.CommandText = "PR_Admin_SelectByUserNamePassword";
                        objCmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = UserName;
                        objCmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = Password;
                        #endregion Prepare Command

                        #region ReadData and Set Controls
                        AdminENT entAdmin = new AdminENT();

                        using (SqlDataReader objSDR = objCmd.ExecuteReader())
                        {
                            if (objSDR.HasRows == true)
                            {
                                while (objSDR.Read())
                                {
                                    if (!objSDR["AdminID"].Equals(DBNull.Value))
                                    {
                                        entAdmin.AdminID = Convert.ToInt32(objSDR["AdminID"]);
                                    }
                                    if (!objSDR["AdminName"].Equals(DBNull.Value))
                                    {
                                        entAdmin.AdminName = Convert.ToString(objSDR["AdminName"]);
                                    }
                                    if (!objSDR["AdminImage"].Equals(DBNull.Value))
                                    {
                                        entAdmin.AdminImage = Convert.ToString(objSDR["AdminImage"]);
                                    }
                                    if (!objSDR["Address"].Equals(DBNull.Value))
                                    {
                                        entAdmin.Address = Convert.ToString(objSDR["Address"]);
                                    }
                                    if (!objSDR["Email"].Equals(DBNull.Value))
                                    {
                                        entAdmin.Email = Convert.ToString(objSDR["Email"]);
                                    }
                                    if (!objSDR["Mobile"].Equals(DBNull.Value))
                                    {
                                        entAdmin.Mobile = Convert.ToString(objSDR["Mobile"]);
                                    }
                                    if (!objSDR["UserName"].Equals(DBNull.Value))
                                    {
                                        entAdmin.UserName = Convert.ToString(objSDR["UserName"]);
                                    }
                                }
                            }
                        }

                        return(entAdmin);

                        #endregion ReadData and Set Controls
                    }
                    catch (SqlException sqlEx)
                    {
                        Message = sqlEx.InnerException.Message;
                        return(null);
                    }
                    catch (Exception ex)
                    {
                        Message = ex.InnerException.Message;
                        return(null);
                    }
                    finally
                    {
                        if (objConn.State == ConnectionState.Open)
                        {
                            objConn.Close();
                        }
                    }
                }
            }
        }
示例#51
0
 public void AddSqlString()
 {
     Assert.Equal("First TestStringThis is just a test SqlString", (string)(SqlString.Add(_test1, _test2)));
     Assert.Equal("First TestStringPlainString", (string)(SqlString.Add(_test1, "PlainString")));
     Assert.True(SqlString.Add(_test1, null).IsNull);
 }
示例#52
0
        public void GetXsdTypeTest()
        {
            XmlQualifiedName qualifiedName = SqlString.GetXsdType(null);

            Assert.Equal("string", qualifiedName.Name);
        }
示例#53
0
        public void Clone()
        {
            SqlString TestSqlString = _test1.Clone();

            Assert.Equal(_test1, TestSqlString);
        }
示例#54
0
 public SqlStringTest()
 {
     _test1 = new SqlString("First TestString");
     _test2 = new SqlString("This is just a test SqlString");
     _test3 = new SqlString("This is just a test SqlString");
 }
        protected void InitProjection(SqlString projectionString, SqlString whereString, SqlString orderByString, SqlString groupByString, SqlString havingString, IDictionary <string, IFilter> enabledFilters, LockMode lockMode, IList <EntityProjection> entityProjections)
        {
            AddAssociations();

            int countEntities = entityProjections.Count;

            if (countEntities > 0)
            {
                var associations = new OuterJoinableAssociation[countEntities];
                var eagerProps   = new bool[countEntities];
                var suffixes     = new string[countEntities];
                for (var i = 0; i < countEntities; i++)
                {
                    var e = entityProjections[i];
                    associations[i] = CreateAssociation(e.Persister.EntityMetamodel.EntityType, e.TableAlias);
                    if (e.FetchLazyProperties)
                    {
                        eagerProps[i] = true;
                    }
                    suffixes[i] = e.ColumnAliasSuffix;
                }

                InitPersisters(associations, lockMode);

                Suffixes             = suffixes;
                EagerPropertyFetches = eagerProps;
            }
            else
            {
                Persisters = Array.Empty <ILoadable>();
                Suffixes   = Array.Empty <string>();
            }

            InitStatementString(null, projectionString, whereString, orderByString, groupByString, havingString, lockMode);
        }
 public void ExpandQueryParameters(IDbCommand cmd, SqlString sqlString)
 {
     _innerDriver.ExpandQueryParameters(cmd, sqlString);
 }
示例#57
0
 public void SetWithClauseFragment(String withClauseJoinAlias, SqlString withClauseFragment)
 {
     _withClauseJoinAlias = withClauseJoinAlias;
     _withClauseFragment  = withClauseFragment;
 }
示例#58
0
        public override DataTable SelectOne()
        {
            SqlCommand cmdToExecute = new SqlCommand();

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

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

            try
            {
                cmdToExecute.Parameters.Add(new SqlParameter("@RoomType_ID", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _roomType_ID));
                cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
                // Open connection.
                _mainConnection.Open();

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

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

                if (toReturn.Rows.Count > 0)
                {
                    _roomType_Online_ID = (Int32)toReturn.Rows[0]["RoomType_Online_ID"];
                    _roomType_ID        = (Int32)toReturn.Rows[0]["RoomType_ID"];
                    _description        = toReturn.Rows[0]["RoomType_OnlineDetails"] == System.DBNull.Value ? String.Empty : (string)toReturn.Rows[0]["RoomType_OnlineDetails"];
                    //_createdUser = (Int32)toReturn.Rows[0]["CreatedUser"];
                    //_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
                    //_lastModifiedUser = (Int32)toReturn.Rows[0]["LastModifiedUser"];
                    //_lastModifiedDate = (DateTime)toReturn.Rows[0]["LastModifiedDate"];

                    /*_num_rooms = (Int32)toReturn.Rows[0]["Number_Of_Rooms"];
                     *                  _num_adults = (Int32)toReturn.Rows[0]["Number_Of_Adults"];
                     *                  _num_kids = (Int32)toReturn.Rows[0]["Number_Of_Children"];
                     * _number_Of_Bathroom = (Int32)toReturn.Rows[0]["Number_Of_Bathrooms"];
                     * _number_Of_BedRooms = (Int32)toReturn.Rows[0]["Number_Of_BedRooms"];
                     * _number_Of_Kitchen = (Int32)toReturn.Rows[0]["Number_Of_Kitchen"];
                     * _number_Of_LivingRooms = (Int32)toReturn.Rows[0]["Number_Of_LivingRooms"];*/
                }
                return(toReturn);
            }
            catch (Exception ex)
            {
                // some error occured. Bubble it to caller and encapsulate Exception object
                throw new Exception("RoomType_OnlineDetails::SelectOne::Error occured.", ex);
            }
            finally
            {
                // Close connection.
                _mainConnection.Close();
                cmdToExecute.Dispose();
                adapter.Dispose();
            }
        }
        public UnionSubclassEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache,
                                            ISessionFactoryImplementor factory, IMapping mapping) : base(persistentClass, cache, factory)
        {
            if (IdentifierGenerator is IdentityGenerator)
            {
                throw new MappingException("Cannot use identity column key generation with <union-subclass> mapping for: " + EntityName);
            }

            // TABLE

            var dialect            = factory.Dialect;
            var defaultCatalogName = factory.Settings.DefaultCatalogName;
            var defaultSchemaName  = factory.Settings.DefaultSchemaName;

            tableName = persistentClass.Table.GetQualifiedName(dialect, defaultCatalogName, defaultSchemaName);

            #region Custom SQL

            SqlString sql;
            bool      callable;
            ExecuteUpdateResultCheckStyle checkStyle;

            sql        = persistentClass.CustomSQLInsert;
            callable   = sql != null && persistentClass.IsCustomInsertCallable;
            checkStyle = sql == null
                                                        ? ExecuteUpdateResultCheckStyle.Count
                                                        : (persistentClass.CustomSQLInsertCheckStyle
                                                           ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
            customSQLInsert         = new SqlString[] { sql };
            insertCallable          = new bool[] { callable };
            insertResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

            sql        = persistentClass.CustomSQLUpdate;
            callable   = sql != null && persistentClass.IsCustomUpdateCallable;
            checkStyle = sql == null
                                                        ? ExecuteUpdateResultCheckStyle.Count
                                                        : (persistentClass.CustomSQLUpdateCheckStyle
                                                           ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
            customSQLUpdate         = new SqlString[] { sql };
            updateCallable          = new bool[] { callable };
            updateResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

            sql        = persistentClass.CustomSQLDelete;
            callable   = sql != null && persistentClass.IsCustomDeleteCallable;
            checkStyle = sql == null
                                                        ? ExecuteUpdateResultCheckStyle.Count
                                                        : (persistentClass.CustomSQLDeleteCheckStyle
                                                           ?? ExecuteUpdateResultCheckStyle.DetermineDefault(sql, callable));
            customSQLDelete         = new SqlString[] { sql };
            deleteCallable          = new bool[] { callable };
            deleteResultCheckStyles = new ExecuteUpdateResultCheckStyle[] { checkStyle };

            #endregion

            discriminatorValue    = persistentClass.SubclassId;
            discriminatorSQLValue = persistentClass.SubclassId.ToString();

            #region PROPERTIES

            int subclassSpan = persistentClass.SubclassSpan + 1;
            subclassClosure    = new string[subclassSpan];
            subclassClosure[0] = EntityName;

            #endregion

            #region SUBCLASSES

            subclassByDiscriminatorValue[persistentClass.SubclassId] = persistentClass.EntityName;
            if (persistentClass.IsPolymorphic)
            {
                int k = 1;
                foreach (Subclass sc in persistentClass.SubclassIterator)
                {
                    subclassClosure[k++] = sc.EntityName;
                    subclassByDiscriminatorValue[sc.SubclassId] = sc.EntityName;
                }
            }

            #endregion

            #region SPACES
            //TODO: i'm not sure, but perhaps we should exclude abstract denormalized tables?

            int spacesSize = 1 + persistentClass.SynchronizedTables.Count;
            spaces    = new string[spacesSize];
            spaces[0] = tableName;
            using (var iSyncTab = persistentClass.SynchronizedTables.GetEnumerator())
            {
                for (var i = 1; i < spacesSize; i++)
                {
                    iSyncTab.MoveNext();
                    spaces[i] = iSyncTab.Current;
                }
            }

            subclassSpaces = persistentClass.SubclassTableClosureIterator
                             .Select(table =>
                                     table.GetQualifiedName(dialect, defaultCatalogName, defaultSchemaName))
                             .Distinct().ToArray();

            subquery = GenerateSubquery(persistentClass, mapping);

            if (IsMultiTable)
            {
                var tableNames = new List <string>();
                var keyColumns = new List <string[]>();
                if (!IsAbstract)
                {
                    tableNames.Add(tableName);
                    keyColumns.Add(IdentifierColumnNames);
                }
                foreach (var tab in persistentClass.SubclassTableClosureIterator)
                {
                    if (!tab.IsAbstractUnionTable)
                    {
                        string _tableName =
                            tab.GetQualifiedName(dialect, defaultCatalogName, defaultSchemaName);
                        tableNames.Add(_tableName);

                        var names = tab.PrimaryKey.ColumnIterator
                                    .Select(column => column.GetQuotedName(dialect))
                                    .ToArray();

                        keyColumns.Add(names);
                    }
                }

                constraintOrderedTableNames     = tableNames.ToArray();
                constraintOrderedKeyColumnNames = keyColumns.ToArray();
            }
            else
            {
                constraintOrderedTableNames     = new string[] { tableName };
                constraintOrderedKeyColumnNames = new string[][] { IdentifierColumnNames };
            }
            #endregion

            InitLockers();

            InitSubclassPropertyAliasesMap(persistentClass);

            PostConstruct(mapping);
        }
示例#60
0
        public virtual async Task <DbCommand> PrepareBatchCommandAsync(CommandType type, SqlString sql, SqlType[] parameterTypes, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (sql.Equals(_batchCommandSql) && ArrayHelper.ArrayEquals(parameterTypes, _batchCommandParameterTypes))
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("reusing command " + _batchCommand.CommandText);
                }
            }
            else
            {
                _batchCommand               = await(PrepareCommandAsync(type, sql, parameterTypes, cancellationToken)).ConfigureAwait(false);    // calls ExecuteBatch()
                _batchCommandSql            = sql;
                _batchCommandParameterTypes = parameterTypes;
            }

            return(_batchCommand);
        }