コード例 #1
0
        internal OletxCommittableTransaction CreateTransaction(
            TransactionOptions properties
            )
        {
            OletxCommittableTransaction tx = null;
            RealOletxTransaction        realTransaction = null;
            ITransactionShim            transactionShim = null;
            Guid txIdentifier = Guid.Empty;
            OutcomeEnlistment outcomeEnlistment = null;

            // Demand the distributed transation permission to create one of
            // these.
            DistributedTransactionPermission txPerm =
                new DistributedTransactionPermission(PermissionState.Unrestricted);

            txPerm.Demand();

            TransactionManager.ValidateIsolationLevel(properties.IsolationLevel);

            // Never create a transaction with an IsolationLevel of Unspecified.
            if (IsolationLevel.Unspecified == properties.IsolationLevel)
            {
                properties.IsolationLevel = configuredTransactionOptions.IsolationLevel;
            }

            properties.Timeout = TransactionManager.ValidateTimeout(properties.Timeout);

            this.dtcTransactionManagerLock.AcquireReaderLock(-1);
            try
            {
                //
                OletxTransactionIsolationLevel oletxIsoLevel = OletxTransactionManager.ConvertIsolationLevel(properties.IsolationLevel);
                UInt32 oletxTimeout = DtcTransactionManager.AdjustTimeout(properties.Timeout);

                outcomeEnlistment = new OutcomeEnlistment();
                IntPtr outcomeEnlistmentHandle = IntPtr.Zero;
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    outcomeEnlistmentHandle = HandleTable.AllocHandle(outcomeEnlistment);

                    dtcTransactionManager.ProxyShimFactory.BeginTransaction(
                        oletxTimeout,
                        oletxIsoLevel,
                        outcomeEnlistmentHandle,
                        out txIdentifier,
                        out transactionShim
                        );
                }
                catch (COMException ex)
                {
                    OletxTransactionManager.ProxyException(ex);
                    throw;
                }
                finally
                {
                    if (transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero)
                    {
                        HandleTable.FreeHandle(outcomeEnlistmentHandle);
                    }
                }

                realTransaction = new RealOletxTransaction(
                    this,
                    transactionShim,
                    outcomeEnlistment,
                    txIdentifier,
                    oletxIsoLevel,
                    true
                    );
                tx = new OletxCommittableTransaction(realTransaction);
                if (DiagnosticTrace.Information)
                {
                    TransactionCreatedTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx),
                                                        tx.TransactionTraceId
                                                        );
                }
            }
            finally
            {
                this.dtcTransactionManagerLock.ReleaseReaderLock();
            }

            return(tx);
        }
コード例 #2
0
ファイル: AssemblyPrepare.cs プロジェクト: mdae/MonoRT
    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("Too few arguments.");
            return;
        }

        string[] strarray = new string[args.Length - 1];

        for (int iIndex = 0; iIndex < (args.Length - 1); iIndex++)
        {
            strarray [iIndex] = args [iIndex + 1];
        }
        object[] objarray = new object[] { strarray };

        Assembly AppAssembly = Assembly.LoadFile(args [0]);

        AssemblyName[] RefAssemblyNames = AppAssembly.GetReferencedAssemblies();
        Assembly[]     AssemblyArray    = new Assembly[RefAssemblyNames.Length + 1];
        AssemblyArray [0] = AppAssembly;

        for (int i = 0; i < RefAssemblyNames.Length; i++)
        {
            AssemblyArray [i + 1] = Assembly.Load(RefAssemblyNames [i]);
        }

        Console.WriteLine();
        //Console.WriteLine ("Assemblys to pre-comile:");
        foreach (Assembly assem in AssemblyArray)
        {
            Console.WriteLine(assem.GetName());
        }

        foreach (Assembly assem in AssemblyArray)
        {
            //Console.WriteLine ("Pre-Compile: " + assem.GetName ());
            Type[] mytypes = assem.GetTypes();

            //BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);

            foreach (Type t in mytypes)
            {
                MethodInfo[] mi = t.GetMethods(flags);
                // Object obj = Activator.CreateInstance(t);

                foreach (MethodInfo m in mi)
                {
                    if ((m.IsAbstract == true) || (m.IsGenericMethod == true) || (m.IsGenericMethodDefinition == true) || (m.ContainsGenericParameters == true))
                    {
                        continue;
                    }

                    try{
                        RuntimeHelpers.PrepareMethod(m.MethodHandle);
                    }
                    catch (SystemException ex)
                    {
                        if (ex is System.EntryPointNotFoundException ||
                            ex is System.DllNotFoundException ||
                            ex is System.ArgumentException)
                        {
                        }
                        else
                        {
                            Console.WriteLine("Method that causes exception: " + m.Name);
                            throw;
                        }
                    }
                }
            }
        }
        MethodInfo Entr = AppAssembly.EntryPoint;

        //Console.WriteLine ("EntryPoint: " + Entr.Name);

        Entr.Invoke(null, objarray);
        return;
    }
コード例 #3
0
 public int GetHashCode(T obj) => RuntimeHelpers.GetHashCode(obj);
コード例 #4
0
 static MyFakes()
 {
     // Called after all the fields have been initialized to override any settings with local ones.
     RuntimeHelpers.RunClassConstructor(typeof(MyFakesLocal).TypeHandle);
 }
コード例 #5
0
 static DesEdeWrapEngine()
 {
     byte[] array = new byte[8];
     RuntimeHelpers.InitializeArray((global::System.Array)array, (RuntimeFieldHandle) /*OpCode not supported: LdMemberToken*/);
     IV2 = array;
 }
コード例 #6
0
 int IEqualityComparer <T> .GetHashCode(T obj)
 {
     return(RuntimeHelpers.GetHashCode(obj));
 }
