示例#1
0
 // Return a dynamicly allocated KeyInfo structure that can be used with OP_OpenRead or OP_OpenWrite to access database index pIdx.
 //
 // If successful, a pointer to the new structure is returned. In this case the caller is responsible for calling sqlite3DbFree(db, ) on the returned
 // pointer. If an error occurs (out of memory or missing collation sequence), NULL is returned and the state of pParse updated to reflect
 // the error.
 internal static KeyInfo sqlite3IndexKeyinfo(Parse pParse, Index pIdx)
 {
     var nCol = pIdx.nColumn;
     var db = pParse.db;
     var pKey = new KeyInfo();
     if (pKey != null)
     {
         pKey.db = pParse.db;
         pKey.aSortOrder = new byte[nCol];
         pKey.aColl = new CollSeq[nCol];
         for (var i = 0; i < nCol; i++)
         {
             var zColl = pIdx.azColl[i];
             Debug.Assert(zColl != null);
             pKey.aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
             pKey.aSortOrder[i] = pIdx.aSortOrder[i];
         }
         pKey.nField = (ushort)nCol;
     }
     if (pParse.nErr != 0)
     {
         pKey = null;
         sqlite3DbFree(db, ref pKey);
     }
     return pKey;
 }
示例#2
0
		static KeyInfo ValuePair(Enum token, object value)
		{
			KeyInfo k=new KeyInfo();
			k.ki_key=(int)(object)token;
			k.ki_name=token.ToString();
			return k;
		}
        private static ProofKeysHelper GetHelper()
        {
            KeyInfo current = new KeyInfo(key, modulus, exponent);
            KeyInfo old = new KeyInfo(oldKey, oldModulus, oldExponent);

            return new ProofKeysHelper(current, old);
        }
示例#4
0
 internal KeyValue(KeyInfo key, byte[] keyBuffer)
 {
     if (key == null || keyBuffer == null) {
         throw new ArgumentNullException();
     }
     if (key.Length < keyBuffer.Length) {
         throw new ArgumentException();
     }
     this.Key = key;
     this.KeyBuffer = keyBuffer;
     this.ComplementCount = 0;
 }
示例#5
0
 public TmKeyRec(int _buffSize, BUFF_TYPE _buffType)
 {
     mBuffSize = _buffSize;
     mInfo = new KeyInfo();
     mRecInfo = new KeyInfo[mBuffSize];
     mBuffPtr = -1;
     mRecSize = mRecCtr = mPlayCtr = 0;
     mState = STATE.STOP;
     mBuffType = _buffType;
     mPad = new PAD();
     mDebug = new KeyInfoDebug();
 }
示例#6
0
 public KeyValue(KeyInfo key, object[] segmentValues, bool isMinimumComplement = true)
 {
     if (key == null || segmentValues == null) {
         throw new ArgumentNullException();
     }
     if (segmentValues.Length == 0 || segmentValues.Length > key.Segments.Count()) {
         throw new ArgumentException();
     }
     this.Key = key;
     this.KeyBuffer = new byte[this.Key.Length];
     this.SetValues(segmentValues, 0, isMinimumComplement);
 }
示例#7
0
 public TmKeyRec(TmKeyRec _origin)
 {
     mBuffSize = _origin.mBuffSize;
     mInfo = new KeyInfo(_origin.keyInfo);
     //		mRecInfo = (KeyInfo[])_origin.mRecInfo.Clone();
     mRecInfo = new KeyInfo[_origin.mBuffSize];
     Array.Copy(_origin.mRecInfo,0,mRecInfo,0,_origin.mRecSize);
     mBuffPtr = _origin.mBuffPtr;
     mRecSize = _origin.mRecSize;
     mRecCtr = _origin.mRecCtr;
     mPlayCtr = _origin.mPlayCtr;
     mState = _origin.mState;
     mBuffType = _origin.mBuffType;
     mPad = new PAD(_origin.mPad);
     mDebug = new KeyInfoDebug();
 }
示例#8
0
        public uint[] OverflowIDs; // Cache of overflow page locations

        #endif

        #region Methods

        // was:sqlite3BtreeCursorZero
        public void Zero()
        {
            Next = null;
            Prev = null;
            KeyInfo = null;
            RootID = 0;
            _cachedRowID = 0;
            Info = new MemPage.CellInfo();
            Writeable = false;
            AtLast = false;
            ValidNKey = false;
            State = 0;
            Key = null;
            NKey = 0;
            SkipNext = 0;
            #if !SQLITE_OMIT_INCRBLOB
            IsIncrblob = false;
            OverflowIDs = null;
            #endif
            PageID = 0;
        }
示例#9
0
        public bool isIncrblobHandle; // True if this cursor is an incr. io handle

        #endif

        #region Methods

        public void Clear()
        {
            pNext = null;
            pPrev = null;
            pKeyInfo = null;
            pgnoRoot = 0;
            cachedRowid = 0;
            info = new CellInfo();
            wrFlag = 0;
            atLast = 0;
            validNKey = false;
            eState = 0;
            pKey = null;
            nKey = 0;
            skipNext = 0;
            #if !SQLITE_OMIT_INCRBLOB
            isIncrblobHandle = false;
            aOverflow = null;
            #endif
            iPage = 0;
        }
示例#10
0
        public override bool UIKeyPressed(KeyInfo key)
        {
            if (key == null) throw new ArgumentNullException("key");
            switch (key.VirtualKeyCode)
            {
                case KeyCode.F1:

                    if (key.Is())
                    {
                        Far.Api.ShowHelp(Far.Api.GetType().Assembly.Location, SettingsUI.HelpSettings, HelpOptions.None);
                        return true;
                    }

                    break;

                case KeyCode.Delete:
                case KeyCode.F8:

                    SetDefaults();
                    return true;
            }

            return base.UIKeyPressed(key);
        }
示例#11
0
 // Methods
 internal SvgElement(string prefix, string localname, string ns, SvgDocument doc)
     : base(prefix, localname, ns, doc)
 {
     this.timeLineVisible = true;
     KeyInfo[] infoArray1 = new KeyInfo[1] { new KeyInfo(0, 0) } ;
     this.infoList = new ArrayList(infoArray1);
     this.showParticular = false;
     this.inKey = false;
     this.animatelist = new SvgElementCollection();
     this.svgAttributes = new Hashtable(0x10);
     this.svgAnimAttributes = new Hashtable(0x10);
     this.svgStyleAttributes = new Hashtable(0x10);
     this.beforeChangeValueStr = string.Empty;
     this.showchild = true;
     this.pretime = -1;
     this.AnimateNameValues = new Hashtable(0x10);
     this.AttributePos = new Hashtable();
     this.FormatOutXml = true;
     this.UseElement = null;
     this.CreateParse = true;
     this.ownerDocument = doc;
     this.FormatElement = false;
     this.AllowRename = true;
 }
            public static string Sign(string xml, X509Certificate2 certificate)
            {
                if (xml == null) throw new ArgumentNullException("xml");
                if (certificate == null) throw new ArgumentNullException("certificate");
                if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key");

                XmlDocument doc = new XmlDocument();

                doc.PreserveWhitespace = true;
                doc.LoadXml(xml);

                SignedXml signedXml = new SignedXml(doc);
                signedXml.SigningKey = certificate.PrivateKey;

                // Attach certificate KeyInfo
                KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(keyInfoData);
                signedXml.KeyInfo = keyInfo;

                // Attach transforms
                var reference = new Reference("");
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
                reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
                signedXml.AddReference(reference);

                // Compute signature
                signedXml.ComputeSignature();
                var signatureElement = signedXml.GetXml();

                // Add signature to bundle
                doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));

                return doc.OuterXml;
            }
示例#13
0
		// Inverse Utilities (name=>code)
		static int FindCode(KeyInfo[] info, string key)
		{
			foreach(KeyInfo i in info) if(i.ki_name==key) return i.ki_key;

			// not a registered key; might be generic code
			if(!key.StartsWith("Unknown-")) return -1;

			try
			{
				key=key.Substring(8);
				return int.Parse(key);
			}
			catch
			{
				return -1;
			}
		}
示例#14
0
 public FirkinStream ReadValue(KeyInfo keyInfo)
 {
     return(new FirkinStream(_streamSyncRoot, _stream, (long)keyInfo.ValuePosition, (long)keyInfo.ValueSize));
 }
        public void GT()
        {
            var keyType = new KeyInfo(KeyDataType.IntKey, KeyType.ScalarIndex, "test", true);

            //many in the middle
            var idx1 = populate(1, 2, 3, 3, 3, 4, 5);

            IList <CachedObject> result1 =
                idx1.GetMany(MakeIntValue(3, keyType), QueryOperator.Gt).OrderBy(o => o.PrimaryKey).ToList();

            Assert.AreEqual(result1.Count, 2);
            Assert.AreEqual(result1[0].PrimaryKey, 5);
            Assert.AreEqual(result1[1].PrimaryKey, 6);

            var count = idx1.GetCount(MakeIntValue(3, keyType), QueryOperator.Gt);

            Assert.AreEqual(count, 2);


            //many at the end
            var idx2 = populate(1, 2, 3, 3, 3);

            result1 = idx2.GetMany(MakeIntValue(3, keyType), QueryOperator.Gt).OrderBy(o => o.PrimaryKey).ToList();
            Assert.AreEqual(result1.Count, 0);

            count = idx2.GetCount(MakeIntValue(3, keyType), QueryOperator.Gt);
            Assert.AreEqual(count, 0);

            //many at the beginning
            var idx3 = populate(3, 3, 3, 4, 4, 80);

            result1 = idx3.GetMany(MakeIntValue(3, keyType), QueryOperator.Gt).OrderBy(o => o.PrimaryKey).ToList();
            Assert.AreEqual(result1.Count, 3);
            Assert.AreEqual(result1[0].PrimaryKey, 3);
            Assert.AreEqual(result1[1].PrimaryKey, 4);
            Assert.AreEqual(result1[2].PrimaryKey, 5);
            count = idx3.GetCount(MakeIntValue(3, keyType), QueryOperator.Gt);
            Assert.AreEqual(count, 3);

            //all equal
            var idx4 = populate(3, 3, 3);

            result1 = idx4.GetMany(MakeIntValue(3, keyType), QueryOperator.Gt).OrderBy(o => o.PrimaryKey).ToList();
            Assert.AreEqual(result1.Count, 0);
            count = idx4.GetCount(MakeIntValue(3, keyType), QueryOperator.Gt);
            Assert.AreEqual(count, 0);


            //one in the middle
            var idx5 = populate(1, 3, 5, 7, 9, 111);

            result1 = idx5.GetMany(MakeIntValue(7, keyType), QueryOperator.Gt).OrderBy(o => o.PrimaryKey).ToList();
            Assert.AreEqual(result1.Count, 2);
            Assert.AreEqual(result1[0].PrimaryKey, 4);
            Assert.AreEqual(result1[1].PrimaryKey, 5);

            count = idx5.GetCount(MakeIntValue(7, keyType), QueryOperator.Gt);
            Assert.AreEqual(count, 2);

            //value not found
            result1 = idx5.GetMany(MakeIntValue(8, keyType), QueryOperator.Gt).OrderBy(o => o.PrimaryKey).ToList();
            Assert.AreEqual(result1.Count, 2);
            Assert.AreEqual(result1[0].PrimaryKey, 4);
            Assert.AreEqual(result1[1].PrimaryKey, 5);

            count = idx5.GetCount(MakeIntValue(8, keyType), QueryOperator.Gt);
            Assert.AreEqual(count, 2);
        }
        private static void checkLS(IndexBase indexByValue)
        {
            var keyType = new KeyInfo(KeyDataType.IntKey, KeyType.ScalarIndex, "IndexKeyValue", true);

            //non existent value in the middle
            {
                IList <CachedObject> result1 =
                    indexByValue.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt)
                    .OrderBy(o => o.PrimaryKey)
                    .ToList();
                Assert.AreEqual(result1.Count, 3);
                Assert.AreEqual(result1[0].PrimaryKey.ToString(), "#1");
                Assert.AreEqual(result1[1].PrimaryKey.ToString(), "#2");
                Assert.AreEqual(result1[2].PrimaryKey.ToString(), "#3");

                var count = indexByValue.GetCount(MakeIntValue(12, keyType), QueryOperator.Lt);
                Assert.AreEqual(count, 3);
            }

            //existent value in the middle
            {
                IList <CachedObject> result1 =
                    indexByValue.GetMany(MakeIntValue(13, keyType), QueryOperator.Lt)
                    .OrderBy(o => o.PrimaryKey)
                    .ToList();
                Assert.AreEqual(result1.Count, 3);
                Assert.AreEqual(result1[2].PrimaryKey.ToString(), "#3");

                var count = indexByValue.GetCount(MakeIntValue(12, keyType), QueryOperator.Lt);
                Assert.AreEqual(count, 3);
            }

            //value < all
            {
                IList <CachedObject> result1 =
                    indexByValue.GetMany(MakeIntValue(0, keyType), QueryOperator.Lt).OrderBy(o => o.PrimaryKey)
                    .ToList();
                Assert.AreEqual(result1.Count, 0);

                var count = indexByValue.GetCount(MakeIntValue(0, keyType), QueryOperator.Lt);
                Assert.AreEqual(count, 0);
            }

            //value > all
            {
                IList <CachedObject> result1 =
                    indexByValue.GetMany(MakeIntValue(99, keyType), QueryOperator.Lt)
                    .OrderBy(o => o.PrimaryKey)
                    .ToList();
                Assert.AreEqual(result1.Count, 6);

                var count = indexByValue.GetCount(MakeIntValue(99, keyType), QueryOperator.Lt);
                Assert.AreEqual(count, 6);
            }

            //first value
            {
                IList <CachedObject> result1 =
                    indexByValue.GetMany(MakeIntValue(1, keyType), QueryOperator.Lt).OrderBy(o => o.PrimaryKey)
                    .ToList();
                Assert.AreEqual(result1.Count, 0);

                var count = indexByValue.GetCount(MakeIntValue(1, keyType), QueryOperator.Lt);
                Assert.AreEqual(count, 0);
            }
        }
        public TRetornoAssinatura AssinarNFe(string XMLString, string RefUri, X509Certificate2 _X509Cert)

        /*
         * Entradas:
         * XMLString: string XML a ser assinada
         * RefUri : Referência da URI a ser assinada ( infNFe, Cancelamento e inutilzacao)
         * X509Cert : certificado digital a ser utilizado na assinatura digital
         *
         * Retornos:
         * Assinar : 0 - Assinatura realizada com sucesso
         * 1 - Erro: Problema ao acessar o certificado digital - %exceção%
         * extinto* 2 - Problemas no certificado digital
         * 3 - XML mal formado + exceção
         * 4 - A tag de assinatura %RefUri% inexiste
         * 5 - A tag de assinatura %RefUri% não é unica
         * 6 - Erro Ao assinar o documento - ID deve ser string %RefUri(Atributo)%
         * 7 - Erro: Ao assinar o documento - %exceção%
         *
         * XMLStringAssinado : string XML assinada
         *
         * XMLDocAssinado : XMLDocument do XML assinado
         */
        {
            var resultado = TRetornoAssinatura.Assinada;

            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                // certificado ok
                //_X509Cert = collection1[0];

                // Cria um novo XML.
                XmlDocument doc = new XmlDocument();
                //XmlDocument doc2 = new XmlDocument();
                //doc.PreserveWhitespace = false;
                // carrega o conteudo XML passado
                try
                {
                    doc.LoadXml(XMLString);
                    // Verifica se a tag a ser assinada existe é única
                    int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;
                    if (qtdeRefUri == 0)
                    {
                        // a URI indicada não existe
                        resultado    = TRetornoAssinatura.RefURiNaoExiste;//4;
                        msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
                    }
                    // Exsiste mais de uma tag a ser assinada
                    else
                    {
                        if (qtdeRefUri > 1)
                        {
                            // existe mais de uma URI indicada
                            resultado    = TRetornoAssinatura.RefURiNaoUnica; //5;
                            msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";
                        }
                        //else if (_listaNum.IndexOf(doc.GetElementsByTagName(RefUri).Item(0).Attributes.ToString().Substring(1,1))>0)
                        //{
                        // resultado = 6;
                        // msgResultado = "Erro: Ao assinar o documento - ID deve ser string (" + doc.GetElementsByTagName(RefUri).Item(0).Attributes + ")";
                        //}
                        else
                        {
                            try
                            {
                                // cria um objeto xml assinado
                                SignedXml signedXml = new SignedXml(doc);
                                // adiciona a chave do certificado
                                signedXml.SigningKey = _X509Cert.PrivateKey;
                                // Cria a referencia para assinatura
                                Reference reference = new Reference();
                                // pega o uri que deve ser assinada
                                XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes;
                                foreach (XmlAttribute _atributo in _Uri)
                                {
                                    if (_atributo.Name == "Id")
                                    {
                                        reference.Uri = "#" + _atributo.InnerText;
                                    }
                                }
                                #region calculo assinatura NFe
                                // adiciona um XmlDsigEnvelopedSignatureTransform para a assinatura
                                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                reference.AddTransform(env);
                                XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                reference.AddTransform(c14);
                                // adiciona a referencia no xml assinado
                                signedXml.AddReference(reference);
                                // Cria a chave
                                KeyInfo keyInfo = new KeyInfo();
                                // carrega o certificado em um keyinfox509
                                // e adiciona ao keyinfo
                                keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));
                                // adiciona o keyinfo ao xml assinado
                                signedXml.KeyInfo = keyInfo;
                                signedXml.ComputeSignature();
                                #endregion

                                // busca a representacao XML da assinatura e salva no XML
                                XmlElement xmlDigitalSignature = signedXml.GetXml();
                                // adiciona a assinatura no documento
                                doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                //salva o documento assinado
                                XMLDoc = new XmlDocument();
                                //XMLDoc.PreserveWhitespace = false;
                                XMLDoc = doc;
                            }
                            catch (Exception caught)
                            {
                                resultado    = TRetornoAssinatura.ErroAoAssinarDocumento;// 7;
                                msgResultado = "Erro: Ao assinar o documento - " + caught.Message;
                            }
                        }
                    }
                }
                catch (Exception caught)
                {
                    resultado    = TRetornoAssinatura.XMLMalFormado;// 3;
                    msgResultado = "Erro: XML mal formado - " + caught.Message;
                }
            }
            catch (Exception caught)
            {
                resultado    = TRetornoAssinatura.ProblemaAoAcessarCertificado;// 1;
                msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message;
            }
            return(resultado);
        }
