コード例 #1
0
ファイル: WISEObject.cs プロジェクト: Durlek/SAAB-CM
 public WISEObject(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = transactionHandle;
 }
コード例 #2
0
ファイル: EntityEquipment.cs プロジェクト: GULPF/SAAB-CM
 public EntityEquipment(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = TransactionHandle.None;
 }
コード例 #3
0
        /// <summary>
        /// Initializes a new instance of the CkKipParams class.
        /// </summary>
        /// <param name='mechanism'>Underlying cryptographic mechanism (CKM)</param>
        /// <param name='key'>Handle to a key that will contribute to the entropy of the derived key (CKM_KIP_DERIVE) or will be used in the MAC operation (CKM_KIP_MAC)</param>
        /// <param name='seed'>Input seed</param>
        public CkKipParams(ulong? mechanism, ObjectHandle key, byte[] seed)
        {
            _lowLevelStruct.Mechanism = IntPtr.Zero;
            _lowLevelStruct.Key = 0;
            _lowLevelStruct.Seed = IntPtr.Zero;
            _lowLevelStruct.SeedLen = 0;

            if (mechanism != null)
            {
                byte[] bytes = ConvertUtils.ULongToBytes(mechanism.Value);
                _lowLevelStruct.Mechanism = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Mechanism, bytes);
            }

            if (key == null)
                throw new ArgumentNullException("key");
            
            _lowLevelStruct.Key = key.ObjectId;

            if (seed != null)
            {
                _lowLevelStruct.Seed = UnmanagedMemory.Allocate(seed.Length);
                UnmanagedMemory.Write(_lowLevelStruct.Seed, seed);
                _lowLevelStruct.SeedLen = Convert.ToUInt64(seed.Length);
            }
        }
コード例 #4
0
 public EntityEquipmentSensorCBRNAP2Ce(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = transactionHandle;
 }
コード例 #5
0
ファイル: Entity.GroundVehicle.cs プロジェクト: GULPF/SAAB-CM
 public EntityGroundVehicle(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = transactionHandle;
 }
コード例 #6
0
        /// <summary>
        /// Initializes a new instance of the CkCmsSigParams class.
        /// </summary>
        /// <param name='certificateHandle'>Object handle for a certificate associated with the signing key</param>
        /// <param name='signingMechanism'>Mechanism to use when signing a constructed CMS SignedAttributes value</param>
        /// <param name='digestMechanism'>Mechanism to use when digesting the data</param>
        /// <param name='contentType'>String indicating complete MIME Content-type of message to be signed or null if the message is a MIME object</param>
        /// <param name='requestedAttributes'>DER-encoded list of CMS Attributes the caller requests to be included in the signed attributes</param>
        /// <param name='requiredAttributes'>DER-encoded list of CMS Attributes (with accompanying values) required to be included in the resulting signed attributes</param>
        public CkCmsSigParams(ObjectHandle certificateHandle, ulong? signingMechanism, ulong? digestMechanism, string contentType, byte[] requestedAttributes, byte[] requiredAttributes)
        {
            _lowLevelStruct.CertificateHandle = CK.CK_INVALID_HANDLE;
            _lowLevelStruct.SigningMechanism = IntPtr.Zero;
            _lowLevelStruct.DigestMechanism = IntPtr.Zero;
            _lowLevelStruct.ContentType = IntPtr.Zero;
            _lowLevelStruct.RequestedAttributes = IntPtr.Zero;
            _lowLevelStruct.RequestedAttributesLen = 0;
            _lowLevelStruct.RequiredAttributes = IntPtr.Zero;
            _lowLevelStruct.RequiredAttributesLen = 0;

            if (certificateHandle == null)
                throw new ArgumentNullException("certificateHandle");

            _lowLevelStruct.CertificateHandle = certificateHandle.ObjectId;

            if (signingMechanism != null)
            {
                byte[] bytes = ConvertUtils.ULongToBytes(signingMechanism.Value);
                _lowLevelStruct.SigningMechanism = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SigningMechanism, bytes);
            }

            if (digestMechanism != null)
            {
                byte[] bytes = ConvertUtils.ULongToBytes(digestMechanism.Value);
                _lowLevelStruct.DigestMechanism = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.DigestMechanism, bytes);
            }

            if (contentType != null)
            {
                byte[] bytes = ConvertUtils.Utf8StringToBytes(contentType);
                Array.Resize(ref bytes, bytes.Length + 1);
                bytes[bytes.Length - 1] = 0;
                
                _lowLevelStruct.ContentType = UnmanagedMemory.Allocate(bytes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.ContentType, bytes);
            }

            if (requestedAttributes != null)
            {
                _lowLevelStruct.RequestedAttributes = UnmanagedMemory.Allocate(requestedAttributes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.RequestedAttributes, requestedAttributes);
                _lowLevelStruct.RequestedAttributesLen = Convert.ToUInt64(requestedAttributes.Length);
            }

            if (requiredAttributes != null)
            {
                _lowLevelStruct.RequiredAttributes = UnmanagedMemory.Allocate(requiredAttributes.Length);
                UnmanagedMemory.Write(_lowLevelStruct.RequiredAttributes, requiredAttributes);
                _lowLevelStruct.RequiredAttributesLen = Convert.ToUInt64(requiredAttributes.Length);
            }
        }
コード例 #7
0
ファイル: WISEObjectFactory.cs プロジェクト: Durlek/SAAB-CM
 public WISEObject CreateObject(SensorTypes sensorType, ObjectHandle hObject)
 {
     switch (sensorType)
     {
         case SensorTypes.lcd:   return new EntityEquipmentSensorCBRNLCD(_sink, _hDatabase, hObject);
         case SensorTypes.ap2ce: return new EntityEquipmentSensorCBRNAP2Ce(_sink, _hDatabase, hObject);
         case SensorTypes.raid:  return new EntityEquipmentSensorCBRNRAID(_sink, _hDatabase, hObject);
         case SensorTypes.i28:   return new EntityEquipmentSensorCBRNI28(_sink, _hDatabase, hObject);
         case SensorTypes.i27:   return new EntityEquipmentSensorCBRNI27(_sink, _hDatabase, hObject);
     }
     throw new NotImplementedException();
 }
コード例 #8
0
 /// <summary>
 /// Initializes a new instance of the CkX942MqvDeriveParams class.
 /// </summary>>
 /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
 /// <param name='otherInfo'>Some data shared between the two parties</param>
 /// <param name='publicData'>Other party's first X9.42 Diffie-Hellman public key value</param>
 /// <param name='privateDataLen'>The length in bytes of the second X9.42 Diffie-Hellman private key</param>
 /// <param name='privateData'>Key handle for second X9.42 Diffie-Hellman private key value</param>
 /// <param name='publicData2'>Other party's second X9.42 Diffie-Hellman public key value</param>
 /// <param name='publicKey'>Handle to the first party's ephemeral public key</param>
 public CkX942MqvDeriveParams(ulong kdf, byte[] otherInfo, byte[] publicData, ulong privateDataLen, ObjectHandle privateData, byte[] publicData2, ObjectHandle publicKey)
 {
     _lowLevelStruct.Kdf = 0;
     _lowLevelStruct.OtherInfoLen = 0;
     _lowLevelStruct.OtherInfo = IntPtr.Zero;
     _lowLevelStruct.PublicDataLen = 0;
     _lowLevelStruct.PublicData = IntPtr.Zero;
     _lowLevelStruct.PrivateDataLen = 0;
     _lowLevelStruct.PrivateData = 0;
     _lowLevelStruct.PublicDataLen2 = 0;
     _lowLevelStruct.PublicData2 = IntPtr.Zero;
     _lowLevelStruct.PublicKey = 0;
     
     _lowLevelStruct.Kdf = kdf;
     
     if (otherInfo != null)
     {
         _lowLevelStruct.OtherInfo = UnmanagedMemory.Allocate(otherInfo.Length);
         UnmanagedMemory.Write(_lowLevelStruct.OtherInfo, otherInfo);
         _lowLevelStruct.OtherInfoLen = Convert.ToUInt64(otherInfo.Length);
     }
     
     if (publicData != null)
     {
         _lowLevelStruct.PublicData = UnmanagedMemory.Allocate(publicData.Length);
         UnmanagedMemory.Write(_lowLevelStruct.PublicData, publicData);
         _lowLevelStruct.PublicDataLen = Convert.ToUInt64(publicData.Length);
     }
     
     _lowLevelStruct.PrivateDataLen = privateDataLen;
     
     if (privateData == null)
         throw new ArgumentNullException("privateData");
     
     _lowLevelStruct.PrivateData = privateData.ObjectId;
     
     if (publicData2 != null)
     {
         _lowLevelStruct.PublicData2 = UnmanagedMemory.Allocate(publicData2.Length);
         UnmanagedMemory.Write(_lowLevelStruct.PublicData2, publicData2);
         _lowLevelStruct.PublicDataLen2 = Convert.ToUInt64(publicData2.Length);
     }
     
     if (publicKey == null)
         throw new ArgumentNullException("publicKey");
     
     _lowLevelStruct.PublicKey = publicKey.ObjectId;
 }
コード例 #9
0
        /// <summary>
        /// Initializes a new instance of the CkEcmqvDeriveParams class.
        /// </summary>>
        /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
        /// <param name='sharedData'>Some data shared between the two parties</param>
        /// <param name='publicData'>Other party's first EC public key value</param>
        /// <param name='privateDataLen'>The length in bytes of the second EC private key</param>
        /// <param name='privateData'>Key handle for second EC private key value</param>
        /// <param name='publicData2'>Other party's second EC public key value</param>
        /// <param name='publicKey'>Handle to the first party's ephemeral public key</param>
        public CkEcmqvDeriveParams(uint kdf, byte[] sharedData, byte[] publicData, uint privateDataLen, ObjectHandle privateData, byte[] publicData2, ObjectHandle publicKey)
        {
            _lowLevelStruct.Kdf = 0;
            _lowLevelStruct.SharedDataLen = 0;
            _lowLevelStruct.SharedData = IntPtr.Zero;
            _lowLevelStruct.PublicDataLen = 0;
            _lowLevelStruct.PublicData = IntPtr.Zero;
            _lowLevelStruct.PrivateDataLen = 0;
            _lowLevelStruct.PrivateData = 0;
            _lowLevelStruct.PublicDataLen2 = 0;
            _lowLevelStruct.PublicData2 = IntPtr.Zero;
            _lowLevelStruct.PublicKey = 0;

            _lowLevelStruct.Kdf = kdf;
            
            if (sharedData != null)
            {
                _lowLevelStruct.SharedData = UnmanagedMemory.Allocate(sharedData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.SharedData, sharedData);
                _lowLevelStruct.SharedDataLen = Convert.ToUInt32(sharedData.Length);
            }
            
            if (publicData != null)
            {
                _lowLevelStruct.PublicData = UnmanagedMemory.Allocate(publicData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData, publicData);
                _lowLevelStruct.PublicDataLen = Convert.ToUInt32(publicData.Length);
            }
            
            _lowLevelStruct.PrivateDataLen = privateDataLen;
            
            if (privateData == null)
                throw new ArgumentNullException("privateData");
            
            _lowLevelStruct.PrivateData = privateData.ObjectId;
            
            if (publicData2 != null)
            {
                _lowLevelStruct.PublicData2 = UnmanagedMemory.Allocate(publicData2.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData2, publicData2);
                _lowLevelStruct.PublicDataLen2 = Convert.ToUInt32(publicData2.Length);
            }

            if (publicKey == null)
                throw new ArgumentNullException("publicKey");
            
            _lowLevelStruct.PublicKey = publicKey.ObjectId;
        }
