Example #1
2
	static void Main(string[] args) {
		if (args.Length != 4) {
			Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path");
			return;
		}

		String certFile = args[0];
		String password = args[1];
		String input    = args[2];
		String output   = args[3];

		X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.Load(input);

		var XmlToSign = new XmlDocument();
  	XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml);

		SignedXml signedXml = new SignedXml(XmlToSign);
		signedXml.SigningKey = cert.PrivateKey;

		Reference reference = new Reference();
		reference.Uri = "";

    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);

		signedXml.AddReference(reference);
		signedXml.ComputeSignature();
		XmlElement xmlDigitalSignature = signedXml.GetXml();
		xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
		xmlDoc.Save(output);
	}
Example #2
2
        public override object EncodeCMS(X509Certificate2 certificate, string xmlFilePath)
        {
            XmlDocument Document = new XmlDocument();
            Document.PreserveWhitespace = true;
            XmlTextReader XmlFile = new XmlTextReader(xmlFilePath);
            Document.Load(XmlFile);
            XmlFile.Close();
            XmlNodeList SignaturesList = Document.GetElementsByTagName("Signature");
            // Remove existing signatures, this is not a countersigning.
            for (int i = 0; i < SignaturesList.Count; i++)
            {
                SignaturesList[i].ParentNode.RemoveChild(SignaturesList[i]);
                i--;
            }

            SignedXml SignedXml = new SignedXml(Document);
            SignedXml.SigningKey = certificate.PrivateKey;
            Reference Reference = new Reference();
            Reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform EnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
            Reference.AddTransform(EnvelopedSignatureTransform);
            SignedXml.AddReference(Reference);
            KeyInfo Key = new KeyInfo();
            Key.AddClause(new KeyInfoX509Data(certificate));
            SignedXml.KeyInfo = Key;
            SignedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement XmlDigitalSignature = SignedXml.GetXml();

            return XmlDigitalSignature;
        }
        private static string SignXml(XmlDocument unsignedXml,
                                        AsymmetricAlgorithm key)
        {
            if (unsignedXml.DocumentElement == null)
            {
                throw new ArgumentNullException("unsignedXml");
            }

            // Create a reference to be signed. Blank == Everything
                var emptyReference = new Reference { Uri = "" };

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

            var signedXml = new SignedXml(unsignedXml) { SigningKey = key };
            signedXml.AddReference(emptyReference);
            signedXml.ComputeSignature();

            var digitalSignature = signedXml.GetXml();
       
                unsignedXml.DocumentElement.AppendChild(
                    unsignedXml.ImportNode(digitalSignature, true));

            var signedXmlOut = new StringBuilder();
            using (var swOut = new StringWriter(signedXmlOut))
            {
                unsignedXml.Save(swOut);
            }

            return signedXmlOut.ToString();
        }
Example #4
1
        // Sign an XML file.  
        // This document cannot be verified unless the verifying  
        // code has the key with which it was signed. 
        public static void SignXml(XmlDocument xmlDoc, RSA Key)
        {
            // Check arguments. 
            if (xmlDoc == null)
                throw new ArgumentException("xmlDoc");
            if (Key == null)
                throw new ArgumentException("Key");

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

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

            // 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);

            // 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();

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
        public StartPage()
        {
            try
            {
                InitializeComponent();
                _dbConnectionString  = ConfigurationSettings.AppSettings["DBConStr"];

                DataAccess.conStr = _dbConnectionString;

                MainMenu _mainMenu = new MainMenu(_dbConnectionString);
                _mainFrame.Navigate(_mainMenu);
                dataAccess = new DataAccess();
                lines = dataAccess.getLines();
                lineQ = new Queue<int>();

                foreach (line l in lines)
                    lineQ.Enqueue(l.ID);

                reference = new Reference();

                andonManager = new AndonManager(AndonManager.MODE.SLAVE);                        
                
                andonManager.andonAlertEvent += new EventHandler<AndonAlertEventArgs>(andonManager_andonAlertEvent);

                andonManager.start();

            }

            catch( Exception e)
            {
                tbMsg.Text+= e.Message;
            }
        }
 internal void AddDependency(Reference dependency)
 {
     if (!this.dependencies.Contains(dependency))
     {
         this.dependencies.Add(dependency);
     }
 }
        protected void btnSaveRef_Click(object sender, EventArgs e)
        {
            Reference NewRef = new Reference();

            if (getCurrentReference > 0)
            {
                NewRef.LoadByPrimaryKey(getCurrentReference);
            }
            else
            {
                NewRef.AddNew();
            }
            if (CollImgFileUpload.HasFile)
            {
                Bitmap UpImg = (Bitmap)Bitmap.FromStream(CollImgFileUpload.PostedFile.InputStream);
                string path = "UploadedFiles/References/" + DateTime.Now.ToString("ddMMyyyyhhmmss") + CollImgFileUpload.FileName;
                UpImg.Save(MapPath(path), System.Drawing.Imaging.ImageFormat.Png);
                NewRef.MainImagePath = path;
            }

            NewRef.IsActive = chkActive.Checked;
            NewRef.NameAr = txtRefernceName.Text;
            NewRef.DescriptionAr = txtDescription.Text;
            NewRef.DescriptionEn = txtDescription.Text;
            NewRef.Save();

            Response.Redirect("ManageReference.aspx?refid=" + NewRef.ReferenceID.ToString());
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the Whitespace class.
        /// </summary>
        /// <param name="text">The whitespace text.</param>
        /// <param name="location">The location of the whitespace in the code.</param>
        /// <param name="parent">The parent code unit.</param>
        /// <param name="generated">True if the token is inside of a block of generated code.</param>
        internal Whitespace(
            string text,
            CodeLocation location,
            Reference<ICodePart> parent,
            bool generated)
            : base(text,
            CsTokenType.WhiteSpace,
            CsTokenClass.Whitespace,
            location,
            parent,
            generated)
        {
            Param.AssertValidString(text, "text");
            Param.AssertNotNull(location, "location");
            Param.AssertNotNull(parent, "parent");
            Param.Ignore(generated);

            for (int i = 0; i < text.Length; ++i)
            {
                if (text[i] == ' ')
                {
                    ++this.spaceCount;
                }
                else if (text[i] == '\t')
                {
                    ++this.tabCount;
                }
            }
        }
		public MethodWithInvocationGenerator(MetaMethod method, Reference interceptors, Type invocation, GetTargetExpressionDelegate getTargetExpression, CreateMethodDelegate createMethod)
			: base(method, createMethod)
		{
			this.interceptors = interceptors;
			this.getTargetExpression = getTargetExpression;
			this.invocation = invocation;
		}
        public ActionResult AddReference(Spell spell, Reference reference)
        {
            // Check if the user is logged in
            if (Request.IsAuthenticated)
            {
                // Validate reference
                if (true)
                {
                    // Add reference to spell
                    spell.BookReferences.Add(reference);

                    // Update spell in database
                    _spellService.UpdateSpell(spell);

                    // Send the user back to the details page to see their update
                    return RedirectToAction("Details", spell.Id);
                }
                else
                {
                    // If the reference is not valid,
                    // report it to the user
                    return View();
                }
            }

            return RedirectToAction("Index");
        }
		public InvocationWithGenericDelegateContributor(Type delegateType, MetaMethod method, Reference targetReference)
		{
			Debug.Assert(delegateType.GetTypeInfo().IsGenericType, "delegateType.IsGenericType");
			this.delegateType = delegateType;
			this.method = method;
			this.targetReference = targetReference;
		}
		public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, Expression[] args, Reference targetField, MethodEmitter invokeMethodOnTarget)
		{
			var allArgs = GetAllArgs(args, targetField);
			var @delegate = (Reference)invocation.GetField("delegate");

			return new MethodInvocationExpression(@delegate, GetCallbackMethod(), allArgs);
		}
		public MethodInvocationExpression GetCallbackMethodInvocation(AbstractTypeEmitter invocation, Expression[] args,
		                                                              Reference targetField,
		                                                              MethodEmitter invokeMethodOnTarget)
		{
			var @delegate = GetDelegate(invocation, invokeMethodOnTarget);
			return new MethodInvocationExpression(@delegate, GetCallbackMethod(), args);
		}
        public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert)
        {
            if(xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

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

            var signedXml = new SignedXml(xmlDocument);

            signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey;

            var reference = new Reference();
            reference.Uri = "";
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

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

            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signedXml.GetXml(), true));
        }
 public ConnectionRequestHandler(Reference @ref, Ice.ConnectionI connection, bool compress)
 {
     _reference = @ref;
     _response = _reference.getMode() == Reference.Mode.ModeTwoway;
     _connection = connection;
     _compress = compress;
 }
		// http://developers.facebook.com/docs/reference/api/Comment/
		public Comment(string id, Reference from, string message, DateTime createdTime)
		{
			this.ID          = id         ;
			this.From        = from       ;
			this.Message     = message    ;
			this.CreatedTime = createdTime;
		}