示例#18
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, DSA DSAKey)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the DSA key to the SignedXml document.
        signedXml.SigningKey = DSAKey;

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add a transformation to the reference.
        Transform trns = new XmlDsigC14NTransform();

        reference.AddTransform(trns);

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);


        // Add a DSAKeyValue to the KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new DSAKeyValue((DSA)DSAKey));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }
示例#19
0
        /// <summary>
        /// Sign an xml element with the supplied cert.
        /// </summary>
        /// <param name="xmlElement">xmlElement to be signed. The signature is
        /// added as a node in the document, right after the Issuer node.</param>
        /// <param name="cert">Certificate to use when signing.</param>
        /// <param name="includeKeyInfo">Include public key in signed output.</param>
        /// <param name="signingAlgorithm">The signing algorithm to use.</param>
        public static void Sign(
            this XmlElement xmlElement,
            X509Certificate2 cert,
            bool includeKeyInfo,
            string signingAlgorithm)
        {
            if (xmlElement == null)
            {
                throw new ArgumentNullException(nameof(xmlElement));
            }

            if (cert == null)
            {
                throw new ArgumentNullException(nameof(cert));
            }

            var signedXml = new SignedXmlWithIdFix(xmlElement.OwnerDocument);

            // The transform XmlDsigExcC14NTransform and canonicalization method XmlDsigExcC14NTransformUrl is important for partially signed XML files
            // see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.signedxml.xmldsigexcc14ntransformurl(v=vs.110).aspx
            // The reference URI has to be set correctly to avoid assertion injections
            // For both, the ID/Reference and the Transform/Canonicalization see as well:
            // https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf section 5.4.2 and 5.4.3

            signedXml.SigningKey = EnvironmentHelpers.IsNetCore
                ? cert.PrivateKey
                : ((RSACryptoServiceProvider)cert.PrivateKey)
                                   .GetSha256EnabledRSACryptoServiceProvider();
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod        = signingAlgorithm;

            // We need a document unique ID on the element to sign it -- make one up if it's missing
            string id = xmlElement.GetAttribute("ID");

            if (String.IsNullOrEmpty(id))
            {
                id = "_" + Guid.NewGuid().ToString("N");
                xmlElement.SetAttribute("ID", id);
            }

            var reference = new Reference
            {
                Uri          = "#" + id,
                DigestMethod = GetCorrespondingDigestAlgorithm(signingAlgorithm)
            };

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            if (includeKeyInfo)
            {
                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));
                signedXml.KeyInfo = keyInfo;
            }

            xmlElement.InsertAfter(
                xmlElement.OwnerDocument.ImportNode(signedXml.GetXml(), true),
                xmlElement["Issuer", Saml2Namespaces.Saml2Name]);
        }
示例#20
0
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string[] ElementsToSign)
    {
        // Check the arguments.
        if (FileName == null)
        {
            throw new ArgumentNullException("FileName");
        }
        if (SignedFileName == null)
        {
            throw new ArgumentNullException("SignedFileName");
        }
        if (Key == null)
        {
            throw new ArgumentNullException("Key");
        }
        if (ElementsToSign == null)
        {
            throw new ArgumentNullException("ElementsToSign");
        }

        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Loop through each passed element to sign
        // and create a reference.
        foreach (string s in ElementsToSign)
        {
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = s;

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);
        }

        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }
 public static void Generate(XmlElement xmlElement, AsymmetricAlgorithm signingKey, KeyInfo keyInfo)
 {
     SAMLMetadataSignature.Generate(xmlElement, signingKey, keyInfo, "#default md saml ds xs xsi", (string)null, (string)null);
 }
示例#22
0
        /// <summary>
        /// An example on how to decrypt an encrypted assertion.
        /// </summary>
        /// <param name="file">The file.</param>
        public static void DecryptAssertion(string file)
        {
            var doc = new XmlDocument();

            doc.Load(file);
            var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, doc);

            var encryptedData = new EncryptedData();

            encryptedData.LoadXml(encryptedDataElement);

            var nodelist = doc.GetElementsByTagName(Schema.XmlDSig.KeyInfo.ElementName, Saml20Constants.Xmldsig);

            Assert.True(nodelist.Count > 0);

            var key = new KeyInfo();

            key.LoadXml((XmlElement)nodelist[0]);

            // Review: Is it possible to figure out which certificate to load based on the Token?

            /*
             * Comment:
             * It would be possible to provide a key/certificate identifier in the EncryptedKey element, which contains the "recipient" attribute.
             * The implementation (Safewhere.Tokens.Saml20.Saml20EncryptedAssertion) currently just expects an appropriate asymmetric key to be provided,
             * and is not not concerned about its origin.
             * If the need arises, we can easily extend the Saml20EncryptedAssertion class with a property that allows extraction key info, eg. the "recipient"
             * attribute.
             */
            var cert = Certificates.InMemoryResourceUtility.GetInMemoryCertificate("sts_dev_certificate.pfx", "test1234");

            // ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm
            // Look through the list of KeyInfo elements to find the encrypted key.
            SymmetricAlgorithm symmetricKey = null;

            foreach (KeyInfoClause keyInfoClause in key)
            {
                if (keyInfoClause is KeyInfoEncryptedKey)
                {
                    var keyInfoEncryptedKey = (KeyInfoEncryptedKey)keyInfoClause;
                    var encryptedKey        = keyInfoEncryptedKey.EncryptedKey;
                    symmetricKey = new RijndaelManaged
                    {
                        Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)cert.PrivateKey, false)
                    };
                }
            }

            // Explode if we didn't manage to find a viable key.
            Assert.NotNull(symmetricKey);
            var encryptedXml = new EncryptedXml();
            var plaintext    = encryptedXml.DecryptData(encryptedData, symmetricKey);

            var assertion = new XmlDocument();

            assertion.Load(new StringReader(System.Text.Encoding.UTF8.GetString(plaintext)));

            // A very simple test to ensure that there is indeed an assertion in the plaintext.
            Assert.Equal(Assertion.ElementName, assertion.DocumentElement.LocalName);
            Assert.Equal(Saml20Constants.Assertion, assertion.DocumentElement.NamespaceURI);

            // At this point, assertion will contain a decrypted assertion.
        }
        public static void Generate(XmlElement xmlElement, AsymmetricAlgorithm signingKey, KeyInfo keyInfo, string inclusiveNamespacesPrefixList, string digestMethod, string signatureMethod)
        {
            if (inclusiveNamespacesPrefixList == null)
            {
                inclusiveNamespacesPrefixList = "#default md saml ds xs xsi";
            }
            XmlElement xmlSignature = XmlSignature.Generate(xmlElement, SAMLMetadataSignature.GetID(xmlElement), signingKey, keyInfo, (SignedXml) new SignedMetadata(xmlElement), inclusiveNamespacesPrefixList, digestMethod, signatureMethod);

            SAMLMetadataSignature.AddSignature(xmlElement, xmlSignature);
        }
 public static bool Verify(XmlElement xmlElement, KeyInfo keyInfo)
 {
     return(XmlSignature.Verify(xmlElement, keyInfo, (SignedXml) new SignedMetadata(xmlElement)));
 }
示例#25
0
 public void SetUp()
 {
     info = new KeyInfo();
 }
示例#26
0
    static void sqlite3VdbeChangeP4( Vdbe p, int addr, union_p4 _p4, int n )
    {
      Op pOp;
      sqlite3 db;
      Debug.Assert( p != null );
      db = p.db;
      Debug.Assert( p.magic == VDBE_MAGIC_INIT );
      if ( p.aOp == null /*|| db.mallocFailed != 0 */)
      {
        if ( n != P4_KEYINFO && n != P4_VTAB )
        {
          freeP4( db, n, _p4 );
        }
        return;
      }
      Debug.Assert( p.nOp > 0 );
      Debug.Assert( addr < p.nOp );
      if ( addr < 0 )
      {
        addr = p.nOp - 1;
      }
      pOp = p.aOp[addr];
      freeP4( db, pOp.p4type, pOp.p4.p );
      pOp.p4.p = null;
      if ( n == P4_INT32 )
      {
        /* Note: this cast is safe, because the origin data point was an int
        ** that was cast to a (string ). */
        pOp.p4.i = _p4.i; // SQLITE_PTR_TO_INT(zP4);
        pOp.p4type = P4_INT32;
      }
      else if ( n == P4_INT64 )
      {
        pOp.p4.pI64 = _p4.pI64;
        pOp.p4type = n;
      }
      else if ( n == P4_REAL )
      {
        pOp.p4.pReal = _p4.pReal;
        pOp.p4type = n;
      }
      else if ( _p4 == null )
      {
        pOp.p4.p = null;
        pOp.p4type = P4_NOTUSED;
      }
      else if ( n == P4_KEYINFO )
      {
        KeyInfo pKeyInfo;
        int nField, nByte;

        nField = _p4.pKeyInfo.nField;
        //nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo.aColl[0]) + nField;
        pKeyInfo = new KeyInfo();//sqlite3DbMallocRaw(0, nByte);
        pOp.p4.pKeyInfo = pKeyInfo;
        if ( pKeyInfo != null )
        {
          //u8 *aSortOrder;
          // memcpy((char)pKeyInfo, zP4, nByte - nField);
          //aSortOrder = pKeyInfo.aSortOrder;
          //if( aSortOrder ){
          //  pKeyInfo.aSortOrder = (unsigned char)&pKeyInfo.aColl[nField];
          //  memcpy(pKeyInfo.aSortOrder, aSortOrder, nField);
          //}
          pKeyInfo = _p4.pKeyInfo.Copy();
          pOp.p4type = P4_KEYINFO;
        }
        else
        {
          //p.db.mallocFailed = 1;
          pOp.p4type = P4_NOTUSED;
        }
        pOp.p4.pKeyInfo = _p4.pKeyInfo;
        pOp.p4type = P4_KEYINFO;
      }
      else if ( n == P4_KEYINFO_HANDOFF || n == P4_KEYINFO_STATIC )
      {
        pOp.p4.pKeyInfo = _p4.pKeyInfo;
        pOp.p4type = P4_KEYINFO;
      }
      else if ( n == P4_FUNCDEF )
      {
        pOp.p4.pFunc = _p4.pFunc;
        pOp.p4type = P4_FUNCDEF;
      }
      else if ( n == P4_COLLSEQ )
      {
        pOp.p4.pColl = _p4.pColl;
        pOp.p4type = P4_COLLSEQ;
      }
      else if ( n == P4_DYNAMIC || n == P4_STATIC || n == P4_MPRINTF )
      {
        pOp.p4.z = _p4.z;
        pOp.p4type = P4_DYNAMIC;
      }
      else if ( n == P4_MEM )
      {
        pOp.p4.pMem = _p4.pMem;
        pOp.p4type = P4_MEM;
      }
      else if ( n == P4_INTARRAY )
      {
        pOp.p4.ai = _p4.ai;
        pOp.p4type = P4_INTARRAY;
      }
      else if ( n == P4_SUBPROGRAM )
      {
        pOp.p4.pProgram = _p4.pProgram;
        pOp.p4type = P4_SUBPROGRAM;
      }
      else if ( n == P4_VTAB )
      {
        pOp.p4.pVtab = _p4.pVtab;
        pOp.p4type = P4_VTAB;
        sqlite3VtabLock( _p4.pVtab );
        Debug.Assert( ( _p4.pVtab ).db == p.db );
      }
      else if ( n < 0 )
      {
        pOp.p4.p = _p4.p;
        pOp.p4type = n;
      }
      else
      {
        //if (n == 0) n =  n = sqlite3Strlen30(zP4);
        pOp.p4.z = _p4.z;// sqlite3DbStrNDup(p.db, zP4, n);
        pOp.p4type = P4_DYNAMIC;
      }
    }
示例#27
0
        public Stream Decrypt(EncryptionMethod encryptionMethod, KeyInfo keyInfo, Stream toDecrypt)
        {
            Assert.NotNull(encryptionMethod);
            Assert.NotNull(keyInfo);
            Assert.NotNull(toDecrypt);
            Assert.True(encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES128Url ||
                        encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES192Url ||
                        encryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncAES256Url);

            Assert.Equal(keyInfo.Count, 1);

            byte[] decryptedKey = null;

            foreach (KeyInfoClause clause in keyInfo)
            {
                if (clause is KeyInfoEncryptedKey)
                {
                    KeyInfoEncryptedKey encryptedKeyInfo = clause as KeyInfoEncryptedKey;
                    EncryptedKey        encryptedKey     = encryptedKeyInfo.EncryptedKey;

                    Assert.Equal(encryptedKey.EncryptionMethod.KeyAlgorithm, EncryptedXml.XmlEncRSAOAEPUrl);
                    Assert.Equal(encryptedKey.KeyInfo.Count, 1);
                    Assert.NotEqual(_asymmetricKeys.Count, 0);

                    RSAParameters rsaParams      = new RSAParameters();
                    RSAParameters rsaInputParams = new RSAParameters();

                    foreach (KeyInfoClause rsa in encryptedKey.KeyInfo)
                    {
                        if (rsa is RSAKeyValue)
                        {
                            rsaParams = (rsa as RSAKeyValue).Key.ExportParameters(false);
                            break;
                        }
                        else
                        {
                            Assert.True(false, "Invalid License - MalformedKeyInfoClause");
                        }
                    }

                    bool keyMismatch = true;
                    foreach (AsymmetricAlgorithm key in _asymmetricKeys)
                    {
                        RSA rsaKey = key as RSA;
                        Assert.NotNull(rsaKey);

                        rsaInputParams = rsaKey.ExportParameters(false);

                        if (!PublicKeysEqual(rsaParams, rsaInputParams))
                        {
                            continue;
                        }

                        keyMismatch = false;

                        // Decrypt session key
                        byte[] encryptedKeyValue = encryptedKey.CipherData.CipherValue;

                        if (encryptedKeyValue == null)
                        {
                            throw new CryptographicException("MissingKeyCipher");
                        }

                        decryptedKey = EncryptedXml.DecryptKey(encryptedKeyValue,
                                                               rsaKey, true);
                        break;
                    }

                    if (keyMismatch)
                    {
                        throw new Exception("Invalid License - AsymmetricKeyMismatch");
                    }
                }
                else if (clause is KeyInfoName)
                {
                    Assert.True(false, "This test should not have KeyInfoName clauses");
                }
                else
                {
                    throw new CryptographicException("MalformedKeyInfoClause");
                }

                break;
            }

            if (decryptedKey == null)
            {
                throw new CryptographicException("KeyDecryptionFailure");
            }

            using (Aes aes = Aes.Create())
            {
                aes.Key     = decryptedKey;
                aes.Padding = PaddingMode.PKCS7;
                aes.Mode    = CipherMode.CBC;
                return(DecryptStream(toDecrypt, aes));
            }
        }
示例#28
0
    /*
    ** Given the nKey-byte encoding of a record in pKey[], parse the
    ** record into a UnpackedRecord structure.  Return a pointer to
    ** that structure.
    **
    ** The calling function might provide szSpace bytes of memory
    ** space at pSpace.  This space can be used to hold the returned
    ** VDbeParsedRecord structure if it is large enough.  If it is
    ** not big enough, space is obtained from sqlite3Malloc().
    **
    ** The returned structure should be closed by a call to
    ** sqlite3VdbeDeleteUnpackedRecord().
    */
    static UnpackedRecord sqlite3VdbeRecordUnpack(
    KeyInfo pKeyInfo,   /* Information about the record format */
    int nKey,           /* Size of the binary record */
    byte[] pKey,        /* The binary record */
    UnpackedRecord pSpace, //  char *pSpace,          /* Unaligned space available to hold the object */
    int szSpace         /* Size of pSpace[] in bytes */
    )
    {
      byte[] aKey = pKey;
      UnpackedRecord p;     /* The unpacked record that we will return */
      int nByte;            /* Memory space needed to hold p, in bytes */
      int d;
      u32 idx;
      int u;                /* Unsigned loop counter */
      int szHdr = 0;
      Mem pMem;
      int nOff;           /* Increase pSpace by this much to 8-byte align it */

      /*
      ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
      ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
      ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
      */
      //nOff = ( 8 - ( SQLITE_PTR_TO_INT( pSpace ) & 7 ) ) & 7;
      //pSpace += nOff;
      //szSpace -= nOff;
      //nByte = ROUND8( sizeof( UnpackedRecord ) ) + sizeof( Mem ) * ( pKeyInfo->nField + 1 );
      //if ( nByte > szSpace)
      //{
      //var  p = new UnpackedRecord();//sqlite3DbMallocRaw(pKeyInfo.db, nByte);
      //  if ( p == null ) return null;
      //  p.flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
      //}
      //else
      {
        p = pSpace;//(UnpackedRecord)pSpace;
        p.flags = UNPACKED_NEED_DESTROY;
      }
      p.pKeyInfo = pKeyInfo;
      p.nField = (u16)( pKeyInfo.nField + 1 );
      //p->aMem = pMem = (Mem)&( (char)p )[ROUND8( sizeof( UnpackedRecord ) )];
      //Debug.Assert( EIGHT_BYTE_ALIGNMENT( pMem ) );
      p.aMem = new Mem[p.nField + 1];
      idx = (u32)getVarint32( aKey, 0, out szHdr );// GetVarint( aKey, szHdr );
      d = (int)szHdr;
      u = 0;
      while ( idx < (int)szHdr && u < p.nField && d <= nKey )
      {
        p.aMem[u] = sqlite3Malloc( p.aMem[u] );
        pMem = p.aMem[u];
        u32 serial_type = 0;

        idx += (u32)getVarint32( aKey, idx, out serial_type );// GetVarint( aKey + idx, serial_type );
        pMem.enc = pKeyInfo.enc;
        pMem.db = pKeyInfo.db;
        /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
        //pMem.zMalloc = null;
        d += (int)sqlite3VdbeSerialGet( aKey, d, serial_type, pMem );
        //pMem++;
        u++;
      }
      Debug.Assert( u <= pKeyInfo.nField + 1 );
      p.nField = (u16)u;
      return p;// (void)p;
    }
        /// <summary>
        /// Realiza la contrafirma de la firma actual
        /// </summary>
        /// <param name="sigDocument"></param>
        /// <param name="parameters"></param>
        public SignatureDocument CounterSign(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            if (parameters.Signer == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma.");
            }

            SignatureDocument.CheckSignatureDocument(sigDocument);

            SignatureDocument counterSigDocument = new SignatureDocument();

            counterSigDocument.Document = (XmlDocument)sigDocument.Document.Clone();
            counterSigDocument.Document.PreserveWhitespace = true;

            XadesSignedXml counterSignature = new XadesSignedXml(counterSigDocument.Document);

            SetSignatureId(counterSignature);

            counterSignature.SigningKey = parameters.Signer.SigningKey;

            _refContent      = new Reference();
            _refContent.Uri  = "#" + sigDocument.XadesSignature.SignatureValueId;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = "http://uri.etsi.org/01903#CountersignedSignature";
            _refContent.AddTransform(new XmlDsigC14NTransform());
            counterSignature.AddReference(_refContent);

            _mimeType = "text/xml";
            _encoding = "UTF-8";

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + counterSignature.Signature.Id;
            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)parameters.Signer.Certificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)parameters.Signer.SigningKey));
            counterSignature.KeyInfo = keyInfo;

            Reference referenceKeyInfo = new Reference();

            referenceKeyInfo.Id  = "ReferenceKeyInfo-" + counterSignature.Signature.Id;
            referenceKeyInfo.Uri = "#KeyInfoId-" + counterSignature.Signature.Id;
            counterSignature.AddReference(referenceKeyInfo);

            XadesObject counterSignatureXadesObject = new XadesObject();

            counterSignatureXadesObject.Id = "CounterSignatureXadesObject-" + Guid.NewGuid().ToString();
            counterSignatureXadesObject.QualifyingProperties.Target = "#" + counterSignature.Signature.Id;
            counterSignatureXadesObject.QualifyingProperties.SignedProperties.Id = "SignedProperties-" + counterSignature.Signature.Id;

            AddSignatureProperties(counterSigDocument, counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                                   counterSignatureXadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                                   counterSignatureXadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties, parameters);

            counterSignature.AddXadesObject(counterSignatureXadesObject);

            foreach (Reference signReference in counterSignature.SignedInfo.References)
            {
                signReference.DigestMethod = parameters.DigestMethod.URI;
            }

            counterSignature.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;

            counterSignature.AddXadesNamespace = true;
            counterSignature.ComputeSignature();

            counterSigDocument.XadesSignature = new XadesSignedXml(counterSigDocument.Document);
            counterSigDocument.XadesSignature.LoadXml(sigDocument.XadesSignature.GetXml());

            UnsignedProperties unsignedProperties = counterSigDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.CounterSignatureCollection.Add(counterSignature);
            counterSigDocument.XadesSignature.UnsignedProperties = unsignedProperties;

            counterSigDocument.UpdateDocument();

            return(counterSigDocument);
        }