コード例 #7
0
        /// <summary>获取方法在JIT编译后的地址(JIT Stubs)</summary>
        /// <remarks>
        /// MethodBase.DeclaringType.TypeHandle.Value: 指向该类型方法表(编译后)在 JIT Stubs 的起始位置。
        /// Method.MethodHandle.Value: 表示该方法的索引序号。
        /// CLR 2.0 SP2 (2.0.50727.3053) 及其后续版本中,该地址的内存布局发生了变化。直接用 "Method.MethodHandle.Value + 2" 即可得到编译后的地址。
        /// </remarks>
        /// <param name="method"></param>
        /// <returns></returns>
        unsafe public static IntPtr GetMethodAddress(MethodBase method)
        {
            var isAboveNet2Sp2 = Environment.Version.Major >= 2 && Environment.Version.MinorRevision >= 3053;

            // 处理动态方法
            if (method is DynamicMethod)
            {
                //byte* ptr = (byte*)GetDynamicMethodRuntimeHandle(method).ToPointer();

                FieldInfo fieldInfo = typeof(DynamicMethod).GetField("m_method", BindingFlags.NonPublic | BindingFlags.Instance);
                byte *    ptr       = (byte *)((RuntimeMethodHandle)FieldInfoX.Create(fieldInfo).GetValue(method)).Value.ToPointer();

                if (isAboveNet2Sp2)
                {
                    // 确保方法已经被编译
                    RuntimeHelpers.PrepareMethod(method.MethodHandle);

                    if (IntPtr.Size == 8)
                    {
                        return(new IntPtr((ulong *)*(ptr + 5) + 12));
                    }
                    else
                    {
                        return(new IntPtr((uint *)*(ptr + 5) + 12));
                    }
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        return(new IntPtr((ulong *)ptr + 6));
                    }
                    else
                    {
                        return(new IntPtr((uint *)ptr + 6));
                    }
                }
            }

            // 确保方法已经被编译
            RuntimeHelpers.PrepareMethod(method.MethodHandle);

            if (isAboveNet2Sp2)
            {
                return(new IntPtr((int *)method.MethodHandle.Value.ToPointer() + 2));
            }

            // 要跳过的
            var skip = 10;

            // 读取方法索引
            var location = (UInt64 *)(method.MethodHandle.Value.ToPointer());
            var index    = (int)(((*location) >> 32) & 0xFF);

            // 区分处理x86和x64
            if (IntPtr.Size == 8)
            {
                // 获取方法表
                var methodTable = (ulong *)method.DeclaringType.TypeHandle.Value.ToPointer();
                return(new IntPtr(methodTable + index + skip));
            }
            else
            {
                // 获取方法表
                var methodTable = (uint *)method.DeclaringType.TypeHandle.Value.ToPointer();
                return(new IntPtr(methodTable + index + skip));
            }
        }
コード例 #8
0
        void lbList_DoubleClick(object sender, EventArgs e)

        {
            btnOK_Click(RuntimeHelpers.GetObjectValue(sender), e);
        }
コード例 #9
0
 // Token: 0x06000047 RID: 71 RVA: 0x000022F7 File Offset: 0x000004F7
 public GClass5()
 {
     this.timer_0  = new Timer(new TimerCallback(this.method_8), null, -1, -1);
     this.object_0 = RuntimeHelpers.GetObjectValue(new object());
 }
コード例 #10
0
    public static void WarmUp(string methodName)
    {
        var handle = FindMethodWithName(methodName).MethodHandle;

        RuntimeHelpers.PrepareMethod(handle);
    }