コード例 #10
0
 /// <summary>
 /// Initializes a new instance of the CkEcmqvDeriveParams class.
 /// </summary>>
 /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
 /// <param name='sharedData'>Some data shared between the two parties</param>
 /// <param name='publicData'>Other party's first EC public key value</param>
 /// <param name='privateDataLen'>The length in bytes of the second EC private key</param>
 /// <param name='privateData'>Key handle for second EC private key value</param>
 /// <param name='publicData2'>Other party's second EC public key value</param>
 /// <param name='publicKey'>Handle to the first party's ephemeral public key</param>
 public CkEcmqvDeriveParams(ulong kdf, byte[] sharedData, byte[] publicData, ulong privateDataLen, ObjectHandle privateData, byte[] publicData2, ObjectHandle publicKey)
 {
     if (Platform.UnmanagedLongSize == 4)
     {
         if (Platform.StructPackingSize == 0)
             _params40 = new HighLevelAPI40.MechanismParams.CkEcmqvDeriveParams(Convert.ToUInt32(kdf), sharedData, publicData, Convert.ToUInt32(privateDataLen), privateData.ObjectHandle40, publicData2, publicKey.ObjectHandle40);
         else
             _params41 = new HighLevelAPI41.MechanismParams.CkEcmqvDeriveParams(Convert.ToUInt32(kdf), sharedData, publicData, Convert.ToUInt32(privateDataLen), privateData.ObjectHandle41, publicData2, publicKey.ObjectHandle41);
     }
     else
     {
         if (Platform.StructPackingSize == 0)
             _params80 = new HighLevelAPI80.MechanismParams.CkEcmqvDeriveParams(kdf, sharedData, publicData, privateDataLen, privateData.ObjectHandle80, publicData2, publicKey.ObjectHandle80);
         else
             _params81 = new HighLevelAPI81.MechanismParams.CkEcmqvDeriveParams(kdf, sharedData, publicData, privateDataLen, privateData.ObjectHandle81, publicData2, publicKey.ObjectHandle81);
     }
 }
