/// <summary>
        /// Get references for specified locale.
        /// </summary>
        /// <param name="userContext">
        /// Information about the user that makes this method call.
        /// </param>
        /// <param name="locale">Currently used locale.</param>
        /// <returns>References for specified locale.</returns>
        protected override ReferenceList GetReferences(IUserContext userContext,
                                                       ILocale locale)
        {
            ReferenceList references;

            if (userContext.Transaction.IsNull())
            {
                lock (References)
                {
                    if (References.ContainsKey(locale.ISOCode))
                    {
                        references = (ReferenceList)(References[locale.ISOCode]);
                    }
                    else
                    {
                        references = new ReferenceList();
                        References[locale.ISOCode] = references;
                    }
                }
            }
            else
            {
                references = new ReferenceList();
            }

            return(references);
        }
示例#2
0
        private async void LoadData()
        {
            try
            {
                isLoaded = false;
                isBusy   = true;
                ReferenceList.Clear();
                responseObject = await trackingService.GetReferences(requestObject.JobType, requestObject.JobId);

                if (responseObject.ReturnCode == "ERR_SUCCESS")
                {
                    foreach (Reference a in responseObject.References)
                    {
                        ReferenceList.Add(a);
                    }
                }
                else
                {
                    //Error
                }
            }
            catch (Exception e)
            {
                //Exception
            }
            finally
            {
                isLoaded = true;
                isBusy   = false;
            }
        }
示例#3
0
 public Amf0(SerializationContext context, Base b, Amf3 amf3)
 {
     this.b       = b;
     this.amf3    = amf3;
     this.context = context;
     refs         = new ReferenceList <object>();
 }
示例#4
0
        public XmlElement DecryptSingleElementByKeyNumber(int encryptedKeyNumber)
        {
            EncryptedKey encryptedKey = new EncryptedKey();

            encryptedKey.LoadXml((XmlElement)this._encryptedKeyElements[encryptedKeyNumber]);
            ReferenceList      referenceList      = encryptedKey.ReferenceList;
            EncryptedReference encryptedReference = referenceList.Item(0);
            string             uri     = encryptedReference.Uri;
            KeyInfo            keyInfo = encryptedKey.KeyInfo;

            this._referenceList.Clear();
            ArrayList referenceElementList = new ArrayList();

            referenceElementList = this.FindXmlElementByURI(uri, this._tempdocument.ChildNodes[1]);
            XmlElement keyInfoElement = this._tempdocument.CreateElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);

            keyInfoElement.AppendChild(_tempdocument.ImportNode((XmlNode)encryptedKey.GetXml(), true));
            XmlElement encryptedDataElement   = (XmlElement)referenceElementList[0];
            RSACryptoServiceProvider provider = this._webService.RSACryptoServiceProvider;
            EncryptedXml             encXml   = new EncryptedXml(this._tempdocument);

            encXml.AddKeyNameMapping("Web Service Public Key", provider);
            EncryptedData data = new EncryptedData();

            data.LoadXml((XmlElement)encryptedDataElement);
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();

            algo.Key = encXml.DecryptEncryptedKey(encryptedKey);
            byte[] t = encXml.DecryptData(data, algo);
            encXml.ReplaceData(encryptedDataElement, t);
            this._tempdocument.GetElementsByTagName("wsse:Security")[0].RemoveChild(_tempdocument.GetElementsByTagName("xenc:EncryptedKey")[0]);
            XmlElement root = (XmlElement)this._decryptedDataList[encryptedKeyNumber];

            return((XmlElement)root);
        }
        public ScenesWindowElementReference(Rect aStartPos, GUIContent aContent, GUIStyle aStyle, SceneEditor sceneEditor,
                                            params GUILayoutOption[] aOptions)
            : base(aStartPos, aContent, aStyle, sceneEditor, aOptions)
        {
            new ReferenceComponent(Rect.zero, new GUIContent(""), aStyle);
            PreviewTitle = "Scene.Preview".Traslate();

            referenceList = new ReferenceList()
            {
                onSelectCallback = (list) =>
                {
                    sceneEditor.SelectedElement = (referenceList.list[list.index] as ElementContainer).getErdc();
                },
                onRemoveCallback = (list) =>
                {
                    sceneEditor.SelectedElement = null;
                }
            };

            sceneEditor.onSelectElement += (element) =>
            {
                if (element is ElementReferenceDataControl)
                {
                    var erdc = element as ElementReferenceDataControl;
                    referenceList.index = referenceList.list.Cast <ElementContainer>().Select(e => e.getErdc()).ToList().IndexOf(erdc);
                }
                else
                {
                    referenceList.index = -1;
                }
            };
        }
示例#6
0
 public ProjectInfo(Project project)
 {
     _project = project;
     _properties = new ProjectPropertyList(_project);
     _references = new ReferenceList(_project);
     _dependencies = new List<string>();
 }
        public static ReferenceList GetSomeReferences(Boolean refresh)
        {
            ReferenceList references;

            references = new ReferenceList();
            references.AddRange(Data.ArtDatabankenService.ReferenceManager.GetReferences(refresh).GetRange(0, 10));
            return(references);
        }
示例#8
0
            public Amf3(SerializationContext context, AmfWriter writer, Base b)
            {
                this.b       = b;
                this.writer  = writer;
                this.context = context;

                this.refObjects = new ReferenceList <object>();
                this.refStrings = new ReferenceList <string>();
                this.refClasses = new ReferenceList <ClassInfo>();
            }
示例#9
0
 public override void Reset()
 {
     AssetBundleName = String.Empty;
     LastUsedTime    = 0.0f;
     IsReady         = false;
     ReferenceCount  = 0;
     ReferenceList.Clear();
     LoadedAssetMap.Clear();
     AssetsPath = null;
 }
示例#10
0
            public Amf3(SerializationContext context, AmfReader reader, Base b)
            {
                this.b       = b;
                this.reader  = reader;
                this.context = context;

                refObjects = new ReferenceList <object>();
                refStrings = new ReferenceList <string>();
                refClasses = new ReferenceList <ClassDescription>();
            }
示例#11
0
        public IQueryable <sys_EnumReference> GetEntityListByName(ReferenceList name)
        {
            Guid companyId = this.GetCurrentCompanyId();

            string _name = name.ToString();

            return(this._repoEnumReference
                   .Query().Filter(x => x.name == _name && x.companyId == companyId)
                   .Get()
                   .OrderBy(x => x.displayOrder));
        }