コード例 #11
0
        public void ctor_EndgameTokens(Menu.Menu menu, MenuObject owner, Vector2 pos, FContainer container, KarmaLadder ladder)
        {
            //Created Delegate to call Menu.PositionedMenuObject constructor
            Type[] constructorSignature = new Type[3];
            constructorSignature[0] = typeof(Menu.Menu);
            constructorSignature[1] = typeof(Menu.MenuObject);
            constructorSignature[2] = typeof(Vector2);
            RuntimeMethodHandle handle = typeof(Menu.PositionedMenuObject).GetConstructor(constructorSignature).MethodHandle;

            RuntimeHelpers.PrepareMethod(handle);
            IntPtr ptr = handle.GetFunctionPointer();
            Action <Menu.Menu, Menu.MenuObject, Vector2> funct = (Action <Menu.Menu, Menu.MenuObject, Vector2>)Activator.CreateInstance(typeof(Action <Menu.Menu, Menu.MenuObject, Vector2>), this, ptr);

            funct(menu, owner, pos);//Menu.PositionedMenuObject constructor

            //Original Code:
            this.tokens = new List <EndgameTokens.Token>();
            bool flag = false;

            this.addPassageButtonWhenTokenBecomesVisible = false;
            int num = 0;

            for (int i = 0; i < ladder.endGameMeters.Count; i++)
            {
                if (ladder.endGameMeters[i].fullfilledNow)
                {
                    this.addPassageButtonWhenTokenBecomesVisible = true;
                }
                if (ladder.endGameMeters[i].tracker.GoalFullfilled && !ladder.endGameMeters[i].tracker.consumed)
                {
                    if (ladder.endGameMeters[i].tracker.GoalAlreadyFullfilled && !flag)
                    {
                        flag = true;
                    }
                    this.tokens.Add(new EndgameTokens.Token(menu, this, default(Vector2), ladder.endGameMeters[i], container, num));
                    this.subObjects.Add(this.tokens[this.tokens.Count - 1]);
                    num++;
                }
                if (ladder.endGameMeters[i].fullfilledNow)
                {
                    this.forceShowTokenAdd = true;
                }
            }
            // New Code:
            if (menu is SleepAndDeathScreen) //To avoid calling menu as SleepAndDeathScreen when menu is MultiplayerSleepAndDeathScreen
            {
                if ((menu as SleepAndDeathScreen).winState != null)
                {
                    for (int j = 0; j < (menu as SleepAndDeathScreen).winState.endgameTrackers.Count; j++)
                    {
                        if (!(menu as SleepAndDeathScreen).winState.endgameTrackers[j].GoalAlreadyFullfilled && (menu as SleepAndDeathScreen).winState.endgameTrackers[j].GoalFullfilled)
                        {
                            this.pingAchivements = true;
                            break;
                        }
                    }
                }
                if (flag)
                {
                    (menu as SleepAndDeathScreen).AddPassageButton(false);
                    this.addPassageButtonWhenTokenBecomesVisible = false;
                }
            }
            else
            {
                if ((menu as MultiplayerSleepAndDeathScreen).winState != null)
                {
                    for (int j = 0; j < (menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers.Count; j++)
                    {
                        if (!(menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].GoalAlreadyFullfilled && (menu as MultiplayerSleepAndDeathScreen).winState.endgameTrackers[j].GoalFullfilled)
                        {
                            this.pingAchivements = true;
                            break;
                        }
                    }
                }
            }
        }
コード例 #12
0
        public void executePrivate(int startRow, int maxRows)
        {
            this.m_WhereString = " WHERE " + this.filterString + "  TM1.[NAZIVPARTNER] like '%' + @NAZIVPARTNER + '%'";
            if (maxRows >= 0)
            {
                if (startRow == 0)
                {
                    this.scmdbuf = "SELECT TOP " + maxRows.ToString() + "  TM1.[IDPARTNER], TM1.[NAZIVPARTNER], TM1.[PARTNERMJESTO], TM1.[PARTNEREMAIL], TM1.[PARTNERULICA], TM1.[MB], TM1.[PARTNEROIB] FROM [PARTNER] TM1" + this.m_WhereString + "" + this.orderString + "";
                }
                else
                {
                    if (string.Compare(this.m_WhereString.TrimEnd(new char[] { ' ' }), "".TrimEnd(new char[] { ' ' }), false, CultureInfo.CurrentCulture) == 0)
                    {
                        this.sWhereSep = " WHERE ";
                    }
                    else
                    {
                        this.sWhereSep = " AND ";
                    }
                    int internalRecordCount = this.GetInternalRecordCount(this.AV8NAZIVPA);
                    this.m_TopRowCount = Conversions.ToInteger(Interaction.IIf(internalRecordCount >= (startRow + maxRows), maxRows, RuntimeHelpers.GetObjectValue(Interaction.IIf(internalRecordCount >= startRow, internalRecordCount - startRow, 0))));
                    if (this.m_TopRowCount == 0)
                    {
                        return;
                    }
                    this.scmdbuf = "SELECT TM1.[IDPARTNER], TM1.[NAZIVPARTNER], TM1.[PARTNERMJESTO], TM1.[PARTNEREMAIL], TM1.[PARTNERULICA], TM1.[MB], TM1.[PARTNEROIB] FROM [PARTNER] TM1 WHERE TM1.[IDPARTNER] IN ( SELECT TOP " + maxRows.ToString() + " TM1.[IDPARTNER]  FROM [PARTNER] TM1" + this.m_WhereString + "" + this.sWhereSep + "TM1.[IDPARTNER] NOT IN ( SELECT TOP " + startRow.ToString() + " TM1.[IDPARTNER]  FROM [PARTNER] TM1" + this.m_WhereString + "" + this.orderString + ")" + this.orderString + ")" + this.orderString + "";
                }
            }
            else
            {
                this.scmdbuf = "SELECT TM1.[IDPARTNER], TM1.[NAZIVPARTNER], TM1.[PARTNERMJESTO], TM1.[PARTNEREMAIL], TM1.[PARTNERULICA], TM1.[MB], TM1.[PARTNEROIB] FROM [PARTNER] TM1" + this.m_WhereString + "" + this.orderString + " ";
            }
            this.cmPARTNERSelect2 = this.connDefault.GetCommand(this.scmdbuf, false);
            if (this.cmPARTNERSelect2.IDbCommand.Parameters.Count == 0)
            {
                this.cmPARTNERSelect2.IDbCommand.Parameters.Add(this.dsDefault.GetDbParameter("@NAZIVPARTNER", DbType.String, 100));
            }
            this.lV8NAZIVPA = StringUtil.PadRight(StringUtil.RTrim(this.AV8NAZIVPA), 100, "%");
            this.cmPARTNERSelect2.SetParameter(0, this.lV8NAZIVPA);
            this.cmPARTNERSelect2.ErrorMask |= ErrorMask.Lock;
            this.PARTNERSelect2              = this.cmPARTNERSelect2.FetchData();
            int num = 0;

            while (this.cmPARTNERSelect2.HasMoreRows && (num != maxRows))
            {
                this.m_IDPARTNER                 = this.dsDefault.Db.GetInt32(this.PARTNERSelect2, 0, ref this.m__IDPARTNERIsNull);
                this.m_NAZIVPARTNER              = this.dsDefault.Db.GetString(this.PARTNERSelect2, 1, ref this.m__NAZIVPARTNERIsNull).TrimEnd(new char[] { ' ' });
                this.m_PARTNERMJESTO             = this.dsDefault.Db.GetString(this.PARTNERSelect2, 2, ref this.m__PARTNERMJESTOIsNull);
                this.m_PARTNEREMAIL              = this.dsDefault.Db.GetString(this.PARTNERSelect2, 3, ref this.m__PARTNEREMAILIsNull);
                this.m_PARTNERULICA              = this.dsDefault.Db.GetString(this.PARTNERSelect2, 4, ref this.m__PARTNERULICAIsNull);
                this.m_MB                        = this.dsDefault.Db.GetString(this.PARTNERSelect2, 5, ref this.m__MBIsNull);
                this.m_PARTNEROIB                = this.dsDefault.Db.GetString(this.PARTNERSelect2, 6, ref this.m__PARTNEROIBIsNull);
                this.m_PT                        = this.m_NAZIVPARTNER + " | " + NumberUtil.ToString((long)this.m_IDPARTNER, "");
                this.rowPARTNER                  = this.trazi_partneraSet.PARTNER.NewPARTNERRow();
                this.rowPARTNER["IDPARTNER"]     = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__IDPARTNERIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_IDPARTNER));
                this.rowPARTNER["NAZIVPARTNER"]  = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__NAZIVPARTNERIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_NAZIVPARTNER));
                this.rowPARTNER["PARTNERMJESTO"] = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__PARTNERMJESTOIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_PARTNERMJESTO));
                this.rowPARTNER["PARTNEREMAIL"]  = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__PARTNEREMAILIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_PARTNEREMAIL));
                this.rowPARTNER["PARTNERULICA"]  = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__PARTNERULICAIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_PARTNERULICA));
                this.rowPARTNER["MB"]            = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__MBIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_MB));
                this.rowPARTNER["PARTNEROIB"]    = RuntimeHelpers.GetObjectValue(Interaction.IIf(this.m__PARTNEROIBIsNull, RuntimeHelpers.GetObjectValue(Convert.DBNull), this.m_PARTNEROIB));
                this.rowPARTNER.PT               = this.m_PT;
                this.AddRowPartner();
                num++;
                this.cmPARTNERSelect2.HasMoreRows = this.PARTNERSelect2.Read();
            }
            this.PARTNERSelect2.Close();
            this.Cleanup();
        }