コード例 #11
0
 /// <summary>
 /// Initializes a new instance of the CkX942Dh2DeriveParams class.
 /// </summary>
 /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
 /// <param name='otherInfo'>Some data shared between the two parties</param>
 /// <param name='publicData'>Other party's first X9.42 Diffie-Hellman public key value</param>
 /// <param name='privateDataLen'>The length in bytes of the second X9.42 Diffie-Hellman private key</param>
 /// <param name='privateData'>Key handle for second X9.42 Diffie-Hellman private key value</param>
 /// <param name='publicData2'>Other party's second X9.42 Diffie-Hellman public key value</param>
 public CkX942Dh2DeriveParams(ulong kdf, byte[] otherInfo, byte[] publicData, ulong privateDataLen, ObjectHandle privateData, byte[] publicData2)
 {
     if (Platform.UnmanagedLongSize == 4)
     {
         if (Platform.StructPackingSize == 0)
             _params40 = new HighLevelAPI40.MechanismParams.CkX942Dh2DeriveParams(Convert.ToUInt32(kdf), otherInfo, publicData, Convert.ToUInt32(privateDataLen), privateData.ObjectHandle40, publicData2);
         else
             _params41 = new HighLevelAPI41.MechanismParams.CkX942Dh2DeriveParams(Convert.ToUInt32(kdf), otherInfo, publicData, Convert.ToUInt32(privateDataLen), privateData.ObjectHandle41, publicData2);
     }
     else
     {
         if (Platform.StructPackingSize == 0)
             _params80 = new HighLevelAPI80.MechanismParams.CkX942Dh2DeriveParams(kdf, otherInfo, publicData, privateDataLen, privateData.ObjectHandle80, publicData2);
         else
             _params81 = new HighLevelAPI81.MechanismParams.CkX942Dh2DeriveParams(kdf, otherInfo, publicData, privateDataLen, privateData.ObjectHandle81, publicData2);
     }
 }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the CkKipParams class.
        /// </summary>
        /// <param name='mechanism'>Underlying cryptographic mechanism (CKM)</param>
        /// <param name='key'>Handle to a key that will contribute to the entropy of the derived key (CKM_KIP_DERIVE) or will be used in the MAC operation (CKM_KIP_MAC)</param>
        /// <param name='seed'>Input seed</param>
        public CkKipParams(ulong? mechanism, ObjectHandle key, byte[] seed)
        {
            if (Platform.UnmanagedLongSize == 4)
            {
                uint? uintMechanism = (mechanism == null) ? null : (uint?)Convert.ToUInt32(mechanism.Value);

                if (Platform.StructPackingSize == 0)
                    _params40 = new HighLevelAPI40.MechanismParams.CkKipParams(uintMechanism, key.ObjectHandle40, seed);
                else
                    _params41 = new HighLevelAPI41.MechanismParams.CkKipParams(uintMechanism, key.ObjectHandle41, seed);
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                    _params80 = new HighLevelAPI80.MechanismParams.CkKipParams(mechanism, key.ObjectHandle80, seed);
                else
                    _params81 = new HighLevelAPI81.MechanismParams.CkKipParams(mechanism, key.ObjectHandle81, seed);
            }
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the CkCmsSigParams class.
        /// </summary>
        /// <param name='certificateHandle'>Object handle for a certificate associated with the signing key</param>
        /// <param name='signingMechanism'>Mechanism to use when signing a constructed CMS SignedAttributes value</param>
        /// <param name='digestMechanism'>Mechanism to use when digesting the data</param>
        /// <param name='contentType'>String indicating complete MIME Content-type of message to be signed or null if the message is a MIME object</param>
        /// <param name='requestedAttributes'>DER-encoded list of CMS Attributes the caller requests to be included in the signed attributes</param>
        /// <param name='requiredAttributes'>DER-encoded list of CMS Attributes (with accompanying values) required to be included in the resulting signed attributes</param>
        public CkCmsSigParams(ObjectHandle certificateHandle, ulong? signingMechanism, ulong? digestMechanism, string contentType, byte[] requestedAttributes, byte[] requiredAttributes)
        {
            if (Platform.UnmanagedLongSize == 4)
            {
                uint? uintSigningMechanism = (signingMechanism == null) ? null : (uint?)Convert.ToUInt32(signingMechanism.Value);
                uint? uintDigestMechanism = (digestMechanism == null) ? null : (uint?)Convert.ToUInt32(digestMechanism.Value);

                if (Platform.StructPackingSize == 0)
                    _params40 = new HighLevelAPI40.MechanismParams.CkCmsSigParams(certificateHandle.ObjectHandle40, uintSigningMechanism, uintDigestMechanism, contentType, requestedAttributes, requiredAttributes);
                else
                    _params41 = new HighLevelAPI41.MechanismParams.CkCmsSigParams(certificateHandle.ObjectHandle41, uintSigningMechanism, uintDigestMechanism, contentType, requestedAttributes, requiredAttributes);
            }
            else
            {
                if (Platform.StructPackingSize == 0)
                    _params80 = new HighLevelAPI80.MechanismParams.CkCmsSigParams(certificateHandle.ObjectHandle80, signingMechanism, digestMechanism, contentType, requestedAttributes, requiredAttributes);
                else
                    _params81 = new HighLevelAPI81.MechanismParams.CkCmsSigParams(certificateHandle.ObjectHandle81, signingMechanism, digestMechanism, contentType, requestedAttributes, requiredAttributes);
            }
        }
コード例 #14
0
 /// <summary>
 /// Creates new instance of Pkcs11X509Certificate2Context class
 /// </summary>
 /// <param name="certificateInfo">Detailed information about X.509 certificate stored on PKCS#11 token</param>
 /// <param name="certHandle">High level PKCS#11 object handle of certificate object</param>
 /// <param name="privKeyHandle">High level PKCS#11 object handle of private key object</param>
 /// <param name="pubKeyHandle">High level PKCS#11 object handle of public key object</param>
 /// <param name="keyUsageRequiresLogin">Flag indicating whether key usage requires context specific login to be perfromed</param>
 /// <param name="tokenContext">Internal context for Pkcs11Token class</param>
 internal Pkcs11X509CertificateContext(Pkcs11X509CertificateInfo certificateInfo, ObjectHandle certHandle, ObjectHandle privKeyHandle, ObjectHandle pubKeyHandle, bool keyUsageRequiresLogin, Pkcs11TokenContext tokenContext)
 {
     _certificateInfo       = certificateInfo ?? throw new ArgumentNullException(nameof(certificateInfo));
     _certHandle            = certHandle ?? throw new ArgumentNullException(nameof(certHandle));
     _privKeyHandle         = privKeyHandle;
     _pubKeyHandle          = pubKeyHandle;
     _keyUsageRequiresLogin = keyUsageRequiresLogin;
     _tokenContext          = tokenContext ?? throw new ArgumentNullException(nameof(tokenContext));
 }
コード例 #15
0
        static void Main(string[] args)
        {
            // создаём HTML версию рендерера
            HTMLRenderer r = new HTMLRenderer();

            // создаём объект игры и пробрасываем ему рендерер (внедрение через конструктор)
            game = new GoGame(r);

            // создаём слушатель HTTP запросов
            HttpListener listener = new HttpListener();

            // настраиваем его чтобы он слушал на определённом порту
            listener.Prefixes.Add("http://*:55555/");
            // стартуем его
            listener.Start();

            // на всякий случай выводим в консоль чтобы мы знали что сервер слушает
            Console.WriteLine("listening");

            // инициализируем игру (ToDo: потом нужно это убрать в контроллер)
            game.Init(10, 5);

            // создаём бесконечный цикл чтобы слушать запросы с клиента
            while (true)
            {
                // контекст - это кто, что спросил, с какого IP, какой браузер итд - сопутствующие запросу данные
                // чтобы мы не парились с тем как нам возвращать данные на клиент по этому запросу, уже всё сделано за нас:
                // поскольку контекст содержит запрос (Request) и ответ (Response) мы можем просто положить чтото в response и это пойдёт на клиент

                // получаем контекст из слушателя - это происходит при любом запросе с клиента
                // (всмысле в этой точке программа ждёт запроса, цикл просто так не гоняется без дела)
                // когда запрос получен, выполняется эта строка: получаем контекст из слушателя
                HttpListenerContext context = listener.GetContext();
                // получаем запрос из контекста
                HttpListenerRequest request = context.Request;

                // чтобы не бегать по сложному объекту контекст, искать там запрос, доставать оттуда URL который пользователь ввёл в браузер, просто извлекаем его в переменную
                String rawurl = request.RawUrl;

                // сюда мы будем класть ответ сервера, неважно какая подсистема его сформирует
                String responsestring = "";

                // убираем / вначале, чтобы переиспользовать эту строку в нескольких местах
                String TrimmedURL = rawurl.TrimStart('/');

                // дальше идёт ветвление на MVC и просто файлы: если запрошен какойто файл, отдаём его. если нет точки в строке (признак расширения файла) то идём на MVC
                if (!rawurl.Contains('.'))
                {
                    ///MVC веточка

                    // что такое HTTPContext? поставьте туда мышку и нажмите F12 (или RMB -> Go To Definition)
                    // тупо три переменные сформированные в одну кучку - класс
                    // что делает функция GetContext - тоже можно посмотреть через F12:
                    // она URL вида Controller/Action/Parameters разбирает на части по разделителю '/' и складывает в нужные части с проверками есть они или нет
                    // не хотим париться как она это делает - выносим в отдельную функцию



                    HTTPContext ct = GetContext(TrimmedURL);

                    // если контекст удалось заполнить (хоть чтото)...
                    if (ct != null)
                    {
                        // ...начинаем изучать Reflection
                        // Reflection это способность среды исполнения CLR отвечать на вопросы программы о самой себе.
                        // получаем ссылку на ту сборку которая запрашивает информацию о самой этой сборке
                        Assembly asm = Assembly.GetCallingAssembly();

                        // ещё одна новая тема - лямбда-выражения.
                        // их особенность в том, что в качестве параметра им передаются не переменные, а алгоритмы (упакованные в анонимные функции)
                        // например:
                        // список (List) типов TypeInfo


                        // тут будет список всех типов из сборки, унаследованных от Controller
                        List <TypeInfo> Controllers =
                            // получается так:
                            // мы просим сборку (asm)
                            asm
                            // дать нам все определённые типы (defined types)
                            .DefinedTypes
                            // дальше одно и то же объяснение разными словами - каждая строчка объясняет одноитоже
                            // где (кагбэ функция без имени, которая принимает параметр и возвращает значение)
                            // Where (то что пришло => а это я верну)
                            // где (какойто входной аргумент типа TypeInfo (потому что List<TypeInfo>)) стрелка лямбды (=>) выражение которое возвращает да или нет (фильтр по которому ищем)
                            // где (инфа_о_типе => унаследован ли инфа_о_типе от класса Controller?).преобразовать к списку
                            // где (TypeInfo => является ли элемент BaseType переданного TypeInfo типом "Controller" приведённым к типу Type?).к списку
                            .Where(x => x.BaseType == typeof(Controller)).ToList();

                        // фух! сложно!
                        // вот так правильно, на уроке не получалось потому что подход мы использовали слишком простой
                        // вот так сложнее но эффективнее - можно класть типы в любую папочку и использовать для них любой namespace,
                        // Reflection через методы сборки подберёт их из самой сборки и правильно настроит
                        // вот магия Reflection!

                        // получаем имя сборки - как мы называемся?
                        AssemblyName an = asm.GetName();

                        // получаем полное имя класса вместе с namespace чтобы проблема папочек решалась автоматически
                        // имя класса с неймспейсом =  кого имя совпадает с тем что считается именем контроллера, пришедшим из браузера
                        String ClassName = Controllers
                                                               // список контроллеров, отфильтруй нам контроллеры по имени, которое совпадает с тем что в ct.Controller,
                                           .Where(x => x.Name == ct.Controller)
                                                               // и проконтролируй чтобы он там был, а если его там нет верни null
                                           .SingleOrDefault()? // внимание, ? означает что дальше идём только если тут чтото есть, если нет то следующая строка не будет выполняться. (сокращённая запись if != null)
                                                               // если в предыдущей строке не был результат null то берём из того что получили FullName - это и будет имя класса (fully-qualified name), например assembly.namespace.classname, или к примеру Server.MVC.Home
                                           .FullName;

                        // из имени класса и имени сборки создаём наш класс, завёрнутый в обслуживающую обёртку
                        ObjectHandle tclass = Activator.CreateInstance(an.Name, ClassName);

                        // получаем его тип (класс это сам класс например "Home" или "Game", а Type - это объект, который описывает этот класс, через него можно получить информацию об этом классе)
                        Type type = asm.GetType(ClassName);

                        // разворачиваем обёртку - получаем объект, созданный активатором из имени сборки и имени класса
                        object unwc = tclass.Unwrap();

                        //приводим развёрнутый объект к типу Controller чтобы иметь доступ к контексту, и чтобы компилятор мог проконтролировать это до исполнения
                        ((Controller)unwc).Context = ct;

                        // если указан какойто метод, который нужно выполнить, то выполняем его (он поумолчанию Index)
                        if (ct.Action != null)
                        {
                            // заполняем наш ответ тем, что вернёт метод контроллера (функция класса)
                            // просим тип вызвать (invoke) заданный метод для заданного объекта класса
                            // это так, потому что метод берётся из класса, а вызывается для объекта,
                            // поэтому методу Invoke нужно передать объект, для которого вызвать этот метод
                            // в конце приводим это всё к строке, потому что иначе компилятор не сможет проконтролировать тип
                            responsestring = type.GetMethod(ct.Action).Invoke(unwc, null).ToString();
                        }
                    }
                }
                else
                {
                    // веточка не MVC, старый тип запуска игр

                    // идём игроком (выполняем команду с клиента)
                    game.MoveUser(TrimmedURL);

                    // рендерим поле
                    String GameField = game.RenderField();

                    //получаем файл-шаблон для нашей игры
                    String tfile = GetFileContent("Game");

                    //заменяем там тэг "<game /> на отрендеренное игровое поле
                    tfile = tfile.Replace("<game />", GameField);

                    //заполняем строку вывода на клиент
                    responsestring = tfile;
                }

                // получаем ответ клиенту из контекста
                HttpListenerResponse response = context.Response;

                // буфер - чтобы можно было обрабатывать по частям, кодируем всё в UTF8
                byte[] buffer = Encoding.UTF8.GetBytes(responsestring);
                // сколько там букаф? осилим?
                response.ContentLength64 = buffer.Length;
                // получаем поток из ответа
                Stream output = response.OutputStream;
                // пишем в поток содержимое буфера
                output.Write(buffer, 0, buffer.Length);
                // закрываем поток
                output.Close();

                // выводим в консоль на всякий случай чтобы если на клиенте чтото пойдёт не так мы в консоли видели проблему
                Console.WriteLine($"String {responsestring} sent to client");
            }
        }
コード例 #16
0
        private static StaticAdapter CreateAdapter(AppDomain targetDomain, ObjectHandle objHandle)
        {
            Type tAdapter = TypeOf <StaticAdapter> .TypeID;

            return((StaticAdapter)targetDomain.CreateInstanceAndUnwrap(tAdapter.Assembly.FullName, tAdapter.FullName, false, 0, null, new[] { objHandle }, null, null));
        }
コード例 #17
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public void Insert(IntPtr targetIndex, ObjectHandle objectHandle)
 {
     NativeException nativeException;
     NativeMethods.insert(this, targetIndex, objectHandle, out nativeException);
     nativeException.ThrowIfNecessary();
 }
コード例 #18
0
        public bool Run(object[] inputParams)
        {
            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, false))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(false))
                {
                    string pin          = Convert.ToString(inputParams[0]);
                    string keyLabel     = Convert.ToString(inputParams[1]);
                    string pathSource   = Convert.ToString(inputParams[2]);
                    bool   needMetaData = Convert.ToBoolean(inputParams[3]);

                    if (String.IsNullOrEmpty(pathSource))
                    {
                        pathSource = Settings.Pkcs11LibraryPath;
                    }

                    // Login as normal user
                    session.Login(CKU.CKU_USER, pin);

                    // Prepare attribute template that defines search criteria
                    List <ObjectAttribute> objectAttributes = new List <ObjectAttribute>();
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, (uint)CKO.CKO_SECRET_KEY));
                    objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, keyLabel));

                    // Initialize searching
                    session.FindObjectsInit(objectAttributes);

                    // Get search results
                    List <ObjectHandle> foundObjects = session.FindObjects(1);

                    // Terminate searching
                    session.FindObjectsFinal();

                    if (foundObjects.Count < 1)
                    {
                        return(false);
                    }

                    ObjectHandle foundKey = foundObjects[0];

                    byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
                                  0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 };

                    // Specify encryption mechanism with initialization vector as parameter
                    Mechanism mechanism = new Mechanism(CKM.CKM_AES_CBC_PAD, iv);
                    // Specify a file to read from and to create.

                    string pathCipherSource   = @".\TestEncryptedResult.dat";
                    string pathDeCipherSource = @".\TestDecryptedResult.dat";
                    // META data string must start with "META:"
                    byte[] metaData = ConvertUtils.Utf8StringToBytes("META: This is the meta data to put into the log");

                    using (FileStream sourceFileStream = new FileStream(pathSource, FileMode.Open, FileAccess.Read),
                           cipherSourceStream = new FileStream(pathCipherSource, FileMode.Create, FileAccess.Write))
                    {
                        // Encrypt data multi part
                        Console.WriteLine("Encrypted File: " + pathSource + " into " + pathCipherSource);
                        if (needMetaData)
                        {
                            session.Encrypt(mechanism, foundKey, sourceFileStream, cipherSourceStream, metaData);
                        }
                        else
                        {
                            session.Encrypt(mechanism, foundKey, sourceFileStream, cipherSourceStream);
                        }
                    }


                    using (FileStream decipherSourceStream = new FileStream(pathDeCipherSource, FileMode.Create, FileAccess.Write),
                           cipherSourceFileStream = new FileStream(pathCipherSource, FileMode.Open, FileAccess.Read))
                    {
                        Console.WriteLine("Decrypted File: " + pathCipherSource + " into " + pathDeCipherSource);
                        if (needMetaData)
                        {
                            session.Decrypt(mechanism, foundKey, cipherSourceFileStream, decipherSourceStream, metaData);
                        }
                        else
                        {
                            session.Decrypt(mechanism, foundKey, cipherSourceFileStream, decipherSourceStream);
                        }
                    }

                    // now do file comparison
                    Console.WriteLine("Comparing source file and decrypted source file...: ");

                    // Do something interesting with decrypted data
                    if (FilesAreEqual(new FileInfo(pathSource), new FileInfo(pathDeCipherSource)))
                    {
                        Console.WriteLine("Source and Decrypted Data Matches!");
                    }
                    session.Logout();

                    slot.CloseSession(session);
                }
            }
            return(true);
        }