Example #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Immediate"/> class.
 /// </summary>
 /// <param name="reference">A reference.</param>
 public Immediate(Reference reference)
     : this(reference, DataSize.None)
 {
     #region Contract
     Contract.Requires<ArgumentNullException>(reference != null);
     #endregion
 }
 private static void AuthenticodeSignLicenseDom(XmlDocument licenseDom, System.Deployment.Internal.CodeSigning.CmiManifestSigner signer, string timeStampUrl)
 {
     if (signer.Certificate.PublicKey.Key.GetType() != typeof(RSACryptoServiceProvider))
     {
         throw new NotSupportedException();
     }
     System.Deployment.Internal.CodeSigning.ManifestSignedXml xml = new System.Deployment.Internal.CodeSigning.ManifestSignedXml(licenseDom) {
         SigningKey = signer.Certificate.PrivateKey
     };
     xml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
     xml.KeyInfo.AddClause(new RSAKeyValue(signer.Certificate.PublicKey.Key as RSA));
     xml.KeyInfo.AddClause(new KeyInfoX509Data(signer.Certificate, signer.IncludeOption));
     Reference reference = new Reference {
         Uri = ""
     };
     reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
     reference.AddTransform(new XmlDsigExcC14NTransform());
     xml.AddReference(reference);
     xml.ComputeSignature();
     XmlElement node = xml.GetXml();
     node.SetAttribute("Id", "AuthenticodeSignature");
     XmlNamespaceManager nsmgr = new XmlNamespaceManager(licenseDom.NameTable);
     nsmgr.AddNamespace("r", "urn:mpeg:mpeg21:2003:01-REL-R-NS");
     (licenseDom.SelectSingleNode("r:license/r:issuer", nsmgr) as XmlElement).AppendChild(licenseDom.ImportNode(node, true));
     if ((timeStampUrl != null) && (timeStampUrl.Length != 0))
     {
         TimestampSignedLicenseDom(licenseDom, timeStampUrl);
     }
     licenseDom.DocumentElement.ParentNode.InnerXml = "<msrel:RelData xmlns:msrel=\"http://schemas.microsoft.com/windows/rel/2005/reldata\">" + licenseDom.OuterXml + "</msrel:RelData>";
 }
Example #19
0
        public static void add_reference(Dictionary<string, Reference> refmap, Reference refer)
        {
            if (refmap.ContainsKey(refer.Label))
                return;

            refmap.Add(refer.Label, refer);
        }
Example #20
0
		internal Channel(DiscordClient client, string id, string serverId, string recipientId)
			: base(client, id)
		{
			_server = new Reference<Server>(serverId, 
				x => _client.Servers[x], 
				x => x.AddChannel(this), 
				x => x.RemoveChannel(this));
			_recipient = new Reference<User>(recipientId, 
				x => _client.Users.GetOrAdd(x, _server.Id), 
				x =>
				{
					Name = "@" + x.Name;
					if (_server.Id == null)
						x.GlobalUser.PrivateChannel = this;
				},
				x =>
				{
					if (_server.Id == null)
						x.GlobalUser.PrivateChannel = null;
                });
			_permissionOverwrites = _initialPermissionsOverwrites;
			_areMembersStale = true;

			//Local Cache
			_messages = new ConcurrentDictionary<string, Message>();
		}
        public ListsStorageActions(TableStorage tableStorage, IUuidGenerator generator, Reference<SnapshotReader> snapshot, Reference<WriteBatch> writeBatch, IBufferPool bufferPool)
			: base(snapshot, bufferPool)
		{
			this.tableStorage = tableStorage;
			this.generator = generator;
			this.writeBatch = writeBatch;
		}
Example #22
0
        public void ConstructorTest()
        {
            Reference r = new Reference();

            Assert.IsNotNull(r);
            Assert.IsTrue(r.IsTransient());
        }