示例#30
0
        static DCinemaSecurityMessageType SignETM(DCinemaSecurityMessageType extraTheatreMessage, X509Certificate2 x509Certificate2)
        {
            SignedXml signedXml = null;

            try
            {
                signedXml            = new SignedXml();
                signedXml.SigningKey = x509Certificate2.PrivateKey;
                //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/ 2001/04/xmldsig-more#rsasha256";
                //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments";

                StringWriter  stringWriter  = new StringWriter();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DCinemaSecurityMessageType));
                xmlSerializer.Serialize(stringWriter, extraTheatreMessage);
                string serializedXML = stringWriter.ToString();

                #region Build the AuthenticatedPublic DataObject & Reference

                string      xmlAuthenticatedPublic = GetCleanElement(serializedXML, "AuthenticatedPublic");
                XmlDocument docAuthenticatedPublic = new XmlDocument();
                docAuthenticatedPublic.LoadXml(xmlAuthenticatedPublic.ToString());

                //XmlAttribute attrAuthenticatedPublic = docAuthenticatedPublic.CreateAttribute("xmlns");
                //attrAuthenticatedPublic.Value = "http://www.smpte-ra.org/schemas/430-3/2006/ETM";
                //docAuthenticatedPublic.DocumentElement.Attributes.Append(attrAuthenticatedPublic);

                DataObject dataObjectAuthenticatedPublic = new DataObject("AuthenticatedPublic", "", "", docAuthenticatedPublic.DocumentElement);
                //DataObject dataObjectAuthenticatedPublic = new DataObject();
                dataObjectAuthenticatedPublic.Data = docAuthenticatedPublic.ChildNodes;
                dataObjectAuthenticatedPublic.Id   = "AuthenticatedPublic";

                signedXml.AddObject(dataObjectAuthenticatedPublic);

                Reference referenceAuthenticatedPublic = new Reference();
                referenceAuthenticatedPublic.Uri          = "#AuthenticatedPublic";
                referenceAuthenticatedPublic.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

                signedXml.AddReference(referenceAuthenticatedPublic);

                #endregion

                #region Build the AuthenticatedPublic DataObject & Reference

                string      xmlAuthenticatedPrivate = GetCleanElement(serializedXML, "AuthenticatedPrivate");
                XmlDocument docAuthenticatedPrivate = new XmlDocument();
                docAuthenticatedPrivate.LoadXml(xmlAuthenticatedPrivate.ToString());

                //XmlAttribute attrAuthenticatedPrivate = docAuthenticatedPrivate.CreateAttribute("xmlns");
                //attrAuthenticatedPrivate.Value = "http://www.smpte-ra.org/schemas/430-3/2006/FLM";
                //docAuthenticatedPrivate.DocumentElement.Attributes.Append(attrAuthenticatedPrivate);

                DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement);
                //DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement);
                //dataObjectAuthenticatedPrivate.Data = docAuthenticatedPrivate.ChildNodes;
                //dataObjectAuthenticatedPrivate.Id = "AuthenticatedPrivate";

                signedXml.AddObject(dataObjectAuthenticatedPrivate);

                Reference referenceAuthenticatedPrivate = new Reference();
                referenceAuthenticatedPrivate.Uri          = "#AuthenticatedPrivate";
                referenceAuthenticatedPrivate.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

                // Add the reference to the message.
                signedXml.AddReference(referenceAuthenticatedPrivate);

                #endregion

                // Add a KeyInfo.
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(x509Certificate2, X509IncludeOption.WholeChain));
                signedXml.KeyInfo = keyInfo;

                // Compute the signature.
                signedXml.ComputeSignature();

                XmlElement    singedElement    = signedXml.GetXml();
                XmlSerializer signedSerializer = new XmlSerializer(singedElement.GetType());
                StreamWriter  signedWriter     = new StreamWriter(@"\SOURCE_SMPTE\Output\signedSerializer.Test.xml");
                signedSerializer.Serialize(signedWriter, singedElement);
                signedWriter.Close();
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }

            extraTheatreMessage.Signature = signedXml.Signature.GetXml();

            return(extraTheatreMessage);
        }
示例#31
0
        public async Task CreateAsync(KeyInfo key)
        {
            Ensure.NotNull(key, nameof(key));

            await db.Keys.InsertAsync(key);
        }
        public void ExtremeCases()
        {
            //void index

            var keyType = new KeyInfo(KeyDataType.IntKey, KeyType.ScalarIndex, "test", true);

            IndexBase index  = populate();
            var       result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);

            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 0);


            //one element index, value not found
            index  = populate(15);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 1);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 1);


            //one element index, value found
            index  = populate(12);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
            Assert.AreEqual(result.Count, 1);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 1);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 1);

            //two element index (different values)
            index  = populate(12, 15);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
            Assert.AreEqual(result.Count, 1);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 1);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 1);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 2);


            //two element index (same value)
            index  = populate(12, 12);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
            Assert.AreEqual(result.Count, 2);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 2);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 2);


            //three element index (same value ==)
            index  = populate(12, 12, 12);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
            Assert.AreEqual(result.Count, 3);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 3);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 3);

            //three element index (same value !=)
            index  = populate(15, 15, 15);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType));
            Assert.AreEqual(result.Count, 0);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Gt);
            Assert.AreEqual(result.Count, 3);
            result = index.GetMany(MakeIntValue(12, keyType), QueryOperator.Ge);
            Assert.AreEqual(result.Count, 3);
        }
        public Stream Decrypt(EncryptionMethod encryptionMethod, KeyInfo keyInfo, Stream toDecrypt)
        {
            Assert.NotNull(encryptionMethod);
            Assert.NotNull(keyInfo);
            Assert.NotNull(toDecrypt);
            Assert.True(encryptionMethod.KeyAlgorithm == NS.XmlEncAES128Url ||
                        encryptionMethod.KeyAlgorithm == NS.XmlEncAES192Url ||
                        encryptionMethod.KeyAlgorithm == NS.XmlEncAES256Url);

            Assert.Equal(keyInfo.Count, 1);

            byte[] decryptedKey = null;

            foreach (KeyInfoClause clause in keyInfo)
            {
                if (clause is KeyInfoEncryptedKey)
                {
                    KeyInfoEncryptedKey encryptedKeyInfo = clause as KeyInfoEncryptedKey;
                    EncryptedKey        encryptedKey     = encryptedKeyInfo.GetEncryptedKey();

                    Assert.Equal(encryptedKey.EncryptionMethod.KeyAlgorithm, NS.XmlEncRSAOAEPUrl);
                    Assert.Equal(encryptedKey.KeyInfo.Count, 1);
                    Assert.NotEqual(_asymmetricKeys.Count, 0);

                    RsaKeyParameters rsaParams      = null;
                    RsaKeyParameters rsaInputParams = null;

                    foreach (KeyInfoClause rsa in encryptedKey.KeyInfo)
                    {
                        if (rsa is RsaKeyValue)
                        {
                            rsaParams = (rsa as RsaKeyValue).GetKey();
                            break;
                        }
                        else
                        {
                            Assert.True(false, "Invalid License - MalformedKeyInfoClause");
                        }
                    }

                    bool keyMismatch = true;
                    foreach (AsymmetricCipherKeyPair key in _asymmetricKeys)
                    {
                        RsaKeyParameters rsaKey = key.Private as RsaKeyParameters;
                        Assert.NotNull(rsaKey);

                        rsaInputParams = key.Public as RsaKeyParameters;
                        Assert.NotNull(rsaInputParams);

                        if (!PublicKeysEqual(rsaParams, rsaInputParams))
                        {
                            continue;
                        }

                        keyMismatch = false;


                        byte[] encryptedKeyValue = encryptedKey.CipherData.CipherValue;

                        if (encryptedKeyValue == null)
                        {
                            throw new System.Security.Cryptography.CryptographicException("MissingKeyCipher");
                        }

                        decryptedKey = XmlDecryption.DecryptKey(encryptedKeyValue,
                                                                rsaKey, true);
                        break;
                    }

                    if (keyMismatch)
                    {
                        throw new Exception("Invalid License - AsymmetricKeyMismatch");
                    }
                }
                else if (clause is KeyInfoName)
                {
                    Assert.True(false, "This test should not have KeyInfoName clauses");
                }
                else
                {
                    throw new System.Security.Cryptography.CryptographicException("MalformedKeyInfoClause");
                }

                break;
            }

            if (decryptedKey == null)
            {
                throw new System.Security.Cryptography.CryptographicException("KeyDecryptionFailure");
            }

            return(DecryptStream(toDecrypt, new KeyParameter(decryptedKey), "AES/CBC/PKCS7"));
        }
        public void Lesser()
        {
            //register the type to get a valid TypeDescription
            //the type description is used to create CachedObjects from objects of the registered type
            var typeDescription = ClientSideTypeDescription.RegisterType(typeof(CacheableTypeOk));

            KeyInfo valueKey = null;

            foreach (var keyInfo in typeDescription.IndexFields)
            {
                if (keyInfo.Name == "IndexKeyValue")
                {
                    valueKey = keyInfo.AsKeyInfo;
                }
            }

            Assert.IsNotNull(valueKey);


            //fill in order
            {
                var indexByValue = new OrderedIndex(valueKey);

                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(1, 101, "A", DateTime.Now, 1)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(2, 102, "A", DateTime.Now, 4)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(3, 103, "A", DateTime.Now, 6)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(4, 104, "A", DateTime.Now, 13)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(5, 105, "A", DateTime.Now, 14)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(6, 106, "A", DateTime.Now, 80)));

                checkLE(indexByValue);
                checkLS(indexByValue);
            }

            //fill out of order
            {
                var indexByValue = new OrderedIndex(valueKey);

                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(6, 106, "A", DateTime.Now, 80)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(1, 101, "A", DateTime.Now, 1)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(4, 104, "A", DateTime.Now, 13)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(2, 102, "A", DateTime.Now, 4)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(5, 105, "A", DateTime.Now, 14)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(3, 103, "A", DateTime.Now, 6)));


                checkLE(indexByValue);
                checkLS(indexByValue);
            }

            //fill out of order transactional
            {
                var indexByValue = new OrderedIndex(valueKey);

                indexByValue.BeginFill();

                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(6, 106, "A", DateTime.Now, 80)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(1, 101, "A", DateTime.Now, 1)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(4, 104, "A", DateTime.Now, 13)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(2, 102, "A", DateTime.Now, 4)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(5, 105, "A", DateTime.Now, 14)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(3, 103, "A", DateTime.Now, 6)));
                indexByValue.EndFill();

                checkLE(indexByValue);
                checkLS(indexByValue);
            }


            //all equals
            {
                var indexByValue = new OrderedIndex(valueKey);

                var keyType = new KeyInfo(KeyDataType.IntKey, KeyType.ScalarIndex, "test", true);

                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(6, 106, "A", DateTime.Now, 45)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(1, 101, "A", DateTime.Now, 45)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(4, 104, "A", DateTime.Now, 45)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(2, 102, "A", DateTime.Now, 45)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(5, 105, "A", DateTime.Now, 45)));
                indexByValue.Put(CachedObject.Pack(new CacheableTypeOk(3, 103, "A", DateTime.Now, 45)));

                //value not fount (too small)
                var result1 = indexByValue.GetMany(MakeIntValue(12, keyType), QueryOperator.Le);
                Assert.AreEqual(result1.Count, 0);

                result1 = indexByValue.GetMany(MakeIntValue(12, keyType), QueryOperator.Lt);
                Assert.AreEqual(result1.Count, 0);

                //value not found (too big)
                result1 = indexByValue.GetMany(MakeIntValue(50, keyType), QueryOperator.Le);
                Assert.AreEqual(result1.Count, 6);

                result1 = indexByValue.GetMany(MakeIntValue(50, keyType), QueryOperator.Lt);
                Assert.AreEqual(result1.Count, 6);

                //value found (all match the index key )
                result1 = indexByValue.GetMany(MakeIntValue(45, keyType), QueryOperator.Le);
                Assert.AreEqual(result1.Count, 6);

                //not found (Lt)
                result1 = indexByValue.GetMany(MakeIntValue(45, keyType), QueryOperator.Lt);
                Assert.AreEqual(result1.Count, 0);
            }
        }
        public static XmlElement GetSignature(XmlDocument document, X509Certificate2 cert, string elementToSignId)
        {
            SignedXml signedXml = new SignedXml(document)
            {
                SigningKey = cert.PrivateKey
            };

            signedXml.SigningKey = cert.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference()
            {
                Uri = elementToSignId
            };


            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true);

            reference.AddTransform(env);

            //canonicalize
            XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();

            reference.AddTransform(c14t);


            //Key Info

            KeyInfoName kin = new KeyInfoName()
            {
                Value = cert.Subject
            };

            //RSA Key Provider
            // RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;
            // RSAKeyValue rkv = new RSAKeyValue(rsaprovider);


            //System.Security.Cryptography..X509IssuerSerial xserial;
            //xserial.IssuerName = cert.IssuerName.Name;
            //xserial.SerialNumber = cert.SerialNumber;

            KeyInfo         keyInfo     = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);

            //keyInfo.AddClause(new KeyInfoX509Data(cert));
            keyInfoData.AddIssuerSerial(cert.IssuerName.Name, cert.SerialNumber);
            keyInfo.AddClause(keyInfoData);


            keyInfo.AddClause(kin);
            //keyInfo.AddClause(rkv);
            // Add the KeyInfo object to the SignedXml object.
            keyInfo.AddClause(new RSAKeyValue((RSA)cert.PrivateKey));
            signedXml.KeyInfo = keyInfo;

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();


            return(xmlDigitalSignature);
        }
示例#36
0
 private void OnKeyUp(KeyInfo info)
 {
     RaisePropertyChanged("TotalHits");
     RaisePropertyChanged("AggregatedKeys");
 }
示例#37
0
        public string FirmarXml(string tramaXml)
        {
            // Vamos a firmar el XML con la ruta del certificado que está como serializado.

            var certificate = new X509Certificate2();

            certificate.Import(Convert.FromBase64String(RutaCertificadoDigital),
                               PasswordCertificado, X509KeyStorageFlags.MachineKeySet);

            var xmlDoc = new XmlDocument();

            string resultado;

            using (var documento = new MemoryStream(Convert.FromBase64String(tramaXml)))
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(documento);
                int tipo;

                if (TipoDocumento == 1 || TipoDocumento == 2 || TipoDocumento == 3 || TipoDocumento == 4)
                {
                    tipo = 1;
                }
                else
                {
                    tipo = 0;
                }

                var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext)
                                    .Item(tipo);
                if (nodoExtension == null)
                {
                    throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
                }
                nodoExtension.RemoveAll();

                // Creamos el objeto SignedXml.
                var signedXml = new SignedXml(xmlDoc)
                {
                    SigningKey = (RSA)certificate.PrivateKey
                };
                signedXml.SigningKey = certificate.PrivateKey;
                var xmlSignature = signedXml.Signature;

                var env = new XmlDsigEnvelopedSignatureTransform();

                var reference = new Reference(string.Empty);
                reference.AddTransform(env);
                xmlSignature.SignedInfo.AddReference(reference);

                var keyInfo  = new KeyInfo();
                var x509Data = new KeyInfoX509Data(certificate);

                x509Data.AddSubjectName(certificate.Subject);

                keyInfo.AddClause(x509Data);
                xmlSignature.KeyInfo = keyInfo;
                xmlSignature.Id      = "SignatureErickOrlando";
                signedXml.ComputeSignature();

                // Recuperamos el valor Hash de la firma para este documento.
                if (reference.DigestValue != null)
                {
                    DigestValue = Convert.ToBase64String(reference.DigestValue);
                }
                ValorFirma = Convert.ToBase64String(signedXml.SignatureValue);

                nodoExtension.AppendChild(signedXml.GetXml());

                var settings = new XmlWriterSettings()
                {
                    Encoding = Encoding.GetEncoding("ISO-8859-1")
                };

                using (var memDoc = new MemoryStream())
                {
                    using (var writer = XmlWriter.Create(memDoc, settings))
                    {
                        xmlDoc.WriteTo(writer);
                    }

                    resultado = Convert.ToBase64String(memDoc.ToArray());
                }
            }

            return(resultado);
        }