コード例 #19
0
        static int Main(string[] args)
        {
            Console.WriteLine("test " + AppDomain.CurrentDomain.FriendlyName);
            AppDomain app2 = AppDomain.CreateDomain("2");

            if (!RemotingServices.IsTransparentProxy(app2))
            {
                return(1);
            }

            ObjectHandle o     = AppDomain.CurrentDomain.CreateInstance(typeof(R1).Assembly.FullName, typeof(R1).FullName);
            R1           myobj = (R1)o.Unwrap();

            // should not be a proxy in our domain..
            if (RemotingServices.IsTransparentProxy(myobj))
            {
                Console.WriteLine("CreateInstance return TP for in our current domain");
                return(2);
            }

            o = app2.CreateInstance(typeof(R1).Assembly.FullName, typeof(R1).FullName);

            Console.WriteLine("type: " + o.GetType().ToString());

            myobj = (R1)o.Unwrap();
            if (!RemotingServices.IsTransparentProxy(myobj))
            {
                return(3);
            }

            Console.WriteLine("unwrapped type: " + myobj.GetType().ToString());

            R2   r2      = null;
            bool bSerExc = false;

            // this should crash
            try
            {
                r2 = myobj.TestMBV();
            }
            catch (SerializationException)
            {
                bSerExc = true;
            }

            if (!bSerExc)
            {
                return(4);
            }

            // Test generic virtual interface methods on proxies

            o     = app2.CreateInstance(typeof(R1).Assembly.FullName, typeof(R1).FullName);
            myobj = (R1)o.Unwrap();

            GenericIFace iface = (GenericIFace)myobj;

            if (iface.Foo <int> () != 0)
            {
                return(5);
            }
            if (iface.Foo <string> () != null)
            {
                return(6);
            }

            // Test type identity (#504886, comment #10 ff.)

            if (typeof(R1) != myobj.GetType())
            {
                return(7);
            }

            AppDomain.Unload(app2);

            Console.WriteLine("test-ok");
            return(0);
        }
コード例 #20
0
        /// <summary>
        /// Creates an empty default implementation of <see cref="INetworkData"/>.
        /// </summary>
        public static INetworkData CreateNetworkData()
        {
            ObjectHandle o = Activator.CreateInstance("PerseusLibS", "PerseusLibS.Data.Network.NetworkData");

            return((INetworkData)o.Unwrap());
        }