Example #23
0
		public Post(string id, Reference from, DateTime createdTime, DateTime updatedTime)
		{
			this.ID          = id;
			this.From        = from;
			this.CreatedTime = createdTime;
			this.UpdatedTime = updatedTime;
		}
        // load the treeView
        private void buildTree(TreeNode parentNode, Reference childReference)
        {
            // Query for the children of the reference
            QueryResult result = this.repoService.queryChildren(childReference);
            if (result.resultSet.rows != null)
            {
                foreach (ResultSetRow row in result.resultSet.rows)
                {
                    // only interested in folders
                    if (row.node.type.Contains("folder") == true)
                    {
                        foreach (NamedValue namedValue in row.columns)
                        {
                            if (namedValue.name.Contains("name") == true)
                            {
                                // add a node to the tree view
                                TreeNode node = this.addChildNode(parentNode, namedValue.value, row.node);

                                // Create the reference for the node selected
                                Alfresco.RepositoryWebService.Reference reference = new Alfresco.RepositoryWebService.Reference();
                                reference.store = this.spacesStore;
                                reference.uuid = row.node.id;
                                // add the child nodes
                                buildTree(node, reference);
                            }
                        }
                    }
                }
            }
        }
Example #25
0
        public void LowLevelRemoteStreamAsync()
        {
            using (var store = NewRemoteDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    for (int i = 0; i < 1500; i++)
                    {
                        session.Store(new User());
                    }
                    session.SaveChanges();
                }

                WaitForIndexing(store);
                
                var queryHeaderInfo = new Reference<QueryHeaderInformation>();
                var enumerator =
                    store.AsyncDatabaseCommands.StreamQueryAsync(new RavenDocumentsByEntityName().IndexName, new IndexQuery
                    {
                        Query = "",
                        SortedFields = new[] {new SortedField(Constants.DocumentIdFieldName),}
                    }, queryHeaderInfo).Result;

                Assert.Equal(1500, queryHeaderInfo.Value.TotalResults);

                int count = 0;
                while (enumerator.MoveNextAsync().Result)
                {
                    count++;
                }

                Assert.Equal(1500, count);
            }
        }
		protected override void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters, MethodEmitter invokeMethodOnTarget, Reference targetField)
		{
			invokeMethodOnTarget.CodeBuilder.AddStatement(
				new ExpressionStatement(
					new MethodInvocationExpression(SelfReference.Self, InvocationMethods.EnsureValidTarget)));
			base.ImplementInvokeMethodOnTarget(invocation, parameters, invokeMethodOnTarget, targetField);
		}
Example #27
0
 public void NotEquals()
 {
     var a = new Reference(1);
     var b = new Reference(2);
     Assert.AreNotEqual(a, b);
     Assert.AreNotEqual(a, null);
 }
        /// <summary>
        /// Use an X509 certificate to append a computed signature to an XML serialized Response
        /// </summary>
        /// <param name="XMLSerializedSAMLResponse"></param>
        /// <param name="ReferenceURI">Assertion ID from SAML Response</param>
        /// <param name="SigningCert">X509 Certificate for signing</param>
        /// <remarks>Referenced this article:
        ///     http://www.west-wind.com/weblog/posts/2008/Feb/23/Digitally-Signing-an-XML-Document-and-Verifying-the-Signature
        /// </remarks>
        public static void AppendSignatureToXMLDocument(ref XmlDocument XMLSerializedSAMLResponse, String ReferenceURI, X509Certificate2 SigningCert)
        {
            XmlNamespaceManager ns = new XmlNamespaceManager(XMLSerializedSAMLResponse.NameTable);
            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            XmlElement xeAssertion = XMLSerializedSAMLResponse.DocumentElement.SelectSingleNode("saml:Assertion", ns) as XmlElement;

            //SignedXml signedXML = new SignedXml(XMLSerializedSAMLResponse);
            SignedXml signedXML = new SignedXml(xeAssertion);

            signedXML.SigningKey = SigningCert.PrivateKey;
            signedXML.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            Reference reference = new Reference();
            reference.Uri = ReferenceURI;
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXML.AddReference(reference);
            signedXML.ComputeSignature();

            XmlElement signature = signedXML.GetXml();

            XmlElement xeResponse = XMLSerializedSAMLResponse.DocumentElement;

            xeResponse.AppendChild(signature);
        }
Example #29
0
        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;
        }
        public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert)
        {
            if (xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

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

            var signedXml = new SignedXml(xmlDocument);

            // 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 = (RSACryptoServiceProvider)cert.PrivateKey;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            var reference = new Reference { Uri = "#" + xmlDocument.DocumentElement.GetAttribute("ID") };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

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

            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signedXml.GetXml(), true));
        }