示例#38
0
		static string FindName(KeyInfo[] info, int key)
		{
			foreach(KeyInfo i in info) if(i.ki_key==key) return i.ki_name;
			return string.Format("Unknown-{0}", key);
		}
示例#39
0
    /// <summary>
    /// This function does all the nasty work at determining what keys need to be returned for
    /// a given statement.
    /// </summary>
    /// <param name="cnn"></param>
    /// <param name="reader"></param>
    /// <param name="stmt"></param>
    internal SQLiteKeyReader(SQLiteConnection cnn, SQLiteDataReader reader, SQLiteStatement stmt)
    {
      Dictionary<string, int> catalogs = new Dictionary<string, int>();
      Dictionary<string, List<string>> tables = new Dictionary<string, List<string>>();
      List<string> list;
      List<KeyInfo> keys = new List<KeyInfo>();

      // Record the statement so we can use it later for sync'ing
      _stmt = stmt;

      // Fetch all the attached databases on this connection
      using (DataTable tbl = cnn.GetSchema("Catalogs"))
      {
        foreach (DataRow row in tbl.Rows)
        {
          catalogs.Add((string)row["CATALOG_NAME"], Convert.ToInt32(row["ID"], CultureInfo.InvariantCulture));
        }
      }

      // Fetch all the unique tables and catalogs used by the current statement
      using (DataTable schema = reader.GetSchemaTable(false, false))
      {
        foreach (DataRow row in schema.Rows)
        {
          // Check if column is backed to a table
          if (row[SchemaTableOptionalColumn.BaseCatalogName] == DBNull.Value)
            continue;

          // Record the unique table so we can look up its keys
          string catalog = (string)row[SchemaTableOptionalColumn.BaseCatalogName];
          string table = (string)row[SchemaTableColumn.BaseTableName];

          if (tables.ContainsKey(catalog) == false)
          {
            list = new List<string>();
            tables.Add(catalog, list);
          }
          else
            list = tables[catalog];

          if (list.Contains(table) == false)
            list.Add(table);
        }

        // For each catalog and each table, query the indexes for the table.
        // Find a primary key index if there is one.  If not, find a unique index instead
        foreach (KeyValuePair<string, List<string>> pair in tables)
        {
          for (int i = 0; i < pair.Value.Count; i++)
          {
            string table = pair.Value[i];
            DataRow preferredRow = null;
            using (DataTable tbl = cnn.GetSchema("Indexes", new string[] { pair.Key, null, table }))
            {
              // Loop twice.  The first time looking for a primary key index, 
              // the second time looking for a unique index
              for (int n = 0; n < 2 && preferredRow == null; n++)
              {
                foreach (DataRow row in tbl.Rows)
                {
                  if (n == 0 && (bool)row["PRIMARY_KEY"] == true)
                  {
                    preferredRow = row;
                    break;
                  }
                  else if (n == 1 && (bool)row["UNIQUE"] == true)
                  {
                    preferredRow = row;
                    break;
                  }
                }
              }
              if (preferredRow == null) // Unable to find any suitable index for this table so remove it
              {
                pair.Value.RemoveAt(i);
                i--;
              }
              else // We found a usable index, so fetch the necessary table details
              {
                using (DataTable tblTables = cnn.GetSchema("Tables", new string[] { pair.Key, null, table }))
                {
                  // Find the root page of the table in the current statement and get the cursor that's iterating it
                  int database = catalogs[pair.Key];
                  int rootPage = Convert.ToInt32(tblTables.Rows[0]["TABLE_ROOTPAGE"], CultureInfo.InvariantCulture);
                  int cursor = stmt._sql.GetCursorForTable(stmt, database, rootPage);

                  // Now enumerate the members of the index we're going to use
                  using (DataTable indexColumns = cnn.GetSchema("IndexColumns", new string[] { pair.Key, null, table, (string)preferredRow["INDEX_NAME"] }))
                  {
                    KeyQuery query = null;

                    List<string> cols = new List<string>();
                    for (int x = 0; x < indexColumns.Rows.Count; x++)
                    {
                      bool addKey = true;
                      // If the column in the index already appears in the query, skip it
                      foreach (DataRow row in schema.Rows)
                      {
                        if (row.IsNull(SchemaTableColumn.BaseColumnName))
                          continue;

                        if ((string)row[SchemaTableColumn.BaseColumnName] == (string)indexColumns.Rows[x]["COLUMN_NAME"] &&
                            (string)row[SchemaTableColumn.BaseTableName] == table &&
                            (string)row[SchemaTableOptionalColumn.BaseCatalogName] == pair.Key)
                        {
                          indexColumns.Rows.RemoveAt(x);
                          x--;
                          addKey = false;
                          break;
                        }
                      }
                      if (addKey == true)
                        cols.Add((string)indexColumns.Rows[x]["COLUMN_NAME"]);
                    }

                    // If the index is not a rowid alias, record all the columns
                    // needed to make up the unique index and construct a SQL query for it
                    if ((string)preferredRow["INDEX_NAME"] != "sqlite_master_PK_" + table)
                    {
                      // Whatever remains of the columns we need that make up the index that are not
                      // already in the query need to be queried separately, so construct a subquery
                      if (cols.Count > 0)
                      {
                        string[] querycols = new string[cols.Count];
                        cols.CopyTo(querycols);
                        query = new KeyQuery(cnn, pair.Key, table, querycols);
                      }
                    }

                    // Create a KeyInfo struct for each column of the index
                    for (int x = 0; x < indexColumns.Rows.Count; x++)
                    {
                      string columnName = (string)indexColumns.Rows[x]["COLUMN_NAME"];
                      KeyInfo key = new KeyInfo();

                      key.rootPage = rootPage;
                      key.cursor = cursor;
                      key.database = database;
                      key.databaseName = pair.Key;
                      key.tableName = table;
                      key.columnName = columnName;
                      key.query = query;
                      key.column = x;

                      keys.Add(key);
                    }
                  }
                }
              }
            }
          }
        }
      }

      // Now we have all the additional columns we have to return in order to support
      // CommandBehavior.KeyInfo
      _keyInfo = new KeyInfo[keys.Count];
      keys.CopyTo(_keyInfo);
    }
示例#40
0
    // Use this for initialization
    public void Initialize(KeyInfo [] animKeys)
    {
        Keys = new KeyInfo[animKeys.Length];
        for(int i = 0; i < animKeys.Length ; i++){
            Keys[i] = animKeys[i];
        }

        _keyCnt = Keys.Length - 2 ;	// -1 because keys 0 and keys.length-1 are the same, -2 because the last frame gives extreme results
        //Alloc space according to keyframe count
        for(int i = 0; i < 2; i++) {
            SpaceMetric[i] = new float[_keyCnt];
            SpaceIndex[i] = new int[_keyCnt];
            WeightMetric[i] = new float[_keyCnt];
            WeightIndex[i] = new int[_keyCnt];
            TimeMetric[i] = new float[_keyCnt];
            TimeIndex[i] = new int[_keyCnt];
            FlowMetric[i] = new float[_keyCnt -1]; //eliminate the last element as it is unnaturally big
            FlowIndex[i] = new int[_keyCnt];

            Curvature[i] = new float[_keyCnt];

            //Initialize histograms
            SpaceHist[i] = new float[NBins + 1];
            TimeHist[i] = new float[NBins + 1];
            FlowHist[i] = new float[NBins + 1];
            WeightHist[i] = new float[NBins + 1];
            CurvatureHist[i] = new float[NBins + 1];

            for(int j = 0; j < NBins +1 ; j++) {
                SpaceHist[i][j] = 0;
                TimeHist[i][j] = 0;
                FlowHist[i][j] = 0;
                WeightHist[i][j] = 0;
                CurvatureHist[i][j] = 0;
            }

        }

        Segments.Clear();
        KeySegments.Clear();

        for(int i = 0; i < 10; i++) {
            PostureMetric[i] = new float[_keyCnt]; // 10 angles for keyframes
            PostureHist[i] = new float[NBins + 1];
            for(int j = 0; j< NBins +1 ; j++)
                PostureHist[i][j] = 0;

        }
    }
示例#41
0
    /* Forward reference */
    //static int multiSelectOrderBy(
    //  Parse* pParse,        /* Parsing context */
    //  Select* p,            /* The right-most of SELECTs to be coded */
    //  SelectDest* pDest     /* What to do with query results */
    //);

#if !SQLITE_OMIT_COMPOUND_SELECT
    /*
** This routine is called to process a compound query form from
** two or more separate queries using UNION, UNION ALL, EXCEPT, or
** INTERSECT
**
** "p" points to the right-most of the two queries.  the query on the
** left is p.pPrior.  The left query could also be a compound query
** in which case this routine will be called recursively.
**
** The results of the total query are to be written into a destination
** of type eDest with parameter iParm.
**
** Example 1:  Consider a three-way compound SQL statement.
**
**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
**
** This statement is parsed up as follows:
**
**     SELECT c FROM t3
**      |
**      `----.  SELECT b FROM t2
**                |
**                `-----.  SELECT a FROM t1
**
** The arrows in the diagram above represent the Select.pPrior pointer.
** So if this routine is called with p equal to the t3 query, then
** pPrior will be the t2 query.  p.op will be TK_UNION in this case.
**
** Notice that because of the way SQLite parses compound SELECTs, the
** individual selects always group from left to right.
*/
    static int multiSelect(
    Parse pParse,             /* Parsing context */
    Select p,                 /* The right-most of SELECTs to be coded */
    SelectDest pDest          /* What to do with query results */
    )
    {
      int rc = SQLITE_OK;       /* Success code from a subroutine */
      Select pPrior;            /* Another SELECT immediately to our left */
      Vdbe v;                   /* Generate code to this VDBE */
      SelectDest dest = new SelectDest(); /* Alternative data destination */
      Select pDelete = null;    /* Chain of simple selects to delete */
      sqlite3 db;               /* Database connection */
#if !SQLITE_OMIT_EXPLAIN
      int iSub1 = 0;            /* EQP id of left-hand query */
      int iSub2 = 0;            /* EQP id of right-hand query */
#endif

      /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
*/
      Debug.Assert( p != null && p.pPrior != null );  /* Calling function guarantees this much */
      db = pParse.db;
      pPrior = p.pPrior;
      Debug.Assert( pPrior.pRightmost != pPrior );
      Debug.Assert( pPrior.pRightmost == p.pRightmost );
      dest = pDest;
      if ( pPrior.pOrderBy != null )
      {
        sqlite3ErrorMsg( pParse, "ORDER BY clause should come after %s not before",
        selectOpName( p.op ) );
        rc = 1;
        goto multi_select_end;
      }
      if ( pPrior.pLimit != null )
      {
        sqlite3ErrorMsg( pParse, "LIMIT clause should come after %s not before",
        selectOpName( p.op ) );
        rc = 1;
        goto multi_select_end;
      }

      v = sqlite3GetVdbe( pParse );
      Debug.Assert( v != null );  /* The VDBE already created by calling function */

      /* Create the destination temporary table if necessary
      */
      if ( dest.eDest == SRT_EphemTab )
      {
        Debug.Assert( p.pEList != null );
        sqlite3VdbeAddOp2( v, OP_OpenEphemeral, dest.iParm, p.pEList.nExpr );
        sqlite3VdbeChangeP5( v, BTREE_UNORDERED );
        dest.eDest = SRT_Table;
      }

      /* Make sure all SELECTs in the statement have the same number of elements
      ** in their result sets.
      */
      Debug.Assert( p.pEList != null && pPrior.pEList != null );
      if ( p.pEList.nExpr != pPrior.pEList.nExpr )
      {
        sqlite3ErrorMsg( pParse, "SELECTs to the left and right of %s" +
        " do not have the same number of result columns", selectOpName( p.op ) );
        rc = 1;
        goto multi_select_end;
      }

      /* Compound SELECTs that have an ORDER BY clause are handled separately.
      */
      if ( p.pOrderBy != null )
      {
        return multiSelectOrderBy( pParse, p, pDest );
      }

      /* Generate code for the left and right SELECT statements.
      */
      switch ( p.op )
      {
        case TK_ALL:
          {
            int addr = 0;
            int nLimit = 0;
            Debug.Assert( pPrior.pLimit == null );
            pPrior.pLimit = p.pLimit;
            pPrior.pOffset = p.pOffset;
            explainSetInteger( ref iSub1, pParse.iNextSelectId );
            rc = sqlite3Select( pParse, pPrior, ref dest );
            p.pLimit = null;
            p.pOffset = null;
            if ( rc != 0 )
            {
              goto multi_select_end;
            }
            p.pPrior = null;
            p.iLimit = pPrior.iLimit;
            p.iOffset = pPrior.iOffset;
            if ( p.iLimit != 0 )
            {
              addr = sqlite3VdbeAddOp1( v, OP_IfZero, p.iLimit );
#if SQLITE_DEBUG
              VdbeComment( v, "Jump ahead if LIMIT reached" );
#endif
            }
            explainSetInteger( ref iSub2, pParse.iNextSelectId );
            rc = sqlite3Select( pParse, p, ref dest );
            testcase( rc != SQLITE_OK );
            pDelete = p.pPrior;
            p.pPrior = pPrior;
            p.nSelectRow += pPrior.nSelectRow;
            if ( pPrior.pLimit != null
             && sqlite3ExprIsInteger( pPrior.pLimit, ref nLimit ) != 0
             && p.nSelectRow > (double)nLimit
            )
            {
              p.nSelectRow = (double)nLimit;
            }
            if ( addr != 0 )
            {
              sqlite3VdbeJumpHere( v, addr );
            }
            break;
          }
        case TK_EXCEPT:
        case TK_UNION:
          {
            int unionTab;    /* VdbeCursor number of the temporary table holding result */
            u8 op = 0;      /* One of the SRT_ operations to apply to self */
            int priorOp;     /* The SRT_ operation to apply to prior selects */
            Expr pLimit, pOffset; /* Saved values of p.nLimit and p.nOffset */
            int addr;
            SelectDest uniondest = new SelectDest();

            testcase( p.op == TK_EXCEPT );
            testcase( p.op == TK_UNION );
            priorOp = SRT_Union;
            if ( dest.eDest == priorOp && ALWAYS( null == p.pLimit && null == p.pOffset ) )
            {
              /* We can reuse a temporary table generated by a SELECT to our
              ** right.
              */
              Debug.Assert( p.pRightmost != p );  /* Can only happen for leftward elements
** of a 3-way or more compound */
              Debug.Assert( p.pLimit == null );      /* Not allowed on leftward elements */
              Debug.Assert( p.pOffset == null );     /* Not allowed on leftward elements */
              unionTab = dest.iParm;
            }
            else
            {
              /* We will need to create our own temporary table to hold the
              ** intermediate results.
              */
              unionTab = pParse.nTab++;
              Debug.Assert( p.pOrderBy == null );
              addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, unionTab, 0 );
              Debug.Assert( p.addrOpenEphm[0] == -1 );
              p.addrOpenEphm[0] = addr;
              p.pRightmost.selFlags |= SF_UsesEphemeral;
              Debug.Assert( p.pEList != null );
            }

            /* Code the SELECT statements to our left
            */
            Debug.Assert( pPrior.pOrderBy == null );
            sqlite3SelectDestInit( uniondest, priorOp, unionTab );
            explainSetInteger( ref iSub1, pParse.iNextSelectId );
            rc = sqlite3Select( pParse, pPrior, ref uniondest );
            if ( rc != 0 )
            {
              goto multi_select_end;
            }

            /* Code the current SELECT statement
            */
            if ( p.op == TK_EXCEPT )
            {
              op = SRT_Except;
            }
            else
            {
              Debug.Assert( p.op == TK_UNION );
              op = SRT_Union;
            }
            p.pPrior = null;
            pLimit = p.pLimit;
            p.pLimit = null;
            pOffset = p.pOffset;
            p.pOffset = null;
            uniondest.eDest = op;
            explainSetInteger( ref iSub2, pParse.iNextSelectId );
            rc = sqlite3Select( pParse, p, ref uniondest );
            testcase( rc != SQLITE_OK );
            /* Query flattening in sqlite3Select() might refill p.pOrderBy.
            ** Be sure to delete p.pOrderBy, therefore, to avoid a memory leak. */
            sqlite3ExprListDelete( db, ref p.pOrderBy );
            pDelete = p.pPrior;
            p.pPrior = pPrior;
            p.pOrderBy = null;
            if ( p.op == TK_UNION )
              p.nSelectRow += pPrior.nSelectRow;
            sqlite3ExprDelete( db, ref p.pLimit );
            p.pLimit = pLimit;
            p.pOffset = pOffset;
            p.iLimit = 0;
            p.iOffset = 0;

            /* Convert the data in the temporary table into whatever form
            ** it is that we currently need.
            */
            Debug.Assert( unionTab == dest.iParm || dest.eDest != priorOp );
            if ( dest.eDest != priorOp )
            {
              int iCont, iBreak, iStart;
              Debug.Assert( p.pEList != null );
              if ( dest.eDest == SRT_Output )
              {
                Select pFirst = p;
                while ( pFirst.pPrior != null )
                  pFirst = pFirst.pPrior;
                generateColumnNames( pParse, null, pFirst.pEList );
              }
              iBreak = sqlite3VdbeMakeLabel( v );
              iCont = sqlite3VdbeMakeLabel( v );
              computeLimitRegisters( pParse, p, iBreak );
              sqlite3VdbeAddOp2( v, OP_Rewind, unionTab, iBreak );
              iStart = sqlite3VdbeCurrentAddr( v );
              selectInnerLoop( pParse, p, p.pEList, unionTab, p.pEList.nExpr,
              null, -1, dest, iCont, iBreak );
              sqlite3VdbeResolveLabel( v, iCont );
              sqlite3VdbeAddOp2( v, OP_Next, unionTab, iStart );
              sqlite3VdbeResolveLabel( v, iBreak );
              sqlite3VdbeAddOp2( v, OP_Close, unionTab, 0 );
            }
            break;
          }
        default:
          Debug.Assert( p.op == TK_INTERSECT );
          {
            int tab1, tab2;
            int iCont, iBreak, iStart;
            Expr pLimit, pOffset;
            int addr;
            SelectDest intersectdest = new SelectDest();
            int r1;

            /* INTERSECT is different from the others since it requires
            ** two temporary tables.  Hence it has its own case.  Begin
            ** by allocating the tables we will need.
            */
            tab1 = pParse.nTab++;
            tab2 = pParse.nTab++;
            Debug.Assert( p.pOrderBy == null );

            addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, tab1, 0 );
            Debug.Assert( p.addrOpenEphm[0] == -1 );
            p.addrOpenEphm[0] = addr;
            p.pRightmost.selFlags |= SF_UsesEphemeral;
            Debug.Assert( p.pEList != null );

            /* Code the SELECTs to our left into temporary table "tab1".
            */
            sqlite3SelectDestInit( intersectdest, SRT_Union, tab1 );
            explainSetInteger( ref iSub1, pParse.iNextSelectId );
            rc = sqlite3Select( pParse, pPrior, ref intersectdest );
            if ( rc != 0 )
            {
              goto multi_select_end;
            }

            /* Code the current SELECT into temporary table "tab2"
            */
            addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, tab2, 0 );
            Debug.Assert( p.addrOpenEphm[1] == -1 );
            p.addrOpenEphm[1] = addr;
            p.pPrior = null;
            pLimit = p.pLimit;
            p.pLimit = null;
            pOffset = p.pOffset;
            p.pOffset = null;
            intersectdest.iParm = tab2;
            explainSetInteger( ref iSub2, pParse.iNextSelectId );
            rc = sqlite3Select( pParse, p, ref intersectdest );
            testcase( rc != SQLITE_OK );
            p.pPrior = pPrior;
            if ( p.nSelectRow > pPrior.nSelectRow )
              p.nSelectRow = pPrior.nSelectRow;
            sqlite3ExprDelete( db, ref p.pLimit );
            p.pLimit = pLimit;
            p.pOffset = pOffset;

            /* Generate code to take the intersection of the two temporary
            ** tables.
            */
            Debug.Assert( p.pEList != null );
            if ( dest.eDest == SRT_Output )
            {
              Select pFirst = p;
              while ( pFirst.pPrior != null )
                pFirst = pFirst.pPrior;
              generateColumnNames( pParse, null, pFirst.pEList );
            }
            iBreak = sqlite3VdbeMakeLabel( v );
            iCont = sqlite3VdbeMakeLabel( v );
            computeLimitRegisters( pParse, p, iBreak );
            sqlite3VdbeAddOp2( v, OP_Rewind, tab1, iBreak );
            r1 = sqlite3GetTempReg( pParse );
            iStart = sqlite3VdbeAddOp2( v, OP_RowKey, tab1, r1 );
            sqlite3VdbeAddOp4Int( v, OP_NotFound, tab2, iCont, r1, 0 );
            sqlite3ReleaseTempReg( pParse, r1 );
            selectInnerLoop( pParse, p, p.pEList, tab1, p.pEList.nExpr,
            null, -1, dest, iCont, iBreak );
            sqlite3VdbeResolveLabel( v, iCont );
            sqlite3VdbeAddOp2( v, OP_Next, tab1, iStart );
            sqlite3VdbeResolveLabel( v, iBreak );
            sqlite3VdbeAddOp2( v, OP_Close, tab2, 0 );
            sqlite3VdbeAddOp2( v, OP_Close, tab1, 0 );
            break;
          }
      }

      explainComposite( pParse, p.op, iSub1, iSub2, p.op != TK_ALL );

      /* Compute collating sequences used by
      ** temporary tables needed to implement the compound select.
      ** Attach the KeyInfo structure to all temporary tables.
      **
      ** This section is run by the right-most SELECT statement only.
      ** SELECT statements to the left always skip this part.  The right-most
      ** SELECT might also skip this part if it has no ORDER BY clause and
      ** no temp tables are required.
      */
      if ( ( p.selFlags & SF_UsesEphemeral ) != 0 )
      {
        int i;                        /* Loop counter */
        KeyInfo pKeyInfo;             /* Collating sequence for the result set */
        Select pLoop;                 /* For looping through SELECT statements */
        CollSeq apColl;               /* For looping through pKeyInfo.aColl[] */
        int nCol;                     /* Number of columns in result set */

        Debug.Assert( p.pRightmost == p );
        nCol = p.pEList.nExpr;
        pKeyInfo = new KeyInfo();           //sqlite3DbMallocZero(db,
        pKeyInfo.aColl = new CollSeq[nCol]; //sizeof(*pKeyInfo)+nCol*(CollSeq*.Length + 1));
        //if ( pKeyInfo == null )
        //{
        //  rc = SQLITE_NOMEM;
        //  goto multi_select_end;
        //}

        pKeyInfo.enc = db.aDbStatic[0].pSchema.enc;// ENC( pParse.db );
        pKeyInfo.nField = (u16)nCol;

        for ( i = 0; i < nCol; i++ )
        {//, apColl++){
          apColl = multiSelectCollSeq( pParse, p, i );
          if ( null == apColl )
          {
            apColl = db.pDfltColl;
          }
          pKeyInfo.aColl[i] = apColl;
        }

        for ( pLoop = p; pLoop != null; pLoop = pLoop.pPrior )
        {
          for ( i = 0; i < 2; i++ )
          {
            int addr = pLoop.addrOpenEphm[i];
            if ( addr < 0 )
            {
              /* If [0] is unused then [1] is also unused.  So we can
              ** always safely abort as soon as the first unused slot is found */
              Debug.Assert( pLoop.addrOpenEphm[1] < 0 );
              break;
            }
            sqlite3VdbeChangeP2( v, addr, nCol );
            sqlite3VdbeChangeP4( v, addr, pKeyInfo, P4_KEYINFO );
            pLoop.addrOpenEphm[i] = -1;
          }
        }
        sqlite3DbFree( db, ref pKeyInfo );
      }

