Example #1
1
		internal WrappedSerializer(Serialization.DataFormat dataFormat, string streamName, TextWriter output) : base(dataFormat, streamName)
		{
			this.firstCall = true;
			this.textWriter = output;
			Serialization.DataFormat dataFormat1 = this.format;
			switch (dataFormat1)
			{
				case Serialization.DataFormat.Text:
				{
					return;
				}
				case Serialization.DataFormat.XML:
				{
					XmlWriterSettings xmlWriterSetting = new XmlWriterSettings();
					xmlWriterSetting.CheckCharacters = false;
					xmlWriterSetting.OmitXmlDeclaration = true;
					this.xmlWriter = XmlWriter.Create(this.textWriter, xmlWriterSetting);
					this.xmlSerializer = new Serializer(this.xmlWriter);
					return;
				}
				default:
				{
					return;
				}
			}
		}
		public override void WriteInstance( Serialization.MaterialSerializer ser, SubRenderState subRenderState,
		                                    Graphics.Pass srcPass, Graphics.Pass dstPass )
		{
			//TODO
			//ser.WriteAttribute(4, "transform_stage");
			//ser.WriteValue("ffp");
		}
 /// <summary>
 /// Overrides the existing values
 /// </summary>
 /// <param name="declaration"></param>
 public void Override(Serialization.StyleDeclaration declaration)
 {
     foreach (StyleProperty property in _styleSheetDeclaration.Properties)
     {
         _cached[property.Name] = property.Value;
     }
 }
Example #4
0
        public static void Main(string[] args)
        {
            var twitterops = new TwitterOperations();
            var gui = new MainWindow();
            var ironmq = new IronMQOperations("AppZwitschern", TokenRepository.LoadFrom("ironmq.credentials.txt"));
            var serialisieren = new Serialization<Versandauftrag>();
            var urlShortener = new TinyUrlOperations();
            var compressor = new TextCompressor();

            FlowRuntimeConfiguration.SynchronizationFactory = () => new SyncWithWPFDispatcher();

            var config = new FlowRuntimeConfiguration()
                .AddStreamsFrom("az.application.flows.flow", Assembly.GetExecutingAssembly())
                .AddFunc<Versandauftrag, Versandauftrag>("versandauftrag_schnueren", twitterops.Versandauftrag_um_access_token_erweitern)
                .AddFunc<Versandauftrag, string>("serialisieren", serialisieren.Serialize)
                .AddAction<string>("enqueue", ironmq.Enqueue, true)
                .AddFunc<string, string[]>("extract_urls", compressor.Extract_Urls)
                .AddFunc<Tuple<string, Tuple<string,string>[]>,string>("replace_urls", compressor.Replace_Urls)
                .AddFunc<IEnumerable<string>, Tuple<String,string>[]>("shorten_urls", urlShortener.ShortenMany)
                .AddOperation(new AutoResetJoin<string, Tuple<string,string>[]>("join"))
                .AddOperation(new Throttle("throttle", 1000))
                .AddAction<string>("display_shortened_text", gui.ShortenedText).MakeSync()
                .AddAction("versandstatus_anzeigen", () => gui.Versandstatus("Versendet!")).MakeSync();

            using (var fr = new FlowRuntime(config)) {
                fr.UnhandledException += ex => MessageBox.Show(ex.InnerException.Message);
                fr.Message += Console.WriteLine;

                gui.Versenden += fr.CreateEventProcessor<Versandauftrag>(".versenden");
                gui.ShortenText += fr.CreateEventProcessor<string>(".shortenText");

                var app = new Application { MainWindow = gui };
                app.Run(gui);
            }
        }
Example #5
0
        private static void Call(Arebis.CodeGeneration.IGenerationHost host,
            IZetboxContext ctx,
            Serialization.SerializationMembersList serializationList,
            Property prop, bool hasPersistentOrder, bool isList,
            string collectionWrapperClass,
            string listWrapperClass)
        {
            if (prop == null) { throw new ArgumentNullException("prop"); }
            if (!isList) { throw new ArgumentOutOfRangeException("prop", "prop must be a List-valued property"); }

            string name = prop.Name;
            string backingName = "_" + name;
            string backingCollectionType = (hasPersistentOrder ? listWrapperClass : collectionWrapperClass);

            string exposedCollectionInterface = hasPersistentOrder ? "IList" : "ICollection";

            string thisInterface = prop.ObjectClass.Name;
            string referencedType = prop.GetElementTypeString();
            string referencedCollectionEntry = prop.GetCollectionEntryFullName();
            string referencedCollectionEntryImpl = referencedCollectionEntry + host.Settings["extrasuffix"] + Zetbox.API.Helper.ImplementationSuffix;

            string providerCollectionType = "ObservableCollection<" + referencedCollectionEntryImpl + ">";
            string underlyingCollectionName = "_" + name + "Collection";

            string moduleNamespace = prop.Module.Namespace;

            Call(
                host, ctx, serializationList,
                name, backingName, backingCollectionType, exposedCollectionInterface,
                thisInterface, referencedType,
                referencedCollectionEntry, referencedCollectionEntryImpl,
                providerCollectionType, underlyingCollectionName, !hasPersistentOrder,
                moduleNamespace,
                prop.DisableExport == true);
        }
 protected override void AddSerialization(Serialization.SerializationMembersList list, string name)
 {
     if (list != null)
     {
         if (HasDefaultValue)
         {
             list.Add("Serialization.SimplePropertyWithDefaultSerialization",
                 disableExport ? Templates.Serialization.SerializerType.Binary : Serialization.SerializerType.All,
                 _prop.Module.Namespace,
                 name,
                 type,
                 backingName,
                 IsSetFlagName);
         }
         else
         {
             list.Add("Serialization.SimplePropertySerialization",
                 disableExport ? Serialization.SerializerType.Binary : Serialization.SerializerType.All,
                 _prop.Module.Namespace,
                 name,
                 type,
                 backingName);
         }
     }
 }
		public override void WriteInstance( Serialization.MaterialSerializer ser, SubRenderState subRenderState,
		                                    Graphics.Pass srcPass, Graphics.Pass dstPass )
		{
			//TODO
			//ser.WriteAttribute(4, "lighting_stage");
			//ser.WriteValue("per_pixel");
		}
Example #8
0
        private void InternalFullSerialize(Serialization.CrySerialize serialize)
        {
            //var serialize = new Serialization.CrySerialize();
            //serialize.Handle = handle;

            FullSerialize(serialize);
        }
Example #9
0
        private void InternalNetSerialize(Serialization.CrySerialize serialize, int aspect, byte profile, int flags)
        {
            // var serialize = new Serialization.CrySerialize();
            //serialize.Handle = handle;

            NetSerialize(serialize, aspect, profile, flags);
        }
        public ObjectReferencePropertyTemplate(Arebis.CodeGeneration.IGenerationHost _host, IZetboxContext ctx, Serialization.SerializationMembersList serializationList, string moduleNamespace, string ownInterface, string name, string implName, string eventName, string fkBackingName, string fkGuidBackingName, string referencedInterface, string referencedImplementation, string associationName, string targetRoleName, string positionPropertyName, string inverseNavigatorName, bool inverseNavigatorIsList, bool eagerLoading, bool relDataTypeExportable, bool callGetterSetterEvents, bool isCalculated, bool disableExport)
            : base(_host)
        {
			this.ctx = ctx;
			this.serializationList = serializationList;
			this.moduleNamespace = moduleNamespace;
			this.ownInterface = ownInterface;
			this.name = name;
			this.implName = implName;
			this.eventName = eventName;
			this.fkBackingName = fkBackingName;
			this.fkGuidBackingName = fkGuidBackingName;
			this.referencedInterface = referencedInterface;
			this.referencedImplementation = referencedImplementation;
			this.associationName = associationName;
			this.targetRoleName = targetRoleName;
			this.positionPropertyName = positionPropertyName;
			this.inverseNavigatorName = inverseNavigatorName;
			this.inverseNavigatorIsList = inverseNavigatorIsList;
			this.eagerLoading = eagerLoading;
			this.relDataTypeExportable = relDataTypeExportable;
			this.callGetterSetterEvents = callGetterSetterEvents;
			this.isCalculated = isCalculated;
			this.disableExport = disableExport;

        }
Example #11
0
		internal WrappedDeserializer(Serialization.DataFormat dataFormat, string streamName, TextReader input) : base(dataFormat, streamName)
		{
			if (dataFormat != Serialization.DataFormat.None)
			{
				this.textReader = input;
				this.firstLine = this.textReader.ReadLine();
				if (string.Compare(this.firstLine, Serialization.XmlCliTag, StringComparison.OrdinalIgnoreCase) == 0)
				{
					dataFormat = Serialization.DataFormat.XML;
				}
				Serialization.DataFormat dataFormat1 = this.format;
				switch (dataFormat1)
				{
					case Serialization.DataFormat.Text:
					{
						return;
					}
					case Serialization.DataFormat.XML:
					{
						this.xmlReader = XmlReader.Create(this.textReader);
						this.xmlDeserializer = new Deserializer(this.xmlReader);
						return;
					}
					default:
					{
						return;
					}
				}
			}
			else
			{
				return;
			}
		}
Example #12
0
 protected virtual void AddSerialization(Serialization.SerializationMembersList list, string underlyingCollectionName)
 {
     if (list != null)
     {
         Serialization.CollectionSerialization.Add(list, ctx, moduleNamespace, name, underlyingCollectionName, orderByValue, disableExport);
     }
 }
Example #13
0
        public override string Read(Serialization.ISerializer serializer)
        {
            if (serializer.GetType() == typeof(Arch.CFramework.AppInternals.Serialization.XMLSerializer))
            {
                XmlDocument xml = new XmlDocument();
                xml.AppendChild(xml.CreateXmlDeclaration("1.0", Encoding.UTF8.BodyName, null));
                var node = xml.CreateElement("HealthCheck");
                xml.AppendChild(node);
                var node1 = xml.CreateElement("Healthies");
                node.AppendChild(node1);
                foreach (var hcb in list.ToList())
                {
                    var n = xml.CreateElement(hcb.GetType().Name);
                    node1.AppendChild(n);
                    var n1 = xml.CreateElement("IsHealthy");
                    n1.InnerText = hcb.Healthy.IsHealthy.ToString();
                    n.AppendChild(n1);
                    n1 = xml.CreateElement("Message");
                    n1.InnerText = hcb.Healthy.Message;
                    n.AppendChild(n1);
                    n1 = xml.CreateElement("Error");
                    if (hcb.Healthy.Error != null)
                        n1.InnerText = hcb.Healthy.Error.ToString();
                    else
                        n1.InnerText = string.Empty;
                    n.AppendChild(n1);
                }

                return xml.OuterXml;
            }
            return base.Read(serializer);
        }
Example #14
0
 protected override void OnSetState(Serialization.Mobile.SerializationInfo info, Core.StateMode mode)
 {
   base.OnSetState(info, mode);
   Name = info.GetValue<string>("SilverlightPrincipal.Criteria.Name");
   Password = info.GetValue<string>("SilverlightPrincipal.Criteria.Password");
   ProviderType = info.GetValue<string>("SilverlightPrincipal.Criteria.ProviderType");
 }
Example #15
0
 protected override void OnGetState(Serialization.Mobile.SerializationInfo info, Core.StateMode mode)
 {
   info.AddValue("SilverlightPrincipal.Criteria.Name", Name);
   info.AddValue("SilverlightPrincipal.Criteria.Password", Password);
   info.AddValue("SilverlightPrincipal.Criteria.ProviderType", ProviderType);
   base.OnGetState(info, mode);
 }
Example #16
0
        public static void Call(Arebis.CodeGeneration.IGenerationHost host,
            IZetboxContext ctx, Serialization.SerializationMembersList serializationList, Property prop)
        {
            if (host == null) { throw new ArgumentNullException("host"); }

            host.CallTemplate("Properties.NotifyingDataProperty",
                ctx, serializationList, prop);
        }
Example #17
0
        public static void Call(Arebis.CodeGeneration.IGenerationHost host,
          IZetboxContext ctx, Serialization.SerializationMembersList serializationList, string backingName)
        {
            if (host == null) { throw new ArgumentNullException("host"); }

            host.CallTemplate("Properties.ExportGuidProperty",
                ctx, serializationList, backingName);
        }
 public static AHPIndexHierarchy ReadIndexHierarchyXml()
 {
     AHPIndexHierarchy TunnelHealIndex = new AHPIndexHierarchy();
     Serialization<AHPIndexHierarchy> Xml2AHPIndex = new Serialization<AHPIndexHierarchy>();
     TunnelHealIndex = Xml2AHPIndex.XMLDeserialization(_hierarchyFilePath);
     SetAhpParent(TunnelHealIndex);
     return TunnelHealIndex;
 }
Example #19
0
 private void PersistenceManager_CurrentTreeChanged(Serialization.PersistenceManager manager, Serialization.PersistentTree oldTree, Serialization.PersistentTree newTree)
 {
     if (newTree != null)
     {
         Tab tab = mainForm.EditorTabs.FindTab(newTree);
         mainForm.EditorTabs.SelectedTab = tab;
     }
 }
Example #20
0
 public override string Read(Serialization.ISerializer serializer)
 {
     Guard.ArgumentNotNull(serializer, "serializer");
     if (serializer.GetType().Name.ToLowerInvariant() == "htmlserializer")
     {
         return "{\"Message\":\"" + this.Message + "\",\"IsSuccess\":\"" + this.IsSuccess + "\"}";
     }
     return base.Read(serializer);
 }