Example #31
0
        static void Main(string[] args)
        {
            using (ConsoleLogger logger = new ConsoleLogger("SetAppCfg: "))
            {
                logger.LogInfo("Running...");
                int exitCode = 0;
                try
                {
                    // set defaults
                    string coreAddr = null;
                    string applName = null;
                    string userName = null;
                    string hostName = null;
                    bool   replace  = false;
                    //bool debugOn = false;
                    // process arguments
                    NamedValueSet appCfg = new NamedValueSet();
                    foreach (var arg in args)
                    {
                        bool argProcessed = true;
                        // switches - begin with /
                        if (arg.StartsWith("/"))
                        {
                            // arg is a switch
                            string[] argParts = arg.Split(':');
                            string   argName  = argParts[0].Substring(1);
                            string   argValue = "";
                            for (int j = 1; j < argParts.Length; j++)
                            {
                                if (j > 1)
                                {
                                    argValue += ':';
                                }
                                argValue += argParts[j];
                            }
                            switch (argName.ToLower())
                            {
                            case "a":
                                applName = argValue;
                                logger.LogInfo("  ApplName: {0}", applName);
                                break;

                            case "u":
                                userName = argValue;
                                logger.LogInfo("  UserName: {0}", userName);
                                break;

                            case "h":
                                hostName = argValue;
                                logger.LogInfo("  HostName: {0}", hostName);
                                break;

                            case "p":     // simple string property
                                string[] propParts = argValue.Split('=');
                                appCfg.Set(new NamedValue(propParts[0], propParts[1]));
                                logger.LogInfo("  Property: {0}={1}", propParts[0], propParts[1]);
                                break;

                            case "nv":     // typed serialised named value
                                appCfg.Set(new NamedValue(argValue));
                                logger.LogInfo("  Property: {0}", argValue);
                                break;

                            case "replace":
                                replace = true;
                                logger.LogInfo("  Replace Old");
                                break;

                            case "debug":
                                //debugOn = true;
                                logger.LogInfo("  Debug On");
                                break;

                            case "s":
                                coreAddr = argValue;
                                logger.LogInfo("  Server  : {0}", coreAddr);
                                break;

                            default:
                                argProcessed = false;
                                break;
                            }
                        }
                        if (!argProcessed)
                        {
                            logger.LogInfo(" Sets configuration values for applications, users and machines");
                            logger.LogInfo(" usage:");
                            logger.LogInfo("   SetAppCfg [options]");
                            logger.LogInfo("      /a:applname           the application name (default: all applications)");
                            logger.LogInfo("      /u:username           the user name (default: all users)");
                            logger.LogInfo("      /h:hostname           the host (machine) name (default: all machines)");
                            logger.LogInfo("      /p:name=value         sets a string property value");
                            logger.LogInfo("      /nv:name/type=value   sets a typed property value with a serialised named value");
                            logger.LogInfo("      /s:address            the address of the core server to connect to eg. localhost:8114");
                            logger.LogInfo("      /replace              old values for the same application/user/host are deleted");
                            logger.LogInfo("      /debug                logs the internal query and results to the debug port");
                            logger.LogInfo(" returns:");
                            logger.LogInfo("  0: success - settings updated");
                            logger.LogInfo("  2: error - see error output for details");
                            throw new ArgumentException("Unknown argument '" + arg + "'");
                        }
                    }
                    // save the app config
                    var refLogger = Reference <ILogger> .Create(logger);

                    using (ICoreClient client = new CoreClientFactory(refLogger).SetServers(coreAddr).Create())
                    {
                        logger.LogInfo("Old/new settings comparison for:");
                        logger.LogInfo("  Application: {0}", applName ?? "(all)");
                        logger.LogInfo("  User name  : {0}", userName ?? "(all)");
                        logger.LogInfo("  Host name  : {0}", hostName ?? "(all)");
                        // get old settings
                        NamedValueSet oldAppCfg = client.LoadAppSettings(applName, userName, hostName);
                        logger.LogInfo("Old settings:");
                        oldAppCfg.LogValues(delegate(string text) { logger.LogInfo("  " + text); });
                        // set new settings
                        client.SaveAppSettings(appCfg, applName, userName, hostName, replace);
                        // get new settings
                        NamedValueSet newAppCfg = client.LoadAppSettings(applName, userName, hostName);
                        logger.LogInfo("New settings:");
                        newAppCfg.LogValues(delegate(string text) { logger.LogInfo("  " + text); });
                    }
                    logger.LogInfo("Success");
                    Environment.ExitCode = exitCode;
                }
                catch (Exception e)
                {
                    logger.Log(e);
                    for (int i = 0; i < args.Length; i++)
                    {
                        logger.LogDebug("  args[{0}]='{1}'", i, args[i]);
                    }
                    logger.LogInfo("FAILED");
                    Environment.ExitCode = 2;
                }
            }
        }
Example #32
0
 /// <summary>
 /// Transform a sentence column to a vector column to represent the whole sentence.
 /// </summary>
 /// <param name="documentDF"><see cref="DataFrame"/> to transform</param>
 public DataFrame Transform(DataFrame documentDF) =>
 new DataFrame((JvmObjectReference)Reference.Invoke("transform", documentDF));
Example #33
0
 public IEnumerable <JsonDocument> GetDocumentsAfter(Etag etag, int take,
                                                     CancellationToken cancellationToken, long?maxSize = null, Etag untilEtag = null, TimeSpan?timeout = null,
                                                     Action <Etag> lastProcessedOnFailure = null, Reference <bool> earlyExit  = null,
                                                     HashSet <string> entityNames         = null, Action <List <DocumentFetchError> > failedToGetHandler = null)
 {
     return(GetDocumentsAfterWithIdStartingWith(etag, null, take, cancellationToken, maxSize, untilEtag,
                                                timeout, lastProcessedOnFailure, earlyExit, entityNames, failedToGetHandler));
 }
Example #34
0
        public IEnumerable <JsonDocument> GetDocumentsAfterWithIdStartingWith(Etag etag, string idPrefix, int take,
                                                                              CancellationToken cancellationToken, long?maxSize = null, Etag untilEtag = null, TimeSpan?timeout = null,
                                                                              Action <Etag> lastProcessedDocument = null, Reference <bool> earlyExit   = null,
                                                                              HashSet <string> entityNames        = null, Action <List <DocumentFetchError> > failedToGetHandler = null)
        {
            if (earlyExit != null)
            {
                earlyExit.Value = false;
            }
            Api.JetSetCurrentIndex(session, Documents, "by_etag");
            Api.MakeKey(session, Documents, etag.TransformToValueForEsentSorting(), MakeKeyGrbit.NewKey);
            if (Api.TrySeek(session, Documents, SeekGrbit.SeekGT) == false)
            {
                yield break;
            }

            long totalSize            = 0;
            int  fetchedDocumentCount = 0;

            Stopwatch duration = null;

            if (timeout != null)
            {
                duration = Stopwatch.StartNew();
            }

            Etag lastDocEtag = null;
            Etag docEtag     = etag;

            var errors = new List <DocumentFetchError>();
            var skipDocumentGetErrors = failedToGetHandler != null;
            var hasEntityNames        = entityNames != null && entityNames.Count > 0;

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                docEtag = Etag.Parse(Api.RetrieveColumn(session, Documents, tableColumnsCache.DocumentsColumns["etag"]));

                // We can skip many documents so the timeout should be at the start of the process to be executed.
                if (timeout != null)
                {
                    if (duration.Elapsed > timeout.Value)
                    {
                        if (earlyExit != null)
                        {
                            earlyExit.Value = true;
                        }
                        break;
                    }
                }

                if (untilEtag != null && fetchedDocumentCount > 0)
                {
                    // This is not a failure, we are just ahead of when we expected to.
                    if (EtagUtil.IsGreaterThan(docEtag, untilEtag))
                    {
                        break;
                    }
                }

                var key = Api.RetrieveColumnAsString(session, Documents, tableColumnsCache.DocumentsColumns["key"], Encoding.Unicode);
                if (!string.IsNullOrEmpty(idPrefix))
                {
                    if (!key.StartsWith(idPrefix, StringComparison.OrdinalIgnoreCase))
                    {
                        // We assume that we have processed it because it is not of our interest.
                        lastDocEtag = docEtag;
                        continue;
                    }
                }

                JsonDocument document;
                try
                {
                    document = GetJsonDocument(hasEntityNames, key, docEtag, entityNames);
                }
                catch (Exception e)
                {
                    if (skipDocumentGetErrors)
                    {
                        errors.Add(new DocumentFetchError
                        {
                            Key       = key,
                            Exception = e
                        });
                        continue;
                    }

                    throw;
                }

                totalSize += document.SerializedSizeOnDisk;
                fetchedDocumentCount++;

                yield return(document);

                lastDocEtag = docEtag;

                if (maxSize != null && totalSize > maxSize.Value)
                {
                    if (untilEtag != null && earlyExit != null)
                    {
                        earlyExit.Value = true;
                    }
                    break;
                }

                if (fetchedDocumentCount >= take)
                {
                    if (untilEtag != null && earlyExit != null)
                    {
                        earlyExit.Value = true;
                    }
                    break;
                }
            }while (Api.TryMoveNext(session, Documents));

            if (skipDocumentGetErrors && errors.Count > 0)
            {
                failedToGetHandler(errors);
            }

            // We notify the last that we considered.
            if (lastProcessedDocument != null)
            {
                lastProcessedDocument(lastDocEtag);
            }
        }