コード例 #13
0
ファイル: FromGoo.cs プロジェクト: BHoM/Grasshopper_Toolkit
        /*******************************************/
        /**** Private Methods                   ****/
        /*******************************************/

        private static T FromGoo <T>(this IGH_Goo goo, IGH_TypeHint hint = null)
        {
            if (goo == null)
            {
                return(default(T));
            }

            // Get the data out of the Goo
            object data = goo.ScriptVariable();

            while (data is IGH_Goo)
            {
                data = ((IGH_Goo)data).ScriptVariable();
            }

            if (data == null)
            {
                return(default(T));
            }

            if (data.GetType().Namespace.StartsWith("Rhino.Geometry") && !typeof(T).Namespace.StartsWith("Rhino.Geometry"))
            {
                data = BH.Engine.Rhinoceros.Convert.IFromRhino(data);
            }

            // Convert the data to an acceptable format
            if (hint != null)
            {
                object result;
                hint.Cast(RuntimeHelpers.GetObjectValue(data), out result);
                data = result;

                if (data.GetType().Namespace.StartsWith("Rhino.Geometry") && !typeof(T).Namespace.StartsWith("Rhino.Geometry"))
                {
                    data = BH.Engine.Rhinoceros.Convert.IFromRhino(data);
                }
            }
            else if (data is T)
            {
                return((T)data);
            }
            else if (data is IEnumerable)
            {
                UnderlyingType subType = data.GetType().UnderlyingType();
                if (typeof(T).IsAssignableFrom(subType.Type))
                {
                    List <T> list = ((IEnumerable)data).Cast <T>().ToList();
                    if (list.Count == 0)
                    {
                        return(default(T));
                    }
                    else
                    {
                        return(list.First());
                    }
                }
            }

            try
            {
                return((T)(data as dynamic));
            }
            catch
            {
                Engine.Base.Compute.RecordError("Failed to cast " + data.GetType().IToText() + " into " + typeof(T).IToText());
                return(default(T));
            }
        }