Example #21
0
 public void SerializeInfo()
 {
     using (var conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=sakila;User Id=test;Password=test;"))
     {
         conn.Open();
         var s = new Serialization();
         s.Serialize(conn);
     }
 }
Example #22
0
 public ObjectListProperty(Arebis.CodeGeneration.IGenerationHost host,
     IZetboxContext ctx,
     Serialization.SerializationMembersList serializationList,
     Relation rel,
     RelationEndRole endRole)
     : this(host, ctx, serializationList, "name", "wrapperName", "wrapperClass", "exposedListType",
         rel, endRole, "positionPropertyName", "otherName", "referencedInterface")
 {
 }
Example #23
0
        public static void Call(Arebis.CodeGeneration.IGenerationHost host,
            IZetboxContext ctx, Serialization.SerializationMembersList serializationList,
            string type, string name, string modulenamespace, bool isCalculated, bool disableExport)
        {
            if (host == null) { throw new ArgumentNullException("host"); }

            string backingName = "_" + name;

            Call(host, ctx, serializationList, type, name, modulenamespace, backingName, isCalculated, disableExport);
        }
Example #24
0
 public NotifyingDataProperty(Arebis.CodeGeneration.IGenerationHost _host, IZetboxContext ctx, Serialization.SerializationMembersList serializationList, Property prop)
     : this(_host, ctx, serializationList, 
             prop.GetElementTypeString(), 
             prop.Name, prop.Module.Namespace, "_" + prop.Name, 
             prop.IsCalculated(), prop.DisableExport == true, 
             prop.ObjectClass.Name, prop.IsNullable(),
             prop.DefaultValue != null && !prop.IsCalculated(), // No default value for calculated properties, default values are used then for database migration
             prop.ExportGuid)
 {
 }
Example #25
0
        public ListProperty(Arebis.CodeGeneration.IGenerationHost _host, IZetboxContext ctx, Serialization.SerializationMembersList serializationList, DataType containingType, String name, Property property)
            : base(_host)
        {
			this.ctx = ctx;
			this.serializationList = serializationList;
			this.containingType = containingType;
			this.name = name;
			this.property = property;

        }
Example #26
0
 public static void Call(Arebis.CodeGeneration.IGenerationHost host,
     IZetboxContext ctx,
     Serialization.SerializationMembersList serializationList,
     ValueTypeProperty prop,
     string collectionWrapperClass,
     string listWrapperClass)
 {
     if (prop == null)
         throw new ArgumentNullException("prop");
     Call(host, ctx, serializationList, prop, prop.HasPersistentOrder, prop.IsList, collectionWrapperClass, listWrapperClass);
 }
Example #27
0
 public NotifyingDataProperty(
     Arebis.CodeGeneration.IGenerationHost _host, IZetboxContext ctx, Serialization.SerializationMembersList serializationList,
     string type, string name, string modulenamespace, string backingName, bool isCalculated, bool disableExport,
     string className, bool isNullable, bool hasDefaultValue, Guid propExportGuid)
     : base(_host, ctx, serializationList, type, name, modulenamespace, backingName, isCalculated, disableExport)
 {
     this.className = className;
     this.isNullable = isNullable;
     this.hasDefaultValue = hasDefaultValue;
     this.propExportGuid = propExportGuid;
 }
        public static void Call(
            Arebis.CodeGeneration.IGenerationHost host, IZetboxContext ctx,
            Serialization.SerializationMembersList serializationList,
            CompoundObjectProperty prop)
        {
            if (host == null) { throw new ArgumentNullException("host"); }
            if (prop == null) { throw new ArgumentNullException("prop"); }

            string propName = prop.Name;

            Call(host, ctx, serializationList, prop, propName, prop.IsList, prop.HasPersistentOrder);
        }
Example #29
0
 public PacketContent Process(Serialization.SerializedInfo request)
 {
     XElement content = request.Content.XmlContent;
     if (content.Name != RequestConstants.RootNodeName)
         throw new InvalidOperationException("thre request is not valid");
     var methodNode = content.Descendants().Single(m => m.Name == RequestConstants.MethodNodeName);
     if (methodNode.Name == RequestConstants.MethodNodeName)
     {
         return MethodRequestProcessor.Process(request, methodNode.Value);
     }
     throw new NotSupportedException();
 }
        public NotifyingValueProperty(Arebis.CodeGeneration.IGenerationHost _host, IZetboxContext ctx, Serialization.SerializationMembersList serializationList, string type, string name, string modulenamespace, string backingName, bool isCalculated, bool disableExport)
            : base(_host)
        {
			this.ctx = ctx;
			this.serializationList = serializationList;
			this.type = type;
			this.name = name;
			this.modulenamespace = modulenamespace;
			this.backingName = backingName;
			this.isCalculated = isCalculated;
			this.disableExport = disableExport;

        }
Example #31
0
        /// <summary>
        /// 生成Update命令
        /// </summary>
        /// <param name="dh">DataHelper</param>
        /// <param name="conditionForUpdate">字定义条件</param>
        /// <param name="Propertys">自定义字段</param>
        /// <returns>命令对象System.Data.Common.DbCommand</returns>
        private MySqlCommand GenerateUpdateCommand(DataHelper dh, BaseEntity EntityInstance, string conditionForUpdate, params string[] Propertys)
        {
            MySqlCommand Command = null;

            #region 生成命令对象
            string strSQL = string.Format("update {0} ", TableName);
            strSQL += " set ";
            string strWhere = " where ";

            #region 处理字段
            Dictionary <string, KeyField>  m_PKeyList  = null;
            Dictionary <string, KeyField>  m_FKeyList  = null;
            Dictionary <string, DataField> m_FieldList = null;
            if ((Propertys != null) && (Propertys.Length != 0))
            {
                #region 处理特定字段
                List <string> PropertyList = new List <string>(Propertys.Length);
                PropertyList.AddRange(Propertys);
                m_PKeyList  = new Dictionary <string, KeyField>();
                m_FKeyList  = new Dictionary <string, KeyField>();
                m_FieldList = new Dictionary <string, DataField>();
                foreach (KeyField Key in this.PKeyList.Values)
                {
                    if (PropertyList.Contains(Key.FieldName))
                    {
                        m_PKeyList.Add(Key.FieldName, Key);
                    }
                }
                foreach (KeyField Key in this.FKeyList.Values)
                {
                    if (PropertyList.Contains(Key.FieldName))
                    {
                        m_FKeyList.Add(Key.FieldName, Key);
                    }
                }
                foreach (DataField Key in this.FieldList.Values)
                {
                    if (PropertyList.Contains(Key.FieldName))
                    {
                        m_FieldList.Add(Key.FieldName, Key);
                    }
                }
                #endregion
            }
            else
            {
                #region 默认全部字段
                m_PKeyList  = this.PKeyList;
                m_FKeyList  = this.FKeyList;
                m_FieldList = this.FieldList;
                #endregion
            }
            #endregion

            #region 生成SQL语句
            foreach (KeyField key in m_FKeyList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                strSQL += key.FieldName + "=" + dh.ParameterSeparateCode + key.FieldName + ",";
            }
            foreach (DataField key in m_FieldList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                strSQL += key.FieldName + "=" + dh.ParameterSeparateCode + key.FieldName + ",";
            }
            if ((conditionForUpdate == null) || (conditionForUpdate.Trim().Length == 0))
            {
                foreach (KeyField key in m_PKeyList.Values)
                {
                    if (key.IsBase)
                    {
                        continue;
                    }
                    strWhere += key.FieldName + "=" + dh.ParameterSeparateCode + key.FieldName + " and ";
                }

                if (strWhere != " where ")
                {
                    strWhere = strWhere.Substring(0, strWhere.Length - 4);
                }
                else
                {
                    strWhere = string.Empty;
                }
            }
            else
            {
                conditionForUpdate = Checkcondition(conditionForUpdate);
                strWhere          += conditionForUpdate;
            }

            strSQL  = strSQL.Substring(0, strSQL.Length - 1);
            strSQL += strWhere;
            #endregion

            Command = dh.GetSqlStringCommand(strSQL);

            #region 填充命令对象
            if ((conditionForUpdate == null) || (conditionForUpdate.ToUpper().Length == 0))
            {
                foreach (KeyField key in m_PKeyList.Values)
                {
                    if (key.IsBase)
                    {
                        continue;
                    }
                    object Value = EntityInstance[key.FieldName];
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Value);
                }
            }

            foreach (KeyField key in m_FKeyList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                object Value = EntityInstance[key.FieldName];
                if (Value == null)
                {
                    Value = DBNull.Value;
                }
                if (key.SerializedType != ESerializedType.NO)
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Serialization.Serialize(Value, key.SerializedType));
                }
                else
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Value);
                }
            }
            foreach (DataField key in m_FieldList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                object Value = EntityInstance[key.FieldName];
                if (Value == null)
                {
                    Value = DBNull.Value;
                }
                if (key.SerializedType != ESerializedType.NO)
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Serialization.Serialize(Value, key.SerializedType));
                }
                else
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Value);
                }
            }
            #endregion

            #endregion
            return(Command);
        }