示例#12
0
        private string DercryptSingleXmlElement(XmlElement encryptedKeyElement)
        {
            EncryptedKey encryptdKey = new EncryptedKey();

            encryptdKey.LoadXml(encryptedKeyElement);
            ReferenceList      referenceList      = encryptdKey.ReferenceList;
            EncryptedReference encryptedReference = referenceList.Item(0);
            string             uri     = encryptedReference.Uri;
            KeyInfo            keyInfo = encryptdKey.KeyInfo;

            this._referenceList.Clear();
            ArrayList  referenceElementList = this.FindXmlElementByURI(uri, this._inputDocument.ChildNodes[1]);
            XmlElement keyInfoElement       = this._inputDocument.CreateElement("KeyInfo", SignedXml.XmlDsigNamespaceUrl);

            keyInfoElement.AppendChild(encryptedKeyElement);
            if (referenceElementList.Count > 0)
            {
                XmlElement encryptedDataElement   = (XmlElement)referenceElementList[0];
                RSACryptoServiceProvider provider = this._webService.RSACryptoServiceProvider;
                XmlDocument doc  = new XmlDocument();
                XmlElement  root = doc.CreateElement("root");
                root.AppendChild(doc.ImportNode((XmlNode)encryptedKeyElement, true));
                root.AppendChild(doc.ImportNode(encryptedDataElement, true));
                doc.AppendChild(root);
                EncryptedXml encxml2 = new EncryptedXml(doc);
                EncryptedKey encKey2 = new EncryptedKey();
                encKey2.LoadXml((XmlElement)doc.GetElementsByTagName("xenc:EncryptedKey")[0]);
                EncryptedData encData2        = new EncryptedData();
                EncryptedData encDataElement2 = new EncryptedData();
                XmlElement    data2           = (XmlElement)doc.GetElementsByTagName("xenc:EncryptedData")[0];
                encDataElement2.LoadXml((XmlElement)doc.GetElementsByTagName("xenc:EncryptedData")[0]);
                encxml2.AddKeyNameMapping("Web Service Public Key", provider);
                SymmetricAlgorithm algo2 = SymmetricAlgorithm.Create();
                algo2.Key = encxml2.DecryptEncryptedKey(encKey2);
                byte[] t2 = encxml2.DecryptData(encDataElement2, algo2);
                encxml2.ReplaceData(data2, t2);
                doc.GetElementsByTagName("root")[0].RemoveChild(doc.GetElementsByTagName("xenc:EncryptedKey")[0]);
                this._tracer.appendDecryptedData(uri, doc.FirstChild.InnerXml);
                EncryptedXml encXml = new EncryptedXml(this._inputDocument);
                encXml.AddKeyNameMapping("Web Service Public Key", provider);
                EncryptedData data = new EncryptedData();
                data.LoadXml((XmlElement)encryptedDataElement);
                SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
                algo.Key = encXml.DecryptEncryptedKey(encryptdKey);
                byte[] t = encXml.DecryptData(data, algo);
                encXml.ReplaceData(encryptedDataElement, t);
                this._encryptedDataList.Add(encryptedDataElement);
                this._decryptedDataList.Add(doc.GetElementsByTagName("root")[0]);
                this._encryptedKeyElements.Add(encryptedKeyElement);
                string decryptedXmlString;
                return(decryptedXmlString = Convert.ToBase64String(t));
            }
            return(string.Empty);
        }
示例#13
0
        private static void WriteReferencesToDgmlFile(ReferenceList result)
        {
            var builder = new GraphBuilder();
            var doc     = builder.BuildDgml(result);

            var path = Path.Combine(Path.GetTempFileName() + ".dgml");

            doc.Save(path);

            Process.Start(path);
        }
示例#14
0
        public ReferenceList AnalyzeReferences(ReferenceList list, IEnumerable <BindingRedirectData> bindingRedirects)
        {
            _referenceList = list;

            FindConflicts();
            FindResolvedConflicts(bindingRedirects);
            AddExplanationToLoadingErrors();
            FindProcessorArchitectureMismatch();

            return(_referenceList);
        }
        public override void establish_context()
        {
            var property = ReflectionHelper.GetAccessor((Expression<Func<ReferenceEntity, object>>)(x => x.ReferenceList));

            referencedEntities = new List<OtherEntity> { new OtherEntity(), new OtherEntity() };

            session = A.Fake<ISession>();
            A.CallTo(() => session.BeginTransaction()).Returns(A.Dummy<ITransaction>());
            specification = new PersistenceSpecification<PropertyEntity>(session);

            sut = new ReferenceList<PropertyEntity, OtherEntity>(property, referencedEntities);
        }
 public override void Reset()
 {
     Bundle          = null;
     AssetBundleName = String.Empty;
     LastUsedTime    = 0.0f;
     IsReady         = false;
     DepAssetBundleInfos.Clear();
     ReferenceCount = 0;
     ReferenceList.Clear();
     LoadedAssetMap.Clear();
     OnBundleUnloadAction = null;
 }
示例#17
0
            // returns true after writing a reference marker if an existing reference existed, otherwise returning false.
            bool ReferenceListAddOrWriteInternal <T>(ReferenceList <T> refs, T value)
            {
                if (refs.Add(value, out var index))
                {
                    // 0: object reference (not inline)
                    // 1: object inline
                    UnmarkedWriteInt29(index << 1);
                    return(true);
                }

                return(false);
            }
        public override void establish_context()
        {
            var property = ReflectionHelper.GetAccessor((Expression<Func<ReferenceEntity, object>>)(x => x.ReferenceList));

            referencedEntities = new List<OtherEntity> {new OtherEntity(), new OtherEntity()};

            session = MockRepository.GenerateStub<ISession>();
            session.Stub(x => x.BeginTransaction()).Return(MockRepository.GenerateStub<ITransaction>());
            specification = new PersistenceSpecification<PropertyEntity>(session);

            sut = new ReferenceList<PropertyEntity, OtherEntity>(property, referencedEntities);
        }
        public void AddReference(ReferenceDefinition referenceDefinition)
        {
            if (referenceDefinition == null)
            {
                throw new ArgumentNullException("referenceDefinition");
            }

            if (References.Contains(referenceDefinition))
            {
                throw new ArgumentException("Reference definition is already added");
            }

            ReferenceList.Add(referenceDefinition);
        }
        public override void establish_context()
        {
            var property = ReflectionHelper.GetAccessor((Expression <Func <ReferenceEntity, object> >)(x => x.ReferenceList));

            referencedEntities = new List <OtherEntity> {
                new OtherEntity(), new OtherEntity()
            };

            session = A.Fake <ISession>();
            A.CallTo(() => session.BeginTransaction()).Returns(A.Dummy <ITransaction>());
            specification = new PersistenceSpecification <PropertyEntity>(session);

            sut = new ReferenceList <PropertyEntity, OtherEntity>(property, referencedEntities);
        }
        public static PersistenceSpecification <T> CheckList <T, TListElement>(this PersistenceSpecification <T> spec,
                                                                               Expression <Func <T, IEnumerable <TListElement> > > expression,
                                                                               IEnumerable <TListElement> propertyValue,
                                                                               IEqualityComparer elementComparer,
                                                                               Action <T, IEnumerable <TListElement> > listSetter)
        {
            Accessor property = ReflectionHelper.GetAccessor(expression);

            var list = new ReferenceList <T, TListElement>(property, propertyValue);

            list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value);

            return(spec.RegisterCheckedProperty(list, elementComparer));
        }
        public override void establish_context()
        {
            var property = ReflectionHelper.GetAccessor((Expression <Func <ReferenceEntity, object> >)(x => x.ReferenceList));

            referencedEntities = new List <OtherEntity> {
                new OtherEntity(), new OtherEntity()
            };

            session = MockRepository.GenerateStub <ISession>();
            session.Stub(x => x.BeginTransaction()).Return(MockRepository.GenerateStub <ITransaction>());
            specification = new PersistenceSpecification <PropertyEntity>(session);

            sut = new ReferenceList <PropertyEntity, OtherEntity>(property, referencedEntities);
        }
        /// <summary>
        /// Set references for specified locale.
        /// </summary>
        /// <param name="userContext">
        /// Information about the user that makes this method call.
        /// </param>
        /// <param name="loadedReferences">Loaded references.</param>
        /// <param name="locale">Currently used locale.</param>
        protected override void SetReferences(IUserContext userContext,
                                              ReferenceList loadedReferences,
                                              ILocale locale)
        {
            ReferenceList cachedReferences;

            if (userContext.Transaction.IsNull())
            {
                lock (References)
                {
                    cachedReferences = (ReferenceList)(References[locale.ISOCode]);
                    cachedReferences.Merge(loadedReferences);
                }
            }
        }