Example #35
0
        private RavenJObject ReadDocumentData(Table table, string key, Etag existingEtag, RavenJObject metadata, Reference <int> docSize)
        {
            try
            {
                var existingCachedDocument = cacher.GetCachedDocument(key, existingEtag);
                if (existingCachedDocument != null)
                {
                    docSize.Value = existingCachedDocument.Size;
                    return(existingCachedDocument.Document);
                }

                RavenJObject document;
                docSize.Value = GetDocumentFromStorage(table, key, metadata, existingEtag, out document);
                return(document);
            }
            catch (Exception e)
            {
                InvalidDataException invalidDataException = null;
                try
                {
                    using (Stream stream = new BufferedStream(new ColumnStream(session, table, tableColumnsCache.DocumentsColumns["data"])))
                        using (var reader = new BinaryReader(stream))
                        {
                            if (reader.ReadUInt32() == DocumentCompression.CompressFileMagic)
                            {
                                invalidDataException = new InvalidDataException(string.Format("Document '{0}' is compressed, but the compression bundle is not enabled.\r\n" +
                                                                                              "You have to enable the compression bundle when dealing with compressed documents.", key), e);
                            }
                        }
                }
                catch (Exception)
                {
                    // we are already in error handling mode, just ignore this
                }
                if (invalidDataException != null)
                {
                    throw invalidDataException;
                }

                throw new InvalidDataException("Failed to de-serialize a document: " + key, e);
            }
        }
Example #36
0
 public TRet GetReference <TRet>(Reference.OutFunc <T, TRet> func)
 {
     return(Ref.GetReference(tr => tr.AsRef(Reference.OutToRefFunc(func))));
 }
Example #37
0
        // ======================================
        //   (2) add alignments
        // ======================================
        void addAlignments(Extrusion pBox)
        {
            //
            // (1) we want to constrain the upper face of the column to the "Upper Ref Level"
            //

            // which direction are we looking at?
            //
            View pView = findElement(typeof(View), "Front") as View;

            // find the upper ref level
            // findElement() is a helper function. see below.
            //
            Level     upperLevel = findElement(typeof(Level), "Upper Ref Level") as Level;
            Reference ref1       = upperLevel.GetPlaneReference();

            // find the face of the box
            // findFace() is a helper function. see below.
            //
            PlanarFace upperFace = findFace(pBox, new XYZ(0.0, 0.0, 1.0)); // find a face whose normal is z-up.
            Reference  ref2      = upperFace.Reference;

            // create alignments
            //
            _doc.FamilyCreate.NewAlignment(pView, ref1, ref2);

            //
            // (2) do the same for the lower level
            //

            // find the lower ref level
            // findElement() is a helper function. see below.
            //
            Level     lowerLevel = findElement(typeof(Level), "Lower Ref. Level") as Level;
            Reference ref3       = lowerLevel.GetPlaneReference();

            // find the face of the box
            // findFace() is a helper function. see below.
            PlanarFace lowerFace = findFace(pBox, new XYZ(0.0, 0.0, -1.0)); // find a face whose normal is z-down.
            Reference  ref4      = lowerFace.Reference;

            // create alignments
            //
            _doc.FamilyCreate.NewAlignment(pView, ref3, ref4);

            //
            // (3)  same idea for the Right/Left/Front/Back
            //
            // get the plan view
            // note: same name maybe used for different view types. either one should work.
            View pViewPlan = findElement(typeof(ViewPlan), "Lower Ref. Level") as View;

            // find reference planes
            ReferencePlane refRight = findElement(typeof(ReferencePlane), "Right") as ReferencePlane;
            ReferencePlane refLeft  = findElement(typeof(ReferencePlane), "Left") as ReferencePlane;
            ReferencePlane refFront = findElement(typeof(ReferencePlane), "Front") as ReferencePlane;
            ReferencePlane refBack  = findElement(typeof(ReferencePlane), "Back") as ReferencePlane;

            // find the face of the box
            PlanarFace faceRight = findFace(pBox, new XYZ(1.0, 0.0, 0.0));
            PlanarFace faceLeft  = findFace(pBox, new XYZ(-1.0, 0.0, 0.0));
            PlanarFace faceFront = findFace(pBox, new XYZ(0.0, -1.0, 0.0));
            PlanarFace faceBack  = findFace(pBox, new XYZ(0.0, 1.0, 0.0));

            // create alignments
            //
            _doc.FamilyCreate.NewAlignment(pViewPlan, refRight.GetReference(), faceRight.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refLeft.GetReference(), faceLeft.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refFront.GetReference(), faceFront.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refBack.GetReference(), faceBack.Reference);
        }
Example #38
0
 /// <summary>
 /// Find <paramref name="num"/> number of words whose vector representation most similar to
 /// the supplied vector. If the supplied vector is the vector representation of a word in
 /// the model's vocabulary, that word will be in the results. Returns a dataframe with the
 /// words and the cosine similarities between the synonyms and the given word vector.
 /// </summary>
 /// <param name="word">The "word" to find similarities for, this can be a string or a
 /// vector representation.</param>
 /// <param name="num">The number of words to find that are similar to "word"</param>
 public DataFrame FindSynonyms(string word, int num) =>
 new DataFrame((JvmObjectReference)Reference.Invoke("findSynonyms", word, num));