Example #32
0
        /*
         * In this example we show how serialization works in Microsoft SEAL. Specifically,
         * we present important concepts that enable the user to optimize the data size when
         * communicating ciphertexts and keys for outsourced computation. Unlike the previous
         * examples, we organize this one in a client-server style for maximal clarity. The
         * server selects encryption parameters, the client generates keys, the server does
         * the encrypted computation, and the client decrypts.
         */
        private static void ExampleSerialization()
        {
            Utilities.PrintExampleBanner("Example: Serialization");

            /*
             * We require ZLIB or Zstandard support for this example to be available.
             */
            if (!Serialization.IsSupportedComprMode(ComprModeType.ZLIB) &&
                !Serialization.IsSupportedComprMode(ComprModeType.ZSTD))
            {
                Console.WriteLine("Neither ZLIB nor Zstandard support is enabled; this example is not available.");
                Console.WriteLine();
                return;
            }

            /*
             * We start by briefly discussing the Serializable<T> generic class. This is
             * a wrapper class that can wrap any serializable class, which include:
             *
             *  - EncryptionParameters
             *  - Modulus
             *  - Plaintext and Ciphertext
             *  - SecretKey, PublicKey, RelinKeys, and GaloisKeys
             *
             * Serializable<T> provides minimal functionality needed to serialize the wrapped
             * object by simply forwarding the calls to corresponding functions of the wrapped
             * object of type T. The need for Serializable<T> comes from the fact that many
             * Microsoft SEAL objects consist of two parts, one of which is pseudorandom data
             * independent of the other part. Until the object is actually being used, the
             * pseudorandom part can be instead stored as a seed. We will call objects with
             * property `seedable'.
             *
             * For example, GaloisKeys can often be very large in size, but in reality half
             * of the data is pseudorandom and can be stored as a seed. Since GaloisKeys are
             * never used by the party that generates them, so it makes sense to expand the
             * seed at the point deserialization. On the other hand, we cannot allow the user
             * to accidentally try to use an unexpanded GaloisKeys object, which is prevented
             * at by ensuring it is always wrapped in a Serializable<GaloisKeys> and can only
             * be serialized.
             *
             * Only some Microsoft SEAL objects are seedable. Specifically, they are:
             *
             *  - PublicKey, RelinKeys, and GaloisKeys
             *  - Ciphertext in secret-key mode (from Encryptor.EncryptSymmetric or
             *    Encryptor.EncryptZeroSymmetric)
             *
             * Importantly, ciphertexts in public-key mode are not seedable. Thus, it may
             * be beneficial to use Microsoft SEAL in secret-key mode whenever the public
             * key is not truly needed.
             *
             * There are a handful of functions that output Serializable<T> objects:
             *
             *  - Encryptor.Encrypt (and variants) output Serializable<Ciphertext>
             *  - KeyGenerator.Create... output Serializable<T> for different key types
             *
             * Note that Encryptor.Encrypt is included in the above list, yet it produces
             * ciphertexts in public-key mode that are not seedable. This is for the sake of
             * consistency in the API for public-key and secret-key encryption. Functions
             * that output Serializable<T> objects also have overloads that take a normal
             * object of type T as a destination parameter, overwriting it. These overloads
             * can be convenient for local testing where no serialization is needed and the
             * object needs to be used at the point of construction. Such an object can no
             * longer be transformed back to a seeded state.
             */

            /*
             * To simulate client-server interaction, we set up a shared C# stream. In real
             * use-cases this can be a network stream, a filestream, or any shared resource.
             *
             * It is critical to note that all data serialized by Microsoft SEAL is in binary
             * form, so it is not meaningful to print the data as ASCII characters. Encodings
             * such as Base64 would increase the data size, which is already a bottleneck in
             * homomorphic encryption. Hence, serialization into text is not supported or
             * recommended.
             *
             * In this example we use a couple of shared MemoryStreams.
             */
            using MemoryStream parmsStream = new MemoryStream();
            using MemoryStream dataStream  = new MemoryStream();
            using MemoryStream skStream    = new MemoryStream();

            /*
             * The server first determines the computation and sets encryption parameters
             * accordingly.
             */
            {
                ulong polyModulusDegree = 8192;
                using EncryptionParameters parms = new EncryptionParameters(SchemeType.CKKS);
                parms.PolyModulusDegree          = polyModulusDegree;
                parms.CoeffModulus = CoeffModulus.Create(
                    polyModulusDegree, new int[] { 50, 30, 50 });

                /*
                 * Serialization of the encryption parameters to our shared stream is very
                 * simple with the EncryptionParameters.Save function.
                 */
                long size = parms.Save(parmsStream);

                /*
                 * Seek the parmsStream head back to beginning of the stream.
                 */
                parmsStream.Seek(0, SeekOrigin.Begin);

                /*
                 * The return value of this function is the actual byte count of data written
                 * to the stream.
                 */
                Utilities.PrintLine();
                Console.WriteLine($"EncryptionParameters: wrote {size} bytes");

                /*
                 * Before moving on, we will take some time to discuss further options in
                 * serialization. These will become particularly important when the user
                 * needs to optimize communication and storage sizes.
                 *
                 * It is possible to enable or disable compression for serialization by
                 * providing EncryptionParameters.Save with the desired compression mode as
                 * in the following examples:
                 *
                 *  long size = parms.Save(sharedStream, ComprModeType.None);
                 *  long size = parms.Save(sharedStream, ComprModeType.ZLIB);
                 *  long size = parms.Save(sharedStream, ComprModeType.ZSTD);
                 *
                 * If Microsoft SEAL is compiled with Zstandard or ZLIB support, the default
                 * is to use one of them. If available, Zstandard is preferred over ZLIB due
                 * to its speed.
                 *
                 * Compression can have a substantial impact on the serialized data size,
                 * because ciphertext and key data consists of many uniformly random integers
                 * modulo the CoeffModulus primes. Especially when using CKKS, the primes in
                 * CoeffModulus can be relatively small compared to the 64-bit words used to
                 * store the ciphertext and key data internally. Serialization writes full
                 * 64-bit words to the destination buffer or stream, possibly leaving in many
                 * zero bytes corresponding to the high-order bytes of the 64-bit words. One
                 * convenient way to get rid of these zeros is to apply a general-purpose
                 * compression algorithm on the encrypted data. The compression rate can be
                 * significant (up to 50-60%) when using CKKS with small primes.
                 */

                /*
                 * In many cases, when working with fixed size memory, it is necessary to know
                 * ahead of time an upper bound on the serialized data size to allocate enough
                 * memory. This information is returned by the EncryptionParameters.SaveSize
                 * function. This function accepts the desired compression mode, or uses the
                 * default option otherwise.
                 *
                 * In more detail, the output of EncryptionParameters.SaveSize is as follows:
                 *
                 *  - Exact buffer size required for ComprModeType.None;
                 *  - Upper bound on the size required for ComprModeType.ZLIB or
                 *    ComprModeType.ZSTD.
                 *
                 * As we can see from the print-out, the sizes returned by these functions
                 * are significantly larger than the compressed size written into the shared
                 * stream in the beginning. This is normal: compression yielded a significant
                 * improvement in the data size, however, it is impossible to know ahead of
                 * time the exact size of the compressed data. If compression is not used,
                 * then the size is exactly determined by the encryption parameters.
                 */
                Utilities.PrintLine();
                Console.Write("EncryptionParameters: data size upper bound (ComprModeType.None): ");
                Console.WriteLine(parms.SaveSize(ComprModeType.None));
                Console.Write("             ");
                Console.Write("EncryptionParameters: data size upper bound (compression): ");
                Console.WriteLine(parms.SaveSize(/* Serialization.ComprModeDefault */));

                /*
                 * As an example, we now serialize the encryption parameters to a fixed
                 * size buffer.
                 */
                using MemoryStream buffer = new MemoryStream(new byte[parms.SaveSize()]);
                parms.Save(buffer);

                /*
                 * To illustrate deserialization, we load back the encryption parameters
                 * from our buffer into another instance of EncryptionParameters. First
                 * we need to seek our stream back to the beginning.
                 */
                buffer.Seek(0, SeekOrigin.Begin);
                using EncryptionParameters parms2 = new EncryptionParameters();
                parms2.Load(buffer);

                /*
                 * We can check that the saved and loaded encryption parameters indeed match.
                 */
                Utilities.PrintLine();
                Console.WriteLine($"EncryptionParameters: parms == parms2: {parms.Equals(parms2)}");
            }

            /*
             * Client starts by loading the encryption parameters, sets up the SEALContext,
             * and creates the required keys.
             */
            {
                using EncryptionParameters parms = new EncryptionParameters();
                parms.Load(parmsStream);

                /*
                 * Seek the parmsStream head back to beginning of the stream because we
                 * will use the same stream to read the parameters repeatedly.
                 */
                parmsStream.Seek(0, SeekOrigin.Begin);

                using SEALContext context = new SEALContext(parms);

                using KeyGenerator keygen = new KeyGenerator(context);
                using SecretKey sk        = keygen.SecretKey;
                keygen.CreatePublicKey(out PublicKey pk);

                /*
                 * We need to save the secret key so we can decrypt later.
                 */
                sk.Save(skStream);
                skStream.Seek(0, SeekOrigin.Begin);

                /*
                 * As in previous examples, in this example we will encrypt in public-key
                 * mode. If we want to send a public key over the network, we should instead
                 * have created it as a seeded object as follows:
                 *
                 *  Serializable<PublicKey> pk = keygen.CreatePublicKey();
                 *
                 * In this example we will also use relinearization keys. These we will
                 * absolutely want to create as seeded objects to minimize communication
                 * cost, unlike in prior examples.
                 */
                using Serializable <RelinKeys> rlk = keygen.CreateRelinKeys();

                /*
                 * To demonstrate the significant space saving from this method, we will
                 * create another set of relinearization keys, this time fully expanded.
                 */
                keygen.CreateRelinKeys(out RelinKeys rlkBig);

                /*
                 * We serialize both relinearization keys to demonstrate the concrete size
                 * difference. If compressed serialization is used, the compression rate
                 * will be the same in both cases. We omit specifying the compression mode
                 * to use the default, as determined by the Microsoft SEAL build system.
                 */
                long sizeRlk    = rlk.Save(dataStream);
                long sizeRlkBig = rlkBig.Save(dataStream);

                Utilities.PrintLine();
                Console.WriteLine($"Serializable<RelinKeys>: wrote {sizeRlk} bytes");
                Console.Write("             ");
                Console.WriteLine($"RelinKeys: wrote {sizeRlkBig} bytes");

                /*
                 * Seek back in dataStream to where rlk data ended, i.e., sizeRlkBig bytes
                 * backwards from current position.
                 */
                dataStream.Seek(-sizeRlkBig, SeekOrigin.Current);

                /*
                 * Next set up the CKKSEncoder and Encryptor, and encrypt some numbers.
                 */
                double      scale   = Math.Pow(2.0, 30);
                CKKSEncoder encoder = new CKKSEncoder(context);
                using Plaintext plain1 = new Plaintext(),
                      plain2           = new Plaintext();
                encoder.Encode(2.3, scale, plain1);
                encoder.Encode(4.5, scale, plain2);

                using Encryptor encryptor = new Encryptor(context, pk);

                /*
                 * The client will not compute on ciphertexts that it creates, so it can
                 * just as well create Serializable<Ciphertext> objects. In fact, we do
                 * not even need to name those objects and instead immediately call
                 * Serializable<Ciphertext>.Save.
                 */
                long sizeEncrypted1 = encryptor.Encrypt(plain1).Save(dataStream);

                /*
                 * As we discussed in the beginning of this example, ciphertexts can
                 * be created in a seeded state in secret-key mode, providing a huge
                 * reduction in the data size upon serialization. To do this, we need
                 * to provide the Encryptor with the secret key in its constructor, or
                 * at a later point with the Encryptor.SetSecretKey function, and use
                 * the Encryptor.EncryptSymmetric function to encrypt.
                 */
                encryptor.SetSecretKey(sk);
                long sizeSymEncrypted2 = encryptor.EncryptSymmetric(plain2).Save(dataStream);

                /*
                 * The size reduction is substantial.
                 */
                Utilities.PrintLine();
                Console.WriteLine($"Serializable<Ciphertext> (public-key): wrote {sizeEncrypted1} bytes");
                Console.Write("             ");
                Console.Write($"Serializable<Ciphertext> (seeded secret-key): ");
                Console.WriteLine($"wrote {sizeSymEncrypted2} bytes");

                /*
                 * Seek to the beginning of dataStream.
                 */
                dataStream.Seek(0, SeekOrigin.Begin);

                /*
                 * We have seen how creating seeded objects can result in huge space
                 * savings compared to creating unseeded objects. This is particularly
                 * important when creating Galois keys, which can be very large. We have
                 * seen how secret-key encryption can be used to achieve much smaller
                 * ciphertext sizes when the public-key functionality is not needed.
                 *
                 * We would also like to draw attention to the fact there we could easily
                 * serialize multiple Microsoft SEAL objects sequentially in a stream. Each
                 * object writes its own size into the stream, so deserialization knows
                 * exactly how many bytes to read. We will see this working below.
                 */
            }

            /*
             * The server can now compute on the encrypted data. We will recreate the
             * SEALContext and set up an Evaluator here.
             */
            {
                using EncryptionParameters parms = new EncryptionParameters();
                parms.Load(parmsStream);
                parmsStream.Seek(0, SeekOrigin.Begin);
                using SEALContext context = new SEALContext(parms);

                using Evaluator evaluator = new Evaluator(context);

                /*
                 * Next we need to load relinearization keys and the ciphertexts from our
                 * dataStream.
                 */
                using RelinKeys rlk         = new RelinKeys();
                using Ciphertext encrypted1 = new Ciphertext(),
                      encrypted2            = new Ciphertext();

                /*
                 * Deserialization is as easy as serialization.
                 */
                rlk.Load(context, dataStream);
                encrypted1.Load(context, dataStream);
                encrypted2.Load(context, dataStream);

                /*
                 * Compute the product, rescale, and relinearize.
                 */
                using Ciphertext encryptedProd = new Ciphertext();
                evaluator.Multiply(encrypted1, encrypted2, encryptedProd);
                evaluator.RelinearizeInplace(encryptedProd, rlk);
                evaluator.RescaleToNextInplace(encryptedProd);

                /*
                 * We use dataStream to communicate encryptedProd back to the client.
                 * There is no way to save the encryptedProd as a seeded object: only
                 * freshly encrypted secret-key ciphertexts can be seeded. Note how the
                 * size of the result ciphertext is smaller than the size of a fresh
                 * ciphertext because it is at a lower level due to the rescale operation.
                 */
                dataStream.Seek(0, SeekOrigin.Begin);
                long sizeEncryptedProd = encryptedProd.Save(dataStream);
                dataStream.Seek(0, SeekOrigin.Begin);

                Utilities.PrintLine();
                Console.Write($"Ciphertext (secret-key): ");
                Console.WriteLine($"wrote {sizeEncryptedProd} bytes");
            }

            /*
             * In the final step the client decrypts the result.
             */
            {
                using EncryptionParameters parms = new EncryptionParameters();
                parms.Load(parmsStream);
                parmsStream.Seek(0, SeekOrigin.Begin);
                using SEALContext context = new SEALContext(parms);

                /*
                 * Load back the secret key from skStream.
                 */
                using SecretKey sk = new SecretKey();
                sk.Load(context, skStream);
                using Decryptor decryptor = new Decryptor(context, sk);
                using CKKSEncoder encoder = new CKKSEncoder(context);

                using Ciphertext encryptedResult = new Ciphertext();
                encryptedResult.Load(context, dataStream);

                using Plaintext plainResult = new Plaintext();
                decryptor.Decrypt(encryptedResult, plainResult);
                List <double> result = new List <double>();
                encoder.Decode(plainResult, result);

                Utilities.PrintLine();
                Console.WriteLine("Decrypt and decode PI * x ^ 3 + 0.4x + 1.");
                Console.WriteLine("    + Expected result:");
                List <double> trueResult = new List <double>((int)encoder.SlotCount);
                for (ulong i = 0; i < encoder.SlotCount; i++)
                {
                    trueResult.Add(2.3 * 4.5);
                }
                Utilities.PrintVector(trueResult, 3, 7);
                Console.WriteLine("    + Computed result ...... Correct.");
                Utilities.PrintVector(result, 3, 7);
            }

            /*
             * Finally, we give a little bit more explanation of the structure of data
             * serialized by Microsoft SEAL. Serialized data always starts with a 16-byte
             * SEALHeader struct, as defined in dotnet/src/Serialization.cs, and is
             * followed by the possibly compressed data for the object.
             *
             * A SEALHeader contains the following data:
             *
             *  [offset 0] 2-byte magic number 0xA15E (Serialization.SEALMagic)
             *  [offset 2] 1-byte indicating the header size in bytes (always 16)
             *  [offset 3] 1-byte indicating the Microsoft SEAL major version number
             *  [offset 4] 1-byte indicating the Microsoft SEAL minor version number
             *  [offset 5] 1-byte indicating the compression mode type
             *  [offset 6] 2-byte reserved field (unused)
             *  [offset 8] 8-byte size in bytes of the serialized data, including the header
             *
             * Currently Microsoft SEAL supports only little-endian systems.
             *
             * As an example, we demonstrate the SEALHeader created by saving a plaintext.
             * Note that the SEALHeader is never compressed, so there is no need to specify
             * the compression mode.
             */
            using Plaintext pt        = new Plaintext("1x^2 + 3");
            using MemoryStream stream = new MemoryStream();
            long dataSize = pt.Save(stream);

            /*
             * Seek the stream head back to beginning of the stream.
             */
            stream.Seek(0, SeekOrigin.Begin);

            /*
             * We can now load just the SEALHeader back from the stream as follows.
             */
            Serialization.SEALHeader header = new Serialization.SEALHeader();
            Serialization.LoadHeader(stream, header);

            /*
             * Now confirm that the size of data written to stream matches with what is
             * indicated by the SEALHeader.
             */
            Utilities.PrintLine();
            Console.WriteLine($"Size written to stream: {dataSize} bytes");
            Console.Write("             ");
            Console.WriteLine($"Size indicated in SEALHeader: {header.Size} bytes");
            Console.WriteLine();
        }