multi_select_end:
      pDest.iMem = dest.iMem;
      pDest.nMem = dest.nMem;
      sqlite3SelectDelete( db, ref pDelete );
      return rc;
    }
示例#42
0
 //P4_KEYINFO
 static void sqlite3VdbeChangeP4( Vdbe p, int addr, KeyInfo pKeyInfo, int n )
 {
   union_p4 _p4 = new union_p4();
   _p4.pKeyInfo = pKeyInfo;
   sqlite3VdbeChangeP4( p, addr, _p4, n );
 }
示例#43
0
    /*
    ** Alternative compound select code generator for cases when there
    ** is an ORDER BY clause.
    **
    ** We assume a query of the following form:
    **
    **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
    **
    ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
    ** is to code both <selectA> and <selectB> with the ORDER BY clause as
    ** co-routines.  Then run the co-routines in parallel and merge the results
    ** into the output.  In addition to the two coroutines (called selectA and
    ** selectB) there are 7 subroutines:
    **
    **    outA:    Move the output of the selectA coroutine into the output
    **             of the compound query.
    **
    **    outB:    Move the output of the selectB coroutine into the output
    **             of the compound query.  (Only generated for UNION and
    **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
    **             appears only in B.)
    **
    **    AltB:    Called when there is data from both coroutines and A<B.
    **
    **    AeqB:    Called when there is data from both coroutines and A==B.
    **
    **    AgtB:    Called when there is data from both coroutines and A>B.
    **
    **    EofA:    Called when data is exhausted from selectA.
    **
    **    EofB:    Called when data is exhausted from selectB.
    **
    ** The implementation of the latter five subroutines depend on which
    ** <operator> is used:
    **
    **
    **             UNION ALL         UNION            EXCEPT          INTERSECT
    **          -------------  -----------------  --------------  -----------------
    **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
    **
    **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
    **
    **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
    **
    **   EofA:   outB, nextB      outB, nextB          halt             halt
    **
    **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
    **
    ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
    ** causes an immediate jump to EofA and an EOF on B following nextB causes
    ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
    ** following nextX causes a jump to the end of the select processing.
    **
    ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
    ** within the output subroutine.  The regPrev register set holds the previously
    ** output value.  A comparison is made against this value and the output
    ** is skipped if the next results would be the same as the previous.
    **
    ** The implementation plan is to implement the two coroutines and seven
    ** subroutines first, then put the control logic at the bottom.  Like this:
    **
    **          goto Init
    **     coA: coroutine for left query (A)
    **     coB: coroutine for right query (B)
    **    outA: output one row of A
    **    outB: output one row of B (UNION and UNION ALL only)
    **    EofA: ...
    **    EofB: ...
    **    AltB: ...
    **    AeqB: ...
    **    AgtB: ...
    **    Init: initialize coroutine registers
    **          yield coA
    **          if eof(A) goto EofA
    **          yield coB
    **          if eof(B) goto EofB
    **    Cmpr: Compare A, B
    **          Jump AltB, AeqB, AgtB
    **     End: ...
    **
    ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
    ** actually called using Gosub and they do not Return.  EofA and EofB loop
    ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
    ** and AgtB jump to either L2 or to one of EofA or EofB.
    */
#if !SQLITE_OMIT_COMPOUND_SELECT
    static int multiSelectOrderBy(
    Parse pParse,         /* Parsing context */
    Select p,             /* The right-most of SELECTs to be coded */
    SelectDest pDest      /* What to do with query results */
    )
    {
      int i, j;             /* Loop counters */
      Select pPrior;        /* Another SELECT immediately to our left */
      Vdbe v;               /* Generate code to this VDBE */
      SelectDest destA = new SelectDest();     /* Destination for coroutine A */
      SelectDest destB = new SelectDest();     /* Destination for coroutine B */
      int regAddrA;         /* Address register for select-A coroutine */
      int regEofA;          /* Flag to indicate when select-A is complete */
      int regAddrB;         /* Address register for select-B coroutine */
      int regEofB;          /* Flag to indicate when select-B is complete */
      int addrSelectA;      /* Address of the select-A coroutine */
      int addrSelectB;      /* Address of the select-B coroutine */
      int regOutA;          /* Address register for the output-A subroutine */
      int regOutB;          /* Address register for the output-B subroutine */
      int addrOutA;         /* Address of the output-A subroutine */
      int addrOutB = 0;     /* Address of the output-B subroutine */
      int addrEofA;         /* Address of the select-A-exhausted subroutine */
      int addrEofB;         /* Address of the select-B-exhausted subroutine */
      int addrAltB;         /* Address of the A<B subroutine */
      int addrAeqB;         /* Address of the A==B subroutine */
      int addrAgtB;         /* Address of the A>B subroutine */
      int regLimitA;        /* Limit register for select-A */
      int regLimitB;        /* Limit register for select-A */
      int regPrev;          /* A range of registers to hold previous output */
      int savedLimit;       /* Saved value of p.iLimit */
      int savedOffset;      /* Saved value of p.iOffset */
      int labelCmpr;        /* Label for the start of the merge algorithm */
      int labelEnd;         /* Label for the end of the overall SELECT stmt */
      int j1;               /* Jump instructions that get retargetted */
      int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
      KeyInfo pKeyDup = null;      /* Comparison information for duplicate removal */
      KeyInfo pKeyMerge;    /* Comparison information for merging rows */
      sqlite3 db;           /* Database connection */
      ExprList pOrderBy;    /* The ORDER BY clause */
      int nOrderBy;         /* Number of terms in the ORDER BY clause */
      int[] aPermute;       /* Mapping from ORDER BY terms to result set columns */
#if !SQLITE_OMIT_EXPLAIN
      int iSub1 = 0;            /* EQP id of left-hand query */
      int iSub2 = 0;            /* EQP id of right-hand query */
#endif

      Debug.Assert( p.pOrderBy != null );
      Debug.Assert( pKeyDup == null ); /* "Managed" code needs this.  Ticket #3382. */
      db = pParse.db;
      v = pParse.pVdbe;
      Debug.Assert( v != null );       /* Already thrown the error if VDBE alloc failed */
      labelEnd = sqlite3VdbeMakeLabel( v );
      labelCmpr = sqlite3VdbeMakeLabel( v );


      /* Patch up the ORDER BY clause
      */
      op = p.op;
      pPrior = p.pPrior;
      Debug.Assert( pPrior.pOrderBy == null );
      pOrderBy = p.pOrderBy;
      Debug.Assert( pOrderBy != null );
      nOrderBy = pOrderBy.nExpr;

      /* For operators other than UNION ALL we have to make sure that
      ** the ORDER BY clause covers every term of the result set.  Add
      ** terms to the ORDER BY clause as necessary.
      */
      if ( op != TK_ALL )
      {
        for ( i = 1; /* db.mallocFailed == 0 && */ i <= p.pEList.nExpr; i++ )
        {
          ExprList_item pItem;
          for ( j = 0; j < nOrderBy; j++ )//, pItem++)
          {
            pItem = pOrderBy.a[j];
            Debug.Assert( pItem.iCol > 0 );
            if ( pItem.iCol == i )
              break;
          }
          if ( j == nOrderBy )
          {
            Expr pNew = sqlite3Expr( db, TK_INTEGER, null );
            //if ( pNew == null )
            //  return SQLITE_NOMEM;
            pNew.flags |= EP_IntValue;
            pNew.u.iValue = i;
            pOrderBy = sqlite3ExprListAppend( pParse, pOrderBy, pNew );
            pOrderBy.a[nOrderBy++].iCol = (u16)i;
          }
        }
      }

      /* Compute the comparison permutation and keyinfo that is used with
      ** the permutation used to determine if the next
      ** row of results comes from selectA or selectB.  Also add explicit
      ** collations to the ORDER BY clause terms so that when the subqueries
      ** to the right and the left are evaluated, they use the correct
      ** collation.
      */
      aPermute = new int[nOrderBy];// sqlite3DbMallocRaw( db, sizeof( int ) * nOrderBy );
      if ( aPermute != null )
      {
        ExprList_item pItem;
        for ( i = 0; i < nOrderBy; i++ )//, pItem++)
        {
          pItem = pOrderBy.a[i];
          Debug.Assert( pItem.iCol > 0 && pItem.iCol <= p.pEList.nExpr );
          aPermute[i] = pItem.iCol - 1;
        }
        pKeyMerge = new KeyInfo();//      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq)+1));
        if ( pKeyMerge != null )
        {
          pKeyMerge.aColl = new CollSeq[nOrderBy];
          pKeyMerge.aSortOrder = new byte[nOrderBy];//(u8)&pKeyMerge.aColl[nOrderBy];
          pKeyMerge.nField = (u16)nOrderBy;
          pKeyMerge.enc = ENC( db );
          for ( i = 0; i < nOrderBy; i++ )
          {
            CollSeq pColl;
            Expr pTerm = pOrderBy.a[i].pExpr;
            if ( ( pTerm.flags & EP_ExpCollate ) != 0 )
            {
              pColl = pTerm.pColl;
            }
            else
            {
              pColl = multiSelectCollSeq( pParse, p, aPermute[i] );
              pTerm.flags |= EP_ExpCollate;
              pTerm.pColl = pColl;
            }
            pKeyMerge.aColl[i] = pColl;
            pKeyMerge.aSortOrder[i] = (byte)pOrderBy.a[i].sortOrder;
          }
        }
      }
      else
      {
        pKeyMerge = null;
      }

      /* Reattach the ORDER BY clause to the query.
      */
      p.pOrderBy = pOrderBy;
      pPrior.pOrderBy = sqlite3ExprListDup( pParse.db, pOrderBy, 0 );

      /* Allocate a range of temporary registers and the KeyInfo needed
      ** for the logic that removes duplicate result rows when the
      ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
      */
      if ( op == TK_ALL )
      {
        regPrev = 0;
      }
      else
      {
        int nExpr = p.pEList.nExpr;
        Debug.Assert( nOrderBy >= nExpr /*|| db.mallocFailed != 0 */ );
        regPrev = sqlite3GetTempRange( pParse, nExpr + 1 );
        sqlite3VdbeAddOp2( v, OP_Integer, 0, regPrev );
        pKeyDup = new KeyInfo();//sqlite3DbMallocZero(db,
        //sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq)+1) );
        if ( pKeyDup != null )
        {
          pKeyDup.aColl = new CollSeq[nExpr];
          pKeyDup.aSortOrder = new byte[nExpr];//(u8)&pKeyDup.aColl[nExpr];
          pKeyDup.nField = (u16)nExpr;
          pKeyDup.enc = ENC( db );
          for ( i = 0; i < nExpr; i++ )
          {
            pKeyDup.aColl[i] = multiSelectCollSeq( pParse, p, i );
            pKeyDup.aSortOrder[i] = 0;
          }
        }
      }

      /* Separate the left and the right query from one another
      */
      p.pPrior = null;
      sqlite3ResolveOrderGroupBy( pParse, p, p.pOrderBy, "ORDER" );
      if ( pPrior.pPrior == null )
      {
        sqlite3ResolveOrderGroupBy( pParse, pPrior, pPrior.pOrderBy, "ORDER" );
      }

      /* Compute the limit registers */
      computeLimitRegisters( pParse, p, labelEnd );
      if ( p.iLimit != 0 && op == TK_ALL )
      {
        regLimitA = ++pParse.nMem;
        regLimitB = ++pParse.nMem;
        sqlite3VdbeAddOp2( v, OP_Copy, ( p.iOffset != 0 ) ? p.iOffset + 1 : p.iLimit,
        regLimitA );
        sqlite3VdbeAddOp2( v, OP_Copy, regLimitA, regLimitB );
      }
      else
      {
        regLimitA = regLimitB = 0;
      }
      sqlite3ExprDelete( db, ref p.pLimit );
      p.pLimit = null;
      sqlite3ExprDelete( db, ref p.pOffset );
      p.pOffset = null;

      regAddrA = ++pParse.nMem;
      regEofA = ++pParse.nMem;
      regAddrB = ++pParse.nMem;
      regEofB = ++pParse.nMem;
      regOutA = ++pParse.nMem;
      regOutB = ++pParse.nMem;
      sqlite3SelectDestInit( destA, SRT_Coroutine, regAddrA );
      sqlite3SelectDestInit( destB, SRT_Coroutine, regAddrB );

      /* Jump past the various subroutines and coroutines to the main
      ** merge loop
      */
      j1 = sqlite3VdbeAddOp0( v, OP_Goto );
      addrSelectA = sqlite3VdbeCurrentAddr( v );


      /* Generate a coroutine to evaluate the SELECT statement to the
      ** left of the compound operator - the "A" select.
      */
      VdbeNoopComment( v, "Begin coroutine for left SELECT" );
      pPrior.iLimit = regLimitA;
      explainSetInteger( ref iSub1, pParse.iNextSelectId );
      sqlite3Select( pParse, pPrior, ref destA );
      sqlite3VdbeAddOp2( v, OP_Integer, 1, regEofA );
      sqlite3VdbeAddOp1( v, OP_Yield, regAddrA );
      VdbeNoopComment( v, "End coroutine for left SELECT" );

      /* Generate a coroutine to evaluate the SELECT statement on
      ** the right - the "B" select
      */
      addrSelectB = sqlite3VdbeCurrentAddr( v );
      VdbeNoopComment( v, "Begin coroutine for right SELECT" );
      savedLimit = p.iLimit;
      savedOffset = p.iOffset;
      p.iLimit = regLimitB;
      p.iOffset = 0;
      explainSetInteger( ref iSub2, pParse.iNextSelectId );
      sqlite3Select( pParse, p, ref destB );
      p.iLimit = savedLimit;
      p.iOffset = savedOffset;
      sqlite3VdbeAddOp2( v, OP_Integer, 1, regEofB );
      sqlite3VdbeAddOp1( v, OP_Yield, regAddrB );
      VdbeNoopComment( v, "End coroutine for right SELECT" );

      /* Generate a subroutine that outputs the current row of the A
      ** select as the next output row of the compound select.
      */
      VdbeNoopComment( v, "Output routine for A" );
      addrOutA = generateOutputSubroutine( pParse,
      p, destA, pDest, regOutA,
      regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd );

      /* Generate a subroutine that outputs the current row of the B
      ** select as the next output row of the compound select.
      */
      if ( op == TK_ALL || op == TK_UNION )
      {
        VdbeNoopComment( v, "Output routine for B" );
        addrOutB = generateOutputSubroutine( pParse,
        p, destB, pDest, regOutB,
        regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd );
      }

      /* Generate a subroutine to run when the results from select A
      ** are exhausted and only data in select B remains.
      */
      VdbeNoopComment( v, "eof-A subroutine" );
      if ( op == TK_EXCEPT || op == TK_INTERSECT )
      {
        addrEofA = sqlite3VdbeAddOp2( v, OP_Goto, 0, labelEnd );
      }
      else
      {
        addrEofA = sqlite3VdbeAddOp2( v, OP_If, regEofB, labelEnd );
        sqlite3VdbeAddOp2( v, OP_Gosub, regOutB, addrOutB );
        sqlite3VdbeAddOp1( v, OP_Yield, regAddrB );
        sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEofA );
        p.nSelectRow += pPrior.nSelectRow;
      }

      /* Generate a subroutine to run when the results from select B
      ** are exhausted and only data in select A remains.
      */
      if ( op == TK_INTERSECT )
      {
        addrEofB = addrEofA;
        if ( p.nSelectRow > pPrior.nSelectRow )
          p.nSelectRow = pPrior.nSelectRow;
      }
      else
      {
        VdbeNoopComment( v, "eof-B subroutine" );
        addrEofB = sqlite3VdbeAddOp2( v, OP_If, regEofA, labelEnd );
        sqlite3VdbeAddOp2( v, OP_Gosub, regOutA, addrOutA );
        sqlite3VdbeAddOp1( v, OP_Yield, regAddrA );
        sqlite3VdbeAddOp2( v, OP_Goto, 0, addrEofB );
      }

      /* Generate code to handle the case of A<B
      */
      VdbeNoopComment( v, "A-lt-B subroutine" );
      addrAltB = sqlite3VdbeAddOp2( v, OP_Gosub, regOutA, addrOutA );
      sqlite3VdbeAddOp1( v, OP_Yield, regAddrA );
      sqlite3VdbeAddOp2( v, OP_If, regEofA, addrEofA );
      sqlite3VdbeAddOp2( v, OP_Goto, 0, labelCmpr );

      /* Generate code to handle the case of A==B
      */
      if ( op == TK_ALL )
      {
        addrAeqB = addrAltB;
      }
      else if ( op == TK_INTERSECT )
      {
        addrAeqB = addrAltB;
        addrAltB++;
      }
      else
      {
        VdbeNoopComment( v, "A-eq-B subroutine" );
        addrAeqB =
        sqlite3VdbeAddOp1( v, OP_Yield, regAddrA );
        sqlite3VdbeAddOp2( v, OP_If, regEofA, addrEofA );
        sqlite3VdbeAddOp2( v, OP_Goto, 0, labelCmpr );
      }

      /* Generate code to handle the case of A>B
      */
      VdbeNoopComment( v, "A-gt-B subroutine" );
      addrAgtB = sqlite3VdbeCurrentAddr( v );
      if ( op == TK_ALL || op == TK_UNION )
      {
        sqlite3VdbeAddOp2( v, OP_Gosub, regOutB, addrOutB );
      }
      sqlite3VdbeAddOp1( v, OP_Yield, regAddrB );
      sqlite3VdbeAddOp2( v, OP_If, regEofB, addrEofB );
      sqlite3VdbeAddOp2( v, OP_Goto, 0, labelCmpr );

      /* This code runs once to initialize everything.
      */
      sqlite3VdbeJumpHere( v, j1 );
      sqlite3VdbeAddOp2( v, OP_Integer, 0, regEofA );
      sqlite3VdbeAddOp2( v, OP_Integer, 0, regEofB );
      sqlite3VdbeAddOp2( v, OP_Gosub, regAddrA, addrSelectA );
      sqlite3VdbeAddOp2( v, OP_Gosub, regAddrB, addrSelectB );
      sqlite3VdbeAddOp2( v, OP_If, regEofA, addrEofA );
      sqlite3VdbeAddOp2( v, OP_If, regEofB, addrEofB );

      /* Implement the main merge loop
      */
      sqlite3VdbeResolveLabel( v, labelCmpr );
      sqlite3VdbeAddOp4( v, OP_Permutation, 0, 0, 0, aPermute, P4_INTARRAY );
      sqlite3VdbeAddOp4( v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
      pKeyMerge, P4_KEYINFO_HANDOFF );
      sqlite3VdbeAddOp3( v, OP_Jump, addrAltB, addrAeqB, addrAgtB );

      /* Release temporary registers
      */
      if ( regPrev != 0 )
      {
        sqlite3ReleaseTempRange( pParse, regPrev, nOrderBy + 1 );
      }

      /* Jump to the this point in order to terminate the query.
      */
      sqlite3VdbeResolveLabel( v, labelEnd );

      /* Set the number of output columns
      */
      if ( pDest.eDest == SRT_Output )
      {
        Select pFirst = pPrior;
        while ( pFirst.pPrior != null )
          pFirst = pFirst.pPrior;
        generateColumnNames( pParse, null, pFirst.pEList );
      }

      /* Reassembly the compound query so that it will be freed correctly
      ** by the calling function */
      if ( p.pPrior != null )
      {
        sqlite3SelectDelete( db, ref p.pPrior );
      }
      p.pPrior = pPrior;

      /*** TBD:  Insert subroutine calls to close cursors on incomplete
      **** subqueries ****/
      explainComposite( pParse, p.op, iSub1, iSub2, false );
      return SQLITE_OK;
    }