コード例 #14
0
        internal static void ShimNotificationCallback(object state, bool timeout)
        {
            // First we need to get the notification from the shim factory.
            IntPtr enlistmentHandleIntPtr             = IntPtr.Zero;
            ShimNotificationType shimNotificationType = ShimNotificationType.None;
            bool isSinglePhase = false;
            bool abortingHint  = false;

            UInt32          prepareInfoSize   = 0;
            CoTaskMemHandle prepareInfoBuffer = null;

            bool holdingNotificationLock = false;
            bool cleanExit = false;

            IDtcProxyShimFactory localProxyShimFactory = null;

            if (DiagnosticTrace.Verbose)
            {
                MethodEnteredTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx),
                                               "OletxTransactionManager.ShimNotificationCallback"
                                               );
            }

            // This lock doesn't really protect any of our data.  It is here so that if an exception occurs
            // while calling out to the app, we get an escalation to AppDomainUnload.
            Thread.BeginCriticalRegion();
            try
            {
                do
                {
                    // Take a local copy of the proxyShimFactory because if we get an RM TMDown notification,
                    // we will still hold the critical section in that factory, but processing of the TMDown will
                    // cause replacement of the OletxTransactionManager.proxyShimFactory.
                    localProxyShimFactory = OletxTransactionManager.proxyShimFactory;
                    try
                    {
                        Thread.BeginThreadAffinity();
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            localProxyShimFactory.GetNotification(
                                out enlistmentHandleIntPtr,
                                out shimNotificationType,
                                out isSinglePhase,
                                out abortingHint,
                                out holdingNotificationLock,
                                out prepareInfoSize,
                                out prepareInfoBuffer
                                );
                        }
                        finally
                        {
                            if (holdingNotificationLock)
                            {
                                if ((HandleTable.FindHandle(enlistmentHandleIntPtr)) is OletxInternalResourceManager)
                                {
                                    // In this case we know that the TM has gone down and we need to exchange
                                    // the native lock for a managed lock.
                                    processingTmDown = true;
#pragma warning disable 0618
                                    //@
                                    System.Threading.Monitor.Enter(OletxTransactionManager.proxyShimFactory);
#pragma warning restore 0618
                                }
                                else
                                {
                                    holdingNotificationLock = false;
                                }
                                localProxyShimFactory.ReleaseNotificationLock();
                            }
                            Thread.EndThreadAffinity();
                        }

                        // If a TM down is being processed it is possible that the native lock
                        // has been exchanged for a managed lock.  In that case we need to attempt
                        // to take a lock to hold up processing more events until the TM down
                        // processing is complete.
                        if (processingTmDown)
                        {
                            lock (OletxTransactionManager.proxyShimFactory)
                            {
                                // We don't do any work under this lock just make sure that we
                                // can take it.
                            }
                        }

                        if (ShimNotificationType.None != shimNotificationType)
                        {
                            Object target = HandleTable.FindHandle(enlistmentHandleIntPtr);

                            // Next, based on the notification type, cast the Handle accordingly and make
                            // the appropriate call on the enlistment.
                            switch (shimNotificationType)
                            {
                            case ShimNotificationType.Phase0RequestNotify:
                            {
                                try
                                {
                                    OletxPhase0VolatileEnlistmentContainer ph0VolEnlistContainer = target as OletxPhase0VolatileEnlistmentContainer;
                                    if (null != ph0VolEnlistContainer)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            ph0VolEnlistContainer.TransactionIdentifier);
                                        //CSDMain 91509 - We now synchronize this call with the AddDependentClone call in RealOleTxTransaction
                                        ph0VolEnlistContainer.Phase0Request(abortingHint);
                                    }
                                    else
                                    {
                                        OletxEnlistment enlistment = target as OletxEnlistment;
                                        if (null != enlistment)
                                        {
                                            DiagnosticTrace.SetActivityId(
                                                enlistment.TransactionIdentifier);
                                            enlistment.Phase0Request(abortingHint);
                                        }
                                        else
                                        {
                                            Environment.FailFast(SR.GetString(SR.InternalError));
                                        }
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }
                                break;
                            }

                            case ShimNotificationType.VoteRequestNotify:
                            {
                                OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer;
                                if (null != ph1VolEnlistContainer)
                                {
                                    DiagnosticTrace.SetActivityId(
                                        ph1VolEnlistContainer.TransactionIdentifier);
                                    ph1VolEnlistContainer.VoteRequest();
                                }
                                else
                                {
                                    Environment.FailFast(SR.GetString(SR.InternalError));
                                }

                                break;
                            }

                            case ShimNotificationType.CommittedNotify:
                            {
                                try
                                {
                                    OutcomeEnlistment outcomeEnlistment = target as OutcomeEnlistment;
                                    if (null != outcomeEnlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            outcomeEnlistment.TransactionIdentifier);
                                        outcomeEnlistment.Committed();
                                    }
                                    else
                                    {
                                        OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer;
                                        if (null != ph1VolEnlistContainer)
                                        {
                                            DiagnosticTrace.SetActivityId(
                                                ph1VolEnlistContainer.TransactionIdentifier);
                                            ph1VolEnlistContainer.Committed();
                                        }
                                        else
                                        {
                                            Environment.FailFast(SR.GetString(SR.InternalError));
                                        }
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }
                                break;
                            }

                            case ShimNotificationType.AbortedNotify:
                            {
                                try
                                {
                                    OutcomeEnlistment outcomeEnlistment = target as OutcomeEnlistment;
                                    if (null != outcomeEnlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            outcomeEnlistment.TransactionIdentifier);
                                        outcomeEnlistment.Aborted();
                                    }
                                    else
                                    {
                                        OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer;
                                        if (null != ph1VolEnlistContainer)
                                        {
                                            DiagnosticTrace.SetActivityId(
                                                ph1VolEnlistContainer.TransactionIdentifier);
                                            ph1VolEnlistContainer.Aborted();
                                        }
                                        // else
                                        // Voters may receive notifications even
                                        // in cases where they therwise respond
                                        // negatively to the vote request.  It is
                                        // also not guaranteed that we will get a
                                        // notification if we do respond negatively.
                                        // The only safe thing to do is to free the
                                        // Handle when we abort the transaction
                                        // with a voter.  These two things together
                                        // mean that we cannot guarantee that this
                                        // Handle will be alive when we get this
                                        // notification.
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }
                                break;
                            }

                            case ShimNotificationType.InDoubtNotify:
                            {
                                try
                                {
                                    OutcomeEnlistment outcomeEnlistment = target as OutcomeEnlistment;
                                    if (null != outcomeEnlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            outcomeEnlistment.TransactionIdentifier);
                                        outcomeEnlistment.InDoubt();
                                    }
                                    else
                                    {
                                        OletxPhase1VolatileEnlistmentContainer ph1VolEnlistContainer = target as OletxPhase1VolatileEnlistmentContainer;
                                        if (null != ph1VolEnlistContainer)
                                        {
                                            DiagnosticTrace.SetActivityId(
                                                ph1VolEnlistContainer.TransactionIdentifier);
                                            ph1VolEnlistContainer.InDoubt();
                                        }
                                        else
                                        {
                                            Environment.FailFast(SR.GetString(SR.InternalError));
                                        }
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }
                                break;
                            }

                            case ShimNotificationType.PrepareRequestNotify:
                            {
                                byte[] prepareInfo = new byte[prepareInfoSize];
                                Marshal.Copy(prepareInfoBuffer.DangerousGetHandle(), prepareInfo, 0, Convert.ToInt32(prepareInfoSize));
                                bool enlistmentDone = true;

                                try
                                {
                                    OletxEnlistment enlistment = target as OletxEnlistment;
                                    if (null != enlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            enlistment.TransactionIdentifier);
                                        enlistmentDone = enlistment.PrepareRequest(
                                            isSinglePhase,
                                            prepareInfo
                                            );
                                    }
                                    else
                                    {
                                        Environment.FailFast(SR.GetString(SR.InternalError));
                                    }
                                }
                                finally
                                {
                                    if (enlistmentDone)
                                    {
                                        HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                    }
                                }

                                break;
                            }

                            case ShimNotificationType.CommitRequestNotify:
                            {
                                try
                                {
                                    OletxEnlistment enlistment = target as OletxEnlistment;
                                    if (null != enlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            enlistment.TransactionIdentifier);
                                        enlistment.CommitRequest();
                                    }
                                    else
                                    {
                                        Environment.FailFast(SR.GetString(SR.InternalError));
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }

                                break;
                            }

                            case ShimNotificationType.AbortRequestNotify:
                            {
                                try
                                {
                                    OletxEnlistment enlistment = target as OletxEnlistment;
                                    if (null != enlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            enlistment.TransactionIdentifier);
                                        enlistment.AbortRequest();
                                    }
                                    else
                                    {
                                        Environment.FailFast(SR.GetString(SR.InternalError));
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }

                                break;
                            }

                            case ShimNotificationType.EnlistmentTmDownNotify:
                            {
                                try
                                {
                                    OletxEnlistment enlistment = target as OletxEnlistment;
                                    if (null != enlistment)
                                    {
                                        DiagnosticTrace.SetActivityId(
                                            enlistment.TransactionIdentifier);
                                        enlistment.TMDown();
                                    }
                                    else
                                    {
                                        Environment.FailFast(SR.GetString(SR.InternalError));
                                    }
                                }
                                finally
                                {
                                    // We aren't going to get any more notifications on this.
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }

                                break;
                            }


                            case ShimNotificationType.ResourceManagerTmDownNotify:
                            {
                                OletxResourceManager resourceManager = target as OletxResourceManager;
                                try
                                {
                                    if (null != resourceManager)
                                    {
                                        resourceManager.TMDown();
                                    }
                                    else
                                    {
                                        OletxInternalResourceManager internalResourceManager = target as OletxInternalResourceManager;
                                        if (null != internalResourceManager)
                                        {
                                            internalResourceManager.TMDown();
                                        }
                                        else
                                        {
                                            Environment.FailFast(SR.GetString(SR.InternalError));
                                        }
                                    }
                                }
                                finally
                                {
                                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                                }

                                // Note that we don't free the gchandle on the OletxResourceManager.  These objects
                                // are not going to go away.
                                break;
                            }

                            default:
                            {
                                Environment.FailFast(SR.GetString(SR.InternalError));
                                break;
                            }
                            }
                        }
                    }
                    finally
                    {
                        if (null != prepareInfoBuffer)
                        {
                            prepareInfoBuffer.Close();
                        }

                        if (holdingNotificationLock)
                        {
                            holdingNotificationLock = false;
                            processingTmDown        = false;
                            System.Threading.Monitor.Exit(OletxTransactionManager.proxyShimFactory);
                        }
                    }
                }while (ShimNotificationType.None != shimNotificationType);

                cleanExit = true;
            }
            finally
            {
                if (holdingNotificationLock)
                {
                    holdingNotificationLock = false;
                    processingTmDown        = false;
                    System.Threading.Monitor.Exit(OletxTransactionManager.proxyShimFactory);
                }

                if (!cleanExit && enlistmentHandleIntPtr != IntPtr.Zero)
                {
                    HandleTable.FreeHandle(enlistmentHandleIntPtr);
                }

                Thread.EndCriticalRegion();
            }

            if (DiagnosticTrace.Verbose)
            {
                MethodExitedTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx),
                                              "OletxTransactionManager.ShimNotificationCallback"
                                              );
            }
        }