Example #39
0
 public bool AllowReference(Reference refer, XYZ pos)
 {
     return(true);
 }
 public CollectionQueryEnumerable(DocumentDatabase database, DocumentsStorage documents, FieldsToFetch fieldsToFetch, string collection,
                                  IndexQueryServerSide query, QueryTimingsScope queryTimings, DocumentsOperationContext context, IncludeDocumentsCommand includeDocumentsCommand, Reference <int> totalResults)
 {
     _database            = database;
     _documents           = documents;
     _fieldsToFetch       = fieldsToFetch;
     _collection          = collection;
     _isAllDocsCollection = collection == Constants.Documents.Collections.AllDocumentsCollection;
     _query                   = query;
     _queryTimings            = queryTimings;
     _context                 = context;
     _includeDocumentsCommand = includeDocumentsCommand;
     _totalResults            = totalResults;
 }
 /// <summary>
 /// Constructor which sets the cache
 /// </summary>
 /// <param name="cache"></param>
 public PricingStructureCache(ICoreCache cache)
     : this(Reference <ILogger> .Create(new TraceLogger(true)), cache, EnvironmentProp.DefaultNameSpace)
 {
 }
            public Enumerator(DocumentDatabase database, DocumentsStorage documents, FieldsToFetch fieldsToFetch, string collection, bool isAllDocsCollection,
                              IndexQueryServerSide query, QueryTimingsScope queryTimings, DocumentsOperationContext context, IncludeDocumentsCommand includeDocumentsCommand, Reference <int> totalResults, int?queryOperationInternalStart)
            {
                _documents           = documents;
                _fieldsToFetch       = fieldsToFetch;
                _collection          = collection;
                _isAllDocsCollection = isAllDocsCollection;
                _query                       = query;
                _context                     = context;
                _totalResults                = totalResults;
                _totalResults.Value          = 0;
                _queryOperationInternalStart = queryOperationInternalStart;

                if (_fieldsToFetch.IsDistinct)
                {
                    _alreadySeenProjections = new HashSet <ulong>();
                }

                _resultsRetriever = new MapQueryResultRetriever(database, query, queryTimings, documents, context, fieldsToFetch, includeDocumentsCommand);

                (_ids, _startsWith) = ExtractIdsFromQuery(query, context);
            }
        /***************************************************/
        /****              Private methods              ****/
        /***************************************************/

        private static XYZ CeilingPatternAlignment(this Ceiling ceiling, Material material, RevitSettings settings, out double rotation)
        {
            rotation = 0;
            if (ceiling == null || material == null)
            {
                return(null);
            }

            Document doc = ceiling.Document;

            FillPatternElement fillPatternElement;

#if (REVIT2020 || REVIT2021)
            fillPatternElement = doc.GetElement(material.SurfaceForegroundPatternId) as FillPatternElement;
#else
            fillPatternElement = doc.GetElement(material.SurfacePatternId) as FillPatternElement;
#endif

            FillPattern fp = fillPatternElement?.GetFillPattern();
            if (fp == null || fp.GridCount != 2)
            {
                return(null);
            }

            XYZ result = null;
            settings = settings.DefaultIfNull();

            Options o = new Options();
            o.ComputeReferences = true;
            foreach (GeometryObject go in ceiling.get_Geometry(o))
            {
                if (go is Solid)
                {
                    foreach (Autodesk.Revit.DB.Face f in ((Solid)go).Faces)
                    {
                        PlanarFace pf = f as PlanarFace;
                        if (pf == null)
                        {
                            continue;
                        }

                        if (1 + pf.FaceNormal.DotProduct(XYZ.BasisZ) > settings.AngleTolerance)
                        {
                            continue;
                        }

                        ReferenceArray horR   = new ReferenceArray();
                        string         stable = f.Reference.ConvertToStableRepresentation(doc) + "/2";
                        Reference      href   = Reference.ParseFromStableRepresentation(doc, stable);
                        horR.Append(href);

                        stable = f.Reference.ConvertToStableRepresentation(doc) + "/" + (2 + fp.GridCount * 2).ToString();
                        href   = Reference.ParseFromStableRepresentation(doc, stable);
                        horR.Append(href);

                        ReferenceArray verR = new ReferenceArray();
                        stable = f.Reference.ConvertToStableRepresentation(doc) + "/1";
                        href   = Reference.ParseFromStableRepresentation(doc, stable);
                        verR.Append(href);

                        stable = f.Reference.ConvertToStableRepresentation(doc) + "/" + (1 + fp.GridCount * 2).ToString();
                        href   = Reference.ParseFromStableRepresentation(doc, stable);
                        verR.Append(href);

                        using (Transaction t = new Transaction(doc, "temp dim"))
                        {
                            t.Start();
                            Dimension horDim = doc.Create.NewDimension(doc.ActiveView, Autodesk.Revit.DB.Line.CreateBound(XYZ.Zero, pf.XVector), horR);
                            Dimension verDim = doc.Create.NewDimension(doc.ActiveView, Autodesk.Revit.DB.Line.CreateBound(XYZ.Zero, pf.YVector), verR);
                            ElementTransformUtils.MoveElement(doc, horDim.Id, XYZ.BasisX);
                            ElementTransformUtils.MoveElement(doc, verDim.Id, XYZ.BasisX);

                            rotation = -(horDim.Curve as Autodesk.Revit.DB.Line).Direction.AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ);
                            Transform tr = Transform.CreateRotation(XYZ.BasisZ, rotation);
                            double    x  = tr.Inverse.OfPoint(horDim.Origin).X;
                            double    y  = tr.Inverse.OfPoint(verDim.Origin).Y;
                            t.RollBack();

                            foreach (FillGrid fg in fp.GetFillGrids())
                            {
                                if (fg.Angle.ToSI(UnitType.UT_Angle) > settings.AngleTolerance)
                                {
                                    y += fg.Offset * 0.5;
                                }
                                else
                                {
                                    x += fg.Offset * 0.5;
                                }
                            }

                            result = tr.OfPoint(new XYZ(x, y, 0));
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Example #44
0
 protected StorageActionsBase(Reference <SnapshotReader> snapshotReference, IBufferPool bufferPool)
 {
     this.snapshotReference = snapshotReference;
     this.bufferPool        = bufferPool;
 }
Example #45
0
        public static IReference CreateReference <T>(this T referable) where T : class, IReferable
        {
            IReference <T> reference = new Reference <T>(referable);

            return(reference);
        }
Example #46
0
        protected virtual void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters,
                                                             MethodEmitter invokeMethodOnTarget,
                                                             Reference targetField)
        {
            var callbackMethod = GetCallbackMethod(invocation);

            if (callbackMethod == null)
            {
                EmitCallThrowOnNoTarget(invokeMethodOnTarget);
                return;
            }

            if (canChangeTarget)
            {
                EmitCallEnsureValidTarget(invokeMethodOnTarget);
            }

            var args = new Expression[parameters.Length];

            // Idea: instead of grab parameters one by one
            // we should grab an array
            var byRefArguments = new Dictionary <int, LocalReference>();

            for (var i = 0; i < parameters.Length; i++)
            {
                var param = parameters[i];

                var paramType = invocation.GetClosedParameterType(param.ParameterType);
                if (paramType.IsByRef)
                {
                    var localReference = invokeMethodOnTarget.CodeBuilder.DeclareLocal(paramType.GetElementType());
                    invokeMethodOnTarget.CodeBuilder
                    .AddStatement(
                        new AssignStatement(localReference,
                                            new ConvertExpression(paramType.GetElementType(),
                                                                  new MethodInvocationExpression(SelfReference.Self,
                                                                                                 InvocationMethods.GetArgumentValue,
                                                                                                 new LiteralIntExpression(i)))));
                    var byRefReference = new ByRefReference(localReference);
                    args[i]           = new ReferenceExpression(byRefReference);
                    byRefArguments[i] = localReference;
                }
                else
                {
                    args[i] =
                        new ConvertExpression(paramType,
                                              new MethodInvocationExpression(SelfReference.Self,
                                                                             InvocationMethods.GetArgumentValue,
                                                                             new LiteralIntExpression(i)));
                }
            }

            if (byRefArguments.Count > 0)
            {
                invokeMethodOnTarget.CodeBuilder.AddStatement(new TryStatement());
            }

            var methodOnTargetInvocationExpression = GetCallbackMethodInvocation(invocation, args, callbackMethod, targetField, invokeMethodOnTarget);

            LocalReference returnValue = null;

            if (callbackMethod.ReturnType != typeof(void))
            {
                var returnType = invocation.GetClosedParameterType(callbackMethod.ReturnType);
                returnValue = invokeMethodOnTarget.CodeBuilder.DeclareLocal(returnType);
                invokeMethodOnTarget.CodeBuilder.AddStatement(new AssignStatement(returnValue, methodOnTargetInvocationExpression));
            }
            else
            {
                invokeMethodOnTarget.CodeBuilder.AddStatement(new ExpressionStatement(methodOnTargetInvocationExpression));
            }

            AssignBackByRefArguments(invokeMethodOnTarget, byRefArguments);

            if (callbackMethod.ReturnType != typeof(void))
            {
                var setRetVal =
                    new MethodInvocationExpression(SelfReference.Self,
                                                   InvocationMethods.SetReturnValue,
                                                   new ConvertExpression(typeof(object), returnValue.Type, returnValue.ToExpression()));

                invokeMethodOnTarget.CodeBuilder.AddStatement(new ExpressionStatement(setRetVal));
            }

            invokeMethodOnTarget.CodeBuilder.AddStatement(new ReturnStatement());
        }
Example #47
0
 public bool AllowReference(Reference reference, XYZ position) => false;
        // public Reference Create(Reference Reference)
        // {
        //     _reference.InsertOne(Reference);
        //     return Reference;
        // }

        public void Update(string id, Reference ReferenceIn) =>
        _reference.ReplaceOne(Reference => Reference.Id == id, ReferenceIn);
Example #49
0
 public Face(Reference reference, Document doc) : base(reference, doc)
 {
 }
Example #50
0
        public static void CreateCommentAnnotation(List <KnowledgeItem> quotations)
        {
            PreviewControl previewControl = PreviewMethods.GetPreviewControl();

            if (previewControl == null)
            {
                return;
            }

            PdfViewControl pdfViewControl = previewControl.GetPdfViewControl();

            if (pdfViewControl == null)
            {
                return;
            }

            Annotation lastAnnotation = null;

            foreach (KnowledgeItem quotation in quotations)
            {
                if (quotation.EntityLinks.Any() && quotation.EntityLinks.Where(link => link.Target is KnowledgeItem).FirstOrDefault() != null)
                {
                    Reference reference = quotation.Reference;
                    if (reference == null)
                    {
                        return;
                    }

                    Project project = reference.Project;
                    if (project == null)
                    {
                        return;
                    }

                    KnowledgeItem mainQuotation = quotation.EntityLinks.ToList().Where(n => n != null && n.Indication == EntityLink.CommentOnQuotationIndication && n.Target as KnowledgeItem != null).ToList().FirstOrDefault().Target as KnowledgeItem;

                    Annotation mainQuotationAnnotation = mainQuotation.EntityLinks.Where(link => link.Target is Annotation && link.Indication == EntityLink.PdfKnowledgeItemIndication).FirstOrDefault().Target as Annotation;
                    if (mainQuotationAnnotation == null)
                    {
                        return;
                    }

                    Location location = mainQuotationAnnotation.Location;
                    if (location == null)
                    {
                        return;
                    }

                    List <Annotation> oldAnnotations = quotation.EntityLinks.Where(e => e.Indication == EntityLink.PdfKnowledgeItemIndication).Select(e => (Annotation)e.Target).ToList();

                    foreach (Annotation oldAnnotation in oldAnnotations)
                    {
                        location.Annotations.Remove(oldAnnotation);
                    }

                    Annotation newAnnotation = new Annotation(location);

                    newAnnotation.OriginalColor = System.Drawing.Color.FromArgb(255, 255, 255, 0);
                    newAnnotation.Quads         = mainQuotationAnnotation.Quads;
                    newAnnotation.Visible       = false;
                    location.Annotations.Add(newAnnotation);


                    EntityLink newEntityLink = new EntityLink(project);
                    newEntityLink.Source     = quotation;
                    newEntityLink.Target     = newAnnotation;
                    newEntityLink.Indication = EntityLink.PdfKnowledgeItemIndication;
                    project.EntityLinks.Add(newEntityLink);

                    lastAnnotation = newAnnotation;
                }
                pdfViewControl.GoToAnnotation(lastAnnotation);
            }
        }
Example #51
0
 public Vertex(Reference reference, Document doc) : base(reference, doc)
 {
 }
Example #52
0
 public Vertex(int index, Reference reference, Document doc) : base(reference, doc)
 {
     VertexIndex = index;
 }
Example #53
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, string SubjectName)
    {
        if (null == FileName)
        {
            throw new ArgumentNullException("FileName");
        }
        if (null == SignedFileName)
        {
            throw new ArgumentNullException("SignedFileName");
        }
        if (null == SubjectName)
        {
            throw new ArgumentNullException("SubjectName");
        }

        // Load the certificate from the certificate store.
        X509Certificate2 cert = GetCertificateBySubject(SubjectName);

        // 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 = cert.PrivateKey;

        // 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);

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

        // Create a new KeyInfo object.
        KeyInfo keyInfo = new KeyInfo();

        // Load the certificate into a KeyInfoX509Data object
        // and add it to the KeyInfo object.
        KeyInfoX509Data X509KeyInfo = new KeyInfoX509Data(cert, X509IncludeOption.WholeChain);

        keyInfo.AddClause(X509KeyInfo);

        // Add the KeyInfo object to the SignedXml object.
        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.
        using (XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)))
        {
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
    }
Example #54
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;

            app = commandData.Application.Application;
            doc = uidoc.Document;
            //Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "Select a CAD Link");
            //Element elem = doc.GetElement(refer);
            //GeometryElement geoElem = elem.get_Geometry(new Options());



            Reference r  = uidoc.Selection.PickObject(ObjectType.PointOnElement);
            string    ss = r.ConvertToStableRepresentation(doc);



            Element         elem    = doc.GetElement(r);
            GeometryElement geoElem = elem.get_Geometry(new Options());
            GeometryObject  geoObj  = elem.GetGeometryObjectFromReference(r);


            //获取选中的cad图层
            Category  targetCategory  = null;
            ElementId graphicsStyleId = null;


            if (geoObj.GraphicsStyleId != ElementId.InvalidElementId)
            {
                graphicsStyleId = geoObj.GraphicsStyleId;
                GraphicsStyle gs = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle;
                if (gs != null)
                {
                    targetCategory = gs.GraphicsStyleCategory;
                    var name = gs.GraphicsStyleCategory.Name;
                }
            }
                        //隐藏选中的cad图层
                        Transaction trans = new Transaction(doc, "隐藏图层");

            trans.Start();
            if (targetCategory != null)
            {
                doc.ActiveView.SetVisibility(targetCategory, false);
            }


            trans.Commit();



            TransactionGroup transGroup = new TransactionGroup(doc, "绘制模型线");

            transGroup.Start();
            CurveArray curveArray = new CurveArray();


            //判断元素类型
            foreach (var gObj in geoElem)
            {
                GeometryInstance geomInstance = gObj as GeometryInstance;
                                //坐标转换。如果选择的是“自动-中心到中心”,或者移动了importInstance,需要进行坐标转换
                                Transform transform = geomInstance.Transform;


                if (null != geomInstance)
                {
                    foreach (var insObj in geomInstance.SymbolGeometry)
                    {
                        if (insObj.GraphicsStyleId.IntegerValue != graphicsStyleId.IntegerValue)
                        {
                            continue;
                        }


                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.NurbSpline")
                        {
                                                        //未实现
                                                   
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Line")
                        {
                            Line line   = insObj as Line;
                            XYZ  normal = XYZ.BasisZ;
                            XYZ  point  = line.GetEndPoint(0);
                            point = transform.OfPoint(point);


                            curveArray.Append(TransformLine(transform, line));


                            CreateModelCurveArray(curveArray, normal, point);
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.Arc")
                        {
                                                        //未实现
                                                   
                        }
                        if (insObj.GetType().ToString() == "Autodesk.Revit.DB.PolyLine")
                        {
                            PolyLine    polyLine = insObj as PolyLine;
                            IList <XYZ> points   = polyLine.GetCoordinates();


                            for (int i = 0; i < points.Count - 1; i++)
                            {
                                Line line = Line.CreateBound(points[i], points[i + 1]);
                                line = TransformLine(transform, line);
                                curveArray.Append(line);
                            }


                            XYZ normal = XYZ.BasisZ;
                            XYZ point  = points.First();
                            point = transform.OfPoint(point);


                            CreateModelCurveArray(curveArray, normal, point);
                        }
                    }
                }
            }
            transGroup.Assimilate();



            return(Result.Succeeded);
        }
 public bool AllowReference(Reference reference, XYZ position)
 {
     return(true);
 }
 MyClass(Reference <int> ref)
 {
     _ref = ref;
 }
 public bool AllowReference(Reference reference, XYZ position)
 {
     return(refFunc == null ? false : refFunc(reference));
     //return  refFunc(reference);
 }
Example #58
0
 public ClassMethodReference(Reference owner, string name) : base(owner, name)
 {
 }
Example #59
0
        /// <summary>
        /// Inserts a picture
        /// </summary>
        /// <param name="pictureBinary">The picture binary</param>
        /// <param name="mimeType">The picture MIME type</param>
        /// <param name="seoFilename">The SEO filename</param>
        /// <param name="altAttribute">"alt" attribute for "img" HTML element</param>
        /// <param name="titleAttribute">"title" attribute for "img" HTML element</param>
        /// <param name="isNew">A value indicating whether the picture is new</param>
        /// <param name="reference">Reference type</param>
        /// <param name="objectId">Object id for reference</param>
        /// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>
        /// <returns>Picture</returns>
        public virtual async Task <Picture> InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename,
                                                          string altAttribute = null, string titleAttribute = null,
                                                          bool isNew          = true, Reference reference   = Reference.None, string objectId = "", bool validateBinary = false)
        {
            mimeType = CommonHelper.EnsureNotNull(mimeType);
            mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);

            seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);

            if (validateBinary)
            {
                pictureBinary = ValidatePicture(pictureBinary, mimeType);
            }

            var picture = new Picture
            {
                PictureBinary  = _mediaSettings.StoreInDb ? pictureBinary : new byte[0],
                MimeType       = mimeType,
                SeoFilename    = seoFilename,
                AltAttribute   = altAttribute,
                TitleAttribute = titleAttribute,
                Reference      = reference,
                ObjectId       = objectId,
                IsNew          = isNew,
            };
            await _pictureRepository.InsertAsync(picture);

            if (!_mediaSettings.StoreInDb)
            {
                await SavePictureInFile(picture.Id, pictureBinary, mimeType);
            }

            //event notification
            await _mediator.EntityInserted(picture);

            return(picture);
        }
Example #60
0
 public QueueStorageActions(TableStorage tableStorage, IUuidGenerator generator, Reference <SnapshotReader> snapshot, Reference <WriteBatch> writeBatch, IBufferPool bufferPool)
     : base(snapshot, bufferPool)
 {
     this.tableStorage = tableStorage;
     this.writeBatch   = writeBatch;
     this.generator    = generator;
 }