示例#44
0
 //KeyInfo
 static int sqlite3VdbeAddOp4( Vdbe p, int op, int p1, int p2, int p3, KeyInfo pP4, int p4type )
 {
   union_p4 _p4 = new union_p4();
   _p4.pKeyInfo = pP4;
   int addr = sqlite3VdbeAddOp3( p, op, p1, p2, p3 );
   sqlite3VdbeChangeP4( p, addr, _p4, p4type );
   return addr;
 }
示例#45
0
 public static KeyValue Create(KeyInfo key, params object[] segmentValues)
 {
     if (key.Segments.Count != segmentValues.Length) {
         throw new ArgumentException();
     }
     return new KeyValue(key, segmentValues);
 }
示例#46
0
    //Vector3 ComputeInitialSwivelAngle(ArmInfo armInfo) {
    //    float theta;
    //    Vector3 u = new Vector3(1,0,0); //Local x axis
    //    Vector3 n = armInfo.wrist.position - armInfo.shoulder.position;
    //    Vector3 c =  HandleUtility.ProjectPointLine (armInfo.elbow.position, armInfo.shoulder.position, armInfo.wrist.position);
    //    Vector3 pcap = armInfo.elbow.position - c;
    //    Vector3 ptilda = pcap - Vector3.Dot (pcap, n) * n;
    //    theta = Mathf.Atan2(Vector3.Cross(pcap, u).magnitude , Vector3.Dot (ptilda,u));
    //    return new Vector3(theta,0,0);
    //}
    //ARminfo is passed as a transform because animation is sampled
    //We want the end effector position at the sampled time
    public void InitKeyPoints()
    {
        TorsoController torso = GetComponent<TorsoController>();
        ArmInfo[] arms = GetComponent<ArmController>().Arms;

        AssignGoalKeys();

        #if EDITORMODE

          // AnimationClipCurveData[] curveDatas = AnimationUtility.GetAllCurves(animation[animName].clip, true);
          // Keyframe[] frames = curveDatas[0].curve.keys;

        //AnimationCurve xCurve = AnimationUtility.GetEditorCurve(animation[animName].clip,"Hips/Spine/Spine1/RightShoulder/RightArm/RightForeArm/RightHand",typeof(Transform),"m_LocalRotation.x");
        //forearm keys are fewer in number, looks better with  EMOTE
        //AnimationCurve xCurve = AnimationUtility.GetEditorCurve(animation[AnimName].clip, "Hips/Spine/Spine1/RightShoulder/RightArm/RightForeArm", typeof(Transform), "m_LocalRotation.x");
        AnimationCurve xCurve = AnimationUtility.GetEditorCurve(animation[AnimName].clip, "Hips/Spine/Spine1/RightShoulder/RightArm", typeof(Transform), "m_LocalRotation.x");

          Keyframe[] frames = xCurve.keys;

          using (StreamWriter sw = new StreamWriter("keyframes_" + AnimName + ".txt")) {
          sw.WriteLine("MyKeyTimes = new float" + "[" + frames.Length + "];");
            foreach (Keyframe kf in frames) {
                sw.WriteLine("MyKeyTimes[i++]  = " + kf.time + "f; ");
            }
        }
          Debug.Log(AnimName);
        #elif !EDITORMODE

          		//file io does not work in web player
          /*      string[] content = File.ReadAllLines("keyframes.txt");
        MyKeyframe[] frames = new MyKeyframe[content.Length];

        for (int i = 0; i < content.Length; i++) {
            frames[i] = new MyKeyframe();
            frames[i].time = float.Parse(content[i]);

        }*/
        //Will write IO operations  later
          MyKeyframe[] frames = new MyKeyframe[MyKeyTimes.Length];
        for (int i = 0; i < MyKeyTimes.Length; i++) {
            frames[i] = new MyKeyframe();
            frames[i].Time = MyKeyTimes[i];
        }

        #endif
        animation.Play(AnimName);
        int goalKeyInd = 0;

        Keys = new KeyInfo[frames.Length ];

        for(int i = 0; i < frames.Length; i++) {
            animation[AnimName].enabled = true;

        animation[AnimName].time = frames[i].Time;

        animation.Sample ();
        Keys[i] = new KeyInfo();
        Keys[i].Time = animation[AnimName].time;

        //Keys[i].Time = animation[AnimName].length * i / (frames.Length - 1); //FUNDA : If we are using equally-spaced keys. We still sample from original frames, but we change key times.
        if(i == GoalKeys[goalKeyInd]) {
            Keys[i].IsGoal = true;
            goalKeyInd++;
        }
        else if(i < GoalKeys[goalKeyInd])
            Keys[i].IsGoal = false;

        if (Keys[i].FrameNo >= FrameCnt) {
            Keys[i].FrameNo = FrameCnt - 1;
        }

        //body chain and transformation arrays for the specific animation
        BodyChain = torso.BodyChainToArray(torso.Torso.Root);
        Keys[i].BodyPos = torso.BodyPosArr(BodyChain);
        Keys[i].BodyRot = torso.BodyRotArr(BodyChain);

           /*
        BodyChain = torso.BodyChain;
        Keys[i].BodyPos = torso.BodyPos;
        Keys[i].BodyRot = torso.BodyRot;
        */
        for(int arm = 0; arm < 2; arm++) {
            Keys[i].ShoulderPos[arm] = Keys[i].ShoulderPosOrig[arm] = arms[arm].Shoulder.position;
            Keys[i].EePos[arm] = Keys[i].EePosOrig[arm] = arms[arm].Wrist.position;
            Keys[i].ElbowRot[arm] = Keys[i].ElbowRotOrig[arm] = arms[arm].Elbow.localRotation;
            Keys[i].ElbowPos[arm] = Keys[i].ElbowPosOrig[arm] = arms[arm].Elbow.position;
        }
        }

        animation.Stop(AnimName);
        animation.enabled = false;
    }
示例#47
0
    //Gets only transform Keys
    public void InitKeyPoints()
    {
        ArmInfo[] arms = GetComponent<ArmController>().Arms;
        TorsoInfo torso = GetComponent<TorsoController>().Torso;
        #if EDITORMODE

        //Rotation x, y and z curves are the same, so one is enough
        //No keypoints defined for localTransform
        AnimationCurve xCurve = AnimationUtility.GetEditorCurve(animation[AnimName].clip,"Hips/Spine/Spine1/RightShoulder/RightArm/RightForeArm/RightHand",typeof(Transform),"m_LocalRotation.x");

        Keyframe[] frames = xCurve.keys;

         //Keyframe[] frames =animation[AnimName].;

        Keys = new KeyInfo[frames.Length];
         //all frames as Keys   Keys = new KeyInfo[frameCnt ];

        for(int i = 0; i < Keys.Length; i++) {

            animation[AnimName].time = frames[i].time;//(float) Keys[i].frameNo / animation[AnimName].clip.frameRate;
            //animation[AnimName].time = i/animation[AnimName].clip.frameRate;//(float) Keys[i].frameNo / animation[AnimName].clip.frameRate;
            animation.Sample ();
            Keys[i] = new KeyInfo();
            Keys[i].FrameNo  = Mathf.FloorToInt(animation[AnimName].time * animation[AnimName].clip.frameRate);
            Keys[i].Time = animation[AnimName].time;
            for(int arm = 0; arm < 2; arm++) {
                Keys[i].EePos[arm] = Keys[i].EePosOrig[arm] = arms[arm].Wrist.position;
            }

            Keys[i].ClavicleLRot = torso.ClavicleL.rotation;
            Keys[i].ClavicleRRot = torso.ClavicleR.rotation;
            Keys[i].NeckRot = torso.Neck.rotation;
            Keys[i].SpineRot = torso.Spine.rotation;
            Keys[i].Spine1Rot = torso.Spine1.rotation;
            Keys[i].ElbowLRot = torso.ElbowL.rotation;
            Keys[i].ElbowRRot = torso.ElbowR.rotation;

            Keys[i].ClavicleLPos = torso.ClavicleL.position;
            Keys[i].ClavicleRPos = torso.ClavicleR.position;
            Keys[i].NeckPos = torso.Neck.position;
            Keys[i].SpinePos = torso.Spine.position;
            Keys[i].Spine1Pos = torso.Spine1.position;
            Keys[i].ElbowLPos = torso.ElbowL.position;
            Keys[i].ElbowRPos = torso.ElbowR.position;

        }
        //Compute end effector velocity
        for(int i = 0; i < Keys.Length; i++) {
            for(int arm = 0; arm < 2; arm++) {
                if(i == 0)
                    Keys[0].EeVel[arm] = (Keys[1].EePos[arm] - Keys[0].EePos[arm]) / (Keys[1].Time - Keys[0].Time);
                else if(i == Keys.Length - 1)
                    Keys[Keys.Length - 1].EeVel[arm] = (Keys[Keys.Length - 1].EePos[arm] - Keys[Keys.Length - 2].EePos[arm]) / (Keys[Keys.Length - 1].Time - Keys[Keys.Length - 2].Time);
                else
                    Keys[i].EeVel[arm] = (Keys[i + 1].EePos[arm] - Keys[i - 1].EePos[arm]) / (Keys[i + 1].Time - Keys[i - 1].Time);

            }
        }

        //Compute end effector acceleration
         for(int i = 0; i < Keys.Length; i++) {
            for(int arm = 0; arm < 2; arm++) {
                if(i == 0)
                    Keys[0].EeAcc[arm] = (Keys[1].EeVel[arm] - Keys[0].EeVel[arm]) / (Keys[1].Time - Keys[0].Time);
                else if(i == Keys.Length - 1)
                    Keys[Keys.Length - 1].EeAcc[arm] = (Keys[Keys.Length - 1].EeVel[arm] - Keys[Keys.Length - 2].EeVel[arm]) / (Keys[Keys.Length - 1].Time - Keys[Keys.Length - 2].Time);
                else
                    Keys[i].EeAcc[arm] = (Keys[i + 1].EeVel[arm] - Keys[i - 1].EeVel[arm]) / (Keys[i + 1].Time - Keys[i - 1].Time);

            }
        }

        #endif
    }
 private static IList <KeyValue> MakeIntValue(int value, KeyInfo type)
 {
     return(new List <KeyValue> {
         new KeyValue(value, type)
     });
 }