コード例 #15
0
        internal object InstantiateClass(string virtualPath, string className = null, string relativePath = null, bool throwOnError = true)
        {
            var    wrapLog  = Log.Call($"{virtualPath}, {nameof(className)}:{className}, {nameof(relativePath)}:{relativePath}, {throwOnError}");
            string errorMsg = null;

            // Perform various checks on the path values
            var hasErrorMessage = CheckIfPathsOkAndCleanUp(ref virtualPath, relativePath);

            if (hasErrorMessage != null)
            {
                Log.Add($"Error: {hasErrorMessage}");
                wrapLog("failed");
                if (throwOnError)
                {
                    throw new Exception(hasErrorMessage);
                }
                return(null);
            }

            var pathLowerCase = virtualPath.ToLowerInvariant();
            var isCs          = pathLowerCase.EndsWith(CsFileExtension);
            var isCshtml      = pathLowerCase.EndsWith(CsHtmlFileExtension);

            Type compiledType = null;

            if (isCshtml && string.IsNullOrEmpty(className))
            {
#if NETSTANDARD
                throw new Exception("On-the Fly / Runtime Compile Not Yet Implemented in .net standard #TodoNetStandard");
#else
                compiledType = BuildManager.GetCompiledType(virtualPath);
#endif
                if (compiledType == null)
                {
                    errorMsg = $"Couldn't create instance of {virtualPath}. Compiled type == null";
                }
            }
            // compile .cs files
            else if (isCs || isCshtml)
            {
                // if no name provided, use the name which is the same as the file name
                className = className ?? Path.GetFileNameWithoutExtension(virtualPath) ?? "unknown";

                Assembly assembly = null;
#if NETSTANDARD
                var fullPath = _serviceProvider.Build <IServerPaths>().FullContentPath(virtualPath.Backslash());
                try
                {
                    assembly = new Compiler().Compile(fullPath, className);
                }
                catch
                {
                    errorMsg = $"can't compile '{className}' in {virtualPath}";
                }
#else
                assembly = BuildManager.GetCompiledAssembly(virtualPath);
#endif
                if (errorMsg == null)
                {
                    compiledType = assembly?.GetType(className, throwOnError, true);

                    if (compiledType == null)
                    {
                        errorMsg = $"didn't find type '{className}' in {virtualPath}";
                    }
                }
            }
            else
            {
                errorMsg = $"Error: given path '{virtualPath}' doesn't point to a .cs or .cshtml";
            }

            if (errorMsg != null)
            {
                Log.Add(errorMsg + $"; throw error: {throwOnError}");
                wrapLog("failed");
                if (throwOnError)
                {
                    throw new Exception(errorMsg);
                }
                return(null);
            }

            var instance = RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType));
            AttachRelativePath(virtualPath, instance);

            wrapLog($"found: {instance != null}");
            return(instance);
        }
コード例 #16
0
 public override int GetHashCode()
 {
     return(RuntimeHelpers.GetHashCode(RaisePropertyChanged) ^ EventArgs.PropertyName.GetHashCode());
 }
コード例 #17
0
 public override bool Equals(object o)
 {
     return(base.Equals(RuntimeHelpers.GetObjectValue(o)));
 }
コード例 #18
0
 public override bool Equals(object gparam_0)
 {
     return(this.Equals(RuntimeHelpers.GetObjectValue(gparam_0)));
 }