Example #33
0
        public ServicesResponse <Guid> UploadPackage()
        {
            var packageId  = Guid.NewGuid();
            var targetPath = Path.Combine(Playnite.DiagsLocation, $"{packageId}.zip");

            if (!Directory.Exists(Playnite.DiagsLocation))
            {
                Directory.CreateDirectory(Playnite.DiagsLocation);
            }

            if (!Directory.Exists(Playnite.DiagsCrashLocation))
            {
                Directory.CreateDirectory(Playnite.DiagsCrashLocation);
            }

            using (var fs = new FileStream(targetPath, FileMode.OpenOrCreate))
            {
                Request.Body.CopyTo(fs);
            }

            var isCrash = false;
            var version = string.Empty;

            using (var zip = ZipFile.OpenRead(targetPath))
            {
                var diagInfo = zip.GetEntry(DiagnosticPackageInfo.PackageInfoFileName);
                if (diagInfo != null)
                {
                    using (var infoStream = diagInfo.Open())
                    {
                        var info = Serialization.FromJsonStream <DiagnosticPackageInfo>(infoStream);
                        version = info.PlayniteVersion;
                        isCrash = info.IsCrashPackage;
                    }
                }
                else
                {
                    var log = zip.GetEntry("playnite.log");
                    if (log != null)
                    {
                        using (var logStream = log.Open())
                        {
                            using (var tr = new StreamReader(logStream))
                            {
                                while (!tr.EndOfStream)
                                {
                                    var line = tr.ReadLine();
                                    if (line.Contains("Unhandled exception"))
                                    {
                                        isCrash = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    var playniteInfo = zip.GetEntry("playniteInfo.txt");
                    if (playniteInfo != null)
                    {
                        using (var infoStream = playniteInfo.Open())
                        {
                            var info = Serialization.FromJsonStream <Dictionary <string, object> >(infoStream);
                            version = info["Version"].ToString();
                        }
                    }
                }
            }

            if (isCrash)
            {
                var dir = Playnite.DiagsCrashLocation;
                if (!string.IsNullOrEmpty(version))
                {
                    dir = Path.Combine(dir, version);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                }

                var newPath = Path.Combine(dir, Path.GetFileName(targetPath));
                System.IO.File.Move(targetPath, newPath);
            }

            return(new ServicesResponse <Guid>(packageId));
        }
        private void HandleRequest(HttpContext context)
        {
            Trace.TraceMethodCalled(GetType(), "HandleRequest()");

            //Fetch the endpoint configuration
            IDPEndPoint idpEndpoint = RetrieveIDPConfiguration(context.Session[IDPLoginSessionKey].ToString());

            IDPEndPointElement destination =
                DetermineEndpointConfiguration(SAMLBinding.REDIRECT, idpEndpoint.SLOEndpoint, idpEndpoint.metadata.SLOEndpoints());

            //Fetch config object
            SAML20FederationConfig config = ConfigurationReader.GetConfig <SAML20FederationConfig>();

            //Build the response object
            Saml20LogoutResponse response = new Saml20LogoutResponse();

            response.Issuer      = config.ServiceProvider.ID;
            response.Destination = destination.Url;
            response.StatusCode  = Saml20Constants.StatusCodes.Success;

            string message = string.Empty;

            if (context.Request.RequestType == "GET") // HTTP Redirect binding
            {
                HttpRedirectBindingParser parser = new HttpRedirectBindingParser(context.Request.Url);
                IDPEndPoint endpoint             = config.FindEndPoint(idpEndpoint.Id);

                if (endpoint.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Cannot find metadata for IdP");
                    HandleError(context, "Cannot find metadata for IdP " + idpEndpoint.Id);
                    return;
                }

                Saml20MetadataDocument metadata = endpoint.metadata;

                if (!parser.VerifySignature(metadata.GetKeys(KeyTypes.signing)))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Invalid signature redirect-binding, msg: " + parser.Message);
                    HandleError(context, Resources.SignatureInvalid);
                    return;
                }

                message = parser.Message;
            }
            else if (context.Request.RequestType == "POST") // HTTP Post binding
            {
                HttpPostBindingParser parser = new HttpPostBindingParser(context);

                if (!parser.IsSigned())
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Signature not present, msg: " + parser.Message);
                    HandleError(context, Resources.SignatureNotPresent);
                }

                IDPEndPoint endpoint = config.FindEndPoint(idpEndpoint.Id);
                if (endpoint.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Cannot find metadata for IdP");
                    HandleError(context, "Cannot find metadata for IdP " + idpEndpoint.Id);
                    return;
                }

                Saml20MetadataDocument metadata = endpoint.metadata;

                // handle a logout-request
                if (!parser.CheckSignature(metadata.GetKeys(KeyTypes.signing)))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, "Invalid signature post-binding, msg: " + parser.Message);
                    HandleError(context, Resources.SignatureInvalid);
                }

                message = parser.Message;
            }
            else
            {
                //Error: We don't support HEAD, PUT, CONNECT, TRACE, DELETE and OPTIONS
                HandleError(context, Resources.UnsupportedRequestTypeFormat(context.Request.RequestType));
            }

            AuditLogging.logEntry(Direction.IN, Operation.LOGOUTREQUEST, message);

            //Log the user out locally
            DoLogout(context, true);

            LogoutRequest req = Serialization.DeserializeFromXmlString <LogoutRequest>(message);

            response.InResponseTo = req.ID;

            //Respond using redirect binding
            if (destination.Binding == SAMLBinding.REDIRECT)
            {
                HttpRedirectBindingBuilder builder = new HttpRedirectBindingBuilder();
                builder.RelayState = context.Request.Params["RelayState"];
                builder.Response   = response.GetXml().OuterXml;
                builder.signingKey = FederationConfig.GetConfig().SigningCertificate.GetCertificate().PrivateKey;
                string s = destination.Url + "?" + builder.ToQuery();
                context.Response.Redirect(s, true);
                return;
            }

            //Respond using post binding
            if (destination.Binding == SAMLBinding.POST)
            {
                HttpPostBindingBuilder builder = new HttpPostBindingBuilder(destination);
                builder.Action = SAMLAction.SAMLResponse;
                XmlDocument responseDocument = response.GetXml();
                XmlSignatureUtils.SignDocument(responseDocument, response.ID);
                builder.Response   = responseDocument.OuterXml;
                builder.RelayState = context.Request.Params["RelayState"];
                builder.GetPage().ProcessRequest(context);
                return;
            }
        }
Example #35
0
        /// <summary>
        /// Handles the SOAP message.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="inputStream">The input stream.</param>
        private void HandleSoap(HttpContext context, Stream inputStream)
        {
            var parser = new HttpArtifactBindingParser(inputStream);

            Logger.DebugFormat(TraceMessages.SOAPMessageParse, parser.SamlMessage.OuterXml);

            var builder = new HttpArtifactBindingBuilder(context);
            var config  = Saml2Config.GetConfig();
            var idp     = RetrieveIDPConfiguration(parser.Issuer);

            if (parser.IsArtifactResolve)
            {
                Logger.DebugFormat(TraceMessages.ArtifactResolveReceived, parser.SamlMessage);

                if (!parser.CheckSamlMessageSignature(idp.Metadata.Keys))
                {
                    Logger.ErrorFormat(ErrorMessages.ArtifactResolveSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.ArtifactResolveSignatureInvalid);
                }

                builder.RespondToArtifactResolve(parser.ArtifactResolve);
            }
            else if (parser.IsArtifactResponse)
            {
                Logger.DebugFormat(TraceMessages.ArtifactResponseReceived, parser.SamlMessage);

                if (!parser.CheckSamlMessageSignature(idp.Metadata.Keys))
                {
                    Logger.Error(ErrorMessages.ArtifactResponseSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.ArtifactResponseSignatureInvalid);
                }

                var status = parser.ArtifactResponse.Status;
                if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
                {
                    Logger.ErrorFormat(ErrorMessages.ArtifactResponseStatusCodeInvalid, status.StatusCode.Value);
                    throw new Saml20Exception(string.Format(ErrorMessages.ArtifactResponseStatusCodeInvalid, status.StatusCode.Value));
                }

                if (parser.ArtifactResponse.Any.LocalName == LogoutRequest.ElementName)
                {
                    Logger.DebugFormat(TraceMessages.LogoutRequestReceived, parser.ArtifactResponse.Any.OuterXml);

                    var req = Serialization.DeserializeFromXmlString <LogoutRequest>(parser.ArtifactResponse.Any.OuterXml);

                    // Send logoutresponse via artifact
                    var response = new Saml20LogoutResponse
                    {
                        Issuer       = config.ServiceProvider.Id,
                        StatusCode   = Saml20Constants.StatusCodes.Success,
                        InResponseTo = req.Id
                    };

                    var endpoint    = RetrieveIDPConfiguration(StateService.Get <string>(IdpLoginSessionKey));
                    var destination = DetermineEndpointConfiguration(BindingType.Redirect, endpoint.Endpoints.LogoutEndpoint, endpoint.Metadata.IDPSLOEndpoints);

                    builder.RedirectFromLogout(destination, response);
                }
                else if (parser.ArtifactResponse.Any.LocalName == LogoutResponse.ElementName)
                {
                    DoLogout(context);
                }
                else
                {
                    Logger.ErrorFormat(ErrorMessages.ArtifactResponseMissingResponse);
                    throw new Saml20Exception(ErrorMessages.ArtifactResponseMissingResponse);
                }
            }
            else if (parser.IsLogoutReqest)
            {
                Logger.DebugFormat(TraceMessages.LogoutRequestReceived, parser.SamlMessage.OuterXml);

                var req = parser.LogoutRequest;

                // Build the response object
                var response = new Saml20LogoutResponse
                {
                    Issuer       = config.ServiceProvider.Id,
                    StatusCode   = Saml20Constants.StatusCodes.Success,
                    InResponseTo = req.Id
                };

                // response.Destination = destination.Url;
                var doc = response.GetXml();
                XmlSignatureUtils.SignDocument(doc, response.Id);
                if (doc.FirstChild is XmlDeclaration)
                {
                    doc.RemoveChild(doc.FirstChild);
                }

                builder.SendResponseMessage(doc.OuterXml);
            }
            else
            {
                Logger.ErrorFormat(ErrorMessages.SOAPMessageUnsupportedSamlMessage);
                throw new Saml20Exception(ErrorMessages.SOAPMessageUnsupportedSamlMessage);
            }
        }
        // ReceiveData receives the data from a client. It fetches the stream from the TCPClient, then, while the
        // server is started, it read the messages that the stream sends. When the messageContent equals the "@"
        // character, we know the message is done.
        // The function now parses the message (without the @ sign) to the Message class (the message is in JSON).
        // The message type is determined and depending on the type the message gets processed.
        private async Task ReceiveData(TcpClient client)
        {
            var stream = client.GetStream();

            while (_serverStarted)
            {
                var readBytes      = new byte[_bufferSize];
                var messageContent = "";

                while (messageContent.IndexOf("@") < 0)
                {
                    var receivedBytes = await stream.ReadAsync(readBytes, 0, readBytes.Length);

                    messageContent += Encoding.ASCII.GetString(readBytes, 0, receivedBytes);
                }

                var finalMessageContent = messageContent.Substring(0, messageContent.IndexOf("@"));

                var message = Serialization.Deserialize(finalMessageContent);

                switch (message.type)
                {
                // In case the message-type is disconnect, the client sending the message wants to leave
                // the server. In this case, we remove the client's stream from the list of streams. We remove the
                // client from the list of connected clients and we broadcast a message to all other users saying
                // that the user has left the server.
                case MessageType.Disconnect:
                    _connectedStreams.Remove(stream);
                    RemoveClient(message.sender);
                    var leftMessage = new Message(MessageType.Info, $"{_serverName}",
                                                  $"{message.sender} just left the server.", DateTime.Now);

                    await BroadcastMessage(leftMessage);

                    break;

                // In case the message-type is handshake, the client sending the message wants to connect to the
                // server. When this is the case, we check if the name of the client isn't already in use.
                // If the name isn't in use, we add the stream to the list of connected streams and we broadcast
                // a message saying the user has joined.
                case MessageType.Handshake:
                    if (_clientListDataSource.Clients.Contains(message.sender))
                    {
                        var duplicateNameMessage = new Message(MessageType.Error, $"{_serverName}",
                                                               "The username you are trying to connect with is already in use.", DateTime.Now);
                        var serverInfoMessage = new Message(MessageType.Info, $"{_serverName}",
                                                            $"A user with duplicate name {message.sender} was denied to connect.", DateTime.Now);
                        await Messaging.SendMessage(duplicateNameMessage, stream);

                        UI.AddMessage(serverInfoMessage, _chatListDataSource, ChatList);
                        break;
                    }

                    _connectedStreams.Add(stream);
                    AddClient(message.sender);

                    var joinedMessage = new Message(MessageType.Info, $"{_serverName}",
                                                    $"{message.sender} just joined the server!", DateTime.Now);
                    await BroadcastMessage(joinedMessage);

                    break;

                // In any other case, we simply broadcast the message to all users.
                default:
                    await BroadcastMessage(message);

                    break;
                }
            }
        }
Example #37
0
 public void PopulateFromJson(JObject jsonObject)
 {
     m_side = Serialization.JsonTokenValue <int>(jsonObject, "side", 2);
 }
Example #38
0
        /// <summary>
        /// Performs the attribute query against the specified IdP endpoint and adds the resulting attributes to <c>Saml20Identity.Current</c>.
        /// </summary>
        /// <param name="context">The http context.</param>
        /// <param name="endPoint">The IdP to perform the query against.</param>
        /// <param name="nameIdFormat">The name id format.</param>
        public void PerformQuery(HttpContext context, IdentityProvider endPoint, string nameIdFormat)
        {
            Logger.DebugFormat("{0}.{1} called", GetType(), "PerformQuery()");

            var builder = new HttpSoapBindingBuilder(context);

            var name = new NameId
            {
                Value  = Saml20Identity.Current.Name,
                Format = nameIdFormat
            };

            _attrQuery.Subject.Items = new object[] { name };
            _attrQuery.SamlAttribute = _attributes.ToArray();

            var query = new XmlDocument();

            query.LoadXml(Serialization.SerializeToXmlString(_attrQuery));

            XmlSignatureUtils.SignDocument(query, Id);
            if (query.FirstChild is XmlDeclaration)
            {
                query.RemoveChild(query.FirstChild);
            }

            Logger.DebugFormat(TraceMessages.AttrQuerySent, endPoint.Metadata.GetAttributeQueryEndpointLocation(), query.OuterXml);

            Stream s;

            try
            {
                s = builder.GetResponse(endPoint.Metadata.GetAttributeQueryEndpointLocation(), query.OuterXml, endPoint.AttributeQuery);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
                throw;
            }

            var parser = new HttpSoapBindingParser(s);
            var status = parser.GetStatus();

            if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
            {
                Logger.ErrorFormat(ErrorMessages.AttrQueryStatusNotSuccessful, Serialization.SerializeToXmlString(status));
                throw new Saml20Exception(status.StatusMessage);
            }

            bool isEncrypted;
            var  xmlAssertion = Saml20SignonHandler.GetAssertion(parser.SamlMessage, out isEncrypted);

            if (isEncrypted)
            {
                var ass = new Saml20EncryptedAssertion((RSA)Saml2Config.Current.ServiceProvider.SigningCertificate.GetCertificate().PrivateKey);
                ass.LoadXml(xmlAssertion);
                ass.Decrypt();
                xmlAssertion = ass.Assertion.DocumentElement;
            }

            var assertion = new Saml20Assertion(xmlAssertion, null, Saml2Config.Current.AssertionProfile.AssertionValidator, endPoint.QuirksMode);

            Logger.DebugFormat(TraceMessages.AttrQueryAssertionReceived, xmlAssertion == null ? string.Empty : xmlAssertion.OuterXml);

            if (!assertion.CheckSignature(Saml20SignonHandler.GetTrustedSigners(endPoint.Metadata.Keys, endPoint)))
            {
                Logger.Error(ErrorMessages.AssertionSignatureInvalid);
                throw new Saml20Exception(ErrorMessages.AssertionSignatureInvalid);
            }

            foreach (var attr in assertion.Attributes)
            {
                Saml20Identity.Current.AddAttributeFromQuery(attr.Name, attr);
            }
        }
Example #39
0
        public static void CreateDiagPackage(string path, string userActionsDescription, DiagnosticPackageInfo packageInfo)
        {
            var diagTemp = Path.Combine(PlaynitePaths.TempPath, "diag");

            FileSystem.CreateDirectory(diagTemp, true);
            FileSystem.DeleteFile(path);

            ZipFile.CreateFromDirectory(diagTemp, path);
            using (FileStream zipToOpen = new FileStream(path, FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    // Package info
                    var packagePath = Path.Combine(diagTemp, DiagnosticPackageInfo.PackageInfoFileName);
                    File.WriteAllText(packagePath, Serialization.ToJson(packageInfo));
                    archive.CreateEntryFromFile(packagePath, Path.GetFileName(packagePath));

                    // Config
                    if (Directory.Exists(PlaynitePaths.ConfigRootPath))
                    {
                        foreach (var cfg in Directory.GetFiles(PlaynitePaths.ConfigRootPath, "*.json"))
                        {
                            var fileInfo = new FileInfo(cfg);
                            archive.CreateEntryFromFile(cfg, fileInfo.Name);
                        }
                    }

                    // Extension configs
                    if (Directory.Exists(PlaynitePaths.ExtensionsDataPath))
                    {
                        foreach (var cfg in Directory.GetFiles(PlaynitePaths.ExtensionsDataPath, "config.json", SearchOption.AllDirectories))
                        {
                            var fileInfo = new FileInfo(cfg);
                            archive.CreateEntryFromFile(cfg, Path.Combine("extensions", fileInfo.Directory.Name, fileInfo.Name));
                        }
                    }

                    // Installed extensions/themes
                    try
                    {
                        var extensionsPath = Path.Combine(diagTemp, "extensions.txt");
                        File.WriteAllText(extensionsPath, GetManifestInfo(PlaynitePaths.ExtensionsProgramPath, PlaynitePaths.ExtensionManifestFileName));
                        File.AppendAllText(extensionsPath, GetManifestInfo(PlaynitePaths.ThemesProgramPath, PlaynitePaths.ThemeManifestFileName));
                        if (!PlayniteSettings.IsPortable)
                        {
                            File.AppendAllText(extensionsPath, GetManifestInfo(PlaynitePaths.ExtensionsUserDataPath, PlaynitePaths.ExtensionManifestFileName));
                            File.AppendAllText(extensionsPath, GetManifestInfo(PlaynitePaths.ThemesUserDataPath, PlaynitePaths.ThemeManifestFileName));
                        }

                        archive.CreateEntryFromFile(extensionsPath, Path.GetFileName(extensionsPath));
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, "Failed to package extensions list.");
                    }

                    // System Info
                    try
                    {
                        var infoPath = Path.Combine(diagTemp, "sysinfo.txt");
                        File.WriteAllText(infoPath, Serialization.ToJson(Computer.GetSystemInfo(), true));
                        archive.CreateEntryFromFile(infoPath, Path.GetFileName(infoPath));
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, "Failed gather system info.");
                    }

                    // Uninstall regkey export
                    try
                    {
                        var regKeyPath = Path.Combine(diagTemp, "uninstall.txt");
                        var programs   = Programs.GetUnistallProgramsList();
                        File.WriteAllText(regKeyPath, Serialization.ToJson(programs, true));
                        archive.CreateEntryFromFile(regKeyPath, Path.GetFileName(regKeyPath));
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, "Failed gather install app list.");
                    }

                    // UWP app info
                    try
                    {
                        if (Computer.WindowsVersion == WindowsVersion.Win10)
                        {
                            var uwpInfoPath = Path.Combine(diagTemp, "uwp.txt");
                            var uwpApps     = Programs.GetUWPApps();
                            File.WriteAllText(uwpInfoPath, Serialization.ToJson(uwpApps, true));
                            archive.CreateEntryFromFile(uwpInfoPath, Path.GetFileName(uwpInfoPath));
                        }
                    }
                    catch (Exception e) when(!PlayniteEnvironment.ThrowAllErrors)
                    {
                        logger.Error(e, "Failed gather UWP install list.");
                    }

                    // Playnite info
                    var playnitePath = Path.Combine(diagTemp, "playniteInfo.txt");
                    var playniteInfo = new Dictionary <string, object>
                    {
                        { "Version", Updater.GetCurrentVersion().ToString() },
                        { "Portable", PlayniteSettings.IsPortable },
                        { "Memory", (PlayniteProcess.WorkingSetMemory / 1024f) / 1024f },
                        { "Path", PlayniteProcess.Path },
                        { "Cmdline", PlayniteProcess.Cmdline },
                        { "Playnite.DesktopApp.exe_MD5", FileSystem.GetMD5(PlaynitePaths.DesktopExecutablePath) },
                        { "Playnite.FullscreenApp.exe_MD5", FileSystem.GetMD5(PlaynitePaths.FullscreenExecutablePath) },
                        { "Playnite.dll_MD5", FileSystem.GetMD5(PlaynitePaths.PlayniteAssemblyPath) },
                        { "Playnite.Common.dll_MD5", FileSystem.GetMD5(PlaynitePaths.PlayniteCommonAssemblyPath) },
                        { "Playnite.SDK.dll_MD5", FileSystem.GetMD5(PlaynitePaths.PlayniteSDKAssemblyPath) }
                    };

                    File.WriteAllText(playnitePath, Serialization.ToJson(playniteInfo, true));
                    archive.CreateEntryFromFile(playnitePath, Path.GetFileName(playnitePath));

                    // Program file list
                    var fileListPath = Path.Combine(diagTemp, "fileList.txt");
                    File.WriteAllText(fileListPath, string.Join(Environment.NewLine, GetPlayniteFilesList()));
                    archive.CreateEntryFromFile(fileListPath, Path.GetFileName(fileListPath));

                    // User actions description
                    if (!string.IsNullOrWhiteSpace(userActionsDescription))
                    {
                        var descriptionPath = Path.Combine(diagTemp, "userActions.txt");
                        File.WriteAllText(descriptionPath, userActionsDescription);
                        archive.CreateEntryFromFile(descriptionPath, Path.GetFileName(descriptionPath));
                    }

                    void addCefLog(string logPath, ZipArchive archiveObj)
                    {
                        try
                        {
                            var cefEntry = archive.CreateEntry(Path.GetFileName(logPath));
                            using (var cefS = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                                using (var writer = new StreamWriter(cefEntry.Open()))
                                {
                                    cefS.CopyTo(writer.BaseStream);
                                }
                        }
                        catch (Exception e)
                        {
                            logger.Error(e, "Failed to pack CEF log.");
                        }
                    }

                    // Add log files
                    foreach (var logFile in Directory.GetFiles(PlaynitePaths.ConfigRootPath, "*.log", SearchOption.TopDirectoryOnly))
                    {
                        if (Path.GetFileName(logFile) == "cef.log" || Path.GetFileName(logFile) == "debug.log")
                        {
                            addCefLog(logFile, archive);
                        }
                        else
                        {
                            archive.CreateEntryFromFile(logFile, Path.GetFileName(logFile));
                        }
                    }
                }
            }

            FileSystem.DeleteDirectory(diagTemp);
        }
        public void DeserializeFromFileTest()
        {
            nmaprun actual = Serialization.DeserializeFromFile <nmaprun>("scan_1.xml");

            Assert.IsInstanceOfType(actual, typeof(nmaprun));
        }