示例#49
0
        /// <summary>
        /// Return the key object
        /// </summary>
        /// <param name="rootfiles"></param>
        /// <param name="treename"></param>
        /// <param name="inputObjects"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public IQueryResultCacheKey GetKey(Uri[] unsortedRootfiles, string treename, object[] inputObjects,
                                           string[] unsortedCrumbs,
                                           QueryModel query,
                                           bool recheckDates = false,
                                           Func <Uri, DateTime> dateChecker = null)
        {
            ///
            /// Quick check to make sure everything is good
            ///

            TraceHelpers.TraceInfo(23, "GetKey: Initial query calculation");
            if (unsortedRootfiles.Any(f => f == null))
            {
                throw new ArgumentException("one of the root files is null");
            }
            if (string.IsNullOrWhiteSpace(treename))
            {
                throw new ArgumentException("tree name must be valid");
            }
            if (inputObjects != null && inputObjects.Any(o => o == null))
            {
                throw new ArgumentException("one of the input objects is null - not allowed");
            }

            ///
            /// Build the hash, which is a bit of a pain in the butt.
            /// For the root files we don't care about the order given to us in or the order they
            /// are processed in. What we care about is what is there!
            ///

            var rootfiles = (from r in unsortedRootfiles
                             orderby r.OriginalString ascending
                             select r).ToArray();

            TraceHelpers.TraceInfo(24, "GetKey: Creating big string file name and calculating hash");
            int           fnameLength    = rootfiles.Select(f => f.OriginalString).Sum(w => w.Length) + 100;
            StringBuilder fullSourceName = new StringBuilder(fnameLength);

            foreach (var f in rootfiles)
            {
                fullSourceName.Append(f.OriginalString);
            }

            var fileHash = fullSourceName.ToString().GetHashCode();

            //
            // Next, the crumbs. They should also be sorted in order, and we will need
            // a hash code for them too.
            //

            string[] crumbs    = null;
            int      crumbHash = 0;

            if (unsortedCrumbs == null)
            {
                crumbs = new string[0];
            }
            else
            {
                crumbs = (from c in unsortedCrumbs orderby c select c).Distinct().ToArray();
                StringBuilder crumbString = new StringBuilder();
                foreach (var c in crumbs)
                {
                    crumbString.Append(c);
                }
                crumbHash = crumbString.ToString().GetHashCode();
            }

            ///
            /// Save the names of the files for a descriptor we will write out.
            ///

            KeyInfo result = new KeyInfo();

            TraceHelpers.TraceInfo(25, "GetKey: Saving description lines");
            result.DescriptionLines = (from f in rootfiles
                                       select f.OriginalString).ToArray();
            result.ExtraQueryInfoLines = crumbs;

            ///
            /// Text for the query. There are strings like "generated_x" where x is a number. These get incremented each time they are used,
            /// so to protect the caching we need to swap those out with a dummy.
            ///

            TraceHelpers.TraceInfo(26, "GetKey: Pretty printing the query");
            result.QueryText = FormattingQueryVisitor.Format(query);
            result.QueryText = result.QueryText.SwapOutWithUninqueString("\\<generated\\>_[0-9]+");

            ///
            /// And the directory name - we use the first name of the file.
            ///

            TraceHelpers.TraceInfo(27, "GetKey: Getting the cache directory");
            var fpathName = Path.GetFileNameWithoutExtension(rootfiles[0].PathAndQuery.SanitizedPathName(100));

            result.CacheDirectory = new DirectoryInfo(CacheDirectory.FullName + "\\" + fileHash + " - " + treename + "-" + fpathName);

            ///
            /// Scan the files that we are input and find the oldest one there
            ///

            TraceHelpers.TraceInfo(28, "GetKey: calculating the most recent file dates");
            result.OldestSourceFileDate = GetRecentFileDates(rootfiles, recheckDates, dateChecker).Max();

            ///
            /// And now the file that the query should be cached in
            ///

            TraceHelpers.TraceInfo(29, "GetKey: Calculating query hash");
            var queryHash = result.QueryText.GetHashCode();

            TraceHelpers.TraceInfo(30, "GetKey: Calculating the input object hash");
            var    inputObjectHash = CalcObjectHash(inputObjects);
            string queryNameBase   = string.Format(@"\\query {0}-inp{1}-crm{2}", queryHash.ToString(), inputObjectHash, crumbHash);

            result.RootFile = new FileInfo(result.CacheDirectory.FullName + queryNameBase + "_%%CYCLE%%.root");

            // And a complete unique hash string.
            result.UniqueHashString = $"files{fileHash.ToString()}-query{queryHash.ToString()}-objs{inputObjectHash}-crm{crumbHash}";

            TraceHelpers.TraceInfo(31, "GetKey: Done");
            return(result);
        }
示例#50
0
 public static KeyValue MaximumComplement(KeyInfo key, params object[] segmentValues)
 {
     return new KeyValue(key, segmentValues, false);
 }
 private static IList <KeyValue> MakeStringValue(string value, KeyInfo type)
 {
     return(new List <KeyValue> {
         new KeyValue(value, type)
     });
 }
示例#52
0
        /// <summary>
        /// Computes the key info dictionary for the column metadata of the
        /// given data reader.
        /// </summary>
        /// <remarks>
        /// Depending upon the column metadata already present in the data
        /// reader, it may be required to perform further access to the
        /// originating data source using the reader's
        /// <c>OriginatingConnection</c>.  This in turn implies that the
        /// <c>OriginatingConnection</c> must be open and must still
        /// represent the originating session on the originating data source;
        /// otherwise, the reported key info may be incorrect or the attempt
        /// access the data source may simply fail.
        /// </remarks>
        /// <param name="reader">
        /// The reader for which to compute the column metadata key info map.
        /// </param>
        /// <returns>
        /// Map {ColumnIdentifier=&gt;KeyInfo}
        /// </returns>
        /// <exception cref="HsqlDataSourceException">
        /// If a data access error occurs.
        /// </exception>
        internal static Dictionary <ColumnIdentifier, KeyInfo> GetKeyInfo(
            HsqlDataReader reader)
        {
            ResultMetaData metaData = reader.m_result.metaData;
            Dictionary <TableIdentifier, object> tableSet
                = new Dictionary <TableIdentifier, object>();
            object placeholder = new object();

            string[] schemaNames = metaData.schemaNames;
            string[] tableNames  = metaData.tableNames;
            string[] columnNames = metaData.colNames;
            int      count       = columnNames.Length;

            for (int i = 0; i < count; i++)
            {
                string tableName  = tableNames[i];
                string columnName = columnNames[i];

                if (string.IsNullOrEmpty(tableName) ||
                    string.IsNullOrEmpty(columnName))
                {   // not a table column
                    continue;
                }

                string          schemaName      = schemaNames[i];
                TableIdentifier tableIdentifier = new TableIdentifier(
                    schemaName, tableName);

                tableSet[tableIdentifier] = placeholder;
            }

            Dictionary <ColumnIdentifier, KeyInfo> columnMap
                = new Dictionary <ColumnIdentifier, KeyInfo>();

            if (tableSet.Count == 0)
            {
                return(columnMap);
            }

            StringBuilder sb = new StringBuilder('(');

            count = 0;

            foreach (TableIdentifier tableIdentifier in tableSet.Keys)
            {
                if (count > 0)
                {
                    sb.Append(" OR ");
                }

                count++;

                sb.Append("(bri.table_schem");

                string schemaName = tableIdentifier.m_schema;

                if (string.IsNullOrEmpty(schemaName))
                {
                    sb.Append(" IS NULL ");
                }
                else
                {
                    sb.Append(" = ").Append(StringConverter.toQuotedString(
                                                schemaName, '\'', /*escape inner quotes*/ true));
                }

                string tableName = tableIdentifier.m_table;

                sb.Append(" AND bri.table_name = ").Append(
                    StringConverter.toQuotedString(tableName, '\'',
                                                   /*escape inner quotes*/ true));

                sb.Append(')');
            }

            sb.Append(')');

            string predicate = sb.ToString();

            using (HsqlCommand command =
                       reader.OriginatingConnection.CreateCommand())
            {
                command.CommandText = string.Format(KeyInfoQuery, predicate);
                command.CommandType = CommandType.Text;

                using (HsqlDataReader keyInfoReader = command.ExecuteReader())
                {
                    while (keyInfoReader.Read())
                    {
                        bool isKey = keyInfoReader.GetBoolean(3);

                        if (!isKey)
                        {
                            continue;
                        }

                        string schema = keyInfoReader.GetString(0);
                        string table  = keyInfoReader.GetString(1);
                        string column = keyInfoReader.GetString(2);

                        ColumnIdentifier key = new ColumnIdentifier(schema,
                                                                    table, column);

                        if (!columnMap.ContainsKey(key))
                        {
                            KeyInfo keyInfo = new KeyInfo();

                            keyInfo.m_isKey    = true;
                            keyInfo.m_isUnique = false;

                            columnMap.Add(key, keyInfo);
                        }
                    }
                }
            }

            return(columnMap);
        }
示例#53
0
        /*
        ** Generate code to do an analysis of all indices associated with
        ** a single table.
        */
        static void analyzeOneTable(
            Parse pParse, /* Parser context */
            Table pTab,   /* Table whose indices are to be analyzed */
            int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
            int iMem      /* Available memory locations begin here */
            )
        {
            Index pIdx;      /* An index to being analyzed */
            int   iIdxCur;   /* Index of VdbeCursor for index being analyzed */
            int   nCol;      /* Number of columns in the index */
            Vdbe  v;         /* The virtual machine being built up */
            int   i;         /* Loop counter */
            int   topOfLoop; /* The top of the loop */
            int   endOfLoop; /* The end of the loop */
            int   addr;      /* The address of an instruction */
            int   iDb;       /* Index of database containing pTab */

            v = sqlite3GetVdbe(pParse);
            if (v == null || NEVER(pTab == null) || pTab.pIndex == null)
            {
                /* Do no analysis for tables that have no indices */
                return;
            }
            Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
            iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
            Debug.Assert(iDb >= 0);
#if !SQLITE_OMIT_AUTHORIZATION
            if (sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0,
                                 pParse.db.aDb[iDb].zName))
            {
                return;
            }
#endif

            /* Establish a read-lock on the table at the shared-cache level. */
            sqlite3TableLock(pParse, iDb, pTab.tnum, 0, pTab.zName);

            iIdxCur = pParse.nTab++;
            for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext)
            {
                KeyInfo pKey = sqlite3IndexKeyinfo(pParse, pIdx);
                int     regFields; /* Register block for building records */
                int     regRec;    /* Register holding completed record */
                int     regTemp;   /* Temporary use register */
                int     regCol;    /* Content of a column from the table being analyzed */
                int     regRowid;  /* Rowid for the inserted record */
                int     regF2;

                /* Open a cursor to the index to be analyzed
                 */
                Debug.Assert(iDb == sqlite3SchemaToIndex(pParse.db, pIdx.pSchema));
                nCol = pIdx.nColumn;
                sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb,
                                  pKey, P4_KEYINFO_HANDOFF);
#if SQLITE_DEBUG
                VdbeComment(v, "%s", pIdx.zName);
#endif
                regFields = iMem + nCol * 2;
                regTemp   = regRowid = regCol = regFields + 3;
                regRec    = regCol + 1;
                if (regRec > pParse.nMem)
                {
                    pParse.nMem = regRec;
                }

                /* Memory cells are used as follows:
                **
                **    mem[iMem]:             The total number of rows in the table.
                **    mem[iMem+1]:           Number of distinct values in column 1
                **    ...
                **    mem[iMem+nCol]:        Number of distinct values in column N
                **    mem[iMem+nCol+1]       Last observed value of column 1
                **    ...
                **    mem[iMem+nCol+nCol]:   Last observed value of column N
                **
                ** Cells iMem through iMem+nCol are initialized to 0.  The others
                ** are initialized to NULL.
                */
                for (i = 0; i <= nCol; i++)
                {
                    sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem + i);
                }
                for (i = 0; i < nCol; i++)
                {
                    sqlite3VdbeAddOp2(v, OP_Null, 0, iMem + nCol + i + 1);
                }

                /* Do the analysis.
                 */
                endOfLoop = sqlite3VdbeMakeLabel(v);
                sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
                topOfLoop = sqlite3VdbeCurrentAddr(v);
                sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
                for (i = 0; i < nCol; i++)
                {
                    sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
                    sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem + nCol + i + 1);
                    /**** TODO:  add collating sequence *****/
                    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
                }
                sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
                for (i = 0; i < nCol; i++)
                {
                    sqlite3VdbeJumpHere(v, topOfLoop + 2 * (i + 1));
                    sqlite3VdbeAddOp2(v, OP_AddImm, iMem + i + 1, 1);
                    sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem + nCol + i + 1);
                }
                sqlite3VdbeResolveLabel(v, endOfLoop);
                sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
                sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);

                /* Store the results.
                **
                ** The result is a single row of the sqlite_stat1 table.  The first
                ** two columns are the names of the table and index.  The third column
                ** is a string composed of a list of integer statistics about the
                ** index.  The first integer in the list is the total number of entries
                ** in the index.  There is one additional integer in the list for each
                ** column of the table.  This additional integer is a guess of how many
                ** rows of the table the index will select.  If D is the count of distinct
                ** values and K is the total number of rows, then the integer is computed
                ** as:
                **
                **        I = (K+D-1)/D
                **
                ** If K==0 then no entry is made into the sqlite_stat1 table.
                ** If K>0 then it is always the case the D>0 so division by zero
                ** is never possible.
                */
                addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
                sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab.zName, 0);
                sqlite3VdbeAddOp4(v, OP_String8, 0, regFields + 1, 0, pIdx.zName, 0);
                regF2 = regFields + 2;
                sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
                for (i = 0; i < nCol; i++)
                {
                    sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, ' ', 0);
                    sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
                    sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem + i + 1, regTemp);
                    sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
                    sqlite3VdbeAddOp3(v, OP_Divide, iMem + i + 1, regTemp, regTemp);
                    sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
                    sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
                }
                sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, new byte[] { (byte)'a', (byte)'a', (byte)'a' }, 0);
                sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
                sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
                sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
                sqlite3VdbeJumpHere(v, addr);
            }
        }
示例#54
0
    /*
** Generate code for scalar subqueries used as a subquery expression, EXISTS,
** or IN operators.  Examples:
**
**     (SELECT a FROM b)          -- subquery
**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
**     x IN (4,5,11)              -- IN operator with list on right-hand side
**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
**
** The pExpr parameter describes the expression that contains the IN
** operator or subquery.
**
** If parameter isRowid is non-zero, then expression pExpr is guaranteed
** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
** to some integer key column of a table B-Tree. In this case, use an
** intkey B-Tree to store the set of IN(...) values instead of the usual
** (slower) variable length keys B-Tree.
**
** If rMayHaveNull is non-zero, that means that the operation is an IN
** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
** Furthermore, the IN is in a WHERE clause and that we really want
** to iterate over the RHS of the IN operator in order to quickly locate
** all corresponding LHS elements.  All this routine does is initialize
** the register given by rMayHaveNull to NULL.  Calling routines will take
** care of changing this register value to non-NULL if the RHS is NULL-free.
**
** If rMayHaveNull is zero, that means that the subquery is being used
** for membership testing only.  There is no need to initialize any
** registers to indicate the presense or absence of NULLs on the RHS.
**
** For a SELECT or EXISTS operator, return the register that holds the
** result.  For IN operators or if an error occurs, the return value is 0.
*/
#if !SQLITE_OMIT_SUBQUERY
    static int sqlite3CodeSubselect(
    Parse pParse,          /* Parsing context */
    Expr pExpr,            /* The IN, SELECT, or EXISTS operator */
    int rMayHaveNull,      /* Register that records whether NULLs exist in RHS */
    bool isRowid           /* If true, LHS of IN operator is a rowid */
    )
    {
      int testAddr = 0;                       /* One-time test address */
      int rReg = 0;                           /* Register storing resulting */
      Vdbe v = sqlite3GetVdbe( pParse );
      if ( NEVER( v == null ) )
        return 0;
      sqlite3ExprCachePush( pParse );

      /* This code must be run in its entirety every time it is encountered
      ** if any of the following is true:
      **
      **    *  The right-hand side is a correlated subquery
      **    *  The right-hand side is an expression list containing variables
      **    *  We are inside a trigger
      **
      ** If all of the above are false, then we can run this code just once
      ** save the results, and reuse the same result on subsequent invocations.
      */
      if ( !ExprHasAnyProperty( pExpr, EP_VarSelect ) && null == pParse.pTriggerTab )
      {
        int mem = ++pParse.nMem;
        sqlite3VdbeAddOp1( v, OP_If, mem );
        testAddr = sqlite3VdbeAddOp2( v, OP_Integer, 1, mem );
        Debug.Assert( testAddr > 0 /* || pParse.db.mallocFailed != 0 */ );
      }

#if !SQLITE_OMIT_EXPLAIN
      if ( pParse.explain == 2 )
      {
        string zMsg = sqlite3MPrintf(
            pParse.db, "EXECUTE %s%s SUBQUERY %d", testAddr != 0 ? "" : "CORRELATED ",
            pExpr.op == TK_IN ? "LIST" : "SCALAR", pParse.iNextSelectId
        );
        sqlite3VdbeAddOp4( v, OP_Explain, pParse.iSelectId, 0, 0, zMsg, P4_DYNAMIC );
      }
#endif

      switch ( pExpr.op )
      {
        case TK_IN:
          {
            char affinity;              /* Affinity of the LHS of the IN */
            KeyInfo keyInfo;            /* Keyinfo for the generated table */
            int addr;                   /* Address of OP_OpenEphemeral instruction */
            Expr pLeft = pExpr.pLeft;   /* the LHS of the IN operator */

            if ( rMayHaveNull != 0 )
            {
              sqlite3VdbeAddOp2( v, OP_Null, 0, rMayHaveNull );
            }

            affinity = sqlite3ExprAffinity( pLeft );

            /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
            ** expression it is handled the same way. An ephemeral table is
            ** filled with single-field index keys representing the results
            ** from the SELECT or the <exprlist>.
            **
            ** If the 'x' expression is a column value, or the SELECT...
            ** statement returns a column value, then the affinity of that
            ** column is used to build the index keys. If both 'x' and the
            ** SELECT... statement are columns, then numeric affinity is used
            ** if either column has NUMERIC or INTEGER affinity. If neither
            ** 'x' nor the SELECT... statement are columns, then numeric affinity
            ** is used.
            */
            pExpr.iTable = pParse.nTab++;
            addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, (int)pExpr.iTable, !isRowid );
            if ( rMayHaveNull == 0 )
              sqlite3VdbeChangeP5( v, BTREE_UNORDERED );
            keyInfo = new KeyInfo();// memset( &keyInfo, 0, sizeof(keyInfo ));
            keyInfo.nField = 1;

            if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
            {
              /* Case 1:     expr IN (SELECT ...)
              **
              ** Generate code to write the results of the select into the temporary
              ** table allocated and opened above.
              */
              SelectDest dest = new SelectDest();
              ExprList pEList;

              Debug.Assert( !isRowid );
              sqlite3SelectDestInit( dest, SRT_Set, pExpr.iTable );
              dest.affinity = (char)affinity;
              Debug.Assert( ( pExpr.iTable & 0x0000FFFF ) == pExpr.iTable );
              pExpr.x.pSelect.iLimit = 0;
              if ( sqlite3Select( pParse, pExpr.x.pSelect, ref dest ) != 0 )
              {
                return 0;
              }
              pEList = pExpr.x.pSelect.pEList;
              if ( ALWAYS( pEList != null ) && pEList.nExpr > 0 )
              {
                keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq( pParse, pExpr.pLeft,
                pEList.a[0].pExpr );
              }
            }
            else if ( ALWAYS( pExpr.x.pList != null ) )
            {
              /* Case 2:     expr IN (exprlist)
              **
              ** For each expression, build an index key from the evaluation and
              ** store it in the temporary table. If <expr> is a column, then use
              ** that columns affinity when building index keys. If <expr> is not
              ** a column, use numeric affinity.
              */
              int i;
              ExprList pList = pExpr.x.pList;
              ExprList_item pItem;
              int r1, r2, r3;

              if ( affinity == '\0' )
              {
                affinity = SQLITE_AFF_NONE;
              }
              keyInfo.aColl[0] = sqlite3ExprCollSeq( pParse, pExpr.pLeft );

              /* Loop through each expression in <exprlist>. */
              r1 = sqlite3GetTempReg( pParse );
              r2 = sqlite3GetTempReg( pParse );
              sqlite3VdbeAddOp2( v, OP_Null, 0, r2 );
              for ( i = 0; i < pList.nExpr; i++ )
              {//, pItem++){
                pItem = pList.a[i];
                Expr pE2 = pItem.pExpr;
                int iValToIns = 0;

                /* If the expression is not constant then we will need to
                ** disable the test that was generated above that makes sure
                ** this code only executes once.  Because for a non-constant
                ** expression we need to rerun this code each time.
                */
                if ( testAddr != 0 && sqlite3ExprIsConstant( pE2 ) == 0 )
                {
                  sqlite3VdbeChangeToNoop( v, testAddr - 1, 2 );
                  testAddr = 0;
                }

                /* Evaluate the expression and insert it into the temp table */
                if ( isRowid && sqlite3ExprIsInteger( pE2, ref iValToIns ) != 0 )
                {
                  sqlite3VdbeAddOp3( v, OP_InsertInt, pExpr.iTable, r2, iValToIns );
                }
                else
                {
                  r3 = sqlite3ExprCodeTarget( pParse, pE2, r1 );
                  if ( isRowid )
                  {
                    sqlite3VdbeAddOp2( v, OP_MustBeInt, r3,
                                       sqlite3VdbeCurrentAddr( v ) + 2 );
                    sqlite3VdbeAddOp3( v, OP_Insert, pExpr.iTable, r2, r3 );
                  }
                  else
                  {
                    sqlite3VdbeAddOp4( v, OP_MakeRecord, r3, 1, r2, affinity, 1 );
                    sqlite3ExprCacheAffinityChange( pParse, r3, 1 );
                    sqlite3VdbeAddOp2( v, OP_IdxInsert, pExpr.iTable, r2 );
                  }
                }
              }
              sqlite3ReleaseTempReg( pParse, r1 );
              sqlite3ReleaseTempReg( pParse, r2 );
            }
            if ( !isRowid )
            {
              sqlite3VdbeChangeP4( v, addr, keyInfo, P4_KEYINFO );
            }
            break;
          }

        case TK_EXISTS:
        case TK_SELECT:
        default:
          {
            /* If this has to be a scalar SELECT.  Generate code to put the
            ** value of this select in a memory cell and record the number
            ** of the memory cell in iColumn.  If this is an EXISTS, write
            ** an integer 0 (not exists) or 1 (exists) into a memory cell
            ** and record that memory cell in iColumn.
            */
            Select pSel;                        /* SELECT statement to encode */
            SelectDest dest = new SelectDest(); /* How to deal with SELECt result */

            testcase( pExpr.op == TK_EXISTS );
            testcase( pExpr.op == TK_SELECT );
            Debug.Assert( pExpr.op == TK_EXISTS || pExpr.op == TK_SELECT );

            Debug.Assert( ExprHasProperty( pExpr, EP_xIsSelect ) );
            pSel = pExpr.x.pSelect;
            sqlite3SelectDestInit( dest, 0, ++pParse.nMem );
            if ( pExpr.op == TK_SELECT )
            {
              dest.eDest = SRT_Mem;
              sqlite3VdbeAddOp2( v, OP_Null, 0, dest.iParm );
#if SQLITE_DEBUG
              VdbeComment( v, "Init subquery result" );
#endif
            }
            else
            {
              dest.eDest = SRT_Exists;
              sqlite3VdbeAddOp2( v, OP_Integer, 0, dest.iParm );
#if SQLITE_DEBUG
              VdbeComment( v, "Init EXISTS result" );
#endif
            }
            sqlite3ExprDelete( pParse.db, ref pSel.pLimit );
            pSel.pLimit = sqlite3PExpr( pParse, TK_INTEGER, null, null, sqlite3IntTokens[1] );
            pSel.iLimit = 0;
            if ( sqlite3Select( pParse, pSel, ref dest ) != 0 )
            {
              return 0;
            }
            rReg = dest.iParm;
            ExprSetIrreducible( pExpr );
            break;
          }
      }

      if ( testAddr != 0 )
      {
        sqlite3VdbeJumpHere( v, testAddr - 1 );
      }
      sqlite3ExprCachePop( pParse, 1 );

      return rReg;
    }