示例#24
0
        public static List <Plan> CreatePlans(EFDbContext dbContext)
        {
            var planSuper = new Plan
            {
                Name       = "Small",
                Price      = 699,
                Period     = "monthly",
                OrderIndex = 1,
                PlanCode   = "Small",
                Enabled    = true
            };

            var planMedium = new Plan
            {
                Name       = "Medium",
                Price      = 399,
                Period     = "money",
                OrderIndex = 2,
                PlanCode   = "Medium",
                Enabled    = true
            };

            var planSmall = new Plan
            {
                Name       = "Small",
                Price      = 199,
                Period     = "money",
                OrderIndex = 3,
                PlanCode   = "Super",
                Enabled    = true
            };

            var referenceList = new ReferenceList("Security Questions");

            CreateEmailTemplates(dbContext);

            dbContext.Plans.Add(planSuper);
            dbContext.Plans.Add(planMedium);
            dbContext.Plans.Add(planSmall);

            dbContext.ReferenceLists.Add(referenceList);

            dbContext.SaveChanges();

            return(new List <Plan> {
                planSuper, planMedium, planSmall
            });
        }
示例#25
0
        public XmlDocument BuildDgml(ReferenceList referenceList)
        {
            _referenceList = referenceList;

            _doc = new XmlDocument();

            var root = AddRootElement();

            AddNodes(root);
            AddLinks(root);
            AddCategories(root);
            AddStyles(root);
            AddProperties(root);

            return(_doc);
        }
示例#26
0
        public static User CreateUser(EFDbContext dbContext)
        {
            var customer = new Customer("John", "john-domain", "Join-LTD");

            dbContext.Customers.Add(customer);

            var role = new Role
            {
                CustomerId = customer.Id,
                Name       = "User",
                UserType   = UserType.SystemUser,
            };

            dbContext.Roles.Add(role);
            dbContext.SaveChanges();

            var referenceList = new ReferenceList("Security Questions");

            dbContext.ReferenceLists.Add(referenceList);

            var user = new User(customer, "*****@*****.**", "John", "Smith", "Qwerty123");

            dbContext.Users.Add(user);
            user.RoleUsers.Add(new RoleUsers
            {
                Role   = role,
                User   = user,
                RoleId = role.Id,
                UserId = user.Id
            });
            dbContext.SaveChanges();

            customer.AdminUser = user;
            dbContext.SaveChanges();

            dbContext.SecurityQuestions.Add(
                new SecurityQuestion
            {
                User     = user,
                UserId   = user.Id,
                Question = "b",
                Answer   = "AFY/TzXQKOSYGVlRGN1wqoMMkFafUlap2myEs+6wsX3Zr8NheaRhgwJCy/dVqFXiAw=="
            });
            dbContext.SaveChanges();

            return(user);
        }
示例#27
0
        private static void WriteReferencesToConsole(ReferenceList result)
        {
            Console.WriteLine("References:");
            foreach (var item in result.References)
            {
                Console.WriteLine($"{item.Assembly.Name} {item.Assembly.Version} -> {item.ReferencedAssembly.Name} {item.ReferencedAssembly.Version}");
            }

            Console.WriteLine();
            Console.WriteLine("Assemblies:");
            foreach (var item in result.Assemblies)
            {
                Console.WriteLine($"{item.Name} {item.Version}: {item.Category}");
            }

            Console.ReadKey();
        }
示例#28
0
        public IQueryable <ReferenceModel> GetQuery(ReferenceList name)
        {
            Guid companyId = this.GetCurrentCompanyId();

            string _name = name.ToString();

            return(this._repoEnumReference
                   .Query().Filter(x => x.name == _name && x.companyId == companyId)
                   .Get()
                   .OrderBy(x => x.displayOrder)
                   .ThenBy(x => x.value)
                   .Select(x => new ReferenceModel()
            {
                value = x.value,
                description = x.description
            }));
        }
        /// <summary>
        /// Read rows from the excel xml format.
        /// Overridden by each class that inherits this class.
        /// </summary>
        /// <param name="userContext">
        /// Information about the user that makes this method call.
        /// </param>
        /// <param name='xmlDoc'>The xml document that the row node will be read from.</param>
        /// <param name="nsmgr">Namespacemanager containing all namespaces used by the excel compatible xml format</param>
        protected override void ReadExcelXmlRows(IUserContext userContext,
                                                 XmlDocument xmlDoc,
                                                 XmlNamespaceManager nsmgr)
        {
            ReferenceList references;
            XmlNode       dataNode;
            XmlNodeList   rowNodes;

            rowNodes   = xmlDoc.SelectNodes("/ss:Workbook/ss:Worksheet/ss:Table/ss:Row", nsmgr);
            references = new ReferenceList();
            foreach (XmlNode rowNode in rowNodes)
            {
                dataNode = rowNode.SelectSingleNode("ss:Cell/ss:Data", nsmgr);
                references.Add(CoreData.ReferenceManager.GetReference(userContext, dataNode.InnerText.WebParseInt32()));
            }

            References = references;
        }
示例#30
0
        public Guid Provision(CustomersProvisionModel model)
        {
            var fullName = model.FirstName + " " + model.LastName;

            //create customer in stripe
            StripeCustomer stripeCustomer = StripeFactory.GetStripeService().CreateCustomer(fullName, model.Email);

            // Customer
            Customer customer = new Customer(fullName, model.Domain, model.Company, stripeCustomer.Id)
            {
                PlanCreatedOn = stripeCustomer.Created
            };

            _customerRepository.Add(customer);

            // roles
            var role = new Role(customer, "Administrator", true, UserType.SystemUser);

            _roleRepository.Add(role);

            // users
            var user = new User(customer, model.Email, model.FirstName, model.LastName, model.Password, true);

            _userRepository.Add(user);
            role.AddUser(user);
            customer.UpdateAdminUser(user);

            // security questions
            ReferenceList referenceList = _referenceListRepository.Query().SingleOrDefault(l => l.SystemName == "Security Questions");

            foreach (var securityQuestion in SecurityQuestions.Questions)
            {
                referenceList.AddItem(customer, securityQuestion);
            }

            // user security questions
            user.AddSecurityQuestion("a", "a");
            user.AddSecurityQuestion("b", "b");
            user.AddSecurityQuestion("c", "c");

            _unitOfWork.Commit();

            return(customer.Id);
        }
示例#31
0
        public string WriteDefaultLine(bool terminate, int fieldNum)
        {
            List <string> options = new List <string>();

            if (!string.IsNullOrWhiteSpace(Units))
            {
                options.Add($"{{{Units}}}");
            }
            if (HasDefault)
            {
                options.Add($"Def: {Default}");
            }
            if (Keys.Any())
            {
                options.Add($"[{string.Join(", ", Keys)}]");
            }
            if (ReferenceList.Any())
            {
                options.Add($"RefList: [{string.Join(", ", ReferenceList)}]");
            }
            if (ReferenceClassList.Any())
            {
                options.Add($"RefClassList: [{string.Join(", ", ReferenceClassList)}]");
            }
            if (ObjectList.Any())
            {
                options.Add($"[{string.Join(", ", ObjectList)}]");
            }
            if (AutoCalculatable)
            {
                options.Add("AC");
            }
            if (AutoSizeable)
            {
                options.Add("AS");
            }
            if (Required)
            {
                options.Add("REQ");
            }
            options.Add($"#{fieldNum}");

            return($"  {(HasDefault ? Default : "")}{(terminate ? ";" : ",")}   ! {Name} {string.Join(", ", options)}\n");
        }
        /// <summary>
        /// Convert a list of WebReference instances
        /// to a ReferenceList.
        /// </summary>
        /// <param name="userContext">
        /// Information about the user that makes this method call.
        /// </param>
        /// <param name="webReferences">List of WebReference instances.</param>
        /// <returns>A ReferenceList.</returns>
        private ReferenceList GetReferences(IUserContext userContext,
                                            List <WebReference> webReferences)
        {
            ReferenceList references;

            references = null;
            if (webReferences.IsNotEmpty())
            {
                references = new ReferenceList();
                foreach (WebReference webReference in webReferences)
                {
                    references.Add(GetReference(userContext, webReference));
                }

                references.Sort();
            }

            return(references);
        }
        public static PersistenceSpecification <T> CheckInverseList <T, TListElement>(this PersistenceSpecification <T> spec,
                                                                                      Expression <Func <T, IEnumerable <TListElement> > > expression,
                                                                                      IEnumerable <TListElement> propertyValue,
                                                                                      IEqualityComparer elementComparer,
                                                                                      Action <T, TListElement> listItemSetter)
        {
            Accessor property = ReflectionHelper.GetAccessor(expression);

            var list = new ReferenceList <T, TListElement>(property, propertyValue);

            list.ValueSetter = (target, propertyInfo, value) =>
            {
                foreach (var item in value)
                {
                    listItemSetter(target, item);
                }
            };

            return(spec.RegisterCheckedPropertyWithoutTransactionalSave(list, elementComparer));
        }