Example #41
0
 private static byte[] ElementKey <K>(byte[] baseKey, K index)
 {
     byte[] bytes = Serialization.Serialize(index);
     return(ByteArrayUtils.ConcatBytes(baseKey, bytes));
 }
Example #42
0
        public void ApplyInflation(Address from)
        {
            Runtime.Expect(_inflationReady, "inflation not ready");

            Runtime.Expect(Runtime.IsRootChain(), "only on root chain");

            var currentSupply = Runtime.GetTokenSupply(DomainSettings.StakingTokenSymbol);

            var minExpectedSupply = UnitConversion.ToBigInteger(100000000, DomainSettings.StakingTokenDecimals);

            if (currentSupply < minExpectedSupply)
            {
                currentSupply = minExpectedSupply;
            }

            // NOTE this gives an approximate inflation of 3% per year (0.75% per season)
            var        inflationAmount = currentSupply / 133;
            BigInteger mintedAmount    = 0;

            Runtime.Expect(inflationAmount > 0, "invalid inflation amount");

            var masterOrg = Runtime.GetOrganization(DomainSettings.MastersOrganizationName);
            var masters   = masterOrg.GetMembers();

            var rewardList = new List <Address>();

            foreach (var addr in masters)
            {
                var masterDate = Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.GetMasterDate), addr).AsTimestamp();

                if (masterDate <= _lastInflationDate)
                {
                    rewardList.Add(addr);
                }
            }

            if (rewardList.Count > 0)
            {
                var rewardAmount = inflationAmount / 10;

                var rewardStake = rewardAmount / rewardList.Count;
                rewardAmount = rewardList.Count * rewardStake; // eliminate leftovers

                var rewardFuel = _rewardAccum / rewardList.Count;

                var stakeAmount = UnitConversion.ToBigInteger(1, DomainSettings.StakingTokenDecimals);

                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, this.Address, rewardAmount);

                var crownAddress = TokenUtils.GetContractAddress(DomainSettings.RewardTokenSymbol);
                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, crownAddress, stakeAmount);
                Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.Stake), crownAddress, stakeAmount);

                foreach (var addr in rewardList)
                {
                    var reward  = new StakeReward(addr, Runtime.Time);
                    var rom     = Serialization.Serialize(reward);
                    var tokenID = Runtime.MintToken(DomainSettings.RewardTokenSymbol, this.Address, this.Address, rom, new byte[0], 0);
                    Runtime.InfuseToken(DomainSettings.RewardTokenSymbol, this.Address, tokenID, DomainSettings.FuelTokenSymbol, rewardFuel);
                    Runtime.InfuseToken(DomainSettings.RewardTokenSymbol, this.Address, tokenID, DomainSettings.StakingTokenSymbol, rewardStake);
                    Runtime.TransferToken(DomainSettings.RewardTokenSymbol, this.Address, addr, tokenID);
                }

                _rewardAccum -= rewardList.Count * rewardFuel;
                Runtime.Expect(_rewardAccum >= 0, "invalid reward leftover");

                inflationAmount -= rewardAmount;
                inflationAmount -= stakeAmount;
            }

            var refillAmount  = inflationAmount / 50;
            var cosmicAddress = SmartContract.GetAddressForNative(NativeContractKind.Swap);

            Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, cosmicAddress, refillAmount);
            inflationAmount -= refillAmount;

            var phantomOrg = Runtime.GetOrganization(DomainSettings.PhantomForceOrganizationName);

            if (phantomOrg != null)
            {
                var phantomFunding = inflationAmount / 3;
                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, phantomOrg.Address, phantomFunding);
                inflationAmount -= phantomFunding;

                if (phantomOrg.Size == 1)
                {
                    Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.Stake), phantomOrg.Address, phantomFunding);
                }
            }

            var bpOrg = Runtime.GetOrganization(DomainSettings.ValidatorsOrganizationName);

            if (bpOrg != null)
            {
                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, bpOrg.Address, inflationAmount);

                if (bpOrg.Size == 1)
                {
                    Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.Stake), bpOrg.Address, inflationAmount);
                }
            }

            Runtime.Notify(EventKind.Inflation, from, new TokenEventData(DomainSettings.StakingTokenSymbol, mintedAmount, Runtime.Chain.Name));

            _lastInflationDate = Runtime.Time;
            _inflationReady    = false;
        }
        private void HandleResponse(HttpContext context)
        {
            Trace.TraceMethodCalled(GetType(), "HandleResponse()");


            string message = string.Empty;

            if (context.Request.RequestType == "GET")
            {
                HttpRedirectBindingParser parser   = new HttpRedirectBindingParser(context.Request.Url);
                LogoutResponse            response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

                IDPEndPoint idp = RetrieveIDPConfiguration(response.Issuer.Value);

                AuditLogging.IdpId       = idp.Id;
                AuditLogging.AssertionId = response.ID;

                if (idp.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("No IDP metadata, unknown IDP, response: {0}", parser.Message));
                    HandleError(context, Resources.UnknownIDP);
                    return;
                }

                if (!parser.VerifySignature(idp.metadata.Keys))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("Invalid signature in redirect-binding, response: {0}", parser.Message));
                    HandleError(context, Resources.SignatureInvalid);
                    return;
                }

                message = parser.Message;
            }
            else if (context.Request.RequestType == "POST")
            {
                HttpPostBindingParser parser   = new HttpPostBindingParser(context);
                LogoutResponse        response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

                IDPEndPoint idp = RetrieveIDPConfiguration(response.Issuer.Value);

                if (idp.metadata == null)
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("No IDP metadata, unknown IDP, response: {0}", parser.Message));
                    HandleError(context, Resources.UnknownIDP);
                    return;
                }

                if (!parser.IsSigned())
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("Signature not present, response: {0}", parser.Message));
                    HandleError(context, Resources.SignatureNotPresent);
                }

                // signature on final message in logout
                if (!parser.CheckSignature(idp.metadata.Keys))
                {
                    AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                          string.Format("Invalid signature in post-binding, response: {0}", parser.Message));
                    HandleError(context, Resources.SignatureInvalid);
                }

                message = parser.Message;
            }
            else
            {
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                      string.Format("Unsupported request type format, type: {0}", context.Request.RequestType));
                HandleError(context, Resources.UnsupportedRequestTypeFormat(context.Request.RequestType));
            }

            AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE, message);

            XmlDocument doc = new XmlDocument();

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

            XmlElement statElem =
                (XmlElement)doc.GetElementsByTagName(Status.ELEMENT_NAME, Saml20Constants.PROTOCOL)[0];

            Status status = Serialization.DeserializeFromXmlString <Status>(statElem.OuterXml);

            if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
            {
                AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                      string.Format("Unexpected status code: {0}, msg: {1}", status.StatusCode.Value, message));
                HandleError(context, status);
                return;
            }

            AuditLogging.logEntry(Direction.IN, Operation.LOGOUTRESPONSE,
                                  "Assertion validated succesfully");

            //Log the user out locally
            DoLogout(context);
        }