示例#55
0
        public virtual void Run(IConsoleWindow window)
        {
            _statusList.Enqueue("Press ? for Help.");

            IsRunning = true;

            new SpawnEnemiesCommand().Execute(this);
            new SpawnItemsCommand().Execute(this);

            while (IsRunning)
            {
                Console.CursorVisible = false;

                var mapWidth  = window.Area.Width * 2 / 3;
                var mapHeight = window.Area.Height - 1;

                var mapArea = window.CreateConsoleArea(new Area(new Position(0, 1), new Size(mapWidth, mapHeight)));
                mapArea.Clear();
                _renderer.Render(this, mapArea);

                var playerArea = window.CreateConsoleArea(new Area(
                                                              new Position(mapWidth, 1),
                                                              new Size(window.Area.Width - mapWidth, mapHeight)));
                playerArea.Clear();
                _playerRenderer.Render(this, playerArea);


                var statusArea = window.CreateConsoleArea(new Area(Position.Zero, new Size(window.Area.Width, 1)));
                statusArea.Clear();
                while (_statusList.Any())
                {
                    statusArea.Clear();
                    var status = _statusList.Dequeue();
                    if (_statusList.Any())
                    {
                        status += " <more>";
                    }
                    statusArea.Write(Position.Zero, status);
                    window.Render();
                    if (_statusList.Any())
                    {
                        KeyInfo.GetInput();
                    }
                }

                window.Render();

                _commandFactory.Execute(this, KeyInfo.GetInput());

                if (_characters.Count != 0)
                {
                    continue;
                }

                IsRunning = false;
                window.Clear();
                window.Write(Position.Zero, "All your enemies are dead. Congratulations!");
                window.Write(new Position(0, 1), "You are the only one left on earth.");
                window.Render();
            }
        }
示例#56
0
    /*
** Code an output subroutine for a coroutine implementation of a
** SELECT statment.
**
** The data to be output is contained in pIn.iMem.  There are
** pIn.nMem columns to be output.  pDest is where the output should
** be sent.
**
** regReturn is the number of the register holding the subroutine
** return address.
**
** If regPrev>0 then it is the first register in a vector that
** records the previous output.  mem[regPrev] is a flag that is false
** if there has been no previous output.  If regPrev>0 then code is
** generated to suppress duplicates.  pKeyInfo is used for comparing
** keys.
**
** If the LIMIT found in p.iLimit is reached, jump immediately to
** iBreak.
*/
    static int generateOutputSubroutine(
    Parse pParse,          /* Parsing context */
    Select p,              /* The SELECT statement */
    SelectDest pIn,        /* Coroutine supplying data */
    SelectDest pDest,      /* Where to send the data */
    int regReturn,         /* The return address register */
    int regPrev,           /* Previous result register.  No uniqueness if 0 */
    KeyInfo pKeyInfo,      /* For comparing with previous entry */
    int p4type,            /* The p4 type for pKeyInfo */
    int iBreak             /* Jump here if we hit the LIMIT */
    )
    {
      Vdbe v = pParse.pVdbe;
      int iContinue;
      int addr;

      addr = sqlite3VdbeCurrentAddr( v );
      iContinue = sqlite3VdbeMakeLabel( v );

      /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
      */
      if ( regPrev != 0 )
      {
        int j1, j2;
        j1 = sqlite3VdbeAddOp1( v, OP_IfNot, regPrev );
        j2 = sqlite3VdbeAddOp4( v, OP_Compare, pIn.iMem, regPrev + 1, pIn.nMem,
        pKeyInfo, p4type );
        sqlite3VdbeAddOp3( v, OP_Jump, j2 + 2, iContinue, j2 + 2 );
        sqlite3VdbeJumpHere( v, j1 );
        sqlite3ExprCodeCopy( pParse, pIn.iMem, regPrev + 1, pIn.nMem );
        sqlite3VdbeAddOp2( v, OP_Integer, 1, regPrev );
      }
      //if ( pParse.db.mallocFailed != 0 ) return 0;

      /* Suppress the the first OFFSET entries if there is an OFFSET clause
      */
      codeOffset( v, p, iContinue );

      switch ( pDest.eDest )
      {
        /* Store the result as data using a unique key.
        */
        case SRT_Table:
        case SRT_EphemTab:
          {
            int r1 = sqlite3GetTempReg( pParse );
            int r2 = sqlite3GetTempReg( pParse );
            testcase( pDest.eDest == SRT_Table );
            testcase( pDest.eDest == SRT_EphemTab );
            sqlite3VdbeAddOp3( v, OP_MakeRecord, pIn.iMem, pIn.nMem, r1 );
            sqlite3VdbeAddOp2( v, OP_NewRowid, pDest.iParm, r2 );
            sqlite3VdbeAddOp3( v, OP_Insert, pDest.iParm, r1, r2 );
            sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
            sqlite3ReleaseTempReg( pParse, r2 );
            sqlite3ReleaseTempReg( pParse, r1 );
            break;
          }

#if !SQLITE_OMIT_SUBQUERY
        /* If we are creating a set for an "expr IN (SELECT ...)" construct,
** then there should be a single item on the stack.  Write this
** item into the set table with bogus data.
*/
        case SRT_Set:
          {
            int r1;
            Debug.Assert( pIn.nMem == 1 );
            p.affinity =
            sqlite3CompareAffinity( p.pEList.a[0].pExpr, pDest.affinity );
            r1 = sqlite3GetTempReg( pParse );
            sqlite3VdbeAddOp4( v, OP_MakeRecord, pIn.iMem, 1, r1, p.affinity, 1 );
            sqlite3ExprCacheAffinityChange( pParse, pIn.iMem, 1 );
            sqlite3VdbeAddOp2( v, OP_IdxInsert, pDest.iParm, r1 );
            sqlite3ReleaseTempReg( pParse, r1 );
            break;
          }

#if FALSE  //* Never occurs on an ORDER BY query */
/* If any row exist in the result set, record that fact and abort.
*/
case SRT_Exists: {
sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest.iParm);
/* The LIMIT clause will terminate the loop for us */
break;
}
#endif

        /* If this is a scalar select that is part of an expression, then
** store the results in the appropriate memory cell and break out
** of the scan loop.
*/
        case SRT_Mem:
          {
            Debug.Assert( pIn.nMem == 1 );
            sqlite3ExprCodeMove( pParse, pIn.iMem, pDest.iParm, 1 );
            /* The LIMIT clause will jump out of the loop for us */
            break;
          }
#endif //* #if !SQLITE_OMIT_SUBQUERY */

        /* The results are stored in a sequence of registers
** starting at pDest.iMem.  Then the co-routine yields.
*/
        case SRT_Coroutine:
          {
            if ( pDest.iMem == 0 )
            {
              pDest.iMem = sqlite3GetTempRange( pParse, pIn.nMem );
              pDest.nMem = pIn.nMem;
            }
            sqlite3ExprCodeMove( pParse, pIn.iMem, pDest.iMem, pDest.nMem );
            sqlite3VdbeAddOp1( v, OP_Yield, pDest.iParm );
            break;
          }

        /* If none of the above, then the result destination must be
        ** SRT_Output.  This routine is never called with any other
        ** destination other than the ones handled above or SRT_Output.
        **
        ** For SRT_Output, results are stored in a sequence of registers.
        ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
        ** return the next row of result.
        */
        default:
          {
            Debug.Assert( pDest.eDest == SRT_Output );
            sqlite3VdbeAddOp2( v, OP_ResultRow, pIn.iMem, pIn.nMem );
            sqlite3ExprCacheAffinityChange( pParse, pIn.iMem, pIn.nMem );
            break;
          }
      }

      /* Jump to the end of the loop if the LIMIT is reached.
      */
      if ( p.iLimit != 0 )
      {
        sqlite3VdbeAddOp3( v, OP_IfZero, p.iLimit, iBreak, -1 );
      }

      /* Generate the subroutine return
      */
      sqlite3VdbeResolveLabel( v, iContinue );
      sqlite3VdbeAddOp1( v, OP_Return, regReturn );

      return addr;
    }
示例#57
0
        public XmlDocument SignXml(XmlDocument xmlDoc, byte[] pfx, RSA rsaKey, string claveCert)
        {
            // Check arguments.
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }
            if (rsaKey == null)
            {
                throw new ArgumentException("Key");
            }

            X509Certificate2         cert = new X509Certificate2(pfx, claveCert);
            RSACryptoServiceProvider Key  = cert.PrivateKey as RSACryptoServiceProvider;

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc)
            {
                SigningKey = Key
            };

            // Add the key to the SignedXml document.
            //signedXml.SigningKey = rsaKey;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            /* */
            KeyInfoX509Data kdata = new KeyInfoX509Data(cert);

            kdata.AddIssuerSerial(cert.Issuer, cert.SerialNumber);
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(kdata);
            signedXml.KeyInfo = keyInfo;
            /* */

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            /* 18.11.2016 - Se agrega prefijo ds a la firma digital */
            // Add prefix "ds:" to signature
            XmlElement signature = signedXml.GetXml();

            SetPrefix("ds", signature);

            // Load modified signature back
            signedXml.LoadXml(signature);

            // this is workaround for overcoming a bug in the library
            signedXml.SignedInfo.References.Clear();

            // Recompute the signature
            signedXml.ComputeSignature();
            string recomputedSignature = Convert.ToBase64String(signedXml.SignatureValue);

            // Replace value of the signature with recomputed one
            ReplaceSignature(signature, recomputedSignature);

            // Append the signature to the XML document.
            xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(signature, true), xmlDoc.DocumentElement.FirstChild);
            /*  */

            /*
             * // Get the XML representation of the signature and save
             * // it to an XmlElement object.
             * XmlElement xmlDigitalSignature = signedXml.GetXml();
             *
             * // Append the element to the XML document.
             * xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
             */

            return(xmlDoc);
        }
示例#58
0
    /*
    ** Given an expression list, generate a KeyInfo structure that records
    ** the collating sequence for each expression in that expression list.
    **
    ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
    ** KeyInfo structure is appropriate for initializing a virtual index to
    ** implement that clause.  If the ExprList is the result set of a SELECT
    ** then the KeyInfo structure is appropriate for initializing a virtual
    ** index to implement a DISTINCT test.
    **
    ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
    ** function is responsible for seeing that this structure is eventually
    ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
    ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
    */
    static KeyInfo keyInfoFromExprList( Parse pParse, ExprList pList )
    {
      sqlite3 db = pParse.db;
      int nExpr;
      KeyInfo pInfo;
      ExprList_item pItem;
      int i;

      nExpr = pList.nExpr;
      pInfo = new KeyInfo();//sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(CollSeq*.Length+1) );
      if ( pInfo != null )
      {
        pInfo.aSortOrder = new byte[nExpr];// pInfo.aColl[nExpr];
        pInfo.aColl = new CollSeq[nExpr];
        pInfo.nField = (u16)nExpr;
        pInfo.enc = db.aDbStatic[0].pSchema.enc;// ENC(db);
        pInfo.db = db;
        for ( i = 0; i < nExpr; i++ )
        {//, pItem++){
          pItem = pList.a[i];
          CollSeq pColl;
          pColl = sqlite3ExprCollSeq( pParse, pItem.pExpr );
          if ( pColl == null )
          {
            pColl = db.pDfltColl;
          }
          pInfo.aColl[i] = pColl;
          pInfo.aSortOrder[i] = (byte)pItem.sortOrder;
        }
      }
      return pInfo;
    }
示例#59
0
        /* TIA 102.AACD-A 3.8.7 */
        public List <RspKeyInfo> ViewKeyInfo()
        {
            List <RspKeyInfo> result = new List <RspKeyInfo>();

            Begin();

            try
            {
                bool more   = true;
                int  marker = 0;

                while (more)
                {
                    InventoryCommandListActiveKeys commandKmmBody = new InventoryCommandListActiveKeys();
                    commandKmmBody.InventoryMarker  = marker;
                    commandKmmBody.MaxKeysRequested = 78;

                    KmmBody responseKmmBody = TxRxKmm(commandKmmBody);

                    if (responseKmmBody is InventoryResponseListActiveKeys)
                    {
                        InventoryResponseListActiveKeys kmm = responseKmmBody as InventoryResponseListActiveKeys;

                        marker = kmm.InventoryMarker;

                        Logger.Debug("inventory marker: {0}", marker);

                        if (marker == 0)
                        {
                            more = false;
                        }

                        Logger.Debug("number of keys returned: {0}", kmm.Keys.Count);

                        for (int i = 0; i < kmm.Keys.Count; i++)
                        {
                            KeyInfo info = kmm.Keys[i];

                            Logger.Debug("* key index {0} *", i);
                            Logger.Debug("keyset id: {0} (dec), {0:X} (hex)", info.KeySetId);
                            Logger.Debug("sln: {0} (dec), {0:X} (hex)", info.SLN);
                            Logger.Debug("algorithm id: {0} (dec), {0:X} (hex)", info.AlgorithmId);
                            Logger.Debug("key id: {0} (dec), {0:X} (hex)", info.KeyId);

                            RspKeyInfo res = new RspKeyInfo();

                            res.KeysetId    = info.KeySetId;
                            res.Sln         = info.SLN;
                            res.AlgorithmId = info.AlgorithmId;
                            res.KeyId       = info.KeyId;

                            result.Add(res);
                        }
                    }
                    else if (responseKmmBody is NegativeAcknowledgment)
                    {
                        NegativeAcknowledgment kmm = responseKmmBody as NegativeAcknowledgment;

                        string statusDescr  = OperationStatusExtensions.ToStatusString(kmm.Status);
                        string statusReason = OperationStatusExtensions.ToReasonString(kmm.Status);
                        throw new Exception(string.Format("received negative acknowledgment{0}status: {1} (0x{2:X2}){0}{3}", Environment.NewLine, statusDescr, kmm.Status, statusReason));
                    }
                    else
                    {
                        throw new Exception("unexpected kmm");
                    }
                }
            }
            catch
            {
                End();

                throw;
            }

            End();

            return(result);
        }