示例#34
0
		public Message SecureMessage ()
		{
			secprop = Message.Properties.Security ?? new SecurityMessageProperty ();

			SecurityToken encToken =
				secprop.InitiatorToken != null ? secprop.InitiatorToken.SecurityToken : security.EncryptionToken;
			// FIXME: it might be still incorrect.
			SecurityToken signToken =
				Parameters == CounterParameters ? null :
				security.SigningToken;
			MessageProtectionOrder protectionOrder =
				security.MessageProtectionOrder;
			SecurityTokenSerializer serializer =
				security.TokenSerializer;
			SecurityBindingElement element =
				security.Element;
			SecurityAlgorithmSuite suite = element.DefaultAlgorithmSuite;

// FIXME: remove this hack
if (!ShouldOutputEncryptedKey)
	encToken = new BinarySecretSecurityToken (secprop.EncryptionKey);

			string messageId = "uuid-" + Guid.NewGuid ();
			int identForMessageId = 1;
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;

			UniqueId relatesTo = RelatesTo;
			if (relatesTo != null)
				msg.Headers.RelatesTo = relatesTo;
			else // FIXME: probably it is always added when it is stateful ?
				msg.Headers.MessageId = new UniqueId ("urn:" + messageId);

			// FIXME: get correct ReplyTo value
			if (Direction == MessageDirection.Input)
				msg.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);

			if (MessageTo != null)
				msg.Headers.To = MessageTo.Uri;

			// wss:Security
			WSSecurityMessageHeader header =
				new WSSecurityMessageHeader (serializer);
			msg.Headers.Add (header);
			// 1. [Timestamp]
			if (element.IncludeTimestamp) {
				WsuTimestamp timestamp = new WsuTimestamp ();
				timestamp.Id = messageId + "-" + identForMessageId++;
				timestamp.Created = DateTime.Now;
				// FIXME: on service side, use element.LocalServiceSettings.TimestampValidityDuration
				timestamp.Expires = timestamp.Created.Add (element.LocalClientSettings.TimestampValidityDuration);
				header.AddContent (timestamp);
			}

			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", msg.Version.Envelope.Namespace);
			nsmgr.AddNamespace ("o", Constants.WssNamespace);
			nsmgr.AddNamespace ("u", Constants.WsuNamespace);
			nsmgr.AddNamespace ("o11", Constants.Wss11Namespace);

			/*WrappedKey*/SecurityToken primaryToken = null;
			DerivedKeySecurityToken dkeyToken = null;
			SecurityToken actualToken = null;
			SecurityKeyIdentifierClause actualClause = null;
			Signature sig = null;

			List<DerivedKeySecurityToken> derivedKeys =
				new List<DerivedKeySecurityToken> ();

			SymmetricAlgorithm masterKey = new RijndaelManaged ();
			masterKey.KeySize = suite.DefaultSymmetricKeyLength;
			masterKey.Mode = CipherMode.CBC;
			masterKey.Padding = PaddingMode.ISO10126;
			SymmetricAlgorithm actualKey = masterKey;

			// 2. [Encryption Token]

			// SecurityTokenInclusionMode
			// - Initiator or Recipient
			// - done or notyet. FIXME: not implemented yet
			// It also affects on key reference output

			bool includeEncToken = // /* FIXME: remove this hack */Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.RecipientParameters.InclusionMode, false);
			bool includeSigToken = // /* FIXME: remove this hack */ Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.InitiatorParameters.InclusionMode, false);

			SecurityKeyIdentifierClause encClause = ShouldOutputEncryptedKey ?
				CounterParameters.CallCreateKeyIdentifierClause (encToken, !ShouldOutputEncryptedKey ? SecurityTokenReferenceStyle.Internal : includeEncToken ? Parameters.ReferenceStyle : SecurityTokenReferenceStyle.External) : null;

			MessagePartSpecification sigSpec = SignaturePart;
			MessagePartSpecification encSpec = EncryptionPart;

			// encryption key (possibly also used for signing)
			// FIXME: get correct SymmetricAlgorithm according to the algorithm suite
			if (secprop.EncryptionKey != null)
				actualKey.Key = secprop.EncryptionKey;