Example #44
0
        /// <summary>
        /// Handles the request.
        /// </summary>
        /// <param name="context">The context.</param>
        private void HandleRequest(HttpContext context)
        {
            Logger.DebugFormat(TraceMessages.LogoutRequestReceived);

            // Fetch the endpoint configuration
            var idp         = RetrieveIDPConfiguration(StateService.Get <string>(IdpLoginSessionKey));
            var destination = DetermineEndpointConfiguration(BindingType.Redirect, idp.Endpoints.LogoutEndpoint, idp.Metadata.IDPSLOEndpoints);

            // Fetch config object
            var config = Saml2Config.GetConfig();

            // Build the response object
            var response = new Saml20LogoutResponse
            {
                Issuer      = config.ServiceProvider.Id,
                Destination = destination.Url,
                StatusCode  = Saml20Constants.StatusCodes.Success
            };

            string message;

            if (context.Request.RequestType == "GET")
            {
                // HTTP Redirect binding
                var parser = new HttpRedirectBindingParser(context.Request.Url);
                Logger.DebugFormat(TraceMessages.LogoutRequestRedirectBindingParse, parser.Message, parser.SignatureAlgorithm, parser.Signature);

                var endpoint = config.IdentityProviders.FirstOrDefault(x => x.Id == idp.Id);
                if (endpoint == null || endpoint.Metadata == null)
                {
                    Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
                    throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
                }

                var metadata = endpoint.Metadata;
                if (!parser.VerifySignature(metadata.GetKeys(KeyTypes.Signing)))
                {
                    Logger.Error(ErrorMessages.RequestSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.RequestSignatureInvalid);
                }

                message = parser.Message;
            }
            else if (context.Request.RequestType == "POST")
            {
                // HTTP Post binding
                var parser = new HttpPostBindingParser(context);
                Logger.DebugFormat(TraceMessages.LogoutRequestPostBindingParse, parser.Message);

                if (!parser.IsSigned)
                {
                    Logger.Error(ErrorMessages.RequestSignatureMissing);
                    throw new Saml20Exception(ErrorMessages.RequestSignatureMissing);
                }

                var endpoint = config.IdentityProviders.FirstOrDefault(x => x.Id == idp.Id);
                if (endpoint == null || endpoint.Metadata == null)
                {
                    Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
                    throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
                }

                var metadata = endpoint.Metadata;

                // Check signature
                if (!parser.CheckSignature(metadata.GetKeys(KeyTypes.Signing)))
                {
                    Logger.Error(ErrorMessages.RequestSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.RequestSignatureInvalid);
                }

                message = parser.Message;
            }
            else
            {
                // Error: We don't support HEAD, PUT, CONNECT, TRACE, DELETE and OPTIONS
                Logger.ErrorFormat(ErrorMessages.UnsupportedRequestType, context.Request.RequestType);
                throw new Saml20Exception(string.Format(ErrorMessages.UnsupportedRequestType, context.Request.RequestType));
            }

            Logger.DebugFormat(TraceMessages.LogoutRequestParsed, message);

            // Log the user out locally
            DoLogout(context, true);

            var req = Serialization.DeserializeFromXmlString <LogoutRequest>(message);

            response.InResponseTo = req.Id;

            // Respond using redirect binding
            if (destination.Binding == BindingType.Redirect)
            {
                var builder = new HttpRedirectBindingBuilder
                {
                    RelayState = context.Request.Params["RelayState"],
                    Response   = response.GetXml().OuterXml,
                    SigningKey = Saml2Config.GetConfig().ServiceProvider.SigningCertificate.GetCertificate().PrivateKey
                };

                Logger.DebugFormat(TraceMessages.LogoutResponseSent, builder.Response);

                context.Response.Redirect(destination.Url + "?" + builder.ToQuery(), true);
                return;
            }

            // Respond using post binding
            if (destination.Binding == BindingType.Post)
            {
                var builder = new HttpPostBindingBuilder(destination)
                {
                    Action = SamlActionType.SAMLResponse
                };

                var responseDocument = response.GetXml();

                Logger.DebugFormat(TraceMessages.LogoutResponseSent, responseDocument.OuterXml);

                XmlSignatureUtils.SignDocument(responseDocument, response.Id);
                builder.Response   = responseDocument.OuterXml;
                builder.RelayState = context.Request.Params["RelayState"];
                builder.GetPage().ProcessRequest(context);
            }
        }
Example #45
0
 public override void PopulateFromJson(JObject jsonObject)
 {
     base.PopulateFromJson(jsonObject);
     m_player             = OwnerFilter.FromJsonProperty(jsonObject, "player");
     m_countMissingSpells = Serialization.JsonTokenValue <bool>(jsonObject, "countMissingSpells", false);
 }
Example #46
0
        /// <summary>
        /// Handles the response.
        /// </summary>
        /// <param name="context">The context.</param>
        private void HandleResponse(HttpContext context)
        {
            Logger.DebugFormat(TraceMessages.LogoutResponseReceived);

            var            message  = string.Empty;
            LogoutResponse response = null;

            if (context.Request.RequestType == "GET")
            {
                var parser = new HttpRedirectBindingParser(context.Request.Url);
                response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

                Logger.DebugFormat(TraceMessages.LogoutResponseRedirectBindingParse, parser.Message, parser.SignatureAlgorithm, parser.Signature);

                var idp = RetrieveIDPConfiguration(response.Issuer.Value);
                if (idp.Metadata == null)
                {
                    Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
                    throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
                }

                if (!parser.VerifySignature(idp.Metadata.Keys))
                {
                    Logger.Error(ErrorMessages.ResponseSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.ResponseSignatureInvalid);
                }

                message = parser.Message;
            }
            else if (context.Request.RequestType == "POST")
            {
                var parser = new HttpPostBindingParser(context);
                Logger.DebugFormat(TraceMessages.LogoutResponsePostBindingParse, parser.Message);

                response = Serialization.DeserializeFromXmlString <LogoutResponse>(parser.Message);

                var idp = RetrieveIDPConfiguration(response.Issuer.Value);
                if (idp.Metadata == null)
                {
                    Logger.ErrorFormat(ErrorMessages.UnknownIdentityProvider, idp.Id);
                    throw new Saml20Exception(string.Format(ErrorMessages.UnknownIdentityProvider, idp.Id));
                }

                if (!parser.IsSigned)
                {
                    Logger.Error(ErrorMessages.ResponseSignatureMissing);
                    throw new Saml20Exception(ErrorMessages.ResponseSignatureMissing);
                }

                // signature on final message in logout
                if (!parser.CheckSignature(idp.Metadata.Keys))
                {
                    Logger.Error(ErrorMessages.ResponseSignatureInvalid);
                    throw new Saml20Exception(ErrorMessages.ResponseSignatureInvalid);
                }

                message = parser.Message;
            }

            if (response == null)
            {
                Logger.ErrorFormat(ErrorMessages.UnsupportedRequestType, context.Request.RequestType);
                throw new Saml20Exception(string.Format(ErrorMessages.UnsupportedRequestType, context.Request.RequestType));
            }

            Logger.DebugFormat(TraceMessages.LogoutResponseParsed, message);

            if (response.Status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
            {
                Logger.ErrorFormat(ErrorMessages.ResponseStatusNotSuccessful, response.Status.StatusCode.Value);
                throw new Saml20Exception(string.Format(ErrorMessages.ResponseStatusNotSuccessful, response.Status.StatusCode.Value));
            }

            // Log the user out locally
            DoLogout(context);
        }
        public void InitPoll(Address from, string subject, ConsensusKind kind, ConsensusMode mode, Timestamp startTime, Timestamp endTime, byte[] serializedChoices, BigInteger votesPerUser)
        {
            // TODO support for passing structs as args
            var choices = Serialization.Unserialize <PollChoice[]>(serializedChoices);

            if (subject.StartsWith(SystemPoll))
            {
                Runtime.Expect(Runtime.Nexus.IsPrimaryValidator(from), "must be validator");

                if (subject.StartsWith(SystemPoll + "stake."))
                {
                    Runtime.Expect(kind >= ConsensusKind.Masters, "must require votes from masters or community");
                }

                Runtime.Expect(mode == ConsensusMode.Majority, "must use majority mode for system governance");
            }

            Runtime.Expect(Runtime.Chain.IsRoot, "not root chain");

            Runtime.Expect(kind == ConsensusKind.Validators, "community polls not yet");

            var maxEntriesPerPoll = Runtime.GetGovernanceValue(MaxEntriesPerPollTag);

            Runtime.Expect(choices.Length > 1, "invalid amount of entries");
            Runtime.Expect(choices.Length <= maxEntriesPerPoll, "too many entries");

            var MaximumPollLength = (uint)Runtime.GetGovernanceValue(MaximumPollLengthTag);

            Runtime.Expect(startTime >= Runtime.Time, "invalid start time");
            var minEndTime = new Timestamp(startTime.Value + MinimumPollLength);
            var maxEndTime = new Timestamp(startTime.Value + MaximumPollLength);

            Runtime.Expect(endTime >= minEndTime, "invalid end time");
            Runtime.Expect(endTime <= maxEndTime, "invalid end time");

            Runtime.Expect(votesPerUser > 0, "number of votes per user too low");
            Runtime.Expect(votesPerUser < choices.Length, "number of votes per user too high");

            Runtime.Expect(IsWitness(from), "invalid witness");

            ConsensusPoll poll;

            if (_pollMap.ContainsKey <string>(subject))
            {
                poll = FetchPoll(subject);
                Runtime.Expect(poll.state == PollState.Consensus || poll.state == PollState.Failure, "poll already in progress");
                poll.round += 1;
                poll.state  = PollState.Inactive;
            }
            else
            {
                poll         = new ConsensusPoll();
                poll.subject = subject;
                poll.round   = 1;
            }

            poll.startTime      = startTime;
            poll.endTime        = endTime;
            poll.kind           = kind;
            poll.mode           = mode;
            poll.state          = PollState.Inactive;
            poll.choicesPerUser = votesPerUser;
            poll.totalVotes     = 0;

            var electionName = SystemPoll + ValidatorContract.ValidatorPollTag;

            if (subject == electionName)
            {
                for (int i = 0; i < choices.Length; i++)
                {
                    Runtime.Expect(choices[i].value.Length == Address.PublicKeyLength, "election choices must be public addresses");
                    var address = new Address(choices[i].value);
                    Runtime.Expect(Runtime.Nexus.IsKnownValidator(address), "election choice must be active or waiting validator");
                }
            }

            poll.entries = new PollValue[choices.Length];
            for (int i = 0; i < choices.Length; i++)
            {
                poll.entries[i] = new PollValue()
                {
                    ranking = -1,
                    value   = choices[i].value,
                    votes   = 0
                };
            }

            _pollMap.Set <string, ConsensusPoll>(subject, poll);

            Runtime.Notify(EventKind.PollCreated, this.Address, subject);
        }
Example #48
0
                void SerializeObject(object obj)
                {
                    Debug.Assert(obj != null);

                    var tinfo     = obj.GetPhpTypeInfo();
                    var classname = tinfo.Name;

                    if (obj is __PHP_Incomplete_Class)
                    {
                        // classname = ((__PHP_Incomplete_Class)obj).ClassName ?? classname;
                        throw new NotImplementedException(nameof(__PHP_Incomplete_Class));
                    }

                    var classnameBytes = Encoding.GetBytes(classname);

                    PhpArray serializedArray = null;

                    byte[] serializedBytes = null;
                    List <KeyValuePair <string, PhpValue> > serializedProperties = null;

                    var __serialize = tinfo.RuntimeMethods[TypeMethods.MagicMethods.__serialize];

                    if (__serialize != null)
                    {
                        // TODO: check accessibility
                        var rvalue = __serialize.Invoke(_ctx, obj);
                        if (rvalue.IsPhpArray(out serializedArray) == false)
                        {
                            // FATAL ERROR
                            // {0}::__serialize must return an array
                            throw PhpException.TypeErrorException(string.Format(LibResources.__serialize_must_return_array, tinfo.Name));
                        }
                    }
                    else if (obj is global::Serializable serializable)
                    {
                        var res = serializable.serialize();
                        if (res.IsDefault)
                        {
                            AcceptNull();
                            return;
                        }

                        serializedBytes = res.ToBytes(Encoding);

                        //if (resdata == null)
                        //{
                        //    // serialize did not return NULL nor a string -> throw an exception
                        //    SPL.Exception.ThrowSplException(
                        //        _ctx => new SPL.Exception(_ctx, true),
                        //        context,
                        //        string.Format(CoreResources.serialize_must_return_null_or_string, value.TypeName), 0, null);
                        //}
                    }
                    else
                    {
                        // try to call the __sleep method
                        // otherwise list object properties

                        var __sleep = tinfo.RuntimeMethods[TypeMethods.MagicMethods.__sleep];
                        // TODO: __sleep accessibility -> ThrowMethodVisibilityError
                        if (__sleep != null)
                        {
                            var sleep_result = __sleep.Invoke(_ctx, obj).ArrayOrNull();
                            if (sleep_result == null)
                            {
                                PhpException.Throw(PhpError.Notice, Core.Resources.ErrResources.sleep_must_return_array);
                                AcceptNull();
                                return;
                            }

                            serializedProperties = EnumerateSerializableProperties(obj, tinfo, sleep_result).ToList();
                        }
                        else
                        {
                            serializedProperties = Serialization.EnumerateSerializableProperties(obj, tinfo).ToList();
                        }
                    }

                    Write((serializedBytes == null) ? Tokens.Object : Tokens.ObjectSer);
                    Write(Tokens.Colon);

                    // write out class name
                    Write(classnameBytes.Length.ToString());
                    Write(Tokens.Colon);
                    Write(Tokens.Quote);

                    Write(classnameBytes);
                    Write(Tokens.Quote);
                    Write(Tokens.Colon);

                    if (serializedBytes != null)
                    {
                        Debug.Assert(serializedProperties == null);

                        // write out the result of serialize
                        Write(serializedBytes.Length.ToString());
                        Write(Tokens.Colon);
                        Write(Tokens.BraceOpen);

                        // write serialized data
                        Write(serializedBytes);
                    }
                    else if (serializedArray != null)
                    {
                        // write out property count
                        Write(serializedArray.Count.ToString());
                        Write(Tokens.Colon);
                        Write(Tokens.BraceOpen);

                        // enumerate array items and serialize them
                        base.Accept(serializedArray);
                    }
                    else
                    {
                        // write out property count
                        Write(serializedProperties.Count.ToString());
                        Write(Tokens.Colon);
                        Write(Tokens.BraceOpen);

                        // write out properties
                        AcceptObjectProperties(serializedProperties);
                    }

                    // }
                    Write(Tokens.BraceClose);
                }
Example #49
0
                IEnumerable <KeyValuePair <string, PhpValue> > EnumerateSerializableProperties(object obj, PhpTypeInfo tinfo, PhpArray properties)
                {
                    Debug.Assert(obj != null);
                    Debug.Assert(tinfo != null);
                    Debug.Assert(properties != null);

                    PhpArray runtime_fields = null;

                    var enumerator = properties.GetFastEnumerator();

                    while (enumerator.MoveNext())
                    {
                        FieldAttributes visibility;
                        string          name = enumerator.CurrentValue.ToStringOrThrow(_ctx);
                        string          declaring_type_name;
                        string          property_name = Serialization.ParseSerializedPropertyName(name, out declaring_type_name, out visibility);

                        PhpTypeInfo declarer;   // for visibility check
                        if (declaring_type_name == null)
                        {
                            declarer = tinfo;
                        }
                        else
                        {
                            declarer = _ctx.GetDeclaredType(declaring_type_name);
                            if (declarer == null)
                            {
                                // property name refers to an unknown class -> value will be null
                                yield return(new KeyValuePair <string, PhpValue>(name, PhpValue.Null));

                                continue;
                            }
                        }

                        // obtain the property desc and decorate the prop name according to its visibility and declaring class
                        var property = tinfo.GetDeclaredProperty(property_name);
                        if (property != null && !property.IsStatic && property.IsVisible(declarer.Type))
                        {
                            // if certain conditions are met, serialize the property as null
                            // (this is to precisely mimic the PHP behavior)
                            if ((visibility == (property.Attributes & FieldAttributes.FieldAccessMask) && visibility != FieldAttributes.Public) ||
                                (visibility == FieldAttributes.Private && declarer != property.ContainingType))
                            {
                                yield return(new KeyValuePair <string, PhpValue>(name, PhpValue.Null));

                                continue;
                            }

                            name = Serialization.FormatSerializedPropertyName(property);
                        }
                        else
                        {
                            property = null; // field is not visible, try runtime fields
                        }

                        // obtain the property value
                        PhpValue val;

                        if (property != null)
                        {
                            val = property.GetValue(_ctx, obj);
                        }
                        else
                        {
                            if (runtime_fields == null)
                            {
                                runtime_fields = tinfo.GetRuntimeFields(obj) ?? PhpArray.Empty;
                            }

                            if (!runtime_fields.TryGetValue(name, out val))
                            {
                                // PHP 5.1+
                                PhpException.Throw(PhpError.Notice, string.Format(Core.Resources.ErrResources.sleep_returned_bad_field, name));
                            }
                        }

                        yield return(new KeyValuePair <string, PhpValue>(name, val));
                    }
                }
Example #50
0
 public static CSOpaqueConstruction fromJSON(string json)
 {
     return(Serialization.Deserialize <CSOpaqueConstruction>(json));
 }
 public void PopulateFromJson(JObject jsonObject)
 {
     m_condition   = (ShouldBeInOrNot)Serialization.JsonTokenValue <int>(jsonObject, "condition", 1);
     m_entityTypes = Serialization.JsonArrayAsList <EntityType>(jsonObject, "entityTypes");
 }
Example #52
0
 public string toJSON()
 {
     return(Serialization.Serialize <CSOpaqueConstruction>(this));
 }
Example #53
0
        public bool DoFillSelf(BaseEntity instance, string Condition, params string[] FieldNames)
        {
            if (FieldNames.Length == 0)
            {
                FieldNames = null;
            }
            SQLQuery      sq  = new SQLQuery(this.DatabaseName);
            DataTable     dt  = sq.GetDTQuery(this.TableName, Condition);
            List <string> Set = new List <string>();

            if (FieldNames != null)
            {
                Set.AddRange(FieldNames);
            }
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                foreach (DataColumn Column in dt.Columns)
                {
                    string Key = Column.ColumnName.ToUpper();
                    if (dr[Key] == DBNull.Value)
                    {
                        continue;
                    }
                    #region 处理字段
                    Field Field = null;
                    if (this.PKeyList.ContainsKey(Key))
                    {
                        Field = this.PKeyList[Key];
                    }
                    else if (this.FKeyList.ContainsKey(Key))
                    {
                        Field = this.FKeyList[Key];
                    }
                    else if (this.FieldList.ContainsKey(Key))
                    {
                        Field = this.FieldList[Key];
                    }
                    #endregion

                    #region 赋值
                    if (FieldNames != null)
                    {
                        if (!Set.Contains(Key))
                        {
                            continue;
                        }
                    }
                    if (Field != null)
                    {
                        if (Field.SerializedType == ESerializedType.NO)
                        {
                            if (Field.FieldType.IsEnum)
                            {
                                instance[Field.PropertyName] = Convert.ToInt32(dr[Key]);
                            }
                            else if (Field.FieldType.ToString() == "System.Boolean")
                            {
                                instance[Field.PropertyName] = Convert.ToBoolean(dr[Key]);
                            }
                            else if (Field.FieldType.ToString() == "System.DateTime")
                            {
                                instance[Field.PropertyName] = DateTime.Parse(dr[Key].ToString());
                            }
                            else
                            {
                                instance[Field.PropertyName] = dr[Key];
                            }
                        }
                        else
                        {
                            instance[Field.PropertyName] = Serialization.Deserialize(dr[Key], Field.FieldType, Field.SerializedType);
                        }
                    }
                    else
                    {
                        instance[Key] = dr[Key];
                    }

                    #endregion
                }
                instance.IsCreated = true;

                return(true);
            }
            return(false);
        }