コード例 #19
0
 void FillSetList()
 {
     if (this.lvBonus.SelectedItems.Count < 1 | this.lvMag.SelectedItems.Count < 1)
     {
         this.lvSet.Items.Clear();
     }
     else
     {
         this.lvSet.BeginUpdate();
         this.lvSet.Items.Clear();
         string[] List    = new string[0];
         int[]    nIDList = new int[0];
         string   text    = this.lvBonus.SelectedItems[0].Text;
         bool     flag    = false;
         if (this.lvMag.Items[0].Selected)
         {
             flag = true;
         }
         if (!flag)
         {
             if (Conversion.Val(RuntimeHelpers.GetObjectValue(this.lvMag.SelectedItems[0].Tag)) > -1.0)
             {
                 this.AddEffect(ref List, ref nIDList, DatabaseAPI.Database.Power[Conversions.ToInteger(this.lvMag.SelectedItems[0].Tag)].PowerName, Conversions.ToInteger(this.lvMag.SelectedItems[0].Tag));
             }
         }
         else
         {
             int num = this.SetBonusList.Length - 1;
             for (int nIDSet = 0; nIDSet <= num; nIDSet++)
             {
                 if (DatabaseAPI.Database.Power[this.SetBonusList[nIDSet]].Effects.Length > 0)
                 {
                     string powerString = this.GetPowerString(this.SetBonusList[nIDSet]);
                     if (text == powerString)
                     {
                         this.AddEffect(ref List, ref nIDList, DatabaseAPI.Database.Power[this.SetBonusList[nIDSet]].PowerName, this.SetBonusList[nIDSet]);
                     }
                 }
             }
         }
         int num2 = DatabaseAPI.Database.EnhancementSets.Count - 1;
         for (int nIDSet = 0; nIDSet <= num2; nIDSet++)
         {
             int num3 = DatabaseAPI.Database.EnhancementSets[nIDSet].Bonus.Length - 1;
             for (int BonusID = 0; BonusID <= num3; BonusID++)
             {
                 int num4 = DatabaseAPI.Database.EnhancementSets[nIDSet].Bonus[BonusID].Index.Length - 1;
                 for (int index = 0; index <= num4; index++)
                 {
                     int num5 = nIDList.Length - 1;
                     for (int index2 = 0; index2 <= num5; index2++)
                     {
                         if (DatabaseAPI.Database.EnhancementSets[nIDSet].Bonus[BonusID].Index[index] == nIDList[index2])
                         {
                             this.AddSetString(nIDSet, BonusID);
                         }
                     }
                 }
             }
             int num6 = DatabaseAPI.Database.EnhancementSets[nIDSet].SpecialBonus.Length - 1;
             for (int BonusID = 0; BonusID <= num6; BonusID++)
             {
                 int num7 = DatabaseAPI.Database.EnhancementSets[nIDSet].SpecialBonus[BonusID].Index.Length - 1;
                 for (int index = 0; index <= num7; index++)
                 {
                     int num8 = nIDList.Length - 1;
                     for (int index2 = 0; index2 <= num8; index2++)
                     {
                         if (DatabaseAPI.Database.EnhancementSets[nIDSet].SpecialBonus[BonusID].Index[index] == nIDList[index2])
                         {
                             this.AddSetString(nIDSet, BonusID);
                         }
                     }
                 }
             }
         }
         if (this.lvSet.Items.Count > 0)
         {
             this.lvSet.Items[0].Selected = true;
         }
         this.lvSet.EndUpdate();
     }
 }
コード例 #20
0
ファイル: CapiNative.cs プロジェクト: tk4218/clrsecurity
        internal static bool TryFindOidInfo(string key,
                                            OidGroup group,
                                            OidKeyType keyType,
                                            bool lookupInActiveDirectory,
                                            out CRYPT_OID_INFO oidInfo)
        {
            Debug.Assert(!String.IsNullOrEmpty(key), "!String.IsNullOrEmpty(key)");

            IntPtr keyPointer = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                // Setting the CRYPT_OID_DISABLE_SEARCH_DS_FLAG (0x80000000) in the group type suppresses
                // the network lookup of the OID information.  We or the bit in directly, since it's not a
                // real group type, and we don't want to mix it into the enumeration itself
                if (!lookupInActiveDirectory)
                {
                    group = (OidGroup)((uint)group | 0x80000000);
                }

                // Convert the key into a native representation based upon search type
                if (keyType == OidKeyType.Oid)
                {
                    keyPointer = Marshal.StringToCoTaskMemAnsi(key);
                }
                else if (keyType == OidKeyType.Name ||
                         keyType == OidKeyType.CngAlgorithmId)
                {
                    keyPointer = Marshal.StringToCoTaskMemUni(key);
                }
                else
                {
                    Debug.Assert(false, "Unsupported key type");
                }
                IntPtr oid = UnsafeNativeMethods.CryptFindOIDInfo(keyType, keyPointer, group);

                // Do the search, and if we succeeded, marshal the data back to the caller.  The
                // CRYPT_OID_INFO being pointed to by the result of the search should not be freed by us
                // because it is owned by CAPI.
                if (oid != IntPtr.Zero)
                {
                    if (!UseWin2k3OidStructures)
                    {
                        oidInfo = (CRYPT_OID_INFO)Marshal.PtrToStructure(oid, typeof(CRYPT_OID_INFO));
                    }
                    else
                    {
                        oidInfo = UpgradeOidInfo((CRYPT_OID_INFO_WIN2K3)Marshal.PtrToStructure(oid, typeof(CRYPT_OID_INFO_WIN2K3)));
                    }

                    return(true);
                }
                else
                {
                    // Did not find the OID
                    oidInfo = new CRYPT_OID_INFO();
                    return(false);
                }
            }
            finally
            {
                if (keyPointer != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(keyPointer);
                }
            }
        }
コード例 #21
0
ファイル: DeepCloneState.cs プロジェクト: zqlovejyc/Foundatio
 public int GetHashCode(object obj)
 {
     return(RuntimeHelpers.GetHashCode(obj));
 }
コード例 #22
0
 int IEqualityComparer <object> .GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj);