// FIXME: remove thid hack
if (!ShouldOutputEncryptedKey)
primaryToken = RequestContext.RequestMessage.Properties.Security.ProtectionToken.SecurityToken as WrappedKeySecurityToken;
else
			primaryToken =
				// FIXME: remove this hack?
				encToken is SecurityContextSecurityToken ? encToken :
				new WrappedKeySecurityToken (messageId + "-" + identForMessageId++,
				actualKey.Key,
				// security.DefaultKeyWrapAlgorithm,
				Parameters.InternalHasAsymmetricKey ?
					suite.DefaultAsymmetricKeyWrapAlgorithm :
					suite.DefaultSymmetricKeyWrapAlgorithm,
				encToken,
				encClause != null ? new SecurityKeyIdentifier (encClause) : null);

			// If it reuses request's encryption key, do not output.
			if (ShouldOutputEncryptedKey)
				header.AddContent (primaryToken);

			actualToken = primaryToken;

			// FIXME: I doubt it is correct...
			WrappedKeySecurityToken requestEncKey = ShouldOutputEncryptedKey ? null : primaryToken as WrappedKeySecurityToken;
			actualClause = requestEncKey == null ? (SecurityKeyIdentifierClause)
				new LocalIdKeyIdentifierClause (actualToken.Id, typeof (WrappedKeySecurityToken)) :
				new InternalEncryptedKeyIdentifierClause (SHA1.Create ().ComputeHash (requestEncKey.GetWrappedKey ()));

			// generate derived key if needed
			if (CounterParameters.RequireDerivedKeys) {
				RijndaelManaged deriv = new RijndaelManaged ();
				deriv.KeySize = suite.DefaultEncryptionKeyDerivationLength;
				deriv.Mode = CipherMode.CBC;
				deriv.Padding = PaddingMode.ISO10126;
				deriv.GenerateKey ();
				dkeyToken = new DerivedKeySecurityToken (
					GenerateId (doc),
					null, // algorithm
					actualClause,
					new InMemorySymmetricSecurityKey (actualKey.Key),
					null, // name
					null, // generation
					null, // offset
					deriv.Key.Length,
					null, // label
					deriv.Key);
				derivedKeys.Add (dkeyToken);
				actualToken = dkeyToken;
				actualKey.Key = ((SymmetricSecurityKey) dkeyToken.SecurityKeys [0]).GetSymmetricKey ();
				actualClause = new LocalIdKeyIdentifierClause (dkeyToken.Id);
				header.AddContent (dkeyToken);
			}

			ReferenceList refList = new ReferenceList ();
			// When encrypted with DerivedKeyToken, put references
			// immediately after the derived token (not inside the
			// primary token).
			// Similarly, when we do not output EncryptedKey,
			// output ReferenceList in the same way.
			if (CounterParameters.RequireDerivedKeys ||
			    !ShouldOutputEncryptedKey)
				header.AddContent (refList);
			else
				((WrappedKeySecurityToken) primaryToken).ReferenceList = refList;

			// [Signature Confirmation]
			if (security.RequireSignatureConfirmation && secprop.ConfirmedSignatures.Count > 0)
				foreach (string value in secprop.ConfirmedSignatures)
					header.AddContent (new Wss11SignatureConfirmation (GenerateId (doc), value));

			SupportingTokenInfoCollection tokenInfos =
				Direction == MessageDirection.Input ?
				security.CollectSupportingTokens (GetAction ()) :
				new SupportingTokenInfoCollection (); // empty

			foreach (SupportingTokenInfo tinfo in tokenInfos)
				header.AddContent (tinfo.Token);

			// populate DOM to sign.
			XPathNavigator nav = doc.CreateNavigator ();
			using (XmlWriter w = nav.AppendChild ()) {
				msg.WriteMessage (w);
			}

			XmlElement body = doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement;
			string bodyId = null;
			XmlElement secElem = null;
			Collection<WSSignedXml> endorsedSignatures =
				new Collection<WSSignedXml> ();
			bool signatureProtection = (protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature);

			// Below are o:Security contents that are not signed...
			if (includeSigToken && signToken != null)
				header.AddContent (signToken);

			switch (protectionOrder) {
			case MessageProtectionOrder.EncryptBeforeSign:
				// FIXME: implement
				throw new NotImplementedException ();
			case MessageProtectionOrder.SignBeforeEncrypt:
			case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature:

				// sign
				// see clause 8 of WS-SecurityPolicy C.2.2
				WSSignedXml sxml = new WSSignedXml (doc);
				SecurityTokenReferenceKeyInfo sigKeyInfo;

				sig = sxml.Signature;
				sig.SignedInfo.CanonicalizationMethod =
					suite.DefaultCanonicalizationAlgorithm;
				foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/u:Timestamp", nsmgr))
					CreateReference (sig, elem, elem.GetAttribute ("Id", Constants.WsuNamespace));
				foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr))
					CreateReference (sig, elem, elem.GetAttribute ("Id", Constants.WsuNamespace));
				foreach (SupportingTokenInfo tinfo in tokenInfos)
					if (tinfo.Mode != SecurityTokenAttachmentMode.Endorsing) {
						XmlElement el = sxml.GetIdElement (doc, tinfo.Token.Id);
						CreateReference (sig, el, el.GetAttribute ("Id", Constants.WsuNamespace));
					}
				XmlNodeList nodes = doc.SelectNodes ("/s:Envelope/s:Header/*", nsmgr);
				for (int i = 0; i < msg.Headers.Count; i++) {
					MessageHeaderInfo h = msg.Headers [i];
					if (h.Name == "Security" && h.Namespace == Constants.WssNamespace)
						secElem = nodes [i] as XmlElement;
					else if (sigSpec.HeaderTypes.Count == 0 ||
					    sigSpec.HeaderTypes.Contains (new XmlQualifiedName (h.Name, h.Namespace))) {
						string id = GenerateId (doc);
						h.Id = id;
						CreateReference (sig, nodes [i] as XmlElement, id);
					}
				}
				if (sigSpec.IsBodyIncluded) {
					bodyId = GenerateId (doc);
					CreateReference (sig, body.ParentNode as XmlElement, bodyId);
				}

				if (security.DefaultSignatureAlgorithm == SignedXml.XmlDsigHMACSHA1Url) {
					// FIXME: use appropriate hash algorithm
					sxml.ComputeSignature (new HMACSHA1 (actualKey.Key));
					sigKeyInfo = new SecurityTokenReferenceKeyInfo (actualClause, serializer, doc);
				}
				else {
					SecurityKeyIdentifierClause signClause =
						CounterParameters.CallCreateKeyIdentifierClause (signToken, includeSigToken ? CounterParameters.ReferenceStyle : SecurityTokenReferenceStyle.External);
					AsymmetricSecurityKey signKey = (AsymmetricSecurityKey) signToken.ResolveKeyIdentifierClause (signClause);
					sxml.SigningKey = signKey.GetAsymmetricAlgorithm (security.DefaultSignatureAlgorithm, true);
					sxml.ComputeSignature ();
					sigKeyInfo = new SecurityTokenReferenceKeyInfo (signClause, serializer, doc);
				}

				sxml.KeyInfo = new KeyInfo ();
				sxml.KeyInfo.AddClause (sigKeyInfo);

				if (!signatureProtection)
					header.AddContent (sig);

				// endorse the signature with (signed)endorsing
				// supporting tokens.

				foreach (SupportingTokenInfo tinfo in tokenInfos) {
					switch (tinfo.Mode) {
					case SecurityTokenAttachmentMode.Endorsing:
					case SecurityTokenAttachmentMode.SignedEndorsing:
						if (sxml.Signature.Id == null) {
							sig.Id = GenerateId (doc);
							secElem.AppendChild (sxml.GetXml ());
						}
						WSSignedXml ssxml = new WSSignedXml (doc);
						ssxml.Signature.SignedInfo.CanonicalizationMethod = suite.DefaultCanonicalizationAlgorithm;
						CreateReference (ssxml.Signature, doc, sig.Id);
						SecurityToken sst = tinfo.Token;
						SecurityKey ssk = sst.SecurityKeys [0]; // FIXME: could be different?
						SecurityKeyIdentifierClause tclause = new LocalIdKeyIdentifierClause (sst.Id); // FIXME: could be different?
						if (ssk is SymmetricSecurityKey) {
							SymmetricSecurityKey signKey = (SymmetricSecurityKey) ssk;
							ssxml.ComputeSignature (signKey.GetKeyedHashAlgorithm (suite.DefaultSymmetricSignatureAlgorithm));
						} else {
							AsymmetricSecurityKey signKey = (AsymmetricSecurityKey) ssk;
							ssxml.SigningKey = signKey.GetAsymmetricAlgorithm (suite.DefaultAsymmetricSignatureAlgorithm, true);
							ssxml.ComputeSignature ();
						}
						ssxml.KeyInfo.AddClause (new SecurityTokenReferenceKeyInfo (tclause, serializer, doc));
						if (!signatureProtection)
							header.AddContent (ssxml.Signature);
						endorsedSignatures.Add (ssxml);

						break;
					}
				}

				// encrypt

				WSEncryptedXml exml = new WSEncryptedXml (doc);

				EncryptedData edata = Encrypt (body, actualKey, actualToken.Id, refList, actualClause, exml, doc);
				EncryptedXml.ReplaceElement (body, edata, false);

				// encrypt signature
				if (signatureProtection) {
					XmlElement sigxml = sig.GetXml ();
					edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc);
					header.AddContent (edata);

					foreach (WSSignedXml ssxml in endorsedSignatures) {
						sigxml = ssxml.GetXml ();
						edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc);
						header.AddContent (edata);
					}

					if (security.RequireSignatureConfirmation) {
						Collection<Wss11SignatureConfirmation> confs = header.FindAll<Wss11SignatureConfirmation> ();
						int count = 0;
						foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr)) {
							edata = Encrypt (elem, actualKey, confs [count].Id, refList, actualClause, exml, doc);
							EncryptedXml.ReplaceElement (elem, edata, false);
							header.Contents.Insert (header.Contents.IndexOf (confs [count]), edata);
							header.Contents.Remove (confs [count++]);
						}
					}
				}

				// encrypt Encrypted supporting tokens
				foreach (SupportingTokenInfo tinfo in tokenInfos) {
					if (tinfo.Mode == SecurityTokenAttachmentMode.SignedEncrypted) {
						XmlElement el = exml.GetIdElement (doc, tinfo.Token.Id);
						tinfo.Encrypted = Encrypt (el, actualKey, actualToken.Id, refList, actualClause, exml, doc);
						EncryptedXml.ReplaceElement (el, tinfo.Encrypted, false);
						header.Contents.Insert (header.Contents.IndexOf (tinfo.Token), tinfo.Encrypted);
						header.Contents.Remove (tinfo.Token);
					}
				}
				break;
			}

			Message ret = new WSSecurityMessage (Message.CreateMessage (msg.Version, msg.Headers.Action, new XmlNodeReader (doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement)), bodyId);
			ret.Properties.Security = (SecurityMessageProperty) secprop.CreateCopy ();
			ret.Properties.Security.EncryptionKey = masterKey.Key;

			// FIXME: can we support TransportToken here?
			if (element is AsymmetricSecurityBindingElement) {
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (encToken, null); // FIXME: second argument
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (signToken, null); // FIXME: second argument
			}
			else
				ret.Properties.Security.ProtectionToken = new SecurityTokenSpecification (primaryToken, null);

			ret.Headers.Clear ();
			ret.Headers.CopyHeadersFrom (msg);

			// Header contents are:
			//	- Timestamp
			//	- SignatureConfirmation if required
			//	- EncryptionToken if included
			//	- derived key token for EncryptionToken
			//	- ReferenceList for encrypted items
			//	- signed supporting tokens
			//	- signed endorsing supporting tokens
			//	(i.e. Signed/SignedEncrypted/SignedEndorsing)
			//	- Signature Token if different from enc token.
			//	- derived key token for sig token if different
			//	- Signature for:
			//		- Timestamp
			//		- supporting tokens (regardless of
			//		  its inclusion)
			//		- message parts in SignedParts
			//		- SignatureToken if TokenProtection
			//		  (regardless of its inclusion)
			//	- Signatures for the main signature (above),
			//	  for every endorsing token and signed
			//	  endorsing token.
			//	