コード例 #21
0
        public static int Main(string[] args)
        {
            try
            {
                SoapSudsArgs soapSudsArgs   = new SoapSudsArgs();
                bool         bInput         = false;
                String       inputDirectory = null;

                if (args.Length == 0)
                {
                    Usage();
                    return(1);
                }

                // Parse Arguments

                for (int i = 0; i < args.Length; i++)
                {
                    if (
                        String.Compare(args[i], "HELP", true, CultureInfo.InvariantCulture) == 0 ||
                        String.Compare(args[i], "?", true, CultureInfo.InvariantCulture) == 0 ||
                        String.Compare(args[i], "/h", true, CultureInfo.InvariantCulture) == 0 ||
                        String.Compare(args[i], "-h", true, CultureInfo.InvariantCulture) == 0 ||
                        String.Compare(args[i], "-?", true, CultureInfo.InvariantCulture) == 0 ||
                        String.Compare(args[i], "/?", true, CultureInfo.InvariantCulture) == 0
                        )
                    {
                        Usage();
                        return(1);
                    }

                    String arg   = args[i];
                    String value = null;

                    if (args[i][0] == '/' || args[i][0] == '-')
                    {
                        int index = args[i].IndexOf(':');
                        if (index != -1)
                        {
                            arg = args[i].Substring(1, index - 1);

                            // make sure ':' isn't last character
                            if (index == (args[i].Length - 1))
                            {
                                throw new ApplicationException(Resource.FormatString("Err_ParamValueEmpty", args[i]));
                            }

                            value = args[i].Substring(index + 1);
                        }
                        else
                        {
                            arg = args[i].Substring(1);
                        }
                    }


                    //Process Input Sources
                    if (String.Compare(arg, "urlToSchema", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "url", true, CultureInfo.InvariantCulture) == 0)
                    {
                        if (bInput)
                        {
                            throw new ApplicationException(Resource.FormatString("Err_MultipleInputSources", value));
                        }

                        bInput = true;
                        soapSudsArgs.urlToSchema = CheckArg(value, "urlToSchema");
                    }
                    else if (String.Compare(arg, "types", true, CultureInfo.InvariantCulture) == 0)
                    {
                        if (bInput)
                        {
                            throw new ApplicationException(Resource.FormatString("Err_MultipleInputSources", value));
                        }
                        bInput = true;
                        String   typesInputString = CheckArg(value, "types");
                        String[] parts            = typesInputString.Split(';');

                        soapSudsArgs.serviceTypeInfos = new ServiceTypeInfo[parts.Length];

                        for (int partType = 0; partType < parts.Length; partType++)
                        {
                            String[] part = parts[partType].Split(',');
                            if (part.Length < 2 || part.Length > 3 ||
                                part[0] == null || part[0].Length == 0 ||
                                part[1] == null || part[1].Length == 0)
                            {
                                throw new ArgumentException(Resource.FormatString("Err_TypeOption", value));
                            }

                            soapSudsArgs.serviceTypeInfos[partType]          = new ServiceTypeInfo();
                            soapSudsArgs.serviceTypeInfos[partType].type     = part[0];
                            soapSudsArgs.serviceTypeInfos[partType].assembly = part[1];
                            if (part.Length == 3)
                            {
                                soapSudsArgs.serviceTypeInfos[partType].serviceEndpoint = part[2];
                            }
                        }
                    }
                    else if (String.Compare(arg, "inputSchemaFile", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "is", true, CultureInfo.InvariantCulture) == 0)
                    {
                        if (bInput)
                        {
                            throw new ApplicationException(Resource.FormatString("Err_MultipleInputSources", value));
                        }
                        bInput = true;
                        soapSudsArgs.inputSchemaFile = CheckArg(value, "inputSchemaFile");
                    }
                    else if (String.Compare(arg, "inputAssemblyFile", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "ia", true, CultureInfo.InvariantCulture) == 0)
                    {
                        if (bInput)
                        {
                            throw new ApplicationException(Resource.FormatString("Err_MultipleInputSources", value));
                        }
                        bInput = true;
                        soapSudsArgs.inputAssemblyFile = CheckArg(value, "inputAssemblyFile");
                    }

                    // Input Options
                    else if (String.Compare(arg, "inputDirectory", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "id", true, CultureInfo.InvariantCulture) == 0)
                    {
                        inputDirectory = CheckArg(value, "inputDirectory");
                    }
                    else if (String.Compare(arg, "serviceEndpoint", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "se", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.serviceEndpoint = CheckArg(value, "serviceEndpoint");
                    }

                    // Output Options
                    else if (String.Compare(arg, "outputSchemaFile", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "os", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.outputSchemaFile = CheckArg(value, "outputSchemaFile");
                    }
                    else if (String.Compare(arg, "outputDirectory", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "od", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.outputDirectory = CheckArg(value, "outputDirectory");
                    }
                    else if (String.Compare(arg, "outputAssemblyFile", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "oa", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.outputAssemblyFile = CheckArg(value, "outputAssemblyFile");
                        if (soapSudsArgs.outputAssemblyFile.EndsWith(".exe") || soapSudsArgs.outputAssemblyFile.EndsWith(".com"))
                        {
                            throw new ApplicationException(Resource.FormatString("Err_OutputAssembly", soapSudsArgs.outputAssemblyFile));
                        }
                    }

                    // Generate Options
                    else if (String.Compare(arg, "generateCode", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "gc", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.gc = true;
                        soapSudsArgs.outputDirectory = ".";
                    }

                    // Other Options
                    else if (String.Compare(arg, "WrappedProxy", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "wp", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.wp = true;
                    }
                    else if (String.Compare(arg, "NoWrappedProxy", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "nowp", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.wp = false;
                    }
                    else if (String.Compare(arg, "proxyNamespace", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "pn", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.proxyNamespace = CheckArg(value, "proxyNamespace");
                    }
                    else if (String.Compare(arg, "sdl", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.sdlType = SdlType.Sdl;
                    }
                    else if (String.Compare(arg, "wsdl", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.sdlType = SdlType.Wsdl;
                    }
                    else if (String.Compare(arg, "strongNameFile", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "sn", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.strongNameFile = CheckArg(value, "strongNameFile");
                    }

                    // Connection Information Options
                    else if (String.Compare(arg, "username", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "u", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.username = CheckArg(value, "username");
                    }
                    else if (String.Compare(arg, "password", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "p", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.password = CheckArg(value, "password");
                    }
                    else if (String.Compare(arg, "domain", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "d", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.domain = CheckArg(value, "domain");
                    }
                    else if (String.Compare(arg, "httpProxyName", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "hpn", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.httpProxyName = CheckArg(value, "httpProxyName");
                    }
                    else if (String.Compare(arg, "httpProxyPort", true, CultureInfo.InvariantCulture) == 0 || String.Compare(arg, "hpp", true, CultureInfo.InvariantCulture) == 0)
                    {
                        soapSudsArgs.httpProxyPort = CheckArg(value, "httpProxyPort");
                    }
                    else
                    {
                        Console.WriteLine(Resource.FormatString("Err_UnknownParameter", arg));
                        return(1);
                    }
                }


                int RetCode = 0;

                // Create an AppDomain to load the implementation part of the app into.
                AppDomainSetup options = new AppDomainSetup();
                if (inputDirectory == null)
                {
                    options.ApplicationBase = Environment.CurrentDirectory;
                }
                else
                {
                    options.ApplicationBase = new DirectoryInfo(inputDirectory).FullName;
                }

                options.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;


                AppDomain domain = AppDomain.CreateDomain("SoapSuds", null, options);
                if (domain == null)
                {
                    throw new ApplicationException(Resource.FormatString("Err_CannotCreateAppDomain"));
                }

                // Create the remote component that will perform the rest of the conversion.
                AssemblyName n        = Assembly.GetExecutingAssembly().GetName();
                AssemblyName codeName = new AssemblyName();
                codeName.Name    = "SoapSudsCode";
                codeName.Version = n.Version;
                codeName.SetPublicKey(n.GetPublicKey());
                codeName.CultureInfo = n.CultureInfo;
                ObjectHandle h = domain.CreateInstance(codeName.FullName, "SoapSudsCode.SoapSudsCode");
                if (h == null)
                {
                    throw new ApplicationException(Resource.FormatString("Err_CannotCreateRemoteSoapSuds"));
                }

                SoapSudsCode soapSudsCode = (SoapSudsCode)h.Unwrap();
                if (soapSudsCode != null)
                {
                    RetCode = soapSudsCode.Run(soapSudsArgs);
                }
            }
            catch (Exception e)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(e.Message);
                while (e.InnerException != null)
                {
                    sb.Append(", ");
                    sb.Append(e.InnerException.Message);
                    e = e.InnerException;
                }
                Console.WriteLine(Resource.FormatString("Err_SoapSuds", sb.ToString()));
                return(1);
            }

            return(0);
        }
コード例 #22
0
        /// <summary>
        /// Creates an empty default implementation of <see cref="IMatrixData"/>.
        /// </summary>
        public static IMatrixData CreateMatrixData()
        {
            ObjectHandle o = Activator.CreateInstance("PerseusLibS", "PerseusLibS.Data.Matrix.MatrixData");

            return((IMatrixData)o.Unwrap());
        }
コード例 #23
0
        /// <summary>
        /// Creates an empty default implementation of <see cref="IDocumentData"/>.
        /// </summary>
        public static IDocumentData CreateDocumentData()
        {
            ObjectHandle o = Activator.CreateInstance("PerseusLibS", "PerseusLibS.Data.DocumentData");

            return((IDocumentData)o.Unwrap());
        }
コード例 #24
0
        static void Main(string[] args)
        {
            try
            {
                // Инициализировать библиотеку
                Console.WriteLine("Library initialization");
                using (var pkcs11 = new Pkcs11(Settings.RutokenEcpDllDefaultPath, Settings.OsLockingDefault))
                {
                    // Получить доступный слот
                    Console.WriteLine("Checking tokens available");
                    Slot slot = Helpers.GetUsableSlot(pkcs11);

                    // Определение поддерживаемых токеном механизмов
                    Console.WriteLine("Checking mechanisms available");
                    List <CKM> mechanisms = slot.GetMechanismList();
                    Errors.Check(" No mechanisms available", mechanisms.Count > 0);
                    bool isGostR3410DeriveSupported = mechanisms.Contains((CKM)Extended_CKM.CKM_GOSTR3410_DERIVE);
                    bool isGostWrapSupported        = mechanisms.Contains((CKM)Extended_CKM.CKM_GOST28147_KEY_WRAP);
                    Errors.Check(" CKM_GOSTR3410_DERIVE isn`t supported!", isGostR3410DeriveSupported);
                    Errors.Check(" CKM_GOST28147_KEY_WRAP isn`t supported!", isGostWrapSupported);

                    // Открыть RW сессию в первом доступном слоте
                    Console.WriteLine("Opening RW session");
                    using (Session session = slot.OpenSession(false))
                    {
                        // Выполнить аутентификацию Пользователя
                        Console.WriteLine("User authentication");
                        session.Login(CKU.CKU_USER, SampleConstants.NormalUserPin);

                        ObjectHandle sessionKeyHandle          = null;
                        ObjectHandle senderDerivedKeyHandle    = null;
                        ObjectHandle recipientDerivedKeyHandle = null;
                        ObjectHandle unwrappedKeyHandle        = null;

                        try
                        {
                            // Генерация параметра для структуры типа CK_GOSTR3410_DERIVE_PARAMS
                            // для выработки общего ключа
                            Console.WriteLine("Preparing data for deriving and wrapping...");
                            byte[] ukm = session.GenerateRandom(SampleConstants.UkmLength);

                            // Генерация значения сессионного ключа
                            byte[] sessionKeyValue = session.GenerateRandom(SampleConstants.Gost28147_KeySize);

                            Console.WriteLine(" Session key data is:");
                            Helpers.PrintByteArray(sessionKeyValue);
                            Console.WriteLine("Preparing has been completed successfully");

                            // Выработка общего ключа на стороне отправителя
                            Console.WriteLine("Deriving key on the sender's side...");
                            Derive_GostR3410_Key(session,
                                                 SenderPrivateKeyAttributes, RecipientPublicKeyAttributes,
                                                 ukm, out senderDerivedKeyHandle);
                            Console.WriteLine("Key has been derived successfully");

                            // Маскировать сессионный ключ с помощью общего выработанного ключа
                            // на стороне отправителя
                            Console.WriteLine("Wrapping key...");
                            Console.WriteLine(" Creating the GOST 28147-89 key to wrap...");
                            // Выработка ключа, который будет замаскирован
                            SessionKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VALUE, sessionKeyValue));
                            sessionKeyHandle = session.CreateObject(SessionKeyAttributes);

                            // Определение параметров механизма маскирования
                            var wrapMechanismParams = new CkKeyDerivationStringData(ukm);
                            var wrapMechanism       = new Mechanism((uint)Extended_CKM.CKM_GOST28147_KEY_WRAP, wrapMechanismParams);

                            // Маскирование ключа на общем ключе, выработанном на стороне отправителя
                            byte[] wrappedKey = session.WrapKey(wrapMechanism, senderDerivedKeyHandle, sessionKeyHandle);

                            Console.WriteLine("  Wrapped key data is:");
                            Helpers.PrintByteArray(wrappedKey);
                            Console.WriteLine(" Key has been wrapped successfully");

                            // Выработка общего ключа на стороне получателя
                            Console.WriteLine("Deriving key on the sender's side...");
                            Derive_GostR3410_Key(session,
                                                 RecipientPrivateKeyAttributes, SenderPublicKeyAttributes,
                                                 ukm, out recipientDerivedKeyHandle);
                            Console.WriteLine("Key has been derived successfully");

                            // Демаскирование сессионного ключа с помощью общего выработанного
                            // ключа на стороне получателя
                            Console.WriteLine("Unwrapping key...");
                            unwrappedKeyHandle =
                                session.UnwrapKey(wrapMechanism, recipientDerivedKeyHandle, wrappedKey, UnwrappedKeyAttributes);

                            // Сравнение ключа
                            // Получаем публичный ключ по его Id
                            var attributes = new List <CKA>
                            {
                                CKA.CKA_VALUE
                            };
                            List <ObjectAttribute> unwrappedKeyValueAttribute =
                                session.GetAttributeValue(unwrappedKeyHandle, attributes);
                            byte[] unwrappedKeyValue = unwrappedKeyValueAttribute[0].GetValueAsByteArray();

                            Console.WriteLine(" Unwrapped key data is:");
                            Helpers.PrintByteArray(unwrappedKeyValue);
                            Console.WriteLine("Unwrapping has been completed successfully");

                            bool equal = (Convert.ToBase64String(sessionKeyValue) ==
                                          Convert.ToBase64String(unwrappedKeyValue));
                            Errors.Check("Session and unwrapped keys are not equal!", equal);

                            Console.WriteLine("Session and unwrapped keys are equal");
                        }
                        finally
                        {
                            Console.WriteLine("Destroying keys");
                            // Удаляем сессионный ключ
                            if (sessionKeyHandle != null)
                            {
                                session.DestroyObject(sessionKeyHandle);
                            }

                            // Удаляем наследованные ключи
                            if (senderDerivedKeyHandle != null)
                            {
                                session.DestroyObject(senderDerivedKeyHandle);
                            }
                            if (recipientDerivedKeyHandle != null)
                            {
                                session.DestroyObject(recipientDerivedKeyHandle);
                            }

                            // Удаляем размаскированный ключ
                            if (unwrappedKeyHandle != null)
                            {
                                session.DestroyObject(unwrappedKeyHandle);
                            }

                            // Сбросить права доступа как в случае исключения,
                            // так и в случае успеха.
                            // Сессия закрывается автоматически.
                            session.Logout();
                        }
                    }
                }
            }
            catch (Pkcs11Exception ex)
            {
                Console.WriteLine($"Operation failed [Method: {ex.Method}, RV: {ex.RV}]");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Operation failed [Message: {ex.Message}]");
            }
        }
コード例 #25
0
        private IAnalysisSet AddReference(Node node, Func <string, ObjectHandle> partialLoader)
        {
            // processes a call to clr.AddReference updating project state
            // so that it contains the newly loaded assembly.
            var callExpr = node as CallExpression;

            if (callExpr == null)
            {
                return(AnalysisSet.Empty);
            }
            foreach (var arg in callExpr.Args)
            {
                var cexpr = arg.Expression as Microsoft.PythonTools.Parsing.Ast.ConstantExpression;
                if (cexpr == null || !(cexpr.Value is string || cexpr.Value is AsciiString))
                {
                    // can't process this add reference
                    continue;
                }

                // TODO: Should we do a .NET reflection only load rather than
                // relying on the CLR module here?  That would prevent any code from
                // running although at least we don't taint our own modules which
                // are loaded with this current code.
                var asmName = cexpr.Value as string;
                if (asmName == null)
                {
                    // check for byte string
                    var bytes = cexpr.Value as AsciiString;
                    if (bytes != null)
                    {
                        asmName = bytes.String;
                    }
                }
                if (asmName != null && !_assemblyLoadSet.Contains(asmName))
                {
                    _assemblyLoadSet.Add(asmName);
                    ObjectHandle asm = null;
                    try {
                        if (partialLoader != null)
                        {
                            asm = partialLoader(asmName);
                        }
                        else
                        {
                            try {
                                asm = LoadAssemblyByName(asmName);
                            } catch {
                                asm = null;
                            }
                            if (asm == null)
                            {
                                asm = LoadAssemblyByPartialName(asmName);
                            }
                        }

                        if (asm == null && _state != null)
                        {
                            foreach (var dir in _state.AnalysisDirectories)
                            {
                                if (!PathUtils.IsValidPath(dir) && !PathUtils.IsValidPath(asmName))
                                {
                                    string path = Path.Combine(dir, asmName);
                                    if (File.Exists(path))
                                    {
                                        asm = Remote.LoadAssemblyFrom(path);
                                    }
                                    else if (File.Exists(path + ".dll"))
                                    {
                                        asm = Remote.LoadAssemblyFrom(path + ".dll");
                                    }
                                    else if (File.Exists(path + ".exe"))
                                    {
                                        asm = Remote.LoadAssemblyFrom(path + ".exe");
                                    }
                                }
                            }
                        }
                    } catch {
                    }
                    if (asm != null && Remote.AddAssembly(asm))
                    {
                        RaiseModuleNamesChanged();
                    }
                }
            }
            return(AnalysisSet.Empty);
        }
コード例 #26
0
        public static object LoadSkin(string name, Type t)
        {
            if (skinExists(name))
            {
                return(getSkin(name));
            }
            if (!Directory.Exists("TMSS/Data/Skins"))
            {
                Directory.CreateDirectory("TMSS/Data/Skins");
            }
            ObjectHandle objhand = Activator.CreateInstance(null, t.FullName);

            object o = objhand.Unwrap();

            BaseSkin sk       = new BaseSkin();
            string   FileName = name + ".tskn";
            string   path     = @"TMSS/Data/Skins/" + FileName;

            Console.Write(" - //Skin// - Loading Skin " + name + " on path: " + path + "...");
            if (!File.Exists(path))
            {
                Console.WriteLine("ERROR: Skin Not Found "); return(null);
            }

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreWhitespace = true;
            XmlReader read = XmlReader.Create(path, settings);

            read.ReadStartElement("TMSkin");
            read.ReadStartElement("FieldCount");
            int count = read.ReadContentAsInt();

            read.ReadEndElement();
            int       i   = 0;
            FieldInfo inf = null;;
            Type      t2  = null;

            while (i < count)
            {
                try
                {
                    string blah = read.LocalName;
                    //string blah = (string)read.ReadElementContentAs( typeof(string), null );
                    inf = t.GetField(blah);
                    t2  = inf.FieldType;                   //inf.GetType();
                    inf.SetValue(o, read.ReadElementContentAs(t2, null));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Invalid operation while setting up Base Skin. " + e + " inf: " + inf + " t2: " + t2 + " o: " + o);
                }
                i++;
            }
            try
            {
                ((BaseSkin)o).BaseDeserialize(read);
                //sk.BaseDeserialize(read);
                read.Close();
                skList.Add(((BaseSkin)o).SkinName, (BaseSkin)o);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to deserialize a base skin of type: " + t + ". Please examine format. " + ex);
            }
            Console.WriteLine("done");
            return(o);
        }
コード例 #27
0
 public void AddObservedObject(IntPtr managedRealmHandle, ObjectHandle objectHandle, IntPtr managedRealmObjectHandle)
 {
     NativeException nativeException;
     NativeMethods.add_observed_object(this, managedRealmHandle, objectHandle, managedRealmObjectHandle, out nativeException);
     nativeException.ThrowIfNecessary();
 }
コード例 #28
0
        public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName)
        {
            ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName);

            return(oh?.Unwrap());
        }
コード例 #29
0
        static void Main(string[] args)
        {
            string  format      = "";
            string  gadget      = "";
            string  formatter   = "";
            string  cmd         = "";
            string  plugin_name = "";
            Boolean test        = false;
            Boolean show_help   = false;

            OptionSet options = new OptionSet()
            {
                { "p|plugin=", "the plugin to be used", v => plugin_name = v },
                { "o|output=", "the output format (raw|base64).", v => format = v },
                { "g|gadget=", "the gadget chain.", v => gadget = v },
                { "f|formatter=", "the formatter.", v => formatter = v },
                { "c|command=", "the command to be executed.", v => cmd = v },
                { "t|test", "whether to run payload locally. Default: false", v => test = v != null },
                { "h|help", "show this message and exit", v => show_help = v != null },
            };

            try
            {
                var notMatchedArguments = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("ysoserial: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try 'ysoserial --help' for more information.");
                System.Environment.Exit(-1);
            }

            if (
                (cmd == "" || formatter == "" || gadget == "" || format == "") &&
                plugin_name == ""
                )
            {
                Console.WriteLine("Missing arguments.");
                show_help = true;
            }

            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes());

            // Populate list of available gadgets
            var generatorTypes = types.Where(p => typeof(Generator).IsAssignableFrom(p) && !p.IsInterface);
            var generators     = generatorTypes.Select(x => x.Name.Replace("Generator", "")).ToList();

            // Populate list of available plugins
            var pluginTypes = types.Where(p => typeof(Plugin).IsAssignableFrom(p) && !p.IsInterface);
            var plugins     = pluginTypes.Select(x => x.Name.Replace("Plugin", "")).ToList();

            // Show help if requested
            if (show_help)
            {
                Console.WriteLine("ysoserial.net generates deserialization payloads for a variety of .NET formatters.");
                Console.WriteLine("");
                if (plugin_name == "")
                {
                    Console.WriteLine("Available formatters:");
                    foreach (string g in generators)
                    {
                        try
                        {
                            if (g != "Generic")
                            {
                                ObjectHandle container = Activator.CreateInstance(null, "ysoserial.Generators." + g + "Generator");
                                Generator    gg        = (Generator)container.Unwrap();
                                Console.WriteLine("\t" + gg.Name() + " (" + gg.Description() + ")");
                                Console.WriteLine("\t\tFormatters:");
                                foreach (string f in gg.SupportedFormatters().ToArray())
                                {
                                    Console.WriteLine("\t\t\t" + f);
                                }
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Gadget not supported");
                            System.Environment.Exit(-1);
                        }
                    }
                    Console.WriteLine("");
                    Console.WriteLine("Available plugins:");
                    foreach (string p in plugins)
                    {
                        try
                        {
                            if (p != "Generic")
                            {
                                ObjectHandle container = Activator.CreateInstance(null, "ysoserial.Plugins." + p + "Plugin");
                                Plugin       pp        = (Plugin)container.Unwrap();
                                Console.WriteLine("\t" + pp.Name() + " (" + pp.Description() + ")");
                                //Console.WriteLine("\t\tOptions:");
                                //pp.Options().WriteOptionDescriptions(Console.Out);
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Plugin not supported");
                            System.Environment.Exit(-1);
                        }
                    }
                    Console.WriteLine("");
                    Console.WriteLine("Usage: ysoserial.exe [options]");
                    Console.WriteLine("Options:");
                    options.WriteOptionDescriptions(Console.Out);
                    System.Environment.Exit(0);
                }
                else
                {
                    try
                    {
                        ObjectHandle container = Activator.CreateInstance(null, "ysoserial.Plugins." + plugin_name + "Plugin");
                        Plugin       pp        = (Plugin)container.Unwrap();
                        Console.WriteLine("Plugin:\n");
                        Console.WriteLine(pp.Name() + " (" + pp.Description() + ")");
                        Console.WriteLine("\nOptions:\n");
                        pp.Options().WriteOptionDescriptions(Console.Out);
                    } catch
                    {
                        Console.WriteLine("Plugin not supported");
                    }
                    System.Environment.Exit(-1);
                }
            }

            object raw = null;

            // Try to execute plugin first
            if (plugin_name != "")
            {
                if (!plugins.Contains(plugin_name))
                {
                    Console.WriteLine("Plugin not supported.");
                    System.Environment.Exit(-1);
                }

                // Instantiate Plugin
                Plugin plugin = null;
                try
                {
                    var container = Activator.CreateInstance(null, "ysoserial.Plugins." + plugin_name + "Plugin");
                    plugin = (Plugin)container.Unwrap();
                }
                catch
                {
                    Console.WriteLine("Plugin not supported!");
                    System.Environment.Exit(-1);
                }

                raw = plugin.Run(args);
            }
            // othersiwe run payload generation
            else if (cmd != "" && formatter != "" && gadget != "" && format != "")
            {
                if (!generators.Contains(gadget))
                {
                    Console.WriteLine("Gadget not supported.");
                    System.Environment.Exit(-1);
                }

                // Instantiate Payload Generator
                Generator generator = null;
                try
                {
                    var container = Activator.CreateInstance(null, "ysoserial.Generators." + gadget + "Generator");
                    generator = (Generator)container.Unwrap();
                }
                catch
                {
                    Console.WriteLine("Gadget not supported!");
                    System.Environment.Exit(-1);
                }

                // Check Generator supports specified formatter
                if (generator.IsSupported(formatter))
                {
                    raw = generator.Generate(cmd, formatter, test);
                }
                else
                {
                    Console.WriteLine("Formatter not supported. Supported formatters are: " + string.Join(", ", generator.SupportedFormatters()));
                    System.Environment.Exit(-1);
                }

                // LosFormatter is already base64 encoded
                if (format.ToLower().Equals("base64") && formatter.ToLower().Equals("losformatter"))
                {
                    format = "raw";
                }
            }

            // If requested, base64 encode the output
            if (format.ToLower().Equals("base64"))
            {
                if (raw.GetType() == typeof(String))
                {
                    raw = Encoding.ASCII.GetBytes((String)raw);
                }
                string b64encoded = Convert.ToBase64String((byte[])raw);
                Console.WriteLine(b64encoded);
            }
            else
            {
                MemoryStream data = new MemoryStream();
                if (raw.GetType() == typeof(String))
                {
                    data = new MemoryStream(Encoding.UTF8.GetBytes((String)raw ?? ""));
                }
                else if (raw.GetType() == typeof(byte[]))
                {
                    data = new MemoryStream((byte[])raw);
                }
                else
                {
                    Console.WriteLine("Unsupported serialized format");
                    System.Environment.Exit(-1);
                }

                using (Stream console = Console.OpenStandardOutput())
                {
                    byte[] buffer = new byte[4 * 1024];
                    int    n      = 1;
                    while (n > 0)
                    {
                        n = data.Read(buffer, 0, buffer.Length);
                        console.Write(buffer, 0, n);
                    }
                    console.Flush();
                }
            }
        }
コード例 #30
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public void Move(ObjectHandle objectHandle, IntPtr targetIndex)
 {
     NativeException nativeException;
     NativeMethods.move(this, objectHandle, targetIndex, out nativeException);
     nativeException.ThrowIfNecessary();
 }
コード例 #31
0
        public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object[] activationAttributes)
        {
            ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName, activationAttributes);

            return(oh?.Unwrap());
        }
コード例 #32
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public static extern void insert(ListHandle listHandle, IntPtr targetIndex, ObjectHandle objectHandle, out NativeException ex);
コード例 #33
0
        private async Task <bool> Calcular_categoria_menor(List <Categoria> categoriasz, List <Periodo> periodos)
        {
            bool resp = false;

            //controladores
            IndicadorsController         controlIndicadores        = new IndicadorsController(db, userManager);
            EjecucionsController         controlEjecucion          = new EjecucionsController(db, userManager);
            PeriodosController           controlPeriodos           = new PeriodosController(db, userManager);
            EjecucionCategoriaController controlEjecucionCategoria = new EjecucionCategoriaController(db, userManager);

            // variables
            List <Indicador>          indicadores           = new List <Indicador>();
            List <Ejecucion>          ejecuciones           = new List <Ejecucion>();
            List <EjecucionCalculada> ejecucionesCalculadas = new List <EjecucionCalculada>();

            //List<Periodo> periodos = controlPeriodos.getAll();

            foreach (Categoria categoriax in categoriasz)
            {
                indicadores = await controlIndicadores.getFromCategoria(categoriax.id);

                List <EjecucionCalculada> listadoEjecuciones = new List <EjecucionCalculada>();
                List <EjecucionCategoria> respuestas         = new List <EjecucionCategoria>();

                foreach (Indicador indicador in indicadores)
                {
                    //-------------- generacion de un objeto genérico para manejar los diferentes tipos de indicadores
                    ObjectHandle       manejador        = Activator.CreateInstance(null, "seguimiento.Formulas." + indicador.TipoIndicador.file); //se crea un manejador  op -objeto generico- y un operador generico que permite llamar a las formulas con la cadena del tipo de indiciador: mantenimiento, incremento etc
                    Object             op               = manejador.Unwrap();
                    Type               t                = op.GetType();
                    MethodInfo         operadorPeriodo  = t.GetMethod("Calculo_periodo");  //operador es un metodo generico que refleja la funcionalidad de Calculo periodo
                    MethodInfo         operadorSubtotal = t.GetMethod("Calculo_subtotal"); //operador es un metodo generico que refleja la funcionalidad de Calculo subtotal
                    MethodInfo         operadorTotal    = t.GetMethod("Calculo_total");    //operador es un metodo generico que refleja la funcionalidad de Calculo total
                    decimal            lineaBase        = 0;
                    EjecucionCalculada respuesta        = new EjecucionCalculada();

                    List <object> listadoParaSubtotal = new List <object>();
                    List <object> listadoParaTotal    = new List <object>();
                    string        msg = "";


                    ejecuciones = await controlEjecucion.getFromIndicador(indicador.id);

                    foreach (Ejecucion registro in ejecuciones)
                    {
                        switch (registro.Periodo.tipo)
                        {
                        case "periodo":
                            object[] args = { registro, lineaBase };                          //carga los argumentos en un objeto
                            respuesta = (EjecucionCalculada)operadorPeriodo.Invoke(op, args); //envia los argumentos mediante invoke al metodo Calculo_periodo
                            listadoEjecuciones.Add(respuesta);                                //almacena cada ejecucionCalcuada en la lista pero antes ajusta el formato con la clase unidadess de medida
                            listadoParaSubtotal.Add(respuesta);                               //almacena ejecucón para el calculo del subtotal
                            break;

                        case "subtotal":
                            Object[] argsSubtotal = { registro, listadoParaSubtotal, lineaBase };      //carga los argumentos en un objeto
                            respuesta = (EjecucionCalculada)operadorSubtotal.Invoke(op, argsSubtotal); //envia los argumentos mediante invoke al metodo Calculo_subtotal
                            listadoEjecuciones.Add(respuesta);                                         //almacena cada ejecucionCalcuada en la lista pero antes ajusta el formato con la clase unidadess de medida
                            listadoParaTotal.Add(respuesta);                                           //almacena ejecucón para el calculo del subtotal
                            listadoParaSubtotal.Clear();
                            break;

                        case "Total":
                            object[] argstotal = { registro, listadoParaTotal, lineaBase };      //carga los argumentos en un objeto
                            respuesta = (EjecucionCalculada)operadorTotal.Invoke(op, argstotal); //envia los argumentos mediante invoke al metodo Calculo_total
                            listadoEjecuciones.Add(respuesta);                                   //almacena cada ejecucionCalcuada en la lista pero antes ajusta el formato con la clase unidadess de medida
                            listadoParaTotal.Clear();
                            break;

                        case "lineabase":
                            var lb = registro.ejecutado;
                            if (lb != null)
                            {
                                lb = lb.Replace(" ", "");
                                lb = lb.Replace("%", "");
                                lb = Regex.Replace(lb, "^-$", "");
                                lb = Regex.Replace(lb, "^_$", "");
                                lb = Regex.Replace(lb, "[a-zA-Z^&()<>//:@#$%;+_!¡]", "");
                                lb = Regex.Replace(lb, "^\\.$", "");
                                lb = Regex.Replace(lb, "^\\.\\.$", "");
                                lb = Regex.Replace(lb, "\\.", "");
                            }

                            try { lineaBase = lb == "" ? 0 : System.Convert.ToDecimal(lb); }
                            catch (System.OverflowException) { msg = "el valor ejecutado genera desbordamiento"; }

                            break;

                        default:

                            break;
                        }
                    }
                }

                foreach (Periodo periodo in periodos)
                {
                    decimal total = 0, calculado = 0;
                    bool    mostrar = false;

                    var ejecucionesperiodo =
                        (from ejecucionx in listadoEjecuciones
                         where ejecucionx.Periodo.id == periodo.id
                         select ejecucionx);

                    foreach (EjecucionCalculada calcuada in ejecucionesperiodo)
                    {
                        if ((calcuada.EjecutadoError == null && calcuada.PlaneadoError == null && calcuada.cargado == true) || calcuada.Periodo.tipo != "periodo")
                        {
                            total     = total + calcuada.Indicador.ponderador;
                            calculado = calculado + (calcuada.Calculado / 100) * calcuada.Indicador.ponderador;
                        }
                    }
                    if (total > 0)
                    {
                        calculado = (calculado / total) * 100;
                        mostrar   = true;
                    }
                    else
                    {
                        calculado = 0;
                    }

                    EjecucionCategoria resultado = new EjecucionCategoria();
                    //resultado.Id = 1;
                    resultado.Calculado = calculado;
                    //resultado.Categoria = categoriax;
                    resultado.IdCategoria = categoriax.id;
                    resultado.idperiodo   = periodo.id;
                    resultado.Maximo      = total;
                    resultado.Mostrar     = mostrar;

                    var r = await controlEjecucionCategoria.Crear(resultado);
                }
            }
            return(resp);
        }
コード例 #34
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public static extern IntPtr move(ListHandle listHandle, ObjectHandle objectHandle, IntPtr targetIndex, out NativeException ex);
コード例 #35
0
        /// <summary>
        /// Creates an empty default implementation of <see cref="IDataWithAnnotationColumns"/>.
        /// </summary>
        public static IDataWithAnnotationColumns CreateDataWithAnnotationColumns()
        {
            ObjectHandle o = Activator.CreateInstance("PerseusLibS", "PerseusLibS.Data.DataWithAnnotationColumns");

            return((IDataWithAnnotationColumns)o.Unwrap());
        }
コード例 #36
0
 public MarshallerProxy(AppDomain targetDomain, ObjectHandle objHandle) : this(CreateAdapter(targetDomain, objHandle))
 {
 }
コード例 #37
0
 internal PrivateKey(ObjectHandle objectHandle, List <ObjectAttribute> objectAttributes, ulong?storageSize)
 {
     ObjectHandle     = objectHandle;
     ObjectAttributes = objectAttributes;
     StorageSize      = storageSize;
 }
コード例 #38
0
 public StaticAdapter(ObjectHandle objHandle) : this(objHandle.Unwrap())
 {
 }
コード例 #39
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public static extern void add(ListHandle listHandle, ObjectHandle objectHandle, out NativeException ex);
コード例 #40
0
 /// <summary>
 /// Gets the available members on the provided remote object.
 /// </summary>
 public ICollection <MemberDoc> GetMembers(ObjectHandle value)
 {
     return(_provider.GetMembers(value.Unwrap()));
 }
コード例 #41
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public static extern IntPtr find(ListHandle listHandle, ObjectHandle objectHandle, out NativeException ex);
コード例 #42
0
 /// <summary>
 /// Gets the overloads available for the provided remote object if it is invokable.
 /// </summary>
 public ICollection <OverloadDoc> GetOverloads(ObjectHandle value)
 {
     return(_provider.GetOverloads(value.Unwrap()));
 }
コード例 #43
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public void Add(ObjectHandle objectHandle)
 {
     NativeException nativeException;
     NativeMethods.add(this, objectHandle, out nativeException);
     nativeException.ThrowIfNecessary();
 }
コード例 #44
0
        /// <summary>
        /// Initializes a new instance of the CkX942Dh2DeriveParams class.
        /// </summary>
        /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
        /// <param name='otherInfo'>Some data shared between the two parties</param>
        /// <param name='publicData'>Other party's first X9.42 Diffie-Hellman public key value</param>
        /// <param name='privateDataLen'>The length in bytes of the second X9.42 Diffie-Hellman private key</param>
        /// <param name='privateData'>Key handle for second X9.42 Diffie-Hellman private key value</param>
        /// <param name='publicData2'>Other party's second X9.42 Diffie-Hellman public key value</param>
        public CkX942Dh2DeriveParams(ulong kdf, byte[] otherInfo, byte[] publicData, ulong privateDataLen, ObjectHandle privateData, byte[] publicData2)
        {
            _lowLevelStruct.Kdf            = 0;
            _lowLevelStruct.OtherInfoLen   = 0;
            _lowLevelStruct.OtherInfo      = IntPtr.Zero;
            _lowLevelStruct.PublicDataLen  = 0;
            _lowLevelStruct.PublicData     = IntPtr.Zero;
            _lowLevelStruct.PrivateDataLen = 0;
            _lowLevelStruct.PrivateData    = 0;
            _lowLevelStruct.PublicDataLen2 = 0;
            _lowLevelStruct.PublicData2    = IntPtr.Zero;

            _lowLevelStruct.Kdf = kdf;

            if (otherInfo != null)
            {
                _lowLevelStruct.OtherInfo = UnmanagedMemory.Allocate(otherInfo.Length);
                UnmanagedMemory.Write(_lowLevelStruct.OtherInfo, otherInfo);
                _lowLevelStruct.OtherInfoLen = Convert.ToUInt64(otherInfo.Length);
            }

            if (publicData != null)
            {
                _lowLevelStruct.PublicData = UnmanagedMemory.Allocate(publicData.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData, publicData);
                _lowLevelStruct.PublicDataLen = Convert.ToUInt64(publicData.Length);
            }

            _lowLevelStruct.PrivateDataLen = privateDataLen;

            if (privateData == null)
            {
                throw new ArgumentNullException("privateData");
            }

            _lowLevelStruct.PrivateData = privateData.ObjectId;

            if (publicData2 != null)
            {
                _lowLevelStruct.PublicData2 = UnmanagedMemory.Allocate(publicData2.Length);
                UnmanagedMemory.Write(_lowLevelStruct.PublicData2, publicData2);
                _lowLevelStruct.PublicDataLen2 = Convert.ToUInt64(publicData2.Length);
            }
        }
コード例 #45
0
ファイル: ListHandle.cs プロジェクト: realm/realm-dotnet
 public IntPtr Find(ObjectHandle objectHandle)
 {
     NativeException nativeException;
     var result = NativeMethods.find(this, objectHandle, out nativeException);
     nativeException.ThrowIfNecessary();
     return result;
 }
コード例 #46
0
ファイル: Entity.GroundVehicle.cs プロジェクト: GULPF/SAAB-CM
        public static bool IsTypeOf(INETWISEDriverSink2 WISE, DatabaseHandle hDatabase, ObjectHandle hObject)
        {
            uint result = WISEError.WISE_ERROR;
            AttributeHandle hAttr = WISEConstants.WISE_INVALID_HANDLE;
            string strEntityType = string.Empty;

            if ((WISE == null) || (hObject == WISEConstants.WISE_INVALID_HANDLE))
            {
                return false;
            }

            result = WISE.GetAttributeHandle(hDatabase, hObject, WISEConstants.WISE_TEMPLATE_OBJECT_TYPE, ref hAttr);
            if (WISEError.CheckCallFailed(result))
            {
                return false;
            }

            result = WISE.GetAttributeValue(hDatabase, hObject, hAttr, ref strEntityType);

            return WISEError.CheckCallSucceeded(result) && IsTypeOf(strEntityType);
        }
コード例 #47
0
 internal bool AddAssembly(ObjectHandle asm)
 {
     return(_remoteInterpreter.AddAssembly(asm));
 }
コード例 #48
0
ファイル: CBRNSensorsDriver.cs プロジェクト: GULPF/SAAB-CM
        protected override WISE_RESULT OnAddObject(DateTime timeStamp, DatabaseHandle hDatabase, ObjectHandle hObject,
                ClassHandle hClass, string strObjectName, TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnAddObject(timeStamp, hDatabase, hObject, hClass, strObjectName, hTransaction);
            WISEError.CheckCallFailedEx(result);

            try
            {
                DatabaseType dbtype = DatabaseType.Unknown;
                result = this.Sink.GetDatabaseType(hDatabase, ref dbtype);
                WISEError.CheckCallFailedEx(result);

                if (dbtype == DatabaseType.Application)
                {
                    // Only process application database objects by default

                    //if (global::CBRNSensors.EntityEquipment.IsTypeOf(this.WISE, hDatabase, hObject))
                    //{
                    //    global::CBRNSensors.EntityEquipment myObject = new global::CBRNSensors.EntityEquipment();
                    //}

                    //
                    // TODO: Add object on driver communication interface.
                    //
                    // This method typically works in either of two ways.
                    // If the underlying protocol requires us to send all object attributes
                    // as a part of the object creation message;
                    //   1. Identify the type of object.
                    //   2. Based on the object type, extract its attributes.
                    //   3. Fill object attribute values into the protocol container associated with object creation.
                    //   4. the creation message on the underlying protocol.
                    //
                    // If the underlying protocol separates the create message from the initial attribute
                    // update message;
                    //   1. Fill object information into the protocol container associated with object creation.
                    //   2. Send the creation message on the underlying protocol.
                    //

                    #region Sample code: Check object type
                    //ClassHandle hTestObjectClass = ClassHandle.Invalid;

                    //// Get handle corresponding to class "TEST_OBJECT" (this can be done once and then cached)
                    //result = this.WISETypeInfo.GetWISEClassHandle(hDatabase, "TEST_OBJECT", ref hTestObjectClass);
                    //WISEError.CheckCallFailedEx(result);

                    //if (hClass == hTestObjectClass)
                    //{
                    //    #region Sample code: Access TEST_OBJECT attributes
                    //    string stringAttributeValue = "";
                    //    AttributeHandle hAttr = AttributeHandle.Invalid;

                    //    result = this.Sink.GetAttributeHandle(hDatabase, hObject, "TEST_STRING", ref hAttr);
                    //    WISEError.CheckCallFailedEx(result);

                    //    result = this.Sink.GetAttributeValue(hDatabase, hObject, hAttr, ref stringAttributeValue);
                    //    WISEError.CheckCallFailedEx(result);
                    //    #endregion
                    //}
                    #endregion
                }
            }
            catch (WISEException ex)
            {
                result = ex.Error.ErrorCode;
            }
            return result;
        }
コード例 #49
0
 public EntityEquipmentSensor(INETWISEDriverSink sink, DatabaseHandle databaseHandle, ObjectHandle objectHandle)
 {
     this.WISESink = sink;
     this.Database = databaseHandle;
     this.Handle = objectHandle;
 }
コード例 #50
0
ファイル: EntityGroundVehicle.cs プロジェクト: GULPF/SAAB-CM
 public EntityGroundVehicle(INETWISEDriverSink sink, DatabaseHandle databaseHandle, ObjectHandle objectHandle)
 {
     this.WISESink = sink;
     this.Database = databaseHandle;
     this.Handle = objectHandle;
 }
コード例 #51
0
 public static extern void add_observed_object(SharedRealmHandle sharedRealm, IntPtr managedRealmHandle, ObjectHandle objectHandle, IntPtr managedRealmObjectHandle, out NativeException ex);
コード例 #52
0
ファイル: ScriptScope.cs プロジェクト: todor-dk/IronSmalltalk
 /// <summary>
 /// Sets the name to the specified value.
 /// </summary>
 /// <exception cref="SerializationException">
 /// The value held by the handle isn't from the scope's app-domain and isn't serializable or MarshalByRefObject.
 /// </exception>
 /// <exception cref="ArgumentNullException"><paramref name="name"/> or <paramref name="handle"/> is a <c>null</c> reference.</exception>
 public void SetVariable(string name, ObjectHandle handle)
 {
     ContractUtils.RequiresNotNull(handle, "handle");
     SetVariable(name, handle.Unwrap());
 }
コード例 #53
0
        public RepositoryBase()
        {
            ObjectHandle handle = System.Activator.CreateInstance(Connect.settingsObject.DbContextAssembly, Connect.settingsObject.DbContextClass);

            _oDbContext = handle.Unwrap();
        }
コード例 #54
0
        /// <summary>
        /// Initializes a new instance of the CkEcmqvDeriveParams class.
        /// </summary>>
        /// <param name='kdf'>Key derivation function used on the shared secret value (CKD)</param>
        /// <param name='sharedData'>Some data shared between the two parties</param>
        /// <param name='publicData'>Other party's first EC public key value</param>
        /// <param name='privateDataLen'>The length in bytes of the second EC private key</param>
        /// <param name='privateData'>Key handle for second EC private key value</param>
        /// <param name='publicData2'>Other party's second EC public key value</param>
        /// <param name='publicKey'>Handle to the first party's ephemeral public key</param>
        public CkEcmqvDeriveParams(uint kdf, byte[] sharedData, byte[] publicData, uint privateDataLen, ObjectHandle privateData, byte[] publicData2, ObjectHandle publicKey)
        {
            _lowLevelStruct.Kdf            = 0;
            _lowLevelStruct.SharedDataLen  = 0;
            _lowLevelStruct.SharedData     = IntPtr.Zero;
            _lowLevelStruct.PublicDataLen  = 0;
            _lowLevelStruct.PublicData     = IntPtr.Zero;
            _lowLevelStruct.PrivateDataLen = 0;
            _lowLevelStruct.PrivateData    = 0;
            _lowLevelStruct.PublicDataLen2 = 0;
            _lowLevelStruct.PublicData2    = IntPtr.Zero;
            _lowLevelStruct.PublicKey      = 0;

            _lowLevelStruct.Kdf = kdf;

            if (sharedData != null)
            {
                _lowLevelStruct.SharedData = LowLevelAPI.UnmanagedMemory.Allocate(sharedData.Length);
                LowLevelAPI.UnmanagedMemory.Write(_lowLevelStruct.SharedData, sharedData);
                _lowLevelStruct.SharedDataLen = (uint)sharedData.Length;
            }

            if (publicData != null)
            {
                _lowLevelStruct.PublicData = LowLevelAPI.UnmanagedMemory.Allocate(publicData.Length);
                LowLevelAPI.UnmanagedMemory.Write(_lowLevelStruct.PublicData, publicData);
                _lowLevelStruct.PublicDataLen = (uint)publicData.Length;
            }

            _lowLevelStruct.PrivateDataLen = privateDataLen;

            if (privateData == null)
            {
                throw new ArgumentNullException("privateData");
            }

            _lowLevelStruct.PrivateData = privateData.ObjectId;

            if (publicData2 != null)
            {
                _lowLevelStruct.PublicData2 = LowLevelAPI.UnmanagedMemory.Allocate(publicData2.Length);
                LowLevelAPI.UnmanagedMemory.Write(_lowLevelStruct.PublicData2, publicData2);
                _lowLevelStruct.PublicDataLen2 = (uint)publicData2.Length;
            }

            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            _lowLevelStruct.PublicKey = publicKey.ObjectId;
        }
コード例 #55
0
ファイル: CBRNSensorsDriver.cs プロジェクト: GULPF/SAAB-CM
        protected override WISE_RESULT OnRemoveObject(DateTime timeStamp, DatabaseHandle hDatabase, ObjectHandle hObject,
            ClassHandle hClass, TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnRemoveObject(timeStamp, hDatabase, hObject, hClass, hTransaction);
            WISEError.CheckCallFailedEx(result);

            try
            {
                DatabaseType dbtype = DatabaseType.Unknown;
                result = this.Sink.GetDatabaseType(hDatabase, ref dbtype);

                if (dbtype == DatabaseType.Application)
                {
                    //
                    // TODO: Remove object on driver communication interface.
                    //
                }
            }
            catch (WISEException ex)
            {
                result = ex.Error.ErrorCode;
            }
            return result;
        }
コード例 #56
0
ファイル: ActivatorTests.cs プロジェクト: programatt/runtime
        public static void TestingCreateInstanceObjectHandleFullSignatureWinRT(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType)
        {
            ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes);

            CheckValidity(oh, returnedFullNameType);
        }
コード例 #57
0
ファイル: CBRNSensorsDriver.cs プロジェクト: GULPF/SAAB-CM
        protected override WISE_RESULT OnUpdateAttribute(DateTime timeStamp, DatabaseHandle hDatabase, ObjectHandle hObject,
            ClassHandle hClass, AttributeHandle hAttribute, object value, AttributeQualityCode quality,
            TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnUpdateAttribute(timeStamp, hDatabase, hObject, hClass, hAttribute, value, quality, hTransaction);
            WISEError.CheckCallFailedEx(result);

            //string myValue = string.Empty;
            //AttributeHandle myAttributeHandle = AttributeHandle.Invalid;
            //this.WISE.GetAttributeHandle(hDatabase, hObject, "SomeAttribute", ref myAttributeHandle);
            //this.WISE.GetAttributeValue(hDatabase, hObject, myAttributeHandle, ref myValue);

            //global::CBRNSensors.EntityEquipmentSensorCBRNLCD stateObject = new global::CBRNSensors.EntityEquipmentSensorCBRNLCD();
            //stateObject.CreateInstance(this.WISE, hDatabase);
            //stateObject.SensorState =
            //stateObject.AddToDatabase(hDatabase);

            return result;
        }
コード例 #58
0
ファイル: ActivatorTests.cs プロジェクト: programatt/runtime
 private static void CheckValidity(ObjectHandle instance, string expected)
 {
     Assert.NotNull(instance);
     Assert.Equal(expected, instance.Unwrap().GetType().FullName);
 }
コード例 #59
0
ファイル: EntityGroundVehicle.cs プロジェクト: GULPF/SAAB-CM
        public static bool IsTypeOf(INETWISEDriverSink sink, DatabaseHandle hDatabase, ObjectHandle hObject)
        {
            WISE_RESULT wResult = WISEError.WISE_OK;
            AttributeHandle hAttr = WISEConstants.WISE_INVALID_HANDLE;
            string strEntityType = string.Empty;

            if ((sink == null) || (hObject == WISEConstants.WISE_INVALID_HANDLE))
            {
                return false;
            }

            // Initialize handle cache
            Initialize(sink as INETWISEStringCache);

            wResult = sink.GetAttributeHandle(hDatabase, hObject, WISEConstants.WISE_TEMPLATE_OBJECT_TYPE, ref hAttr,
                                                   DataType.String);
            bool bResult = WISEError.CheckCallFailed(wResult);

            wResult = sink.GetAttributeValue(hDatabase, hObject, hAttr, ref strEntityType);
            bResult = WISEError.CheckCallSucceeded(wResult);

            return bResult && IsTypeOf(strEntityType);
        }
コード例 #60
0
        public void _02_EncryptAndDecryptMultiPartTest()
        {
            if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
            {
                Assert.Inconclusive("Test cannot be executed on this platform");
            }

            using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
            {
                // Find first slot with token present
                Slot slot = Helpers.GetUsableSlot(pkcs11);

                // Open RW session
                using (Session session = slot.OpenSession(SessionType.ReadWrite))
                {
                    // Login as normal user
                    session.Login(CKU.CKU_USER, Settings.NormalUserPin);

                    // Generate symetric key
                    ObjectHandle generatedKey = Helpers.GenerateKey(session);

                    // Generate random initialization vector
                    byte[] iv = session.GenerateRandom(8);

                    // Specify encryption mechanism with initialization vector as parameter
                    Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);

                    byte[] sourceData    = ConvertUtils.Utf8StringToBytes("Our new password");
                    byte[] encryptedData = null;
                    byte[] decryptedData = null;

                    // Multipart encryption can be used i.e. for encryption of streamed data
                    using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
                    {
                        // Encrypt data
                        // Note that in real world application we would rather use bigger read buffer i.e. 4096
                        session.Encrypt(mechanism, generatedKey, inputStream, outputStream, 8);

                        // Read whole output stream to the byte array so we can compare results more easily
                        encryptedData = outputStream.ToArray();
                    }

                    // Do something interesting with encrypted data

                    // Multipart decryption can be used i.e. for decryption of streamed data
                    using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
                    {
                        // Decrypt data
                        // Note that in real world application we would rather use bigger read buffer i.e. 4096
                        session.Decrypt(mechanism, generatedKey, inputStream, outputStream, 8);

                        // Read whole output stream to the byte array so we can compare results more easily
                        decryptedData = outputStream.ToArray();
                    }

                    // Do something interesting with decrypted data
                    Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));

                    session.DestroyObject(generatedKey);
                    session.Logout();
                }
            }
        }