Example #54
0
        public void UnserializeData(BinaryReader reader)
        {
            this.Type = (VMType)reader.ReadByte();
            switch (this.Type)
            {
            case VMType.Bool:
                this.Data = Serialization.Unserialize <bool>(reader);
                break;

            case VMType.Bytes:
                this.Data = Serialization.Unserialize <byte[]>(reader);
                break;

            case VMType.Number:
                this.Data = Serialization.Unserialize <BigInteger>(reader);
                break;

            case VMType.Timestamp:
                this.Data = Serialization.Unserialize <Timestamp>(reader);
                break;

            case VMType.String:
                this.Data = Serialization.Unserialize <string>(reader);
                break;

            case VMType.Struct:
                var childCount = reader.ReadVarInt();
                var children   = new Dictionary <VMObject, VMObject>();
                while (childCount > 0)
                {
                    var key = new VMObject();
                    key.UnserializeData(reader);

                    var val = new VMObject();
                    val.UnserializeData(reader);

                    children[key] = val;
                    childCount--;
                }

                this.Data = children;
                break;

            // NOTE object type information is lost during serialization, so we reconstruct it as byte array
            case VMType.Object:
                this.Type = VMType.Bytes;
                this.Data = reader.ReadByteArray();
                break;

            case VMType.Enum:
                this.Type = VMType.Enum;
                this.Data = (uint)reader.ReadVarInt();
                break;

            case VMType.None:
                this.Type = VMType.None;
                this.Data = null;
                break;

            default:
                throw new Exception($"invalid unserialize: type {this.Type}");
            }
        }
Example #55
0
        /// <summary>
        /// 生成Insert命令
        /// </summary>
        /// <param name="dh">DataHelper</param>
        /// <param name="IncremetSet">返回自动增长字段,用于Insert完毕后获取incremet的值</param>
        /// <param name="Propertys">指定特定字段插入</param>
        /// <returns>命令对象System.Data.Common.DbCommand</returns>
        private MySqlCommand GenerateInsertCommand(DataHelper dh, BaseEntity EntityInstance, ref Dictionary <string, string> IncremetSet, params string[] Propertys)
        {
            MySqlCommand Command = null;

            #region 生成命令对象
            IncremetSet = new Dictionary <string, string>();
            string strSQL = string.Format("insert into {0}", this.TableName);
            string temp1 = "(", temp2 = " values(";

            #region 处理字段
            Dictionary <string, KeyField>  m_PKeyList = null;
            Dictionary <string, KeyField>  m_FKeyList = null;
            Dictionary <string, DataField> m_FieldList = null;
            if ((Propertys != null) && (Propertys.Length != 0))
            {
                #region 处理特定字段
                List <string> PropertyList = new List <string>(Propertys.Length);
                PropertyList.AddRange(Propertys);
                m_PKeyList  = new Dictionary <string, KeyField>();
                m_FKeyList  = new Dictionary <string, KeyField>();
                m_FieldList = new Dictionary <string, DataField>();
                foreach (KeyField Key in this.PKeyList.Values)
                {
                    if (PropertyList.Contains(Key.FieldName))
                    {
                        m_PKeyList.Add(Key.FieldName, Key);
                    }
                }
                foreach (KeyField Key in this.FKeyList.Values)
                {
                    if (PropertyList.Contains(Key.FieldName))
                    {
                        m_FKeyList.Add(Key.FieldName, Key);
                    }
                }
                foreach (DataField Key in this.FieldList.Values)
                {
                    if (PropertyList.Contains(Key.FieldName))
                    {
                        m_FieldList.Add(Key.FieldName, Key);
                    }
                }
                #endregion
            }
            else
            {
                #region 默认全部字段
                m_PKeyList  = this.PKeyList;
                m_FKeyList  = this.FKeyList;
                m_FieldList = this.FieldList;
                #endregion
            }
            #endregion

            #region 生成SQL语句
            #region 处理主键
            //foreach (KeyField key in m_PKeyList.Values)
            //{
            //    if (key.IsBase) continue;
            //    if (key.Sequence != string.Empty)
            //    {
            //        temp1 += key.FieldName + ",";
            //        temp2 += key.Sequence + ".nextval,";
            //        IncremetSet.Add(key.FieldName, "select " + key.Sequence + ".currval from dual");
            //    }
            //}
            #endregion
            #region 处理其他字段
            foreach (KeyField key in m_FKeyList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                temp1 += key.FieldName + ",";
                temp2 += dh.ParameterSeparateCode + key.FieldName + ",";
            }

            foreach (DataField key in m_FieldList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                temp1 += key.FieldName + ",";
                temp2 += dh.ParameterSeparateCode + key.FieldName + ",";
            }
            temp1 = temp1.Substring(0, temp1.Length - 1);
            temp2 = temp2.Substring(0, temp2.Length - 1);

            strSQL += temp1 + ")" + temp2 + ")";

            #endregion
            #endregion

            Command = dh.GetSqlStringCommand(strSQL);

            #region 填充命令对象
            foreach (KeyField key in m_FKeyList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                object Value = EntityInstance[key.FieldName];
                if (Value == null)
                {
                    Value = DBNull.Value;
                }
                if (key.SerializedType != ESerializedType.NO)
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Serialization.Serialize(Value, key.SerializedType));
                }
                else
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Value);
                }
            }
            foreach (DataField key in m_FieldList.Values)
            {
                if (key.IsBase)
                {
                    continue;
                }
                object Value = EntityInstance[key.FieldName];
                if (Value == null)
                {
                    Value = DBNull.Value;
                }
                if (key.SerializedType != ESerializedType.NO)
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Serialization.Serialize(Value, key.SerializedType));
                }
                else
                {
                    dh.AddInParameter(Command, dh.ParameterSeparateCode + key.FieldName, key.DBType, Value);
                }
            }
            #endregion

            #endregion
            return(Command);
        }
        private void HandleSOAP(HttpContext context, Stream inputStream)
        {
            Trace.TraceMethodCalled(GetType(), "HandleSOAP");

            HttpArtifactBindingParser  parser  = new HttpArtifactBindingParser(inputStream);
            HttpArtifactBindingBuilder builder = new HttpArtifactBindingBuilder(context);
            SAML20FederationConfig     config  = SAML20FederationConfig.GetConfig();

            IDPEndPoint idp = RetrieveIDPConfiguration(parser.Issuer);

            AuditLogging.IdpId = idp.Id;


            if (parser.IsArtifactResolve())
            {
                Trace.TraceData(TraceEventType.Information, Tracing.ArtifactResolveIn);

                if (!parser.CheckSamlMessageSignature(idp.metadata.Keys))
                {
                    HandleError(context, "Invalid Saml message signature");
                    AuditLogging.logEntry(Direction.UNDEFINED, Operation.ARTIFACTRESOLVE, "Signature could not be verified", parser.SamlMessage);
                }
                AuditLogging.AssertionId = parser.ArtifactResolve.ID;
                AuditLogging.logEntry(Direction.IN, Operation.ARTIFACTRESOLVE, "", parser.SamlMessage);
                builder.RespondToArtifactResolve(parser.ArtifactResolve);
            }
            else if (parser.IsArtifactResponse())
            {
                Trace.TraceData(TraceEventType.Information, Tracing.ArtifactResponseIn);

                Status status = parser.ArtifactResponse.Status;
                if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success)
                {
                    AuditLogging.logEntry(Direction.UNDEFINED, Operation.ARTIFACTRESOLVE, string.Format("Unexpected status code for artifact response: {0}, expected 'Success', msg: {1}", status.StatusCode.Value, parser.SamlMessage));
                    HandleError(context, status);
                    return;
                }

                if (parser.ArtifactResponse.Any.LocalName == LogoutRequest.ELEMENT_NAME)
                {
                    if (Trace.ShouldTrace(TraceEventType.Information))
                    {
                        Trace.TraceData(TraceEventType.Information, string.Format(Tracing.LogoutRequest, parser.ArtifactResponse.Any.OuterXml));
                    }

                    //Send logoutresponse via artifact
                    Saml20LogoutResponse response = new Saml20LogoutResponse();
                    response.Issuer = config.ServiceProvider.ID;
                    LogoutRequest req = Serialization.DeserializeFromXmlString <LogoutRequest>(parser.ArtifactResponse.Any.OuterXml);
                    response.StatusCode   = Saml20Constants.StatusCodes.Success;
                    response.InResponseTo = req.ID;
                    IDPEndPoint        endpoint    = RetrieveIDPConfiguration(context.Session[IDPLoginSessionKey].ToString());
                    IDPEndPointElement destination =
                        DetermineEndpointConfiguration(SAMLBinding.REDIRECT, endpoint.SLOEndpoint, endpoint.metadata.SLOEndpoints());

                    builder.RedirectFromLogout(destination, response);
                }
                else if (parser.ArtifactResponse.Any.LocalName == LogoutResponse.ELEMENT_NAME)
                {
                    DoLogout(context);
                }
                else
                {
                    AuditLogging.logEntry(Direction.UNDEFINED, Operation.ARTIFACTRESOLVE, string.Format("Unsupported payload message in ArtifactResponse: {0}, msg: {1}", parser.ArtifactResponse.Any.LocalName, parser.SamlMessage));
                    HandleError(context,
                                string.Format("Unsupported payload message in ArtifactResponse: {0}",
                                              parser.ArtifactResponse.Any.LocalName));
                }
            }
            else if (parser.IsLogoutReqest())
            {
                if (Trace.ShouldTrace(TraceEventType.Information))
                {
                    Trace.TraceData(TraceEventType.Information, string.Format(Tracing.LogoutRequest, parser.SamlMessage.OuterXml));
                }

                LogoutRequest req = parser.LogoutRequest;

                //Build the response object
                Saml20LogoutResponse response = new Saml20LogoutResponse();
                response.Issuer = config.ServiceProvider.ID;
                //response.Destination = destination.Url;
                response.StatusCode   = Saml20Constants.StatusCodes.Success;
                response.InResponseTo = req.ID;
                XmlDocument doc = response.GetXml();
                XmlSignatureUtils.SignDocument(doc, response.ID);
                if (doc.FirstChild is XmlDeclaration)
                {
                    doc.RemoveChild(doc.FirstChild);
                }

                builder.SendResponseMessage(doc.OuterXml);
            }
            else
            {
                Status s = parser.GetStatus();
                if (s != null)
                {
                    HandleError(context, s);
                }
                else
                {
                    AuditLogging.logEntry(Direction.UNDEFINED, Operation.ARTIFACTRESOLVE, string.Format("Unsupported SamlMessage element: {0}, msg: {1}", parser.SamlMessageName, parser.SamlMessage));
                    HandleError(context, string.Format("Unsupported SamlMessage element: {0}", parser.SamlMessageName));
                }
            }
        }