//MessageBuffer zzz = ret.CreateBufferedCopy (100000);
//ret = zzz.CreateMessage ();
//Console.WriteLine (zzz.CreateMessage ());
			return ret;
		}
示例#35
0
		public Message SecureMessage ()
		{
			secprop = Message.Properties.Security ?? new SecurityMessageProperty ();

			SecurityToken encToken =
				secprop.InitiatorToken != null ? secprop.InitiatorToken.SecurityToken : security.EncryptionToken;
			// FIXME: it might be still incorrect.
			SecurityToken signToken =
				Parameters == CounterParameters ? null :
				security.SigningToken;
			MessageProtectionOrder protectionOrder =
				security.MessageProtectionOrder;
			SecurityBindingElement element =
				security.Element;
			SecurityAlgorithmSuite suite = element.DefaultAlgorithmSuite;

			string messageId = "uuid-" + Guid.NewGuid ();
			int identForMessageId = 1;
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
            var action = msg.Headers.Action;

			if (msg.Version.Addressing != AddressingVersion.None) {
                AddAddressingToHeader (msg.Headers);
			}
				
			// wss:Security
			WSSecurityMessageHeader header =
                new WSSecurityMessageHeader (security.TokenSerializer);
			msg.Headers.Add (header);
			// 1. [Timestamp]
			if (element.IncludeTimestamp) {
                AddTimestampToHeader (header, messageId + "-" + identForMessageId++);
			}

			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", msg.Version.Envelope.Namespace);
			nsmgr.AddNamespace ("o", Constants.WssNamespace);
			nsmgr.AddNamespace ("u", Constants.WsuNamespace);
			nsmgr.AddNamespace ("o11", Constants.Wss11Namespace);

			/*WrappedKey*/SecurityToken primaryToken = null;
			SecurityToken actualToken = null;
			SecurityKeyIdentifierClause actualClause = null;

			

			SymmetricAlgorithm masterKey = new RijndaelManaged ();
			masterKey.KeySize = suite.DefaultSymmetricKeyLength;
			masterKey.Mode = CipherMode.CBC;
			masterKey.Padding = PaddingMode.ISO10126;
			SymmetricAlgorithm actualKey = masterKey;

			// 2. [Encryption Token]

			// SecurityTokenInclusionMode
			// - Initiator or Recipient
			// - done or notyet. FIXME: not implemented yet
			// It also affects on key reference output

			bool includeEncToken = // /* FIXME: remove this hack */Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.RecipientParameters.InclusionMode, false);
			bool includeSigToken = // /* FIXME: remove this hack */ Parameters is SslSecurityTokenParameters ? false :
						ShouldIncludeToken (
				Security.InitiatorParameters.InclusionMode, false);

			SecurityKeyIdentifierClause encClause = ShouldOutputEncryptedKey ?
				CounterParameters.CallCreateKeyIdentifierClause (encToken, !ShouldOutputEncryptedKey ? SecurityTokenReferenceStyle.Internal : includeEncToken ? Parameters.ReferenceStyle : SecurityTokenReferenceStyle.External) : null;

			MessagePartSpecification encSpec = EncryptionPart;

			// encryption key (possibly also used for signing)
			// FIXME: get correct SymmetricAlgorithm according to the algorithm suite
			if (secprop.EncryptionKey != null)
				actualKey.Key = secprop.EncryptionKey;

// FIXME: remove thid hack
if (!ShouldOutputEncryptedKey)
primaryToken = secprop.ProtectionToken.SecurityToken as WrappedKeySecurityToken;
else
			primaryToken =
				// FIXME: remove this hack?
				encToken is SecurityContextSecurityToken ? encToken :
				new WrappedKeySecurityToken (messageId + "-" + identForMessageId++,
				actualKey.Key,
				// security.DefaultKeyWrapAlgorithm,
				Parameters.InternalHasAsymmetricKey ?
					suite.DefaultAsymmetricKeyWrapAlgorithm :
					suite.DefaultSymmetricKeyWrapAlgorithm,
				encToken,
				encClause != null ? new SecurityKeyIdentifier (encClause) : null);

			// If it reuses request's encryption key, do not output.
			if (ShouldOutputEncryptedKey)
				header.AddContent (primaryToken);

			actualToken = primaryToken;

			// FIXME: I doubt it is correct...
			WrappedKeySecurityToken requestEncKey = ShouldOutputEncryptedKey ? null : primaryToken as WrappedKeySecurityToken;
			actualClause = requestEncKey == null ? (SecurityKeyIdentifierClause)
				new LocalIdKeyIdentifierClause (actualToken.Id, typeof (WrappedKeySecurityToken)) :
				new InternalEncryptedKeyIdentifierClause (SHA1.Create ().ComputeHash (requestEncKey.GetWrappedKey ()));

			// generate derived key if needed
			if (CounterParameters.RequireDerivedKeys) {
                var dkeyToken = CreateDerivedKey (GenerateId (doc), actualClause, actualKey);
                actualToken = dkeyToken;
                actualKey.Key = ((SymmetricSecurityKey)dkeyToken.SecurityKeys [0]).GetSymmetricKey ();
                actualClause = new LocalIdKeyIdentifierClause (dkeyToken.Id);
                header.AddContent (dkeyToken);
			}

			ReferenceList refList = new ReferenceList ();
			// When encrypted with DerivedKeyToken, put references
			// immediately after the derived token (not inside the
			// primary token).
			// Similarly, when we do not output EncryptedKey,
			// output ReferenceList in the same way.
			if (CounterParameters.RequireDerivedKeys ||
			    !ShouldOutputEncryptedKey)
				header.AddContent (refList);
			else
				((WrappedKeySecurityToken) primaryToken).ReferenceList = refList;

			// [Signature Confirmation]
			if (security.RequireSignatureConfirmation && secprop.ConfirmedSignatures.Count > 0)
				foreach (string value in secprop.ConfirmedSignatures)
					header.AddContent (new Wss11SignatureConfirmation (GenerateId (doc), value));

			SupportingTokenInfoCollection tokenInfos =
				Direction == MessageDirection.Input ?
				security.CollectSupportingTokens (GetAction ()) :
				new SupportingTokenInfoCollection (); // empty

			foreach (SupportingTokenInfo tinfo in tokenInfos)
				header.AddContent (tinfo.Token);

			// populate DOM to sign.
			XPathNavigator nav = doc.CreateNavigator ();
			using (XmlWriter w = nav.AppendChild ()) {
				msg.WriteMessage (w);
			}

			XmlElement body = doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement;
			string bodyId = null;
			Collection<WSSignedXml> endorsedSignatures =
				new Collection<WSSignedXml> ();
			bool signatureProtection = (protectionOrder == MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature);

			// Below are o:Security contents that are not signed...
			if (includeSigToken && signToken != null)
				header.AddContent (signToken);

			switch (protectionOrder) {
			case MessageProtectionOrder.EncryptBeforeSign:
				// FIXME: implement
				throw new NotImplementedException ();
			case MessageProtectionOrder.SignBeforeEncrypt:
			case MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature:

               
                var sig = CreateSignature (doc, body, nsmgr, tokenInfos, 
                    actualClause, actualKey, signToken, includeSigToken, 
                    signatureProtection, header, endorsedSignatures, 
                    ref bodyId);

				
				// encrypt

				WSEncryptedXml exml = new WSEncryptedXml (doc);

				EncryptedData edata = Encrypt (body, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementContentUrl);
				EncryptedXml.ReplaceElement (body, edata, false);

				// encrypt signature
				if (signatureProtection) {
					XmlElement sigxml = sig.GetXml ();
					edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
					header.AddContent (edata);

					foreach (WSSignedXml ssxml in endorsedSignatures) {
						sigxml = ssxml.GetXml ();
						edata = Encrypt (sigxml, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
						header.AddContent (edata);
					}

					if (security.RequireSignatureConfirmation) {
						Collection<Wss11SignatureConfirmation> confs = header.FindAll<Wss11SignatureConfirmation> ();
						int count = 0;
						foreach (XmlElement elem in doc.SelectNodes ("/s:Envelope/s:Header/o:Security/o11:SignatureConfirmation", nsmgr)) {
							edata = Encrypt (elem, actualKey, confs [count].Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
							EncryptedXml.ReplaceElement (elem, edata, false);
							header.Contents.Insert (header.Contents.IndexOf (confs [count]), edata);
							header.Contents.Remove (confs [count++]);
						}
					}
				}


				// encrypt Encrypted supporting tokens
				foreach (SupportingTokenInfo tinfo in tokenInfos) {
					if (tinfo.Mode == SecurityTokenAttachmentMode.SignedEncrypted) {
						XmlElement el = exml.GetIdElement (doc, tinfo.Token.Id);
						tinfo.Encrypted = Encrypt (el, actualKey, actualToken.Id, refList, actualClause, exml, doc, EncryptedXml.XmlEncElementUrl);
						EncryptedXml.ReplaceElement (el, tinfo.Encrypted, false);
						header.Contents.Insert (header.Contents.IndexOf (tinfo.Token), tinfo.Encrypted);
						header.Contents.Remove (tinfo.Token);
					}
				}
				break;
			}


            

			Message ret = new WSSecurityMessage (Message.CreateMessage (msg.Version, action, new XmlNodeReader (doc.SelectSingleNode ("/s:Envelope/s:Body/*", nsmgr) as XmlElement)), bodyId);
			ret.Properties.Security = (SecurityMessageProperty) secprop.CreateCopy ();
			ret.Properties.Security.EncryptionKey = masterKey.Key;

			// FIXME: can we support TransportToken here?
			if (element is AsymmetricSecurityBindingElement) {
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (encToken, null); // FIXME: second argument
				ret.Properties.Security.InitiatorToken = new SecurityTokenSpecification (signToken, null); // FIXME: second argument
			}
			else
				ret.Properties.Security.ProtectionToken = new SecurityTokenSpecification (primaryToken, null);

			ret.Headers.Clear ();
			ret.Headers.CopyHeadersFrom (msg);
            
			// Header contents are:
			//	- Timestamp
			//	- SignatureConfirmation if required
			//	- EncryptionToken if included
			//	- derived key token for EncryptionToken
			//	- ReferenceList for encrypted items
			//	- signed supporting tokens
			//	- signed endorsing supporting tokens
			//	(i.e. Signed/SignedEncrypted/SignedEndorsing)
			//	- Signature Token if different from enc token.
			//	- derived key token for sig token if different
			//	- Signature for:
			//		- Timestamp
			//		- supporting tokens (regardless of
			//		  its inclusion)
			//		- message parts in SignedParts
			//		- SignatureToken if TokenProtection
			//		  (regardless of its inclusion)
			//	- Signatures for the main signature (above),
			//	  for every endorsing token and signed
			//	  endorsing token.
			//	

//MessageBuffer zzz = ret.CreateBufferedCopy (100000);
//ret = zzz.CreateMessage ();
//Console.WriteLine (zzz.CreateMessage ());
			return ret;
		}
        void CreateMember(Type interfaceType, Type duckType, CodeTypeDeclaration codeType, ReferenceList references, CodeFieldReferenceExpression codeFldRef)
        {
            CodeTypeReference codeTRInterface = new CodeTypeReference(TypeX.Create(interfaceType).FullName);

            //// 找到duckType里面是否有公共的_obj;
            //FieldInfo fiObj = duckType.GetField("_obj", BindingFlags.Public | BindingFlags.Instance);
            //Type innerType = fiObj != null ? fiObj.FieldType : null;

            CodeFieldReferenceExpression fdRef = null;

            #region 方法
            foreach (var mi in interfaceType.GetMethods())
            {
                // 忽略专用名字的方法,如属性的get/set,还有构造函数
                if ((mi.Attributes & MethodAttributes.SpecialName) != 0) continue;

                CodeMemberMethod codeMethod = new CodeMemberMethod();
                codeType.Members.Add(codeMethod);

                codeMethod.Name = mi.Name;
                codeMethod.ReturnType = new CodeTypeReference(mi.ReturnType);
                codeMethod.PrivateImplementationType = codeTRInterface;

                references.AddReference(mi.ReturnType);

                ParameterInfo[] parameters = mi.GetParameters();
                CodeArgumentReferenceExpression[] codeArgs = new CodeArgumentReferenceExpression[parameters.Length];

                int n = 0;
                Type[] pits = new Type[parameters.Length];
                foreach (ParameterInfo parameter in parameters)
                {
                    pits[n] = parameter.ParameterType;

                    references.AddReference(parameter.ParameterType);
                    CodeParameterDeclarationExpression codeParam = new CodeParameterDeclarationExpression(parameter.ParameterType, parameter.Name);
                    codeMethod.Parameters.Add(codeParam);
                    codeArgs[n++] = new CodeArgumentReferenceExpression(parameter.Name);
                }

                CodeMethodInvokeExpression codeMethodInvoke = new CodeMethodInvokeExpression(FindMember(duckType, mi, codeFldRef), mi.Name, codeArgs);

                if (mi.ReturnType == typeof(void))
                    codeMethod.Statements.Add(codeMethodInvoke);
                else
                    codeMethod.Statements.Add(new CodeMethodReturnStatement(codeMethodInvoke));
            }
            #endregion

            #region 属性
            foreach (PropertyInfo pi in interfaceType.GetProperties())
            {
                CodeMemberProperty property = new CodeMemberProperty();
                codeType.Members.Add(property);

                property.Name = pi.Name;
                property.Type = new CodeTypeReference(pi.PropertyType);
                property.Attributes = MemberAttributes.Public;
                property.PrivateImplementationType = codeTRInterface;

                references.AddReference(pi.PropertyType);

                ParameterInfo[] parameters = pi.GetIndexParameters();
                CodeArgumentReferenceExpression[] args = new CodeArgumentReferenceExpression[parameters.Length];

                int n = 0;
                foreach (ParameterInfo parameter in parameters)
                {
                    CodeParameterDeclarationExpression codeParam = new CodeParameterDeclarationExpression(parameter.ParameterType, parameter.Name);
                    property.Parameters.Add(codeParam);

                    references.AddReference(parameter.ParameterType);

                    CodeArgumentReferenceExpression codeArgRef = new CodeArgumentReferenceExpression(parameter.Name);
                    args[n++] = codeArgRef;
                }

                fdRef = FindMember(duckType, pi, codeFldRef);

                if (pi.CanRead)
                {
                    property.HasGet = true;

                    if (args.Length == 0)
                    {
                        property.GetStatements.Add(
                            new CodeMethodReturnStatement(
                                new CodePropertyReferenceExpression(
                                    fdRef,
                                    pi.Name
                                )
                            )
                        );
                    }
                    else
                    {
                        property.GetStatements.Add(
                            new CodeMethodReturnStatement(
                                new CodeIndexerExpression(
                                    fdRef,
                                    args
                                )
                            )
                        );
                    }
                }

                if (pi.CanWrite)
                {
                    property.HasSet = true;

                    if (args.Length == 0)
                    {
                        property.SetStatements.Add(
                            new CodeAssignStatement(
                                new CodePropertyReferenceExpression(
                                    fdRef,
                                    pi.Name
                                ),
                                new CodePropertySetValueReferenceExpression()
                            )
                        );
                    }
                    else
                    {
                        property.SetStatements.Add(
                            new CodeAssignStatement(
                                new CodeIndexerExpression(
                                    fdRef,
                                    args
                                ),
                                new CodePropertySetValueReferenceExpression()
                            )
                        );
                    }

                }
            }
            #endregion

            #region 事件
            foreach (EventInfo ei in interfaceType.GetEvents())
            {
                fdRef = FindMember(duckType, ei, codeFldRef);

                StringBuilder sbCode = new StringBuilder();
                sbCode.Append("public event " + ei.EventHandlerType.FullName + " @" + ei.Name + "{");
                //sbCode.Append("add    {" + codeFldObj.Name + "." + ei.Name + "+=value;}");
                //sbCode.Append("remove {" + codeFldObj.Name + "." + ei.Name + "-=value;}");
                if (fdRef == codeFldRef)
                {
                    sbCode.Append("add    {" + codeFldRef.FieldName + "." + ei.Name + "+=value;}");
                    sbCode.Append("remove {" + codeFldRef.FieldName + "." + ei.Name + "-=value;}");
                }
                else
                {
                    sbCode.Append("add    {" + fdRef.FieldName + "." + codeFldRef.FieldName + "." + ei.Name + "+=value;}");
                    sbCode.Append("remove {" + fdRef.FieldName + "." + codeFldRef.FieldName + "." + ei.Name + "-=value;}");
                }
                sbCode.Append("}");

                references.AddReference(ei.EventHandlerType);

                codeType.Members.Add(new CodeSnippetTypeMember(sbCode.ToString()));
            }
            #endregion

            #region 递归基接口
            Type[] ts = interfaceType.GetInterfaces();
            if (ts != null && ts.Length > 0)
            {
                foreach (Type item in ts)
                {
                    CreateMember(item, duckType, codeType, references, codeFldRef);
                }
            }
            #endregion
        }
示例#37
0
		EncryptedData Encrypt (XmlElement target, SymmetricAlgorithm actualKey, string ekeyId, ReferenceList refList, SecurityKeyIdentifierClause encClause, EncryptedXml exml, XmlDocument doc)
		{
			SecurityAlgorithmSuite suite = security.Element.DefaultAlgorithmSuite;
			SecurityTokenSerializer serializer = security.TokenSerializer;

			byte [] encrypted = exml.EncryptData (target, actualKey, false);
			EncryptedData edata = new EncryptedData ();
			edata.Id = GenerateId (doc);
			edata.Type = EncryptedXml.XmlEncElementContentUrl;
			edata.EncryptionMethod = new EncryptionMethod (suite.DefaultEncryptionAlgorithm);
			// FIXME: here wsse:DigestMethod should be embedded 
			// inside EncryptionMethod. Since it is not possible 
			// with S.S.C.Xml.EncryptionMethod, we will have to
			// build our own XML encryption classes.

			edata.CipherData.CipherValue = encrypted;

			DataReference dr = new DataReference ();
			dr.Uri = "#" + edata.Id;
			refList.Add (dr);

			if (ShouldOutputEncryptedKey && !CounterParameters.RequireDerivedKeys)
				edata.KeyInfo = null;
			else {
				edata.KeyInfo = new KeyInfo ();
				edata.KeyInfo.AddClause (new SecurityTokenReferenceKeyInfo (encClause, serializer, doc));
			}

			return edata;
		}
        public Type[] CreateDuckTypes(Type interfaceType, Type[] duckedTypes)
        {
            const string TYPE_PREFIX = "Duck";

            String namespaceName = this.GetType().Namespace + "." + interfaceType.Name;

            CodeCompileUnit codeCU = new CodeCompileUnit();
            CodeNamespace codeNsp = new CodeNamespace(namespaceName);
            codeCU.Namespaces.Add(codeNsp);

            //CodeTypeReference codeTRInterface = new CodeTypeReference(interfaceType);
            CodeTypeReference codeTRInterface = new CodeTypeReference(TypeX.Create(interfaceType).FullName);
            ReferenceList references = new ReferenceList();

            // 遍历处理每一个需要代理的类
            for (int i = 0; i < duckedTypes.Length; i++)
            {
                Type objectType = duckedTypes[i];

                //CodeTypeReference codeTRObject = new CodeTypeReference(objectType);
                CodeTypeReference codeTRObject = new CodeTypeReference(TypeX.Create(objectType).FullName);
                references.AddReference(objectType);

                CodeTypeDeclaration codeType = new CodeTypeDeclaration(TYPE_PREFIX + i);
                codeNsp.Types.Add(codeType);

                codeType.TypeAttributes = TypeAttributes.Public;
                codeType.BaseTypes.Add(codeTRInterface);

                // 声明一个字段
                CodeMemberField codeFldObj = new CodeMemberField(codeTRObject, "_obj");
                codeType.Members.Add(codeFldObj);
                CodeFieldReferenceExpression codeFldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), codeFldObj.Name);

                // 创建一个构造函数
                CodeConstructor codeCtor = new CodeConstructor();
                codeType.Members.Add(codeCtor);
                codeCtor.Attributes = MemberAttributes.Public;
                codeCtor.Parameters.Add(new CodeParameterDeclarationExpression(codeTRObject, "obj"));
                codeCtor.Statements.Add(
                    new CodeAssignStatement(
                        codeFldRef,
                        new CodeArgumentReferenceExpression("obj")
                    )
                );

                // 创建成员
                CreateMember(interfaceType, objectType, codeType, references, codeFldRef);
            }

            #region 编译
            CSharpCodeProvider codeprov = new CSharpCodeProvider();

#if DEBUG
            {
                StringWriter sw = new StringWriter();
                codeprov.GenerateCodeFromCompileUnit(codeCU, sw, new CodeGeneratorOptions());
                string code = sw.ToString();
                Console.WriteLine(code);
            }
#endif

            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.GenerateInMemory = true;
            compilerParams.ReferencedAssemblies.Add(interfaceType.Assembly.Location);

            references.SetToCompilerParameters(compilerParams);

            CompilerResults cres = codeprov.CompileAssemblyFromDom(compilerParams, codeCU);
            if (cres.Errors.Count > 0)
            {
                StringWriter sw = new StringWriter();
                foreach (CompilerError err in cres.Errors)
                    sw.WriteLine(err.ErrorText);

                throw new InvalidOperationException("编译错误: \n\n" + sw.ToString());
            }

            Assembly assembly = cres.CompiledAssembly;

            Type[] res = new Type[duckedTypes.Length];
            for (int i = 0; i < duckedTypes.Length; i++)
            {
                res[i] = assembly.GetType(namespaceName + "." + TYPE_PREFIX + i);
            }

            return res;
            #endregion
        }