예제 #1
0
        private void Setup(int hvoPara)
        {
            int vernWs = StTxtPara.GetWsAtParaOffset(m_cache, hvoPara, 0);

            if (vernWs == m_vernWs)
            {
                return;                 // already setup.
            }
            m_vernWs = vernWs;
            string        sql = string.Format("select txt from WfiWordform_Form where ws={0}", vernWs);
            IOleDbCommand odc = DbOps.MakeRowSet(m_cache, sql, null);

            m_maxChars = 0;
            try
            {
                bool fMoreRows;
                odc.NextRow(out fMoreRows);
                while (fMoreRows)
                {
                    string word = DbOps.ReadString(odc, 0);
                    m_words.Add(word);
                    m_maxChars = Math.Max(m_maxChars, word.Length);
                    odc.NextRow(out fMoreRows);
                }
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
        }
예제 #2
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Execute the query sql, which contains one string parameter whose value is
        /// supplied as param. The result is a single rowset, which may contain one or
        /// zero rows. If it contains zero rows, return val as 0 and result false.
        /// If it contains (at least) one row, read an integer from the first column
        /// of the first row, return it in val, and return true. (but if the value is
        /// null, return 0 and true.)
        /// </summary>
        /// <param name="cache">parameter value, or null if not required.</param>
        /// <param name="sql">The SQL.</param>
        /// <param name="param">optional string parameter...if null, query needs none.</param>
        /// <param name="val">The val.</param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        /// ------------------------------------------------------------------------------------
        protected virtual bool InternalReadOneIntFromCommand(FdoCache cache, string sql, string param,
                                                             out int val)
        {
            val = 0;
            IOleDbCommand odc = null;

            try
            {
                odc = MakeRowSet(cache, sql, param);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);

                if (!fMoreRows)
                {
                    return(false);
                }
                val = ReadInt(odc, 0);
            }
            finally
            {
                ShutdownODC(ref odc);
            }

            return(true);
        }
 //------------------------------------------------------------------------------
 //
 // Method: MicrosoftAccessMetricLoggerImplementation (constructor)
 //
 //------------------------------------------------------------------------------
 /// <summary>
 /// Initialises a new instance of the ApplicationMetrics.MicrosoftAccessMetricLoggerImplementation class.  Note this is an additional constructor to facilitate unit tests, and should not be used to instantiate the class under normal conditions.
 /// </summary>
 /// <param name="databaseFilePath">The full path to the Microsoft Access data file.</param>
 /// <param name="metricCategoryName">The name of the category which the metric events should be logged under in the database.</param>
 /// <param name="bufferProcessingStrategy">Object which implements a processing strategy for the buffers (queues).</param>
 /// <param name="intervalMetricChecking">Specifies whether an exception should be thrown if the correct order of interval metric logging is not followed (e.g. End() method called before Begin()).</param>
 /// <param name="dbConnection">A test (mock) database connection object.</param>
 /// <param name="dbCommand">A test (mock) database command object.</param>
 /// <param name="dateTime">A test (mock) DateTime object.</param>
 /// <param name="exceptionHandler">A test (mock) exception handler object.</param>
 public MicrosoftAccessMetricLoggerImplementation(string databaseFilePath, string metricCategoryName, IBufferProcessingStrategy bufferProcessingStrategy, bool intervalMetricChecking, IOleDbConnection dbConnection, IOleDbCommand dbCommand, IDateTime dateTime, IExceptionHandler exceptionHandler)
     : base(bufferProcessingStrategy, intervalMetricChecking, dateTime, exceptionHandler)
 {
     InitialisePrivateMembers(databaseFilePath, metricCategoryName);
     this.dbConnection = dbConnection;
     this.dbCommand    = dbCommand;
 }
예제 #4
0
        /// <summary>
        /// Have the utility do what it does.
        /// </summary>
        public void Process()
        {
            IOleDbCommand odc = null;

            m_dlg.ProgressBar.Minimum = 0;
            m_dlg.ProgressBar.Maximum = 100;
            m_dlg.ProgressBar.Step    = 50;
            m_dlg.ProgressBar.PerformStep();
            try
            {
                Debug.Assert(m_dlg != null);
                // Send the query to the database.
                FdoCache cache = (FdoCache)m_dlg.Mediator.PropertyTable.GetValue("cache");
                string   db    = cache.DatabaseName;
                cache.DatabaseAccessor.CreateCommand(out odc);
                odc.ExecCommand(m_sqlQuery, (int)SqlStmtType.knSqlStmtNoResults);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(
                    String.Format(LexTextStrings.ksErrorMsgWithStackTrace, e.Message, e.StackTrace));
            }
            finally
            {
                if (odc != null)
                {
                    Marshal.FinalReleaseComObject(odc);
                }
            }
        }