Example #57
0
        private static byte[] PackEvent(object content)
        {
            var bytes = content == null ? new byte[0] : Serialization.Serialize(content);

            return(bytes);
        }
Example #58
0
            public void AddComponentToDiff(AddComponentOp op, ViewDiff diff)
            {
                var data = Serialization.DeserializeUpdate(op.Data.SchemaData.Value);

                diff.AddComponent(data, op.EntityId, op.Data.ComponentId);
            }
        public void SwapToken(Address buyer, Address seller, string baseSymbol, string quoteSymbol, BigInteger tokenID, BigInteger price, byte[] signature)
        {
            Runtime.Expect(Runtime.IsWitness(buyer), "invalid witness");
            Runtime.Expect(seller != buyer, "invalid seller");

            Runtime.Expect(seller.IsUser, "seller must be user address");

            Runtime.Expect(Runtime.TokenExists(baseSymbol), "invalid base token");
            var baseToken = Runtime.GetToken(baseSymbol);

            Runtime.Expect(!baseToken.Flags.HasFlag(TokenFlags.Fungible), "token must be non-fungible");

            var nft = Runtime.ReadToken(baseSymbol, tokenID);

            Runtime.Expect(nft.CurrentChain == Runtime.Chain.Name, "invalid owner");

            var owner = nft.CurrentOwner;

            Runtime.Expect(owner == seller, "invalid owner");

            var swap = new TokenSwap()
            {
                baseSymbol  = baseSymbol,
                quoteSymbol = quoteSymbol,
                buyer       = buyer,
                seller      = seller,
                price       = price,
                value       = tokenID,
            };

            var msg = Serialization.Serialize(swap);

            Runtime.Expect(Ed25519.Verify(signature, msg, seller.PublicKey), "invalid signature");

            Runtime.Expect(Runtime.TokenExists(quoteSymbol), "invalid quote token");
            var quoteToken = Runtime.GetToken(quoteSymbol);

            Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible");

            var balance = Runtime.GetBalance(quoteSymbol, buyer);

            Runtime.Expect(balance >= price, "invalid balance");

            Runtime.Expect(Runtime.TransferTokens(quoteSymbol, buyer, owner, price), "payment failed");
            Runtime.Expect(Runtime.TransferToken(baseSymbol, owner, buyer, tokenID), "transfer failed");

            Runtime.Notify(EventKind.TokenSend, seller, new TokenEventData()
            {
                chainAddress = this.Address, symbol = baseSymbol, value = tokenID
            });
            Runtime.Notify(EventKind.TokenSend, buyer, new TokenEventData()
            {
                chainAddress = this.Address, symbol = quoteSymbol, value = price
            });

            Runtime.Notify(EventKind.TokenReceive, seller, new TokenEventData()
            {
                chainAddress = this.Address, symbol = quoteSymbol, value = price
            });
            Runtime.Notify(EventKind.TokenReceive, buyer, new TokenEventData()
            {
                chainAddress = this.Address, symbol = baseSymbol, value = tokenID
            });
        }
Example #60
0
        /// <summary>
        /// Creates the world events names files
        /// </summary>
        /// <returns></returns>
        private void GenerateFiles()
        {
            // English
            List <MetaEventStageName> english = new List <MetaEventStageName>()
            {
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TimberlineFalls_LeyLine, Name = "Ley-Line Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.IronMarches_LeyLine, Name = "Ley-Line Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.GendarranFields_LeyLine, Name = "Ley-Line Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_CrashSite, Name = "Crash Site"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_Sandstorm, Name = "Sandstorm"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_NightBosses, Name = "Night Bosses"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Daytime, Name = "Daytime"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Night, Name = "Night"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Challenges, Name = "Challenges"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Octovine, Name = "Octovine"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Reset, Name = "Reset"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Pylons, Name = "Pylons"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_Preparation, Name = "Preparation"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_ChakGerent, Name = "Chak Gerent"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_HelpOutposts, Name = "Help Outposts"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DragonsStand_MapActive, Name = "Map Active"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Noran, Name = "Noran's Homestead"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Saidra, Name = "Saidra's Haven"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Loamhurst, Name = "New Loamhurst"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.CrystalOasis_CasinoBlitz, Name = "Casino Blitz"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DesertHighlands_Treasure, Name = "Buried Treasure"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfVabbi_Serpent, Name = "Serpent's Ire"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfIstan_Palawadan, Name = "Palawadan"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.JahaiBluffs_DangerousPrey, Name = "Dangerous Prey"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Keep, Name = "Thunderhead Keep"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Oil, Name = "The Oil Floes"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.EventEnds, Name = "Event Ends"
                }
            };

            // Spanish
            List <MetaEventStageName> spanish = new List <MetaEventStageName>()
            {
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_CrashSite, Name = "Lugar del accidente"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_Sandstorm, Name = "Tormenta de arena"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_NightBosses, Name = "Los jefes noche"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Daytime, Name = "Tiempo de día"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Night, Name = "Noche"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Challenges, Name = "desafíos"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Octovine, Name = "Octovine"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Reset, Name = "Reiniciar"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Pylons, Name = "pilones"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_Preparation, Name = "Preparación"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_ChakGerent, Name = "Chak Gerent"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_HelpOutposts, Name = "Ayuda Outposts"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DragonsStand_MapActive, Name = "mapa activo"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.CrystalOasis_CasinoBlitz, Name = "Carrera del casino"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DesertHighlands_Treasure, Name = "Tesoro Enterrado"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfVabbi_Serpent, Name = "Serpent's Ire"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TimberlineFalls_LeyLine, Name = "Anomalía de Línea Ley"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.IronMarches_LeyLine, Name = "Anomalía de Línea Ley"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.GendarranFields_LeyLine, Name = "Anomalía de Línea Ley"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Noran, Name = "Heredad de Noran"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Saidra, Name = "Refugio de Saidra"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Loamhurst, Name = "Nueva Loamhurst"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfIstan_Palawadan, Name = "Palawadan"
                },
                // TODO: Translate event name (It's google translated data now)
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.JahaiBluffs_DangerousPrey, Name = "Presa peligrosa"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Keep, Name = "Thunderhead Keep"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Oil, Name = "Las oleadas de aceite"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.EventEnds, Name = "Finaliza el evento"
                }
            };

            // French
            List <MetaEventStageName> french = new List <MetaEventStageName>()
            {
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_CrashSite, Name = "Site du crash"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_Sandstorm, Name = "Tempête de Sable"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_NightBosses, Name = "Boss de nuit"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Daytime, Name = "Jour"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Night, Name = "Nuit"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Challenges, Name = "Défis"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Octovine, Name = "Octoliane"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Reset, Name = "Reset"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Pylons, Name = "Pylones"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_Preparation, Name = "Préparation"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_ChakGerent, Name = "Régent Chak"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_HelpOutposts, Name = "Aider les campements"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DragonsStand_MapActive, Name = "Carte active"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.CrystalOasis_CasinoBlitz, Name = "Casino express"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DesertHighlands_Treasure, Name = "Trésor enfoui"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfVabbi_Serpent, Name = "Le courroux des serpents"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TimberlineFalls_LeyLine, Name = "Anomalie des lignes de force"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.IronMarches_LeyLine, Name = "Anomalie des lignes de force"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.GendarranFields_LeyLine, Name = "Anomalie des lignes de force"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Noran, Name = "Demeure de Noran"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Saidra, Name = "Refuge de Saidra"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Loamhurst, Name = "Sylveglèbe-la-neuve"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfIstan_Palawadan, Name = "Palawadan"
                },
                // TODO: Translate event name (It's google translated data now)
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.JahaiBluffs_DangerousPrey, Name = "Proie dangereuse"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Keep, Name = "Thunderhead Keep"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Oil, Name = "Les floes d'huile"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.EventEnds, Name = "fin de l'événement"
                }
            };

            // German
            List <MetaEventStageName> german = new List <MetaEventStageName>()
            {
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_CrashSite, Name = "Crash Site"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_Sandstorm, Name = "Sandsturm"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_NightBosses, Name = "Nacht Bosses"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Daytime, Name = "Tageszeit"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Night, Name = "Nacht"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Challenges, Name = "Herausforderungen"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Octovine, Name = "Octovine"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Reset, Name = "zurückstellen"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Pylons, Name = "pylons"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_Preparation, Name = "Vorbereitung"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_ChakGerent, Name = "Chak Gerent"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_HelpOutposts, Name = "Hilfe Outposts"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DragonsStand_MapActive, Name = "Karte Aktiv"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.CrystalOasis_CasinoBlitz, Name = "Kasino-Blitz"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DesertHighlands_Treasure, Name = "Vergrabene Schätze"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfVabbi_Serpent, Name = "Zorn der Schlangen"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TimberlineFalls_LeyLine, Name = "Ley-Linien-Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.IronMarches_LeyLine, Name = "Ley-Linien-Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.GendarranFields_LeyLine, Name = "Ley-Linien-Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Noran, Name = "Norans Heimstatt"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Saidra, Name = "Saidras Hafen"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Loamhurst, Name = "Neulehmwald"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfIstan_Palawadan, Name = "Palawadan"
                },
                // TODO: Translate event name (It's google translated data now)
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.JahaiBluffs_DangerousPrey, Name = "Gefährliche Beute"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Keep, Name = "Thunderhead Keep"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Oil, Name = "Die Ölschollen"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.EventEnds, Name = "Ereignis endet"
                }
            };

            // Korean
            List <MetaEventStageName> korean = new List <MetaEventStageName>()
            {
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TimberlineFalls_LeyLine, Name = "Ley-Line Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.IronMarches_LeyLine, Name = "Ley-Line Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.GendarranFields_LeyLine, Name = "Ley-Line Anomaly"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_CrashSite, Name = "Crash Site"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DryTop_Sandstorm, Name = "Sandstorm"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_NightBosses, Name = "Night Bosses"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Daytime, Name = "Daytime"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.VerdantBrink_Night, Name = "Night"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Challenges, Name = "Challenges"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Octovine, Name = "Octovine"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Reset, Name = "Reset"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.AuricBasin_Pylons, Name = "Pylons"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_Preparation, Name = "Preparation"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_ChakGerent, Name = "Chak Gerent"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.TangledDepths_HelpOutposts, Name = "Help Outposts"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DragonsStand_MapActive, Name = "Map Active"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Noran, Name = "Noran's Homestead"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Saidra, Name = "Saidra's Haven"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.LakeDoric_Loamhurst, Name = "New Loamhurst"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.CrystalOasis_CasinoBlitz, Name = "Casino Blitz"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DesertHighlands_Treasure, Name = "Buried Treasure"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfVabbi_Serpent, Name = "Serpent's Ire"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.DomainOfIstan_Palawadan, Name = "Palawadan"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.JahaiBluffs_DangerousPrey, Name = "Dangerous Prey"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Keep, Name = "Thunderhead Keep"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.ThunderheadPeaks_Oil, Name = "The Oil Floes"
                },
                new MetaEventStageName()
                {
                    ID = MetaEventStageID.EventEnds, Name = "이벤트 종료"
                }
            };

            Serialization.SerializeToXml(english, this.GetFilePath("en"));
            Serialization.SerializeToXml(spanish, this.GetFilePath("es"));
            Serialization.SerializeToXml(french, this.GetFilePath("fr"));
            Serialization.SerializeToXml(german, this.GetFilePath("de"));
            Serialization.SerializeToXml(korean, this.GetFilePath("ko"));
        }