public void Connect() { Disconnect(); ComPtr pApplication = IntPtr.Zero; try { if (MarshalEx.Succeeded(MarshalEx.GetActiveObject("SolidEdge.Application", out pApplication))) { comTreeView.AddRootNode(pApplication, "Application"); } } catch { GlobalExceptionHandler.HandleException(); } finally { } }
//called when a change occurs in the bound collection private void ComboBoxEx_ListChanged(object sender, ListChangedEventArgs e) { if (m_updatable) { if (e.ListChangedType == ListChangedType.ItemChanged) { //update the item //delete old item Win32Window.SendMessage(this.Handle, CB_DELETESTRING, e.NewIndex, 0); //get display text for new item string newval = this.GetItemText(this.Items[e.NewIndex]); //marshal to native memory IntPtr pString = MarshalEx.StringToHGlobalUni(newval); //send message to native control Win32Window.SendMessage(this.Handle, CB_INSERTSTRING, e.NewIndex, pString); //free native memory MarshalEx.FreeHGlobal(pString); } } }
private PingReply InternalSend(IPAddress address, byte [] buffer, int timeout, PingOptions options) { if (_handlePingV4 == IntPtr.Zero) { _handlePingV4 = IcmpCreateFile(); } if (_replyBuffer == IntPtr.Zero) { _replyBuffer = MarshalEx.AllocHLocal(0xffff); } IPOptions ipo = new IPOptions(options); InitStructure(buffer); IcmpSendEcho2(_handlePingV4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, (uint)address.Address, _requestBuffer, (ushort)buffer.Length, ref ipo, _replyBuffer, 0xffff, (uint)timeout); FreeStructure(); IcmpEchoReply reply = (IcmpEchoReply)Marshal.PtrToStructure(this._replyBuffer, typeof(IcmpEchoReply)); return(new PingReply(reply)); }
public void StringFieldsTest() { CheckDisposed(); // Set class first, or it will throw an exception. int hvo = 1; uint clid = SilDataAccess.MetaDataCache.GetClassId("PhEnvironment"); SilDataAccess.SetInt(hvo, (int)CmObjectFields.kflidCmObject_Class, (int)clid); int tag = (int)SilDataAccess.MetaDataCache.GetFieldId("PhEnvironment", "StringRepresentation", false); ITsPropsBldr propsBldr = TsPropsBldrClass.Create(); propsBldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, "Verse"); ITsStrBldr strBldr = TsStrBldrClass.Create(); // Test StringFields (which are basically the same, except that the // format of the parameters is different) strBldr.Replace(0, 0, "Third", propsBldr.GetTextProps()); ITsString tsString = strBldr.GetString(); int cbFmt; byte[] rgbFmt; using (ArrayPtr arrayPtr = MarshalEx.ArrayToNative(1000, typeof(byte))) { cbFmt = tsString.SerializeFmtRgb(arrayPtr, 1000); rgbFmt = (byte[])MarshalEx.NativeToArray(arrayPtr, cbFmt, typeof(byte)); } VwCacheDa.CacheStringFields(hvo, tag, tsString.Text, tsString.Length, rgbFmt, cbFmt); strBldr.Replace(0, 5, "Fourth", propsBldr.GetTextProps()); tsString = strBldr.GetString(); VwCacheDa.CacheStringFields(hvo, tag, tsString.Text, tsString.Length, rgbFmt, cbFmt); ITsString tsStringNew = SilDataAccess.get_StringProp(hvo, tag); Assert.AreEqual(tsString.Text, tsStringNew.Text); }
public override int ExecuteNonQuery() { if (OpenReader != null) { throw new InvalidOperationException(Strings.OpenReaderExists); } if (_connection == null || _connection.State != ConnectionState.Open) { throw new InvalidOperationException(Strings.FormatCallRequiresOpenConnection("ExecuteNonQuery")); } if (string.IsNullOrWhiteSpace(_commandText)) { throw new InvalidOperationException(Strings.FormatCallRequiresSetCommandText("ExecuteNonQuery")); } ValidateTransaction(); Prepare(); Bind(); Debug.Assert(_connection.Handle != null && !_connection.Handle.IsInvalid, "_connection.Handle is null."); var changes = 0; foreach (var handle in _handles) { var hasChanges = NativeMethods.sqlite3_stmt_readonly(handle) == 0; NativeMethods.sqlite3_step(handle); var rc = NativeMethods.sqlite3_reset(handle); MarshalEx.ThrowExceptionForRC(rc); if (hasChanges) { changes += NativeMethods.sqlite3_changes(_connection.Handle); } } return(changes); }
public void GetClassIdsTest() { // Just use the count for all classes, // even though we know it will never be that high a number that can be returned. int[] ids; var countAllClasses = m_metaDataCache.ClassCount; using (var clids = MarshalEx.ArrayToNative <int>(countAllClasses)) { m_metaDataCache.GetClassIds(countAllClasses, clids); ids = MarshalEx.NativeToArray <int>(clids, countAllClasses); Assert.AreEqual(countAllClasses, ids.Length, "Wrong number of classes returned."); } countAllClasses = 2; using (var clids = MarshalEx.ArrayToNative <int>(countAllClasses)) { // Check ClassL (all of its direct subclasses). m_metaDataCache.GetClassIds(countAllClasses, clids); ids = MarshalEx.NativeToArray <int>(clids, 2); Assert.AreEqual(countAllClasses, ids.Length, "Wrong number of classes returned."); } }
private bool ConnectToSolidEdge() { ComPtr pApplication = IntPtr.Zero; try { if (MarshalEx.Succeeded(MarshalEx.GetActiveObject("SolidEdge.Application", out pApplication))) { _application = pApplication.TryGetUniqueRCW <SolidEdgeFramework.Application>(); _connectionPointController.AdviseSink <SolidEdgeFramework.ISEApplicationEvents>(_application); commandBrowser.ActiveEnvironment = _application.GetActiveEnvironment(); globalParameterBrowser.RefreshGlobalParameters(); objectBrowser.Connect(); // Older versions of Solid Edge don't have the ProcessID property. try { processBrowser.ProcessId = _application.ProcessID; } catch { } return(true); } } catch { GlobalExceptionHandler.HandleException(); } finally { pApplication.Dispose(); } return(false); }
public void UnicodeProp() { CheckDisposed(); string strNew = m_ISilDataAccess.get_UnicodeProp(1119, 2229); Assert.IsNull(strNew); Assert.IsFalse(m_ISilDataAccess.IsDirty()); string str = "UnicodeTest"; m_ISilDataAccess.SetUnicode(1119, 2229, str, str.Length); strNew = m_ISilDataAccess.get_UnicodeProp(1119, 2229); Assert.AreEqual(str, strNew); Assert.IsTrue(m_ISilDataAccess.IsDirty()); str = "SecondUnicodeTest"; m_ISilDataAccess.SetUnicode(1119, 2229, str, str.Length); strNew = m_ISilDataAccess.get_UnicodeProp(1119, 2229); Assert.AreEqual(str, strNew); Assert.IsTrue(m_ISilDataAccess.IsDirty()); str = "ThirdUnicodeTest"; m_ISilDataAccess.set_UnicodeProp(1119, 2229, str); int cch; using (ArrayPtr arrayPtr = MarshalEx.StringToNative(100, true)) { m_ISilDataAccess.UnicodePropRgch(1119, 2229, arrayPtr, 100, out cch); strNew = MarshalEx.NativeToString(arrayPtr, cch, true); Assert.AreEqual(str, strNew); Assert.AreEqual(str.Length, cch); Assert.IsTrue(m_ISilDataAccess.IsDirty()); m_ISilDataAccess.UnicodePropRgch(1119, 2229, ArrayPtr.Null, 0, out cch); Assert.AreEqual(str.Length, cch); CheckProp(1119, 2229, str, CellarModuleDefns.kcptUnicode); } }
public override bool Read() { if (_closed) { throw new InvalidOperationException(Strings.FormatDataReaderClosed("Read")); } if (!_stepped) { _stepped = true; return(_hasRows); } var rc = NativeMethods.sqlite3_step(_stmt); MarshalEx.ThrowExceptionForRC(rc, _db); _done = rc == SQLITE_DONE; return(!_done); }
/// <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); } }
private void Show() { m_data.pszHTML = MarshalEx.StringToHGlobalUni(mText); m_data.pszTitle = MarshalEx.StringToHGlobalUni(mCaption); m_data.hicon = mIcon; m_data.csDuration = mDuration; if (mDuration == 0) { m_data.npPriority = SHNP.ICONIC; } else { m_data.npPriority = SHNP.INFORM; } if (mCritical) { m_data.grfFlags |= SHNF.CRITICAL; } else { m_data.grfFlags ^= (m_data.grfFlags & SHNF.CRITICAL); } int hresult = SHNotificationAdd(ref m_data); if (m_data.pszTitle != IntPtr.Zero) { MarshalEx.FreeHGlobal(m_data.pszTitle); m_data.pszTitle = IntPtr.Zero; } if (m_data.pszHTML != IntPtr.Zero) { MarshalEx.FreeHGlobal(m_data.pszHTML); m_data.pszHTML = IntPtr.Zero; } }
/// <summary> /// Get an array of available network adapters /// </summary> /// <returns>aArray of AdapterInfo classes</returns> public static AdapterInfo[] GetAdaptersInfo() { ArrayList adapters = new ArrayList(); int cb = 0; int ret = GetAdaptersInfoCE(IntPtr.Zero, ref cb); IntPtr pInfo = MarshalEx.AllocHGlobal(cb); //LPTR ret = GetAdaptersInfoCE(pInfo, ref cb); if (ret == 0) { AdapterInfo info = new AdapterInfo(pInfo, 0); while (info != null) { adapters.Add(info); info = info.Next; } } MarshalEx.FreeHGlobal(pInfo); return((AdapterInfo[])adapters.ToArray(Type.GetType("OpenNETCF.Net.AdapterInfo"))); }
private void AddSubNodes(TreeNodeCollection parentNodeCollection, uint superClassClid) { int directSubclassCount; m_mdc.GetDirectSubclasses(superClassClid, 0, out directSubclassCount, null); uint[] uIds; using (ArrayPtr clids = MarshalEx.ArrayToNative(directSubclassCount, typeof(uint))) { m_mdc.GetDirectSubclasses(superClassClid, directSubclassCount, out directSubclassCount, clids); uIds = (uint[])MarshalEx.NativeToArray(clids, directSubclassCount, typeof(uint)); } SortedList <string, uint> list = new SortedList <string, uint>(uIds.Length); foreach (uint subclassClid in uIds) { string classname = m_mdc.GetClassName(subclassClid); list.Add(classname, subclassClid); } foreach (KeyValuePair <string, uint> kvp in list) { AddNode(parentNodeCollection, kvp.Key, kvp.Value); } }
public void StringFields_Simple() { CheckDisposed(); ITsPropsBldr propsBldr = TsPropsBldrClass.Create(); propsBldr.SetStrPropValue((int)FwTextPropType.ktptNamedStyle, "Verse"); ITsStrBldr strBldr = TsStrBldrClass.Create(); // Test StringFields (which are basically the same, except that the // format of the parameters is different) strBldr.Replace(0, 0, "Third", propsBldr.GetTextProps()); ITsString tsString = strBldr.GetString(); using (ArrayPtr arrayPtr = MarshalEx.ArrayToNative(1000, typeof(byte))) { int cbFmt = tsString.SerializeFmtRgb(arrayPtr, 1000); byte[] rgbFmt = (byte[])MarshalEx.NativeToArray(arrayPtr, cbFmt, typeof(byte)); m_IVwCacheDa.CacheStringFields(1118, 2228, tsString.Text, tsString.Length, rgbFmt, cbFmt); ITsString tsStringNew = m_ISilDataAccess.get_StringProp(1118, 2228); Assert.AreEqual(tsString.Text, tsStringNew.Text); } }
/// <summary> /// Get the list of writing systems currrently installed in the system. /// </summary> /// <param name="rgws"></param> /// <param name="cws"></param> public void GetWritingSystems(ArrayPtr rgws, int cws) { var wss = new int[cws]; int i = 0; foreach (CoreWritingSystemDefinition ws in WritingSystems) { if (i >= cws) { break; } wss[i] = ws.Handle; i++; } for (; i < cws; i++) { wss[i] = 0; } MarshalEx.ArrayToNative(rgws, cws, wss); }
/// ------------------------------------------------------------------------------------ /// <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); }
public override void Open() { if (State == ConnectionState.Open) { return; } if (ConnectionString == null) { throw new InvalidOperationException(Strings.OpenRequiresSetConnectionString); } var flags = Constants.SQLITE_OPEN_READWRITE | Constants.SQLITE_OPEN_CREATE; flags |= (ConnectionStringBuilder.Cache == SqliteConnectionCacheMode.Shared) ? Constants.SQLITE_OPEN_SHAREDCACHE : Constants.SQLITE_OPEN_PRIVATECACHE; var path = AdjustForRelativeDirectory(ConnectionStringBuilder.DataSource); var rc = NativeMethods.sqlite3_open_v2(path, out _db, flags, vfs: null); MarshalEx.ThrowExceptionForRC(rc, _db); SetState(ConnectionState.Open); SetFolders(); }
/// <summary> /// Gets all subclasses of the given class, /// including itself (which is always the first result in the list, /// so it can easily be skipped if desired). /// </summary> /// <param name='clid'>Class indentifier to work with.</param> /// <param name='countMaximumToReturn'>Count of the maximum number of subclass IDs to return (Size of the array.) /// When set to zero, countAllSubclasses will contain the full count, so a second call can use the right sized array.</param> /// <param name='countAllSubclasses'>Count of how many subclass IDs are the output array.</param> /// <param name='subclasses'>Array of subclass IDs.</param> /// <remarks> /// The list is therefore a complete list of the classes which are valid to store in a property whose /// signature is the class identified by 'clid'. /// </remarks> public void GetAllSubclasses(int clid, int countMaximumToReturn, out int countAllSubclasses, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ArrayPtrMarshaler), SizeParamIndex = 1)] ArrayPtr /*ULONG[]*/ subclasses) { // It's easier to just use the maximum than to fret about the right count. var ids = new int[countMaximumToReturn]; var allSubclassClids = new List <int>(countMaximumToReturn) { clid }; GetAllSubclassesForClid(clid, allSubclassClids); var iSubclassClid = 0; countAllSubclasses = Math.Min(countMaximumToReturn, allSubclassClids.Count); while (iSubclassClid < countAllSubclasses) { ids[iSubclassClid] = allSubclassClids[iSubclassClid]; ++iSubclassClid; } MarshalEx.ArrayToNative(subclasses, countMaximumToReturn, ids); }
/// <summary> /// Retrieves notification information associated with a handle. /// </summary> /// <param name="handle">Handle to the user notification to retrieve.</param> /// <returns>The requested UserNotification.</returns> public static UserNotificationInfoHeader GetUserNotification(int handle) { //buffer size int size = 0; //first query for buffer size required CeGetUserNotification(handle, 0, ref size, IntPtr.Zero); //create a marshallable buffer IntPtr buffer = MarshalEx.AllocHGlobal(size); //call native getter if (!CeGetUserNotification(handle, (uint)size, ref size, buffer)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Error getting UserNotification"); } UserNotificationInfoHeader nih = UserNotificationInfoHeader.FromPtr(buffer); //free native memory MarshalEx.FreeHGlobal(buffer); return(nih); }
private ITsTextProps spyOnSelection(IVwSelection sel) { // See what got selected int ihvoRoot = 0; // first rootbox int cvsli = sel.CLevels(true); // selection levels-1 involved cvsli--; int tag; int cpropPrevious; int ichAnchor; int ichEnd; int ws; bool fAssocPrev; int ihvoEnd1; ITsTextProps ttp; ArrayPtr rgvsliTemp = MarshalEx.ArrayToNative(cvsli, typeof(SelLevInfo)); sel.AllTextSelInfo(out ihvoRoot, cvsli, rgvsliTemp, out tag, out cpropPrevious, out ichAnchor, out ichEnd, out ws, out fAssocPrev, out ihvoEnd1, out ttp); SelLevInfo[] rgvsli = (SelLevInfo[])MarshalEx.NativeToArray(rgvsliTemp, cvsli, typeof(SelLevInfo)); // use the debugger to look at the vars. Can't get into ttp here. return(ttp); }
public void GetDirectSubclasses() { int countDirectSubclasses; using (var clids = MarshalEx.ArrayToNative <int>(10)) { // Check ClassL (all of its direct subclasses). m_metaDataCache.GetDirectSubclasses(35, 10, out countDirectSubclasses, clids); Assert.AreEqual(2, countDirectSubclasses, "Wrong number of subclasses returned."); var ids = MarshalEx.NativeToArray <int>(clids, 10); for (var i = 0; i < ids.Length; ++i) { var clid = ids[i]; if (i < 2) { Assert.IsTrue(((clid == 28) || (clid == 45)), "Clid should be 28 or 49 for direct subclasses of ClassL."); } else { Assert.AreEqual(0, clid, "Clid should be 0 from here on."); } } } }
public void get_Renderer_Graphite() { using (var control = new Form()) using (var gm = new GraphicsManager(control)) using (var reFactory = new RenderEngineFactory()) { gm.Init(1.0f); try { var wsManager = new WritingSystemManager(); // by default Graphite is disabled CoreWritingSystemDefinition ws = wsManager.Set("en-US"); var chrp = new LgCharRenderProps { ws = ws.Handle, szFaceName = new ushort[32] }; MarshalEx.StringToUShort("Charis SIL", chrp.szFaceName); gm.VwGraphics.SetupGraphics(ref chrp); IRenderEngine engine = reFactory.get_Renderer(ws, gm.VwGraphics); Assert.IsNotNull(engine); Assert.AreSame(wsManager, engine.WritingSystemFactory); Assert.IsInstanceOf(typeof(UniscribeEngine), engine); ws.IsGraphiteEnabled = true; gm.VwGraphics.SetupGraphics(ref chrp); engine = reFactory.get_Renderer(ws, gm.VwGraphics); Assert.IsNotNull(engine); Assert.AreSame(wsManager, engine.WritingSystemFactory); Assert.IsInstanceOf(typeof(GraphiteEngine), engine); wsManager.Save(); } finally { gm.Uninit(); } } }
public void BinaryPropTest() { // ClassH::BinaryProp8:Binary // Set class first, or it will throw an exception. const int hvo = 1; var clidAnal = SilDataAccess.MetaDataCache.GetClassId("ClassH"); SilDataAccess.SetInt(hvo, (int)CmObjectFields.kflidCmObject_Class, clidAnal); var tag = SilDataAccess.MetaDataCache.GetFieldId("ClassH", "BinaryProp8", false); using (var arrayPtr = MarshalEx.ArrayToNative <int>(3)) { int chvo; var prgb = new byte[] { 3, 4, 5 }; SilDataAccess.SetBinary(hvo, tag, prgb, prgb.Length); SilDataAccess.BinaryPropRgb(hvo, tag, arrayPtr, 3, out chvo); var prgbNew = MarshalEx.NativeToArray <byte>(arrayPtr, chvo); Assert.AreEqual(prgb.Length, prgbNew.Length); for (var i = 0; i < prgbNew.Length; i++) { Assert.AreEqual(prgb[i], prgbNew[i]); } } }
public void GetFieldsTest() { int countAllFlidsOut; using (var flids = MarshalEx.ArrayToNative <int>(500)) { countAllFlidsOut = m_metaDataCache.GetFields(0, true, (int)CellarPropertyTypeFilter.All, 0, flids); var countAllFlids = countAllFlidsOut; countAllFlidsOut = m_metaDataCache.GetFields(0, true, (int)CellarPropertyTypeFilter.All, countAllFlidsOut, flids); Assert.AreEqual(countAllFlids, countAllFlidsOut, "Wrong number of fields returned for BaseClass."); } using (var flids = MarshalEx.ArrayToNative <int>(500)) { countAllFlidsOut = m_metaDataCache.GetFields(49, true, (int)CellarPropertyTypeFilter.All, 0, flids); countAllFlidsOut = m_metaDataCache.GetFields(49, true, (int)CellarPropertyTypeFilter.All, countAllFlidsOut, flids); Assert.AreEqual(8, countAllFlidsOut, "Wrong number of fields returned for 49."); } using (var flids = MarshalEx.ArrayToNative <int>(500)) { countAllFlidsOut = m_metaDataCache.GetFields(49, true, (int)CellarPropertyTypeFilter.AllReference, 0, flids); countAllFlidsOut = m_metaDataCache.GetFields(49, true, (int)CellarPropertyTypeFilter.AllReference, countAllFlidsOut, flids); Assert.AreEqual(1, countAllFlidsOut, "Wrong number of fields returned for 49."); } }
/// <summary> /// Apply any changes to the chrp before it is used for real: currently, /// interpret the magic font names. /// </summary> /// <param name="chrp"></param> public void InterpretChrp(ref LgCharRenderProps chrp) { string fontName = MarshalEx.UShortToString(chrp.szFaceName); if (fontName == "<default font>") { MarshalEx.StringToUShort(DefaultFontName, chrp.szFaceName); } if (chrp.ssv != (int)FwSuperscriptVal.kssvOff) { if (chrp.ssv == (int)FwSuperscriptVal.kssvSuper) { chrp.dympOffset += chrp.dympHeight / 3; } else { chrp.dympOffset -= chrp.dympHeight / 5; } chrp.dympHeight = (chrp.dympHeight * 2) / 3; // Make sure no way it can happen twice! chrp.ssv = (int)FwSuperscriptVal.kssvOff; } }
public override void PaintBackground(IVwGraphics vg, PaintTransform ptrans) { // Review JohnT: do we want to allow individual strings to paint borders etc? Should we call base? // base.PaintBackground(vg, ptrans); if (Segment == null) { return; } int dxdWidth; PaintTransform segTrans = ptrans.PaintTransformOffsetBy(Left, Top); // Ideally, we'd just draw the background, but we don't have that capability currently. // The current implementation of DrawTextNoBackground does a good job of redrawing // the foreground text, even if it's already been painted. if (AnyColoredBackground) { Segment.DrawText(IchMin, vg, segTrans.SourceRect, segTrans.DestRect, out dxdWidth); } int dichLim = Segment.get_Lim(IchMin); int ichLim = IchMin + dichLim; int ichMinRun = IchMin; int ichLimRun; int dydOffset = Math.Max(1, segTrans.DpiY / 96); // distance between double underline, also up and down for squiggle. for (; ichMinRun < ichLim; ichMinRun = ichLimRun) { int clrUnder; var unt = Paragraph.Source.GetUnderlineInfo(ichMinRun, out clrUnder, out ichLimRun); ichLimRun = Math.Min(ichLimRun, ichLim); Debug.Assert(ichLimRun > ichMinRun); if (unt == FwUnderlineType.kuntNone) { continue; } // Get info about where to draw underlines for this run //int ydApproxUnderline = rcSrcChild.MapYTo(psbox->Ascent(), rcDst); //// GetCharPlacement seems to be the really expensive part of underlining; don't do it //// if the underline is nowhere near the clip rectangle. Times 2 and times 3 are both one more multiple //// than typically needed. //if (ydApproxUnderline - dydOffset * 2 < ydTopClip - 1 || ydApproxUnderline + dydOffset * 3 > ydBottomClip + 1) // continue; int[] lefts, rights, tops; int cxd; Segment.GetCharPlacement(IchMin, vg, ichMinRun, ichLimRun, segTrans.SourceRect, segTrans.DestRect, true, 0, out cxd, null, null, null); using (var rgxdLefts = MarshalEx.ArrayToNative <int>(cxd)) using (var rgxdRights = MarshalEx.ArrayToNative <int>(cxd)) using (var rgydTops = MarshalEx.ArrayToNative <int>(cxd)) { Segment.GetCharPlacement(IchMin, vg, ichMinRun, ichLimRun, segTrans.SourceRect, segTrans.DestRect, true, cxd, out cxd, rgxdLefts, rgxdRights, rgydTops); lefts = MarshalEx.NativeToArray <int>(rgxdLefts, cxd); rights = MarshalEx.NativeToArray <int>(rgxdRights, cxd); tops = MarshalEx.NativeToArray <int>(rgydTops, cxd); } for (int ixd = 0; ixd < cxd; ixd++) { // top of underline 1 pixel below baseline int ydDrawAt = tops[ixd]; // underline is drawn at most one offset above ydDrawAt and at most 2 offsets below. // Skip the work if it is clipped. //if (ydDrawAt - dydOffset < ydBottomClip + 1 && ydDrawAt + dydOffset * 2 > ydTopClip - 1) //{ //int xLeft = max(rgxdLefts[ixd], xdLeftClip - 1); //int xRight = min(rgxdRights[ixd], xdRightClip + 1); int xLeft = lefts[ixd]; int xRight = rights[ixd]; DrawUnderline(vg, xLeft, xRight, ydDrawAt, segTrans.DpiX / 96, dydOffset, clrUnder, unt, segTrans.XOffsetScroll); //} } } }
/// <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(); } } }
public static ComputeBuffer Create <T>(int count) => new ComputeBuffer(count, MarshalEx.SizeOf <T>());
public static ComputeBuffer Create <T>(T[] data) => new ComputeBuffer(data.Length, MarshalEx.SizeOf <T>());
/// <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); } }