예제 #5
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Fix any writing system references in the database that should be using the newly
        /// created vernacular writing system. Currently this only affects Sort methods.
        /// </summary>
        /// ------------------------------------------------------------------------------------
        protected void FixVernacularWritingSystemReferences(FdoCache cache)
        {
            // Force the first vernacular writing system into the canned sort specs coming
            // from NewLangProj.xml where they refer to names or abbreviations in people and
            // location lists, since these default to showing vernacular languages first.
            string sSql = "declare @ws int " +
                          "select top 1 @ws = Dst from LangProject_CurVernWss " +
                          "update CmSortSpec set PrimaryWs = @ws " +
                          "  where PrimaryField in ('13,13009,7001','13,13006,7001','13,7001','13,7002'," +
                          "'12,7001','12,7002','4006,4006003,7001','4006,4006007,7001','4006,4006002,7001') " +
                          "update CmSortSpec set SecondaryWs = @ws " +
                          "  where SecondaryField in ('13,13009,7001','13,13006,7001','13,7001','13,7002'," +
                          "'12,7001','12,7002','4006,4006003,7001','4006,4006007,7001','4006,4006002,7001') " +
                          "update CmSortSpec set TertiaryWs = @ws " +
                          "  where TertiaryField in ('13,13009,7001','13,13006,7001','13,7001','13,7002'," +
                          "'12,7001','12,7002','4006,4006003,7001','4006,4006007,7001','4006,4006002,7001')";

            IOleDbCommand odc = null;

            cache.DatabaseAccessor.CreateCommand(out odc);
            try
            {
                odc.ExecCommand(sSql, (int)SqlStmtType.knSqlStmtNoResults);
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
        }
예제 #6
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Release the given parameter, and set the input variable to null.
 /// </summary>
 /// <param name="odc">Referecne to the object to close down.</param>
 /// ------------------------------------------------------------------------------------
 static public void ShutdownODC(ref IOleDbCommand odc)
 {
     if ((odc != null) && Marshal.IsComObject(odc))
     {
         Marshal.FinalReleaseComObject(odc);
         odc = null;
     }
 }
예제 #7
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Release the given parameter, and set the input variable to null.
		/// </summary>
		/// <param name="odc">Referecne to the object to close down.</param>
		/// ------------------------------------------------------------------------------------
		static public void ShutdownODC(ref IOleDbCommand odc)
		{
			if ((odc != null) && Marshal.IsComObject(odc))
			{
				Marshal.FinalReleaseComObject(odc);
				odc = null;
			}
		}
예제 #8
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Read a string (up to 4000 characters) from the specified column of the result set.
 /// (This should not be used yet for BigString propertis which might exceed 4000 chars.)
 /// </summary>
 /// <param name="odc">The odc.</param>
 /// <param name="icol">The icol.</param>
 /// <returns></returns>
 /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
 /// ------------------------------------------------------------------------------------
 public static string ReadString(IOleDbCommand odc, int icol)
 {
     byte[] rgbTemp = ReadBytes(odc, icol);
     if (rgbTemp == null)
     {
         return("");
     }
     return(Encoding.Unicode.GetString(rgbTemp));
 }
 //------------------------------------------------------------------------------
 //
 // Method: MicrosoftAccessMetricLoggerImplementation (constructor)
 //
 //------------------------------------------------------------------------------
 /// <summary>
 /// Initialises a new instance of the ApplicationMetrics.MicrosoftAccessMetricLoggerImplementation class.
 /// </summary>
 /// <param name="databaseFilePath">The full path to the Microsoft Access data file.</param>
 /// <param name="metricCategoryName">The name of the category which the metric events should be logged under in the database.</param>
 /// <param name="bufferProcessingStrategy">Object which implements a processing strategy for the buffers (queues).</param>
 /// <param name="intervalMetricChecking">Specifies whether an exception should be thrown if the correct order of interval metric logging is not followed (e.g. End() method called before Begin()).</param>
 public MicrosoftAccessMetricLoggerImplementation(string databaseFilePath, string metricCategoryName, IBufferProcessingStrategy bufferProcessingStrategy, bool intervalMetricChecking)
     : base(bufferProcessingStrategy, intervalMetricChecking)
 {
     InitialisePrivateMembers(databaseFilePath, metricCategoryName);
     dbConnection = new OleDbConnection();
     // Need to cast the connection to an OleDbConnection in order to get the underlying connection
     //   Usually would avoid casting, but in this case it should be safe, as the member was just set to this object type on the previous line
     dbCommand = new OleDbCommand("", ((OleDbConnection)dbConnection).Connection);
 }
예제 #10
0
        /// <summary>
        /// Load the information about the domains of hvoEntry. Returns false
        /// if the entry has no associated domains or none of them are linked to any other entries.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="hvoEntry"></param>
        /// <param name="domains"></param>
        /// <param name="cdaTemp"></param>
        /// <param name="fMoreRows"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        static private bool LoadDomainInfo(FdoCache cache, int hvoEntry, out int[] domainsOut, out IVwCacheDa cdaTemp, IWin32Window owner)
        {
            // This produces first the Semantic domains of the senses of the entry,
            // then restricts to those that occur on some other entry,
            // then looks up the vernacular (or, if none, analysis) name of the domains. The are sorted by
            // domain name.
            // We do left outer joins for the last two so we can distinguish the failure
            // modes "no SDs on senses of initial entry" versus "no other entries in those SDs"
            string sql1 = string.Format("select lssd2.dst, cn.txt, cn.ws from LexEntry le"
                                        + " join LexSense_ ls on ls.owner$ = le.id"
                                        + " join LexSense_SemanticDomains lssd on lssd.src = ls.id "
                                        + " left outer join LexSense_SemanticDomains lssd2 on lssd2.dst = lssd.dst"
                                        + " and exists (select * from CmObject lsother"
                                        + " join LexEntry leother on leother.id = lsother.owner$ and lsother.id = lssd2.src and leother.id != le.id)"
                                        + " left outer join CmPossibility_Name cn on lssd2.dst = cn.obj and cn.ws"
                                        + " in ({0}, {1}) where le.id = {2}"
                                        + " group by lssd2.dst, cn.txt, cn.ws"
                                        + " order by cn.txt", cache.DefaultVernWs, cache.DefaultAnalWs, hvoEntry);

            IOleDbCommand odc           = DbOps.MakeRowSet(cache, sql1, null);
            bool          fGotSrcDomain = false;    // true if we found a semantic domain on some sense of the source entry

            try
            {
                bool       fMoreRows;
                List <int> domains = new List <int>();
                cdaTemp = VwCacheDaClass.Create();
                for (odc.NextRow(out fMoreRows); fMoreRows; odc.NextRow(out fMoreRows))
                {
                    fGotSrcDomain = true;                     // any row indicates success here.
                    int hvoDomain = DbOps.ReadInt(odc, 0);
                    if (hvoDomain == 0)
                    {
                        continue;                         // null row, an SD that occurs on no other entry.
                    }
                    if (!((ISilDataAccess)cdaTemp).get_IsPropInCache(hvoDomain, RelatedWordsVc.ktagName,
                                                                     (int)CellarModuleDefns.kcptString, 0))
                    {
                        ITsString tss = DbOps.ReadTss2(odc, 1);
                        if (tss == null)
                        {
                            tss = FDO.Cellar.CmPossibility.BestAnalysisOrVernName(cache, hvoDomain);
                        }
                        cdaTemp.CacheStringProp(hvoDomain, RelatedWordsVc.ktagName,
                                                tss);
                        domains.Add(hvoDomain);
                    }
                }
                domainsOut = DbOps.ListToIntArray(domains);
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
            return(fGotSrcDomain);
        }
예제 #11
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Read a string (up to 4000 characters) from the specified column of the result set.
        /// (This should not be used yet for BigString properties which might exceed 4000 chars.)
        /// Also read the following column to obtain a writing system.
        /// Returns null if ws is zero (or null).
        /// </summary>
        /// <param name="odc">The odc.</param>
        /// <param name="icol">The icol.</param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        /// ------------------------------------------------------------------------------------
        public static ITsString ReadTss2(IOleDbCommand odc, int icol)
        {
            int ws = ReadInt(odc, icol + 1);

            if (ws != 0)
            {
                return(ReadTss(odc, icol, ws));
            }
            return(null);
        }
예제 #12
0
        // Note: There used to be a method here called AsSql(string data) that just put quotes around any data.
        // Putting strings directly into SQL queries is very dangerous, and a user uncovered this bug by trying
        // to create a custom field with an apostrophe.  All string data should be put into the query using
        // SetStringParamter.

        /// <summary>
        /// Used in preparing a string for an SQL command.  Returns "null" if the string passed in is null, returns "?"
        /// if the string isn't null.  The odc handle is used to do a SetStringParameter with the string and index passed in.
        /// </summary>
        /// <param name="data">string to insert into query</param>
        /// <param name="odc">odc handle to use</param>
        /// <param name="index">index to use for the SetStringParameter if the string is not null.  Will be incremented if the string is not null.</param>
        /// <returns></returns>
        private string AsSql(string data, IOleDbCommand odc, ref uint index)
        {
            if (data == null)
            {
                return("null");
            }

            odc.SetStringParameter(index, (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
                                   null, data, (uint)data.Length);

            index++;              // Increment the index by one for next time

            return("?");
        }
예제 #13
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Return a byte array read from the specified column
 /// </summary>
 /// <param name="odc">The odc.</param>
 /// <param name="icol">ZERO-based column index.</param>
 /// <returns>null or byte array</returns>
 /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
 /// ------------------------------------------------------------------------------------
 public static byte[] ReadBytes(IOleDbCommand odc, int icol)
 {
     using (ArrayPtr prgch = MarshalEx.ArrayToNative(4000, typeof(byte)))
     {
         uint cbSpaceTaken;
         bool fIsNull;
         odc.GetColValue((uint)(icol + 1), prgch, prgch.Size, out cbSpaceTaken, out fIsNull, 0);
         if (fIsNull)
         {
             return(null);
         }
         return((byte[])MarshalEx.NativeToArray(prgch, (int)cbSpaceTaken, typeof(byte)));
     }
 }
예제 #14
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Read the icol'th column from the current row as an integer. Return zero if the
        /// value is null.
        /// </summary>
        /// <param name="odc">The odc.</param>
        /// <param name="icol">ZERO-based column number</param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        /// ------------------------------------------------------------------------------------
        public static int ReadInt(IOleDbCommand odc, int icol)
        {
            bool fIsNull;
            uint cbSpaceTaken;

            using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
            {
                odc.GetColValue((uint)(icol + 1), rgHvo, rgHvo.Size, out cbSpaceTaken, out fIsNull, 0);
                if (fIsNull)
                {
                    return(0);
                }
                return(IntFromStartOfUintArrayPtr(rgHvo));
            }
        }
예제 #15
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// <summary>
        /// Execute the query sql, which contains zero or one string parameter whose value is
        /// supplied as param (or null). The result is a single rowset, which may contain zero or
        /// more rows, each containing cols columns, each an integer value. Read the entire rowset,
        /// returning a List of int[cols] arrays.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="cols"></param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        static public List <int[]> ReadIntArray(FdoCache cache, string sql, string param, int cols)
        {
            List <int[]>  resultList = new List <int[]>();
            IOleDbCommand odc        = null;

            try
            {
                cache.DatabaseAccessor.CreateCommand(out odc);
                if (param != null)
                {
                    odc.SetStringParameter(1,                   // 1-based parameter index
                                           (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
                                           null,                //flags
                                           param,
                                           (uint)param.Length); // despite doc, impl makes clear this is char count
                }
                odc.ExecCommand(sql, (int)SqlStmtType.knSqlStmtSelectWithOneRowset);
                odc.GetRowset(0);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);
                using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
                {
                    while (fMoreRows)
                    {
                        int[] result = new int[cols];
                        for (int i = 0; i < cols; ++i)
                        {
                            bool fIsNull;
                            uint cbSpaceTaken;
                            odc.GetColValue((uint)(i + 1), rgHvo, rgHvo.Size, out cbSpaceTaken, out fIsNull, 0);
                            if (!fIsNull)
                            {
                                result[i] = IntFromStartOfUintArrayPtr(rgHvo);
                            }
                        }
                        resultList.Add(result);
                        odc.NextRow(out fMoreRows);
                    }
                }
            }
            finally
            {
                ShutdownODC(ref odc);
            }
            return(resultList);
        }
예제 #16
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Internals the read ints from command.
        /// </summary>
        /// <param name="cache">The cache.</param>
        /// <param name="sql">The SQL.</param>
        /// <param name="param">The param.</param>
        /// <returns></returns>
        /// ------------------------------------------------------------------------------------
        protected virtual List <int> InternalReadIntsFromCommand(FdoCache cache, string sql, string param)
        {
            List <int>    list = new List <int>();
            IOleDbCommand odc  = null;

            try
            {
                cache.DatabaseAccessor.CreateCommand(out odc);
                if (param != null)
                {
                    odc.SetStringParameter(1,                   // 1-based parameter index
                                           (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
                                           null,                //flags
                                           param,
                                           (uint)param.Length); // despite doc, impl makes clear this is char count
                }
                odc.ExecCommand(sql, (int)SqlStmtType.knSqlStmtSelectWithOneRowset);
                odc.GetRowset(0);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);
                bool fIsNull;
                uint cbSpaceTaken;

                using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
                {
                    while (fMoreRows)
                    {
                        odc.GetColValue(1, rgHvo, rgHvo.Size, out cbSpaceTaken, out fIsNull, 0);
                        if (!fIsNull)
                        {
                            list.Add(IntFromStartOfUintArrayPtr(rgHvo));
                        }
                        odc.NextRow(out fMoreRows);
                    }
                }
            }
            finally
            {
                ShutdownODC(ref odc);
            }
            return(list);
        }
예제 #17
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// <summary>
        /// Execute the query sql, which contains one required integer parameter whose value is
        /// supplied as param. The result is a single rowset, which may contain zero or
        /// more rows. Read an integer from each row and return them as a List.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="sql"></param>
        /// <param name="param">Required integer parameter.</param>
        /// <returns>A List containing zero, or more, integers.</returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        static public List <int> ReadIntsFromCommand(FdoCache cache, string sql, int param)
        {
            List <int>    list = new List <int>();
            IOleDbCommand odc  = null;

            try
            {
                cache.DatabaseAccessor.CreateCommand(out odc);
                uint uintSize = (uint)Marshal.SizeOf(typeof(uint));
                odc.SetParameter(1,           // 1-based parameter index
                                 (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
                                 null,        //flags
                                 (ushort)DBTYPEENUM.DBTYPE_I4,
                                 new uint[] { (uint)param },
                                 uintSize);
                odc.ExecCommand(sql, (int)SqlStmtType.knSqlStmtSelectWithOneRowset);
                odc.GetRowset(0);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);
                bool fIsNull;
                uint cbSpaceTaken;

                using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
                {
                    while (fMoreRows)
                    {
                        odc.GetColValue(1, rgHvo, uintSize, out cbSpaceTaken, out fIsNull, 0);
                        if (!fIsNull)
                        {
                            list.Add(IntFromStartOfUintArrayPtr(rgHvo));
                        }
                        odc.NextRow(out fMoreRows);
                    }
                }
            }
            finally
            {
                ShutdownODC(ref odc);
            }
            return(list);
        }
예제 #18
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// <summary>
        /// Execute the specified SQL and return the string which should be the first column of the first row.
        /// If there aren't that many rows return null.
        /// </summary>
        public static string ReadString(FdoCache cache, string sql, string param)
        {
            IOleDbCommand odc = null;

            try
            {
                odc = MakeRowSet(cache, sql, param);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);

                if (!fMoreRows)
                {
                    return(null);
                }
                return(ReadString(odc, 0));
            }
            finally
            {
                ShutdownODC(ref odc);
            }
        }
예제 #19
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// <summary>
        /// Execute the query sql, which may contain one string parameter whose value is
        /// supplied as param. The result is a single rowset, which may contain one or
        /// zero rows. If it contains zero rows, return 0.
        /// If it contains (at least) one row, read a long from the first column
        /// of the first row and return it. Return zero if it is null.
        /// </summary>
        /// <param name="cache">Cache to read from.</param>
        /// <param name="sql"></param>
        /// <param name="param">optional string parameter...if null, query needs none.</param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        public static long ReadOneLongFromCommand(FdoCache cache, string sql, string param)
        {
            IOleDbCommand odc = null;

            try
            {
                odc = MakeRowSet(cache, sql, param);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);

                if (!fMoreRows)
                {
                    return(0);
                }
                bool fIsNull;
                uint cbSpaceTaken;
                using (ArrayPtr src = MarshalEx.ArrayToNative(1, typeof(long)))
                {
                    odc.GetColValue((uint)(1), src, src.Size, out cbSpaceTaken, out fIsNull, 0);
                    if (fIsNull)
                    {
                        return(0);
                    }
                    // Unfortunately this produces a long with the bytes reversed.
                    ulong revVal = (ulong)Marshal.ReadInt64(src.IntPtr);
                    ulong result = 0;
                    for (int i = 0; i < 8; i++)
                    {
                        ulong b = (revVal >> i * 8) % 0x100;
                        result += b << ((7 - i) * 8);
                    }
                    return((long)result);
                }
            }
            finally
            {
                ShutdownODC(ref odc);
            }
        }
예제 #20
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Execute some arbitrary sql, which may take one
        /// optional parameter (pass null if no param is needed). It is not expected
        /// to return any results.
        /// </summary>
        /// <param name="cache">The cache.</param>
        /// <param name="sql">The SQL.</param>
        /// <param name="param">The param.</param>
        /// ------------------------------------------------------------------------------------
        public static void ExecuteStatementNoResults(FdoCache cache, string sql, string param)
        {
            IOleDbCommand odc = null;

            try
            {
                cache.DatabaseAccessor.CreateCommand(out odc);
                if (param != null)
                {
                    odc.SetStringParameter(1,                   // 1-based parameter index
                                           (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
                                           null,                //flags
                                           param,
                                           (uint)param.Length); // despite doc, impl makes clear this is char count
                }
                odc.ExecCommand(sql, (int)SqlStmtType.knSqlStmtNoResults);
            }
            finally
            {
                ShutdownODC(ref odc);
            }
        }
예제 #21
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Return an array of strings given an SQL query.
        /// <param name="cache">The cache in use</param>
        /// <param name="qry">An SQL query to execute</param>
        /// </summary>
        /// ------------------------------------------------------------------------------------

        public static string[] ReadMultiUnicodeTxtStrings(FdoCache cache, string qry)
        {
            StringCollection col = new StringCollection();
            IOleDbCommand    odc = null;

            cache.DatabaseAccessor.CreateCommand(out odc);
            try
            {
                uint cbSpaceTaken;
                bool fMoreRows;
                bool fIsNull;
                uint uintSize = (uint)Marshal.SizeOf(typeof(uint));
                odc.ExecCommand(qry, (int)SqlStmtType.knSqlStmtSelectWithOneRowset);
                odc.GetRowset(0);
                odc.NextRow(out fMoreRows);
                while (fMoreRows)
                {
                    using (ArrayPtr prgchName = MarshalEx.ArrayToNative(4000, typeof(char)))
                    {
                        odc.GetColValue(1, prgchName, prgchName.Size, out cbSpaceTaken, out fIsNull, 0);
                        byte[] rgbTemp = (byte[])MarshalEx.NativeToArray(prgchName, (int)cbSpaceTaken, typeof(byte));
                        col.Add(Encoding.Unicode.GetString(rgbTemp));
                    }
                    odc.NextRow(out fMoreRows);
                }
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
            string[] strings = new string[col.Count];
            for (int i = 0; i < col.Count; ++i)
            {
                strings[i] = col[i];
            }
            return(strings);
        }
예제 #22
0
        /// <summary>
        /// Load the information about the lexical relations that link to hvoEntry.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="hvoEntry"></param>
        /// <param name="relsOut"></param>
        /// <param name="cdaTemp"></param>
        /// <param name="owner"></param>
        /// <returns>false if the entry has no associated lexical relations, or none of them are linked to any other entries.</returns>
        static private bool LoadLexicalRelationInfo(FdoCache cache, int hvoEntry, out int[] relsOut,
                                                    IVwCacheDa cdaTemp, IWin32Window owner)
        {
            string sql1 = string.Format("SELECT DISTINCT tar2.Src, lrt.MappingType, tar.Ord, cn.Txt, cn.Ws, rev.Txt, rev.Ws"
                                        + " FROM LexReference_Targets tar"
                                        + " LEFT OUTER JOIN LexReference_Targets tar2 ON tar2.Src=tar.Src AND EXISTS (SELECT * FROM CmObject other WHERE other.Id=tar2.Dst AND other.Id != tar.Dst)"
                                        + " LEFT OUTER JOIN LexRefType_Members mem ON mem.Dst=tar2.Src"
                                        + " LEFT OUTER JOIN LexRefType lrt ON lrt.Id=mem.Src"
                                        + " LEFT OUTER JOIN CmPossibility_Name cn ON cn.Obj=mem.Src AND cn.Ws IN ({0}, {1})"
                                        + " LEFT OUTER JOIN LexRefType_ReverseName rev ON rev.Obj=mem.Src AND rev.Ws IN ({0}, {1})"
                                        + " WHERE tar.Dst = {2} OR tar.Dst IN (SELECT Id FROM fnGetOwnedIds({2}, {3}, {4}))",
                                        cache.DefaultVernWs, cache.DefaultAnalWs, hvoEntry,
                                        (int)LexEntry.LexEntryTags.kflidSenses, (int)LexSense.LexSenseTags.kflidSenses);

            IOleDbCommand odc        = DbOps.MakeRowSet(cache, sql1, null);
            bool          fGotLexRef = false;    // true if we found a lexical relation for the entry or one of its senses

            try
            {
                bool       fMoreRows;
                List <int> rels = new List <int>();
                for (odc.NextRow(out fMoreRows); fMoreRows; odc.NextRow(out fMoreRows))
                {
                    fGotLexRef = true;
                    int hvoLexRef = DbOps.ReadInt(odc, 0);
                    if (hvoLexRef == 0)
                    {
                        continue;                               // null row.
                    }
                    if (!((ISilDataAccess)cdaTemp).get_IsPropInCache(hvoLexRef, RelatedWordsVc.ktagName,
                                                                     (int)CellarModuleDefns.kcptString, 0))
                    {
                        int       type       = DbOps.ReadInt(odc, 1);
                        int       ord        = DbOps.ReadInt(odc, 2);
                        ITsString tssName    = DbOps.ReadTss2(odc, 3);
                        ITsString tssRevName = DbOps.ReadTss2(odc, 5);
                        if (type == (int)LexRefType.MappingTypes.kmtEntryAsymmetricPair ||
                            type == (int)LexRefType.MappingTypes.kmtEntryOrSenseAsymmetricPair ||
                            type == (int)LexRefType.MappingTypes.kmtSenseAsymmetricPair)
                        {
                            if (ord != 0 && tssRevName != null && tssRevName.Length > 0)
                            {
                                tssName = tssRevName;
                            }
                        }
                        else if (type == (int)LexRefType.MappingTypes.kmtEntryTree ||
                                 type == (int)LexRefType.MappingTypes.kmtEntryOrSenseTree ||
                                 type == (int)LexRefType.MappingTypes.kmtSenseTree)
                        {
                            if (ord != 0 && tssRevName != null && tssRevName.Length > 0)
                            {
                                tssName = tssRevName;
                            }
                        }
                        cdaTemp.CacheStringProp(hvoLexRef, RelatedWordsVc.ktagName, tssName);
                        rels.Add(hvoLexRef);
                    }
                }
                relsOut = DbOps.ListToIntArray(rels);
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
            return(fGotLexRef);
        }
예제 #23
0
        void SetupDomainsForEntry(int[] domains)
        {
            m_cdaTemp.CacheVecProp(m_hvoEntry, RelatedWordsVc.ktagDomains,
                                   domains, domains.Length);

            // This produces first the Semantic domains of the senses of the entry,
            // then uses a backreference to find all senses linked to those domains.
            // Todo JohnT: this finds only entries that directly own senses linked to the relevant domains.
            // It will not find entries that only have senses with subsenses in the domain.
            // This is because we're specifically looking for MoForms with the same owner as the senses we found.
            // We'd have to do something tricky and recursive to get owning entry of a subsense.
            string sql2 = string.Format("select lscd.dst, cmls.owner$, mff.txt from LexSense ls"
                                        + " join CmObject cols on ls.id = cols.id and cols.owner$ = {0}"
                                        + " join LexSense_SemanticDomains lscd on lscd.src = ls.id"
                                        + " join LexSense_SemanticDomains lscd2 on lscd2.dst = lscd.dst and lscd2.src != ls.id"
                                        + " join CmObject cmls on lscd2.src = cmls.id and cmls.owner$ != {0}"
                                        + " join MoForm_ mf on mf.owner$ = cmls.owner$ and mf.OwnFlid$ = {1}"
                                        + " join MoForm_Form mff on mff.obj = mf.id and mff.ws = {2}"
                                        + " group by lscd.dst, cmls.owner$, mff.txt"
                                        + " order by lscd.dst, mff.txt",
                                        m_hvoEntry, (int)LexEntry.LexEntryTags.kflidLexemeForm, m_cache.DefaultVernWs);

            IOleDbCommand odc = DbOps.MakeRowSet(m_cache, sql2, null);

            try
            {
                bool       fMoreRows;
                List <int> words        = new List <int>();
                int        hvoOldDomain = 0;           // to trigger change of domain on first iteration
                for (odc.NextRow(out fMoreRows); fMoreRows; odc.NextRow(out fMoreRows))
                {
                    int hvoNewDomain = DbOps.ReadInt(odc, 0);
                    if (hvoNewDomain != hvoOldDomain)
                    {
                        if (hvoOldDomain != 0)
                        {
                            m_cdaTemp.CacheVecProp(hvoOldDomain, RelatedWordsVc.ktagWords,
                                                   DbOps.ListToIntArray(words), words.Count);
                            words.Clear();
                        }
                        hvoOldDomain = hvoNewDomain;
                    }
                    int hvoWord = DbOps.ReadInt(odc, 1);
                    // JohnT: if I was better at sql, I could no doubt figure out how to prevent
                    // duplicates in the query above, which are caused by having two or more senses of the
                    // same entry in the same domain. But it's easier to just eliminate them here (and maybe
                    // even faster).
                    if (!words.Contains(hvoWord))
                    {
                        m_cdaTemp.CacheStringProp(hvoWord, RelatedWordsVc.ktagName,
                                                  DbOps.ReadTss(odc, 2, m_cache.DefaultVernWs));
                        words.Add(hvoWord);
                    }
                }
                if (hvoOldDomain != 0)
                {
                    // Cache words of last domain.
                    m_cdaTemp.CacheVecProp(hvoOldDomain, RelatedWordsVc.ktagWords,
                                           DbOps.ListToIntArray(words), words.Count);
                }
                int hvoLf = m_cache.MainCacheAccessor.get_ObjectProp(m_hvoEntry, (int)LexEntry.LexEntryTags.kflidLexemeForm);
                if (hvoLf != 0)
                {
                    ITsString tssCf = m_cache.MainCacheAccessor.get_MultiStringAlt(hvoLf,
                                                                                   (int)MoForm.MoFormTags.kflidForm, m_cache.DefaultVernWs);
                    m_cdaTemp.CacheStringProp(m_hvoEntry, RelatedWordsVc.ktagCf, tssCf);
                }
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
        }
예제 #24
0
        private void SetupLexRelsForEntry(int[] lexrels)
        {
            m_cdaTemp.CacheVecProp(m_hvoEntry, RelatedWordsVc.ktagLexRels,
                                   lexrels, lexrels.Length);
            // This query does not find subsenses.
            string sSql = String.Format(
                "SELECT tar.Src, tar.Dst, tar.Ord, tar2.Ord, lrt.MappingType, cf.Txt, mff.Txt, le.HomographNumber"
                + " FROM LexRefType lrt"
                + " JOIN LexRefType_Members mem ON mem.Src=lrt.Id"
                + " JOIN LexReference_Targets tar ON tar.Src=mem.Dst"
                + " JOIN LexReference_Targets tar2 ON tar2.Src=tar.Src AND (tar2.Dst={0} OR tar2.Dst IN (SELECT Dst FROM LexEntry_Senses WHERE Src={0}))"
                + " JOIN CmObject co ON co.Id=tar.Dst AND co.Id != {0} AND co.Id NOT IN (SELECT Dst FROM LexEntry_Senses WHERE Src={0})"
                + " JOIN LexEntry le ON le.Id IN (co.Id, co.Owner$)"
                + " LEFT OUTER JOIN LexEntry_CitationForm cf ON cf.Obj=le.Id"
                + " LEFT OUTER JOIN MoForm_ mf ON mf.Owner$=le.Id AND mf.OwnFlid$={1}"
                + " LEFT OUTER JOIN MoForm_Form mff ON mff.Obj=mf.Id AND mff.Ws={2}"
                + " ORDER BY tar.Src, tar.Ord",
                m_hvoEntry, (int)LexEntry.LexEntryTags.kflidLexemeForm, m_cache.DefaultVernWs);
            IOleDbCommand odc = DbOps.MakeRowSet(m_cache, sSql, null);

            try
            {
                bool       fMoreRows;
                int        hvoOldLexRef = 0;           // to trigger change of lexical relation on first iteration
                List <int> refs         = new List <int>();
                for (odc.NextRow(out fMoreRows); fMoreRows; odc.NextRow(out fMoreRows))
                {
                    int hvoLexRef = DbOps.ReadInt(odc, 0);
                    if (hvoLexRef != hvoOldLexRef)
                    {
                        if (hvoOldLexRef != 0)
                        {
                            m_cdaTemp.CacheVecProp(hvoOldLexRef, RelatedWordsVc.ktagWords,
                                                   refs.ToArray(), refs.Count);
                            refs.Clear();
                        }
                        hvoOldLexRef = hvoLexRef;
                    }
                    int hvoRef = DbOps.ReadInt(odc, 1);
                    if (refs.Contains(hvoRef))
                    {
                        continue;
                    }
                    refs.Add(hvoRef);
                    int ordRef   = DbOps.ReadInt(odc, 2);
                    int ordEntry = DbOps.ReadInt(odc, 3);
                    int type     = DbOps.ReadInt(odc, 4);
                    if (type == (int)LexRefType.MappingTypes.kmtEntryOrSenseTree ||
                        type == (int)LexRefType.MappingTypes.kmtEntryTree ||
                        type == (int)LexRefType.MappingTypes.kmtSenseTree)
                    {
                        if (ordRef != 0 && ordEntry != 0)
                        {
                            continue;                                           // one of them has to be the root of the tree!
                        }
                    }
                    if (type == (int)LexRefType.MappingTypes.kmtEntryOrSenseSequence ||
                        type == (int)LexRefType.MappingTypes.kmtEntrySequence ||
                        type == (int)LexRefType.MappingTypes.kmtSenseSequence)
                    {
                        // Do we need to include the word itself in a sequence type relation for
                        // this dialog?
                    }
                    ITsString tss = DbOps.ReadTss(odc, 5, m_cache.DefaultVernWs);
                    if (tss == null || tss.Length == 0)
                    {
                        tss = DbOps.ReadTss(odc, 6, m_cache.DefaultVernWs);
                    }
                    if (tss == null || tss.Length == 0)
                    {
                        continue;
                    }
                    int homograph = DbOps.ReadInt(odc, 7);
                    if (homograph > 0)
                    {
                        ITsIncStrBldr tisb = tss.GetIncBldr();
                        tisb.SetIntPropValues((int)FwTextPropType.ktptSuperscript,
                                              (int)FwTextPropVar.ktpvEnum, (int)FwSuperscriptVal.kssvSub);
                        tisb.SetIntPropValues((int)FwTextPropType.ktptBold,
                                              (int)FwTextPropVar.ktpvEnum, (int)FwTextToggleVal.kttvForceOn);
                        tisb.SetIntPropValues((int)FwTextPropType.ktptWs,
                                              (int)FwTextPropVar.ktpvDefault, m_cache.DefaultUserWs);
                        tisb.Append(homograph.ToString());
                        tss = tisb.GetString();
                    }
                    m_cdaTemp.CacheStringProp(hvoRef, RelatedWordsVc.ktagName, tss);
                }
                if (hvoOldLexRef != 0)
                {
                    m_cdaTemp.CacheVecProp(hvoOldLexRef, RelatedWordsVc.ktagWords,
                                           refs.ToArray(), refs.Count);
                    refs.Clear();
                }
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
        }
예제 #25
0
        public virtual void Init(Mediator mediator, XmlNode configurationParameters)
        {
            CheckDisposed();

            m_mediator = mediator;
            m_configurationParameters = configurationParameters;
            m_mediator.AddColleague(this);

            FdoCache cache = (FdoCache)m_mediator.PropertyTable.GetValue("cache");
            List <ILgWritingSystem> usedWses = new List <ILgWritingSystem>();

            using (new SuppressSubTasks(cache))
            {
                foreach (IReversalIndex rev in cache.LangProject.LexDbOA.ReversalIndexesOC)
                {
                    // This benign looking check of the count appears to do nothing,
                    // but it is very important as it ensures the vector is cached. Without it,
                    // crashes turn up in bulk deletion, as no PropChanged is sent,
                    // as the vector is not in the cache.
                    int entryCount = 0;
                    entryCount = rev.EntriesOC.Count;
                    usedWses.Add(rev.WritingSystemRA);
                    if (rev.PartsOfSpeechOA == null)
                    {
                        (rev as ReversalIndex).InitNewInternal();
                    }
                    if (rev.PartsOfSpeechOA.ItemClsid != PartOfSpeech.kClassId)
                    {
                        rev.PartsOfSpeechOA.ItemClsid = PartOfSpeech.kClassId;
                    }
                }
                List <IReversalIndex> corruptReversalIndices = new List <IReversalIndex>();
                foreach (IReversalIndex rev in cache.LangProject.LexDbOA.ReversalIndexesOC)
                {
                    // Make sure each index has a name, if it is available from the writing system.
                    if (rev.WritingSystemRA == null)
                    {
                        // Delete a bogus ReversalIndex that has no writing system.
                        // But, for now only store them for later deletion,
                        // as immediate removal will wreck the looping.
                        corruptReversalIndices.Add(rev);
                        continue;
                    }
                    ILgWritingSystem revWs = rev.WritingSystemRA;
                    string           sql   = string.Format("SELECT Ws, Txt FROM LgWritingSystem_Name WHERE Obj = {0}", revWs.Hvo);
                    IOleDbCommand    odc   = DbOps.MakeRowSet(cache, sql, null);
                    try
                    {
                        bool fMoreRows;
                        odc.NextRow(out fMoreRows);
                        while (fMoreRows)
                        {
                            int    wsHvo   = DbOps.ReadInt(odc, 0);
                            string nameWs  = DbOps.ReadString(odc, 1);
                            string nameRev = rev.Name.GetAlternative(wsHvo);
                            if ((nameRev == null || nameRev == String.Empty) &&
                                (nameWs != null && nameWs.Length > 0))
                            {
                                rev.Name.SetAlternative(nameWs, wsHvo);
                            }
                            odc.NextRow(out fMoreRows);
                        }
                    }
                    finally
                    {
                        DbOps.ShutdownODC(ref odc);
                    }
                }
                // Delete any corrupt reversal indices.
                foreach (IReversalIndex rev in corruptReversalIndices)
                {
                    rev.DeleteUnderlyingObject();
                }
            }
            // Set up for the reversal index combo box or dropdown menu.
            int        firstId     = 0;
            List <int> reversalIds = cache.LangProject.LexDbOA.CurrentReversalIndices;

            if (reversalIds.Count > 0)
            {
                firstId = reversalIds[0];
            }
            else if (cache.LangProject.LexDbOA.ReversalIndexesOC.Count > 0)
            {
                firstId = cache.LangProject.LexDbOA.ReversalIndexesOC.HvoArray[0];
            }
            if (firstId > 0)
            {
                SetReversalIndexHvo(firstId);
            }
        }
예제 #26
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Read a string (up to 4000 characters) from the specified column of the result set.
        /// (This should not be used yet for BigString propertis which might exceed 4000 chars.)
        /// </summary>
        /// <param name="odc">The odc.</param>
        /// <param name="icol">The icol.</param>
        /// <param name="ws">The ws.</param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        /// ------------------------------------------------------------------------------------
        public static ITsString ReadTss(IOleDbCommand odc, int icol, int ws)
        {
            ITsStrFactory tsf = TsStrFactoryClass.Create();

            return(tsf.MakeString(ReadString(odc, icol), ws));
        }
예제 #27
0
        public void LoadBasicData()
        {
            CheckDisposed();

            int hvoPhm_17_21 = 0;

            IOleDbCommand odc = null;

            try
            {
                m_fdoCache.DatabaseAccessor.CreateCommand(out odc);
                string sSql = @"select id from StTxtPara_ " +
                              @"where Owner$ = (select dst from scrsection_content c " +
                              @"join scrSection s on c.src = s.id " +
                              @"where s.VerseRefStart = 57001001) " +
                              @"and substring(contents, 1, 2) = '17'";
                odc.ExecCommand(sSql,
                                (int)SqlStmtType.knSqlStmtSelectWithOneRowset);
                odc.GetRowset(0);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);
                if (fMoreRows)
                {
                    odc.GetInt(1, out hvoPhm_17_21);
                }
            }
            finally
            {
                DbOps.ShutdownODC(ref odc);
            }
            //			SqlConnection sqlConMaster = new SqlConnection(
            //				string.Format("Server={0}; Database={1};" +
            //				"User ID = sa; Password=inscrutable; Pooling=false;",
            //				m_fdoCache.ServerName, m_fdoCache.DatabaseName));
            //			sqlConMaster.Open();
            //			SqlCommand sqlComm = sqlConMaster.CreateCommand();
            //			// Select the hvo of the paragraph containing Philemon 17-21.
            //			string sSql = @"select id from StTxtPara_ " +
            //				@"where Owner$ = (select dst from scrsection_content c " +
            //				@"join scrSection s on c.src = s.id " +
            //				@"where s.VerseRefStart = 57001001) " +
            //				@"and substring(contents, 1, 2) = '17'";
            //			sqlComm.CommandText = sSql;
            //			SqlDataReader sqlreader =
            //				sqlComm.ExecuteReader(System.Data.CommandBehavior.SingleResult);
            //			if (sqlreader.Read())
            //				hvoPhm_17_21 = sqlreader.GetInt32(0);
            //
            //			sqlreader.Close();
            //			sqlreader = null;
            //			sqlComm.Dispose();
            //			sqlComm = null;
            //			sqlConMaster.Close();
            //			sqlConMaster.Dispose();
            //			sqlConMaster = null;

            Assert.IsTrue(hvoPhm_17_21 > 0);

            NewStPara.s_fPopCalledInNewStPara = false;
            m_fdoCache.VwCacheDaAccessor.ClearInfoAbout(hvoPhm_17_21,
                                                        VwClearInfoAction.kciaRemoveObjectInfoOnly);
            NewStPara para = new NewStPara(m_fdoCache, hvoPhm_17_21);

            Assert.IsTrue(NewStPara.s_fPopCalledInNewStPara,
                          "PopulateCsBasic wasn't called in NewStPara");
            Assert.IsNotNull(para.Contents, "Contents of NewStPara is null");

            DerivedStTxtPara2.s_fPopCalledInNewStPara = false;
            DerivedStTxtPara2.s_fPopCalledInDerived   = false;
            m_fdoCache.VwCacheDaAccessor.ClearInfoAbout(hvoPhm_17_21,
                                                        VwClearInfoAction.kciaRemoveObjectInfoOnly);
            DerivedStTxtPara2 para2 = new DerivedStTxtPara2(m_fdoCache, hvoPhm_17_21);

            Assert.IsFalse(DerivedStTxtPara2.s_fPopCalledInNewStPara,
                           "PopulateCsBasic was called in NewStPara instead of DerivedStTxtPara2");
            Assert.IsTrue(DerivedStTxtPara2.s_fPopCalledInDerived,
                          "PoplulateCsBasic wasn't called in DerviedStTxtPara2");
            Assert.IsNotNull(para.Contents, "Contents of DerivedStTxtPara2 is null");

            DerivedStTxtPara.s_fPopCalledInNewStPara = false;
            m_fdoCache.VwCacheDaAccessor.ClearInfoAbout(hvoPhm_17_21,
                                                        VwClearInfoAction.kciaRemoveObjectInfoOnly);
            DerivedStTxtPara para3 = new DerivedStTxtPara(m_fdoCache, hvoPhm_17_21);

            Assert.IsTrue(DerivedStTxtPara.s_fPopCalledInNewStPara,
                          "PoplulateCsBasic wasn't called in DerviedStTxtPara");
            Assert.IsNotNull(para.Contents, "Contents of DerivedStTxtPara is null");
        }
예제 #28
0
파일: FwApp.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Read one int from a column in a result set. Indexes are 1-based.
		/// </summary>
		/// <param name="odc"></param>
		/// <param name="icol"></param>
		/// <returns></returns>
		/// ------------------------------------------------------------------------------------
		private int ReadColVal(IOleDbCommand odc, uint icol)
		{
			bool fIsNull;
			uint cbSpaceTaken;
			uint uintSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(uint));
			uint[] uIds;
			using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
			{
				odc.GetColValue(icol, rgHvo, uintSize, out cbSpaceTaken, out fIsNull, 0);
				uIds = (uint[])MarshalEx.NativeToArray(rgHvo, 1, typeof(uint));
			}
			return (int)uIds[0];
		}
예제 #29
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Read a string (up to 4000 characters) from the specified column of the result set.
		/// (This should not be used yet for BigString propertis which might exceed 4000 chars.)
		/// </summary>
		/// <param name="odc">The odc.</param>
		/// <param name="icol">The icol.</param>
		/// <returns></returns>
		/// <remarks>The SQL command must NOT modify the database in any way!</remarks>
		/// ------------------------------------------------------------------------------------
		public static string ReadString(IOleDbCommand odc, int icol)
		{
			byte[] rgbTemp = ReadBytes(odc, icol);
			if (rgbTemp == null)
				return "";
			return Encoding.Unicode.GetString(rgbTemp);
		}
예제 #30
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Read a string (up to 4000 characters) from the specified column of the result set.
		/// (This should not be used yet for BigString propertis which might exceed 4000 chars.)
		/// </summary>
		/// <param name="odc">The odc.</param>
		/// <param name="icol">The icol.</param>
		/// <param name="ws">The ws.</param>
		/// <returns></returns>
		/// <remarks>The SQL command must NOT modify the database in any way!</remarks>
		/// ------------------------------------------------------------------------------------
		public static ITsString ReadTss(IOleDbCommand odc, int icol, int ws)
		{
			ITsStrFactory tsf = TsStrFactoryClass.Create();
			return tsf.MakeString(ReadString(odc, icol), ws);
		}
예제 #31
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Read a string (up to 4000 characters) from the specified column of the result set.
		/// (This should not be used yet for BigString properties which might exceed 4000 chars.)
		/// Also read the following column to obtain a writing system.
		/// Returns null if ws is zero (or null).
		/// </summary>
		/// <param name="odc">The odc.</param>
		/// <param name="icol">The icol.</param>
		/// <returns></returns>
		/// <remarks>The SQL command must NOT modify the database in any way!</remarks>
		/// ------------------------------------------------------------------------------------
		public static ITsString ReadTss2(IOleDbCommand odc, int icol)
		{
			int ws = ReadInt(odc, icol + 1);
			if (ws != 0)
				return ReadTss(odc, icol, ws);
			return null;
		}
예제 #32
0
        /// <summary>
        /// Update modified row or add a new one, but only if it is a custom field.
        /// </summary>
        public void UpdateDatabase()
        {
            // We do nothing for builtin fields or rows that have not been modified.
            if (m_isDirty && IsCustomField)
            {
                String        sqlCommand;
                IOleDbCommand odc = null;
                m_cache.DatabaseAccessor.CreateCommand(out odc);
                try
                {
                    // TODO: Maybe check for required columns for custom fields.
                    if (IsInstalled)
                    {
                        // Update (or delete) existing row.
                        if (m_doDelete)
                        {
                            sqlCommand = string.Format("DELETE FROM Field$ WITH (SERIALIZABLE) WHERE Id={0}",
                                                       m_id);
                            // TODO KenZ(RandyR): What should happen to the data, if any exists?
                        }
                        else
                        {
                            // Only update changeable fields.
                            // Id, Type, Class, Name, Custom, and CustomId are not changeable by
                            // the user, once they have been placed in the DB, so we won't
                            // update them here no matter what.
                            uint index = 1;                             // Current parameter index
                            sqlCommand = string.Format("UPDATE Field$ WITH (SERIALIZABLE)" +
                                                       " SET Min={0}, Max={1}, Big={2}, UserLabel={3}," +
                                                       " HelpString={4}, ListRootId={5}, WsSelector={6}, XmlUI={7}" +
                                                       " WHERE Id={8}",
                                                       AsSql(m_min), AsSql(m_max), AsSql(m_big), AsSql(m_userlabel, odc, ref index),
                                                       AsSql(m_helpString, odc, ref index), AsSql(m_listRootId), AsWSSql(m_wsSelector),
                                                       AsSql(m_xmlUI, odc, ref index), m_id);
                        }
                        odc.ExecCommand(sqlCommand, (int)SqlStmtType.knSqlStmtNoResults);
                    }
                    else
                    {
                        // ================ Added Start ===========================
                        // First use a stored procedure to determine what the Name field should
                        // be, passing in the UserLabel for possible/future use.
                        string sqlQuery = "declare @res nvarchar(400)"
                                          + " exec GenerateCustomName @res OUTPUT"
                                          + " select @res";
                        uint cbSpaceTaken;
                        bool fMoreRows;
                        bool fIsNull;
                        using (ArrayPtr rgchUsername = MarshalEx.ArrayToNative(100, typeof(char)))
                        {
                            odc.ExecCommand(sqlQuery,
                                            (int)SqlStmtType.knSqlStmtStoredProcedure);
                            odc.GetRowset(0);
                            odc.NextRow(out fMoreRows);
                            // odc.GetColValue calls are all 1-based... (post error comment)
                            odc.GetColValue(1, rgchUsername, rgchUsername.Size, out cbSpaceTaken, out fIsNull,
                                            0);
                            byte[] rgbTemp = (byte[])MarshalEx.NativeToArray(rgchUsername,
                                                                             (int)cbSpaceTaken, typeof(byte));
                            m_name = Encoding.Unicode.GetString(rgbTemp);
                        }
                        // ================ Added End ===========================

                        // Note: There is no need to worry about deletion, as this one isn't in
                        // the DB.  Make new row in DB.
                        // Use SP to create the new one: .
                        uint uintSize = (uint)Marshal.SizeOf(typeof(uint));
                        uint index    = 1;
                        odc.SetParameter(index++, (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISOUTPUT,
                                         null, (ushort)DBTYPEENUM.DBTYPE_I4,
                                         new uint[1] {
                            0
                        }, uintSize);
                        sqlCommand = string.Format("exec AddCustomField$ ? output, {0}, {1}, {2}, " +
                                                   "{3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}",
                                                   AsSql(m_name, odc, ref index), m_type, m_class, AsSql(m_dstCls), AsSql(m_min),
                                                   AsSql(m_max), AsSql(m_big), AsSql(m_userlabel, odc, ref index), AsSql(m_helpString, odc, ref index),
                                                   AsSql(m_listRootId), AsWSSql(m_wsSelector), AsSql(m_xmlUI, odc, ref index));
                        using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
                        {
                            odc.ExecCommand(sqlCommand, (int)SqlStmtType.knSqlStmtStoredProcedure);
                            odc.GetParameter(1, rgHvo, uintSize, out fIsNull);
                            m_id = (int)(((uint[])MarshalEx.NativeToArray(rgHvo, 1,
                                                                          typeof(uint)))[0]);
                        }
                    }
                }
                finally
                {
                    DbOps.ShutdownODC(ref odc);
                }
                // Before continuing, we have to close any open transactions (essentially the
                // File/Save operation).  Otherwise, lots of things can break or timeout...
                if (m_cache.DatabaseAccessor.IsTransactionOpen())
                {
                    m_cache.DatabaseAccessor.CommitTrans();
                }
                if (m_cache.ActionHandlerAccessor != null)
                {
                    m_cache.ActionHandlerAccessor.Commit();
                }
            }
        }
예제 #33
0
		// Note: There used to be a method here called AsSql(string data) that just put quotes around any data.
		// Putting strings directly into SQL queries is very dangerous, and a user uncovered this bug by trying
		// to create a custom field with an apostrophe.  All string data should be put into the query using
		// SetStringParamter.

		/// <summary>
		/// Used in preparing a string for an SQL command.  Returns "null" if the string passed in is null, returns "?"
		/// if the string isn't null.  The odc handle is used to do a SetStringParameter with the string and index passed in.
		/// </summary>
		/// <param name="data">string to insert into query</param>
		/// <param name="odc">odc handle to use</param>
		/// <param name="index">index to use for the SetStringParameter if the string is not null.  Will be incremented if the string is not null.</param>
		/// <returns></returns>
		private string AsSql(string data, IOleDbCommand odc, ref uint index)
		{
			if (data == null)
				return "null";

			odc.SetStringParameter(index, (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
								null, data, (uint)data.Length);

			index++;  // Increment the index by one for next time

			return "?";
		}
예제 #34
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
        /// <summary>
        /// Execute the query sql, which optionally contains one string parameter whose value is
        /// supplied as param. The result is a single rowset, which may contain zero or
        /// more rows, each containing a pair of integers. The row set represents multiple
        /// sequences. A sequence is defined by consecutive rows with the same value for the first
        /// item. Each sequence is entered into the values dictionary, with the column 1 value
        /// as the key, and a list of the column 2 values as the value.
        /// Rows where either value is null or key is zero will be ignored.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="sql"></param>
        /// <param name="param">May be null, if not required.</param>
        /// <param name="values"></param>
        /// <returns></returns>
        /// <remarks>The SQL command must NOT modify the database in any way!</remarks>
        static public void LoadDictionaryFromCommand(FdoCache cache, string sql, string param, Dictionary <int, List <int> > values)
        {
            // As of 11/30/2006, all callers of this method are looking for reference sequence data,
            // so this List of ints cannot be a set.
            List <int>    list = null;
            IOleDbCommand odc  = null;

            try
            {
                cache.DatabaseAccessor.CreateCommand(out odc);
                if (param != null)
                {
                    odc.SetStringParameter(1,                   // 1-based parameter index
                                           (uint)DBPARAMFLAGSENUM.DBPARAMFLAGS_ISINPUT,
                                           null,                //flags
                                           param,
                                           (uint)param.Length); // despite doc, impl makes clear this is char count
                }
                odc.ExecCommand(sql, (int)SqlStmtType.knSqlStmtSelectWithOneRowset);
                odc.GetRowset(0);
                bool fMoreRows;
                odc.NextRow(out fMoreRows);
                bool fIsNull;
                uint cbSpaceTaken;

                int currentKey = 0;

                using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
                {
                    for (; fMoreRows; odc.NextRow(out fMoreRows))
                    {
                        int key, val;
                        odc.GetColValue(1, rgHvo, rgHvo.Size, out cbSpaceTaken, out fIsNull, 0);
                        if (fIsNull)
                        {
                            continue;
                        }
                        key = IntFromStartOfUintArrayPtr(rgHvo);
                        if (key == 0)
                        {
                            continue;
                        }
                        odc.GetColValue(2, rgHvo, rgHvo.Size, out cbSpaceTaken, out fIsNull, 0);
                        if (fIsNull)
                        {
                            continue;
                        }
                        val = IntFromStartOfUintArrayPtr(rgHvo);
                        if (key != currentKey)
                        {
                            list               = new List <int>();
                            currentKey         = key;
                            values[currentKey] = list;
                        }
                        list.Add(val);
                    }
                }
            }
            finally
            {
                ShutdownODC(ref odc);
            }
        }
예제 #35
0
        private CurrentContext WriteFieldStartTag(int flid)
        {
            CurrentContext ccOld = m_cc;
            string         sXml;

            try
            {
                int cpt = m_cache.MetaDataCacheAccessor.GetFieldType((uint)flid);
                switch (cpt)
                {
                case (int)CellarModuleDefns.kcptReferenceAtom:
                case (int)CellarModuleDefns.kcptReferenceCollection:
                case (int)CellarModuleDefns.kcptReferenceSequence:
                    m_cc = CurrentContext.insideLink;
                    break;

                default:
                    m_cc = CurrentContext.insideProperty;
                    break;
                }
                string sField = m_cache.MetaDataCacheAccessor.GetFieldName((uint)flid);
                sXml = GetFieldXmlElementName(sField, (uint)flid / 1000);
                if (sXml == "_" + sField && ccOld == CurrentContext.insideLink && m_cc == CurrentContext.insideProperty)
                {
                    AddMissingObjectLink();
                    sXml = GetFieldXmlElementName(sField, (uint)flid / 1000);
                }
                IndentLine();
                string sUserLabel = null;
                if (sField.StartsWith("custom"))
                {
                    if (!m_dictCustomUserLabels.TryGetValue(flid, out sUserLabel))
                    {
                        IOleDbCommand odc = null;
                        try
                        {
                            odc = DbOps.MakeRowSet(m_cache,
                                                   String.Format("SELECT UserLabel FROM Field$ WHERE Id={0}", flid), null);
                            bool fMoreRows;
                            odc.NextRow(out fMoreRows);
                            if (fMoreRows)
                            {
                                sUserLabel = XmlUtils.MakeSafeXmlAttribute(DbOps.ReadString(odc, 0));
                            }
                        }
                        finally
                        {
                            if (odc != null)
                            {
                                DbOps.ShutdownODC(ref odc);
                            }
                        }
                        m_dictCustomUserLabels.Add(flid, sUserLabel);
                    }
                }
                if (String.IsNullOrEmpty(sUserLabel))
                {
                    m_writer.WriteLine("<{0}>", sXml);
                }
                else
                {
                    m_writer.WriteLine("<{0} userlabel=\"{1}\">", sXml, sUserLabel);
                }
            }
            catch
            {
                sXml = String.Empty;
            }
            m_rgElementTags.Add(sXml);

            return(ccOld);
        }
예제 #36
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Read the icol'th column from the current row as an integer. Return zero if the
		/// value is null.
		/// </summary>
		/// <param name="odc">The odc.</param>
		/// <param name="icol">ZERO-based column number</param>
		/// <returns></returns>
		/// <remarks>The SQL command must NOT modify the database in any way!</remarks>
		/// ------------------------------------------------------------------------------------
		public static int ReadInt(IOleDbCommand odc, int icol)
		{
			bool fIsNull;
			uint cbSpaceTaken;
			using (ArrayPtr rgHvo = MarshalEx.ArrayToNative(1, typeof(uint)))
			{
				odc.GetColValue((uint)(icol + 1), rgHvo, rgHvo.Size, out cbSpaceTaken, out fIsNull, 0);
				if (fIsNull)
					return 0;
				return IntFromStartOfUintArrayPtr(rgHvo);
			}
		}
 //------------------------------------------------------------------------------
 //
 // Method: MicrosoftAccessMetricLogger (constructor)
 //
 //------------------------------------------------------------------------------
 /// <summary>
 /// Initialises a new instance of the ApplicationMetrics.MicrosoftAccessMetricLogger class.  Note this is an additional constructor to facilitate unit tests, and should not be used to instantiate the class under normal conditions.
 /// </summary>
 /// <param name="databaseFilePath">The full path to the Microsoft Access data file.</param>
 /// <param name="metricCategoryName">The name of the category which the metric events should be logged under in the database.</param>
 /// <param name="bufferProcessingStrategy">Object which implements a processing strategy for the buffers (queues).</param>
 /// <param name="intervalMetricChecking">Specifies whether an exception should be thrown if the correct order of interval metric logging is not followed (e.g. End() method called before Begin()).</param>
 /// <param name="dbConnection">A test (mock) database connection object.</param>
 /// <param name="dbCommand">A test (mock) database command object.</param>
 /// <param name="dateTime">A test (mock) DateTime object.</param>
 /// <param name="exceptionHandler">A test (mock) exception handler object.</param>
 public MicrosoftAccessMetricLogger(string databaseFilePath, string metricCategoryName, IBufferProcessingStrategy bufferProcessingStrategy, bool intervalMetricChecking, IOleDbConnection dbConnection, IOleDbCommand dbCommand, IDateTime dateTime, IExceptionHandler exceptionHandler)
 {
     loggerImplementation = new MicrosoftAccessMetricLoggerImplementation(databaseFilePath, metricCategoryName, bufferProcessingStrategy, intervalMetricChecking, dbConnection, dbCommand, dateTime, exceptionHandler);
 }
예제 #38
0
파일: DbOps.cs 프로젝트: sillsdev/WorldPad
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Return a byte array read from the specified column
		/// </summary>
		/// <param name="odc">The odc.</param>
		/// <param name="icol">ZERO-based column index.</param>
		/// <returns>null or byte array</returns>
		/// <remarks>The SQL command must NOT modify the database in any way!</remarks>
		/// ------------------------------------------------------------------------------------
		public static byte[] ReadBytes(IOleDbCommand odc, int icol)
		{
			using (ArrayPtr prgch = MarshalEx.ArrayToNative(4000, typeof(byte)))
			{
				uint cbSpaceTaken;
				bool fIsNull;
				odc.GetColValue((uint)(icol + 1), prgch, prgch.Size, out cbSpaceTaken, out fIsNull, 0);
				if (fIsNull)
					return null;
				return (byte[])MarshalEx.NativeToArray(prgch, (int)cbSpaceTaken, typeof(byte));
			}
		}