コード例 #23
0
        public void NoIdReturnsBaseHashCode()
        {
            var bar = new EntityWithStringPrimaryKey();

            Assert.Equal(RuntimeHelpers.GetHashCode(bar), bar.GetHashCode());
        }
        public unsafe static char[] ToCharArray(this SecureString secureString)
        {
            int length         = secureString.Length;
            var insecureString = new string('\0', length);

            char[] result = null;

            var gcHandle = new GCHandle();

            RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
                delegate
            {
                RuntimeHelpers.PrepareConstrainedRegions();

                try
                {
                }
                finally
                {
                    gcHandle = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
                }

                IntPtr intPtr = IntPtr.Zero;

                RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
                    delegate
                {
                    RuntimeHelpers.PrepareConstrainedRegions();

                    try
                    {
                    }
                    finally
                    {
                        intPtr = Marshal.SecureStringToBSTR(secureString);
                    }

                    var pString         = (char *)intPtr;
                    var pInsecureString = (char *)gcHandle.AddrOfPinnedObject();

                    for (int index = 0; index < length; index++)
                    {
                        pInsecureString[index] = pString[index];
                    }
                },
                    delegate
                {
                    if (intPtr != IntPtr.Zero)
                    {
                        Marshal.ZeroFreeBSTR(intPtr);
                    }
                },
                    null);

                // Use the password.
                result = insecureString.ToCharArray();
            },
                delegate
            {
                if (gcHandle.IsAllocated)
                {
                    // Zero the string.
                    var pInsecureString = (char *)gcHandle.AddrOfPinnedObject();

                    for (int index = 0; index < length; index++)
                    {
                        pInsecureString[index] = '\0';
                    }

                    gcHandle.Free();
                }
            },
                null);

            return(result);
        }
コード例 #25
0
 public void SetvrstaNull()
 {
     this[this.tableporez.vrstaColumn] = RuntimeHelpers.GetObjectValue(Convert.DBNull);
 }
コード例 #26
0
 public bool Equals(object obj)
 {
     return(base.Equals(RuntimeHelpers.GetObjectValue(obj)));
 }
コード例 #27
0
 public override int GetHashCode()
 {
     return(RuntimeHelpers.GetHashCode(this));
 }
コード例 #28
0
ファイル: stat_CA.cs プロジェクト: allalaspace/GEBISOM
 private void MonthCalendar2_DateSelected(object sender, DateRangeEventArgs e)
 {
     DATEFF.Text            = MonthCalendar2.SelectionStart.ToString("dd/MM/yyyy");
     MonthCalendar2.Visible = false;
     B_rechercher_Click(RuntimeHelpers.GetObjectValue(sender), e);
 }
コード例 #29
0
 public override int GetHashCode()
 => Hash.Combine(RuntimeHelpers.GetHashCode(_assemblyLoader), FullPath.GetHashCode());
コード例 #30
0
ファイル: SqlFileStream.cs プロジェクト: yyjdelete/SqlClient
        private void InitializeEaBuffer(byte[] transactionContext)
        {
            if (transactionContext.Length >= UInt16.MaxValue)
            {
                throw ADP.ArgumentOutOfRange("transactionContext");
            }

            UnsafeNativeMethods.FILE_FULL_EA_INFORMATION eaBuffer;
            eaBuffer.nextEntryOffset = 0;
            eaBuffer.flags           = 0;
            eaBuffer.EaName          = 0;

            // string will be written as ANSI chars, so Length == ByteLength in this case
            eaBuffer.EaNameLength  = (byte)EA_NAME_STRING.Length;
            eaBuffer.EaValueLength = (ushort)transactionContext.Length;

            // allocate sufficient memory to contain the FILE_FULL_EA_INFORMATION struct and
            //   the contiguous name/value pair in eaName (note: since the struct already
            //   contains one byte for eaName, we don't need to allocate a byte for the
            //   null character separator).
            m_cbBuffer = Marshal.SizeOf(eaBuffer) + eaBuffer.EaNameLength + eaBuffer.EaValueLength;

            IntPtr pbBuffer = IntPtr.Zero;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
            }
            finally
            {
                pbBuffer = Marshal.AllocHGlobal(m_cbBuffer);
                if (pbBuffer != IntPtr.Zero)
                {
                    SetHandle(pbBuffer);
                }
            }

            bool mustRelease = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                DangerousAddRef(ref mustRelease);
                IntPtr ptr = DangerousGetHandle();

                // write struct into buffer
                Marshal.StructureToPtr(eaBuffer, ptr, false);

                // write property name into buffer
                System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
                byte[] asciiName = ascii.GetBytes(EA_NAME_STRING);

                // calculate offset at which to write the name/value pair
                System.Diagnostics.Debug.Assert(Marshal.OffsetOf(typeof(UnsafeNativeMethods.FILE_FULL_EA_INFORMATION), "EaName").ToInt64() <= (Int64)Int32.MaxValue);
                int cbOffset = Marshal.OffsetOf(typeof(UnsafeNativeMethods.FILE_FULL_EA_INFORMATION), "EaName").ToInt32();
                for (int i = 0; cbOffset < m_cbBuffer && i < eaBuffer.EaNameLength; i++, cbOffset++)
                {
                    Marshal.WriteByte(ptr, cbOffset, asciiName[i]);
                }

                System.Diagnostics.Debug.Assert(cbOffset < m_cbBuffer);

                // write null character separator
                Marshal.WriteByte(ptr, cbOffset, 0);
                cbOffset++;

                System.Diagnostics.Debug.Assert(cbOffset < m_cbBuffer || transactionContext.Length == 0 && cbOffset == m_cbBuffer);

                // write transaction context ID
                for (int i = 0; cbOffset < m_cbBuffer && i < eaBuffer.EaValueLength; i++, cbOffset++)
                {
                    Marshal.WriteByte(ptr, cbOffset, transactionContext[i]);
                }
            }
            finally
            {
                if (mustRelease)
                {
                    DangerousRelease();
                }
            }
        }