public void WriteData(AMFWriter writer, object data)
        {
            NameObjectCollectionBase collection = data as NameObjectCollectionBase;
            object[] attributes = collection.GetType().GetCustomAttributes(typeof(DefaultMemberAttribute), false);
            if (attributes != null  && attributes.Length > 0)
            {
                DefaultMemberAttribute defaultMemberAttribute = attributes[0] as DefaultMemberAttribute;
                PropertyInfo pi = collection.GetType().GetProperty(defaultMemberAttribute.MemberName, new Type[] { typeof(string) });
                if (pi != null)
                {
                    ASObject aso = new ASObject();
                    for (int i = 0; i < collection.Keys.Count; i++)
                    {
                        string key = collection.Keys[i];
                        object value = pi.GetValue(collection, new object[]{ key });
                        aso.Add(key, value);
                    }
                    writer.WriteByte(AMF3TypeCode.Object);
                    writer.WriteAMF3Object(aso);
                    return;
                }
            }

            //We could not access an indexer so write out as it is.
            writer.WriteByte(AMF3TypeCode.Object);
            writer.WriteAMF3Object(data);
        }
예제 #2
0
파일: Plugin.cs 프로젝트: nbhopson/QMail
        private void onMailAudited(string sender, ime.notification.NotifyMessage e, NotificationCenter.Stage stage)
        {
            if (stage == NotificationCenter.Stage.Receiving)
            {
                Application.Current.Dispatcher.Invoke((System.Action)delegate
                {
                    if (!DBWorker.IsDBCreated())
                        return;
                    XElement xml = e.Body as XElement;
                    if (xml == null)
                        return;
                    XElement msgXml = xml.Element("message");
                    if (msgXml == null)
                        return;

                    ASObject mail = new ASObject();
                    mail["uuid"] = msgXml.AttributeValue("uuid");
                    mail["folder"] = "SENDED";
                    MailWorker.instance.updateMailRecord(mail, new string[] { "folder" });
                    MailWorker.instance.dispatchMailEvent(MailWorker.Event.Reset, null, null);
                    Application.Current.Dispatcher.Invoke((System.Action)delegate
                    {
                        e.Show();
                    }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
                }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
            }
        }
        /// <summary>
        /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code.
        /// </summary>
        /// <param name="invocationManager"></param>
        /// <param name="memberInfo"></param>
        /// <param name="obj"></param>
        /// <param name="arguments"></param>
        /// <param name="result"></param>
        public void HandleResult(IInvocationManager invocationManager, MemberInfo memberInfo, object obj, object[] arguments, object result)
		{
			if( result is DataSet )
			{
				DataSet dataSet = result as DataSet;
				ASObject asoResult = new ASObject(_remoteClass);

#if !(NET_1_1)
                foreach (KeyValuePair<object, object> entry in invocationManager.Properties)
#else
				foreach(DictionaryEntry entry in invocationManager.Properties)
#endif
				{
					if( entry.Key is DataTable )
					{
						DataTable dataTable = entry.Key as DataTable;
						if( dataSet.Tables.IndexOf(dataTable) != -1 )
						{
							if( !dataTable.ExtendedProperties.ContainsKey("alias") )
								asoResult[dataTable.TableName] = entry.Value;
							else
								asoResult[ dataTable.ExtendedProperties["alias"] as string ] = entry.Value;
						}
					}
				}
				invocationManager.Result = asoResult;
			}
		}
        public void WriteData(AMFWriter writer, object data)
        {
            var collection = data as NameObjectCollectionBase;
            var attributes = collection.GetType().GetCustomAttributes(typeof(DefaultMemberAttribute), false);
            if (attributes != null  && attributes.Length > 0)
            {
                var defaultMemberAttribute = attributes[0] as DefaultMemberAttribute;
                var pi = collection.GetType().GetProperty(defaultMemberAttribute.MemberName, new[] { typeof(string) });
                if (pi != null)
                {
                    var aso = new ASObject();
                    for (var i = 0; i < collection.Keys.Count; i++)
                    {
                        var key = collection.Keys[i];
                        var value = pi.GetValue(collection, new object[]{ key });
                        aso.Add(key, value);
                    }
                    writer.WriteASO(ObjectEncoding.AMF0, aso);
                    return;
                }
            }

            //We could not access an indexer so write out as it is.
            writer.WriteObject(ObjectEncoding.AMF0, data);
        }
예제 #5
0
		internal NetStatusEventArgs(string message) {
			_info = new ASObject();
			_info["level"] = "error";
			_info["code"] = StatusASO.NC_CALL_FAILED;
			//_info["description"] = message;
			_info["details"] = message;
		}
예제 #6
0
		/// <summary>
		/// Returns the capabilities of the ServiceBrowser as currently implemented. 
		/// Universal Remoting enabled projects may choose to implement all or some of the capabilities of the front-end.
		/// </summary>
		/// <returns>
		/// An array of objects. Each object should be in the format {name:String, version:Number, data:*}. 
		/// </returns>
		public ASObject getCapabilities()
		{
			string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
			ASObject result = new ASObject();
			// authentication: This Remoting implementation supports AMF0/AMF3 authentication
			ASObject asoAuthentication = new ASObject();
			asoAuthentication["name"] = "authentication";
			asoAuthentication["version"] = "FormsAuthentication";
			asoAuthentication["data"] = "true";
			result["authentication"] = asoAuthentication;
			// secure: The user of the service browser must authenticate him/herself with 
			// the unlock method before accessing it. 
			// The roles of all the methods except verifyLogin and getCapabilities should be set 
			// to admin.
			//ASObject secure = new ASObject();
			// codegen: This service browser supports code generation
			ASObject asoCodegen = new ASObject();
			asoCodegen["name"] = "codegen";
			asoCodegen["version"] = version;
			asoCodegen["data"] = CodeGeneratorService.GetCodeTemplates();//.ToArray(typeof(object)) as object[];
			result["codegen"] = asoCodegen;
			result["version"] = version;

			// codesave: This service browser supports code saving. 
			// data in this case may contain the enabled key. 
			// If enabled is set to false, indicates that the remote class has the remote code 
			// saving capability, but it is disabled because of a lack of permissions in the target directory.
			// if data is null, assume enabled is true.
			//ASObject codesave = new ASObject();

			return result;
		}
예제 #7
0
		public ASObject GetInformation()
		{
			ASObject info = new ASObject();
			info["name"] = "Fluorine .NET Flash Remoting Gateway";
			info["version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
			return info;
		}
예제 #8
0
		internal NetStatusEventArgs(Exception exception) {
			_exception = exception;
			_info = new ASObject();
			_info["level"] = "error";
			_info["code"] = StatusASO.NC_CALL_FAILED;
			//_info["description"] = exception.Message;
			_info["details"] = exception.Message;
		}
예제 #9
0
		internal NetStatusEventArgs(string code, Exception exception) {
			_exception = exception;
			_info = new ASObject();
			_info["level"] = "error";
			_info["code"] = code;
			//_info["description"] = exception.Message;
			_info["details"] = exception.Message;
		}
예제 #10
0
 public FluorineFx.ASObject ToRequestObject()
 {
     FluorineFx.ASObject retVal = new ASObject();
     retVal.Add("sigTime", _sigTime);
     retVal.Add("token", _token);
     retVal.Add("flashRevision", _flashRevision);
     retVal.Add("userId", _userId);
     return retVal;
 }
예제 #11
0
		public object ReadData(AMFReader reader, ClassDefinition classDefinition) {
			ASObject aso = new ASObject(_typeIdentifier);
			reader.AddAMF3ObjectReference(aso);
			string key = reader.ReadAMF3String();
			aso.TypeName = _typeIdentifier;
			while (key != string.Empty) {
				object value = reader.ReadAMF3Data();
				aso.Add(key, value);
				key = reader.ReadAMF3String();
			}
			return aso;
		}
예제 #12
0
		public override void Invoke(AMFContext context) {
			MessageBroker messageBroker = _endpoint.GetMessageBroker();
			try {
				AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.CredentialsHeader);
				if (amfHeader != null && amfHeader.Content != null) {
					string userId = ((ASObject)amfHeader.Content)["userid"] as string;
					string password = ((ASObject)amfHeader.Content)["password"] as string;
					//Clear credentials header, further requests will not send the credentials
					ASObject asoObject = new ASObject();
					asoObject["name"] = AMFHeader.CredentialsHeader;
					asoObject["mustUnderstand"] = false;
					asoObject["data"] = null;//clear
					AMFHeader header = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObject);
					context.MessageOutput.AddHeader(header);
					IPrincipal principal = _endpoint.GetMessageBroker().LoginManager.Login(userId, amfHeader.Content as IDictionary);
					string key = EncryptCredentials(_endpoint, principal, userId, password);
					ASObject asoObjectCredentialsId = new ASObject();
					asoObjectCredentialsId["name"] = AMFHeader.CredentialsIdHeader;
					asoObjectCredentialsId["mustUnderstand"] = false;
					asoObjectCredentialsId["data"] = key;//set
					AMFHeader headerCredentialsId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectCredentialsId);
					context.MessageOutput.AddHeader(headerCredentialsId);
				} else {
					amfHeader = context.AMFMessage.GetHeader(AMFHeader.CredentialsIdHeader);
					if (amfHeader != null) {
						string key = amfHeader.Content as string;
						if (key != null)
							_endpoint.GetMessageBroker().LoginManager.RestorePrincipal(key);
					} else {
						_endpoint.GetMessageBroker().LoginManager.RestorePrincipal();
					}
				}
			} catch (UnauthorizedAccessException exception) {
				for (int i = 0; i < context.AMFMessage.BodyCount; i++) {
					AMFBody amfBody = context.AMFMessage.GetBodyAt(i);
					ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception);
					context.MessageOutput.AddBody(errorResponseBody);
				}
			} catch (Exception exception) {
				if (log != null && log.IsErrorEnabled)
					log.Error(exception.Message, exception);
				for (int i = 0; i < context.AMFMessage.BodyCount; i++) {
					AMFBody amfBody = context.AMFMessage.GetBodyAt(i);
					ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception);
					context.MessageOutput.AddBody(errorResponseBody);
				}
			}
		}
예제 #13
0
 public object ParseQuery(string url, string sql)
 {
     ASObject aso = new ASObject();
     try
     {
         FluorineFx.ServiceBrowser.Sql.ISqlScript sqlScript = FluorineFx.ServiceBrowser.Sql.SqlParserService.Parse(sql);
         aso["message"] = "Sql statement was parsed and found to be a valid";
     }
     catch (antlr.RecognitionException ex)
     {
         aso["message"] = "The specified SQL statement failed to be parsed: " + ex.ToString();
     }
     catch (Exception ex)
     {
         aso["message"] = "The specified SQL statement failed to be parsed: " + ex.Message;
     }
     return aso;
 }
예제 #14
0
 public GGChatUser(ASObject user)
 {
     try
     {
         if( user.ContainsKey("banned") )
             _banned = bool.Parse(user["banned"].ToString());
         if (user.ContainsKey("color"))
             _color = (string)user["color"];
         if (user.ContainsKey("id"))
             _id = int.Parse(user["id"].ToString());
         if (user.ContainsKey("level"))
             _level = int.Parse(user["level"].ToString());
         if (user.ContainsKey("name"))
             _name = (string)user["name"];
         if (user.ContainsKey("sex"))
             _gender = int.Parse(user["sex"].ToString());
     }
     catch { }
 }
예제 #15
0
        public MessageClient AddSubscriber(string clientId, string endpointId, Subtopic subtopic, Selector selector)
		{
			lock(_objLock)
			{
                if (subtopic != null)
                {
                    MessagingAdapter messagingAdapter = _messageDestination.ServiceAdapter as MessagingAdapter;
                    if (messagingAdapter != null)
                    {
                        if (!messagingAdapter.AllowSubscribe(subtopic))
                        {
                            ASObject aso = new ASObject();
                            aso["subtopic"] = subtopic.Value;
                            throw new MessageException(aso);
                        }
                    }
                }
                if (!_subscribers.Contains(clientId))
                {
                    //Set in RtmpService
                    MessageClient messageClient = new MessageClient(clientId, _messageDestination, endpointId);
                    messageClient.Subtopic = subtopic;
                    messageClient.Selector = selector;
                    messageClient.AddSubscription(selector, subtopic);
                    AddSubscriber(messageClient);
                    messageClient.NotifyCreatedListeners();
                    return messageClient;
                }
                else
                {
                    MessageClient messageClient = _subscribers[clientId] as MessageClient;
                    IClient client = FluorineContext.Current.Client;
                    if (client != null && !client.Id.Equals(messageClient.Client.Id))
                    {
                        throw new MessageException("Duplicate subscriptions from multiple Flex Clients");
                    }
                    //Reset the endpoint push state for the subscription to make sure its current because a resubscribe could be arriving over a new endpoint or a new session.
                    messageClient.ResetEndpoint(endpointId);
                    return messageClient;
                }
			}
		}
예제 #16
0
        protected SyncWorker()
        {
            sql.Clear();
            sql.Append("select * from ML_Mail where is_synced=@is_synced or is_synced=@is_synced1");

            using (DataSet ds = new DataSet())
            {
                try
                {
                    using (SQLiteCommand cmd = new SQLiteCommand(sql.ToString(), DBWorker.GetConnection()))
                    {
                        cmd.Parameters.AddWithValue("@is_synced", 1);
                        cmd.Parameters.AddWithValue("@is_synced1", 0);
                        using (SQLiteDataAdapter q = new SQLiteDataAdapter(cmd))
                        {
                            q.Fill(ds);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.Write(ex.StackTrace);
                }
                if (ds.Tables.Count > 0)
                {
                    using (DataTable dt = ds.Tables[0])
                    {
                        foreach (DataRow row in dt.Rows)
                        {
                            ASObject mail = new ASObject();
                            foreach (DataColumn column in dt.Columns)
                            {
                                mail[column.ColumnName] = row[column];
                            }
                            mailList.Add(mail);
                        }
                    }
                }
            }
        }
예제 #17
0
        public object SubmitQuery(string url, string sql)
        {
            Hashtable result = new Hashtable();
            try
            {
                DomainUrl domainUrl = new DomainUrl(url);
                Driver driver = DriverFactory.GetDriver(domainUrl);
                using (IDbConnection dbConnection = driver.OpenConnection())
                {
                    IDbCommand command = driver.GetDbCommand(sql, dbConnection);
                    IDbDataAdapter adapter = driver.GetDbDataAdapter();
                    adapter.SelectCommand = command;
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet);

                    ASObject asoResult = new ASObject();
                    DataTable dataTable = dataSet.Tables[0];
                    ArrayList rows = new ArrayList(dataTable.Rows.Count);
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        DataRow dataRow = dataTable.Rows[i];
                        ASObject asoRow = new ASObject();
                        for (int j = 0; j < dataTable.Columns.Count; j++)
                        {
                            DataColumn column = dataTable.Columns[j];
                            asoRow.Add(column.ColumnName, dataRow[column]);
                        }
                        rows.Add(asoRow);
                    }
                    result["result"] = rows;
                }
            }
            catch (Exception ex)
            {
                result["message"] = ex.Message;
            }
            return result;
        }
		public PlayerStatCategory(ASObject thebase)
			: base(thebase)
        {
            BaseObject.SetFields(this, Base);
        }
예제 #19
0
 public AllSummonerData(ASObject obj)
     : base(obj)
 {
     BaseObject.SetFields(this, obj);
 }
예제 #20
0
 /// <summary> 解锁</summary>
 public ASObject CommandStart(TGGSession session, ASObject data)
 {
     return((new Consume.War.WAR_SKYCITY_UNLOCK()).Execute(session.Player.User.id, data));
 }
예제 #21
0
        /// <summary>跑商消耗</summary>
        private ASObject CS_BUSINESS(int cmd, TGGSession session, ASObject data)
        {
            if (!CommonHelper.IsOpen(session.Player.Role.Kind.role_level, (int)OpenModelType.跑商))
            {
                return(CommonHelper.ErrorResult(ResultType.BASE_PLAYER_LEVEL_ERROR));
            }
            var aso     = new ASObject();
            var blldata = data.FirstOrDefault(q => q.Key == "data").Value as ASObject;

            switch (cmd)
            {
            case (int)BusinessCommand.BUSINESS_ACCELERATE:
            {
                aso = (new BUSINESS_ACCELERATE()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_PRICE_INFO:
            {
                aso = (new BUSINESS_PRICE_INFO()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_PACKET_BUY:
            {
                aso = (new BUSINESS_PACKET_BUY()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_GOODS_BUY:
            {
                aso = (new BUSINESS_GOODS_BUY()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_BUY_CAR:
            {
                aso = (new BUSINESS_BUY_CAR()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_GOODS_ADD:
            {
                aso = (new BUSINESS_GOODS_ADD()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_BUY_BARGAIN:
            {
                aso = (new BUSINESS_BUY_BARGAIN()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_AREA_OPEN:
            {
                aso = (new BUSINESS_AREA_OPEN()).Execute(session.Player.User.id, blldata);
                break;
            }

            case (int)BusinessCommand.BUSINESS_FREE_TAX:
            {
                aso = (new BUSINESS_FREE_TAX()).Execute(session.Player.User.id, blldata);
                break;
            }
            }
            return(aso);
        }
예제 #22
0
 public AggregatedStats(ASObject obj)
     : base(obj)
 {
     BaseObject.SetFields(this, obj);
 }
예제 #23
0
        public override void Invoke(AMFContext context)
        {
            MessageOutput messageOutput = context.MessageOutput;

            for (int i = 0; i < context.AMFMessage.BodyCount; i++)
            {
                AMFBody amfBody = context.AMFMessage.GetBodyAt(i);
                //Check for Flex2 messages
                if (amfBody.IsEmptyTarget)
                {
                    object content = amfBody.Content;
                    if (content is IList)
                    {
                        content = (content as IList)[0];
                    }
                    IMessage message = content as IMessage;
                    if (message != null)
                    {
                        Client      client  = null;
                        HttpSession session = null;
                        if (FluorineContext.Current.Client == null)
                        {
                            IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry;
                            string          clientId       = message.GetFlexClientId();
                            if (!clientRegistry.HasClient(clientId))
                            {
                                lock (clientRegistry.SyncRoot)
                                {
                                    if (!clientRegistry.HasClient(clientId))
                                    {
                                        client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                                    }
                                }
                            }
                            if (client == null)
                            {
                                client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                            }
                            FluorineContext.Current.SetClient(client);
                        }
                        session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current);
                        FluorineContext.Current.SetSession(session);
                        //Context initialized, notify listeners.
                        if (session != null && session.IsNew)
                        {
                            session.NotifyCreated();
                        }
                        if (client != null)
                        {
                            if (session != null)
                            {
                                client.RegisterSession(session);
                            }
                            if (client.IsNew)
                            {
                                client.Renew(_endpoint.ClientLeaseTime);
                                client.NotifyCreated();
                            }
                        }

                        /*
                         * RemotingConnection remotingConnection = null;
                         * foreach (IConnection connection in client.Connections)
                         * {
                         *  if (connection is RemotingConnection)
                         *  {
                         *      remotingConnection = connection as RemotingConnection;
                         *      break;
                         *  }
                         * }
                         * if (remotingConnection == null)
                         * {
                         *  remotingConnection = new RemotingConnection(_endpoint, null, client.Id, null);
                         *  remotingConnection.Initialize(client, session);
                         * }
                         * FluorineContext.Current.SetConnection(remotingConnection);
                         */
                    }
                }
                else
                {
                    //Flash remoting
                    AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.AMFDSIdHeader);
                    string    amfDSId   = null;
                    if (amfHeader == null)
                    {
                        amfDSId = Guid.NewGuid().ToString("D");
                        ASObject asoObjectDSId = new ASObject();
                        asoObjectDSId["name"]           = AMFHeader.AMFDSIdHeader;
                        asoObjectDSId["mustUnderstand"] = false;
                        asoObjectDSId["data"]           = amfDSId;//set
                        AMFHeader headerDSId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectDSId);
                        context.MessageOutput.AddHeader(headerDSId);
                    }
                    else
                    {
                        amfDSId = amfHeader.Content as string;
                    }

                    Client      client  = null;
                    HttpSession session = null;
                    if (FluorineContext.Current.Client == null)
                    {
                        IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry;
                        string          clientId       = amfDSId;
                        if (!clientRegistry.HasClient(clientId))
                        {
                            lock (clientRegistry.SyncRoot)
                            {
                                if (!clientRegistry.HasClient(clientId))
                                {
                                    client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                                }
                            }
                        }
                        if (client == null)
                        {
                            client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
                        }
                    }
                    FluorineContext.Current.SetClient(client);
                    session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current);
                    FluorineContext.Current.SetSession(session);
                    //Context initialized, notify listeners.
                    if (session != null && session.IsNew)
                    {
                        session.NotifyCreated();
                    }
                    if (client != null)
                    {
                        if (session != null)
                        {
                            client.RegisterSession(session);
                        }
                        if (client.IsNew)
                        {
                            client.Renew(_endpoint.ClientLeaseTime);
                            client.NotifyCreated();
                        }
                    }
                }
            }
        }
예제 #24
0
 /// <summary>指令处理</summary>
 public ASObject Switch(int commandNumber, TGGSession session, ASObject data)
 {
     return(Switch((int)ModuleNumber.FAMILY, commandNumber, session, data));
 }
 public PlayerStatsSummary(ASObject body)
     : base(body)
 {
     BaseObject.SetFields(this, body);
 }
예제 #26
0
    public static MeshData exportMeshData(Mesh mesh, GameObject gameObject)
    {
        MeshData data = new MeshData();

        /*pos*/
        Vector3[] vectors = formatVertices(mesh.vertices, TransformToMatrix4x4(gameObject.transform));
        /*normal*/
        Vector3[] normals = mesh.normals;
        /*uv*/
        Vector2[] uvs      = mesh.uv;
        Vector4[] tangnets = mesh.tangents;
        Color[]   colors   = mesh.colors;

        data.vertex = vector3toByte(vectors, normals, uvs, tangnets, colors);

        int numVertices = vectors.Length;

        data.numVertices = numVertices;


        int offset = 0;



        ASObject variables = new ASObject();

        if (null != vectors && numVertices == vectors.Length)
        {
            variables.Add("pos", new Variable(3, offset));
            offset += 3;
        }

        if (null != normals && numVertices == normals.Length)
        {
            variables.Add("normal", new Variable(3, offset));
            offset += 3;
        }

        // if(null != tangnets && 0 != tangnets.Length){
        //     variables.Add("tangnet",new Variable(4,offset));
        //     offset += 4;
        // }

        if (null != uvs && numVertices == uvs.Length)
        {
            variables.Add("uv", new Variable(2, offset));
            offset += 2;
        }


        if (null != colors && numVertices == colors.Length)
        {
            variables.Add("color", new Variable(4, offset));
            offset += 4;
        }

        variables.Add("data32PerVertex", new Variable(offset, offset));

        data.data32PerVertex = offset;
        data.variables       = variables;



        data.index = ToUnit16(mesh.triangles);

        data.numTriangles = mesh.triangles.Length / 3;


        data.hitare = toHitArea(mesh.bounds);


        return(data);
    }
예제 #27
0
 public PublicSummoner(ASObject obj)
     : base(obj)
 {
     BaseObject.SetFields(this, obj);
 }
예제 #28
0
        /// <summary>武将修行模块</summary>
        private ASObject CS_ROLETRAIN(int cmd, TGGSession session, ASObject data)
        {
            switch (cmd)
            {
            case (int)RoleTrainCommand.TRAIN_HOME_NPC_REFRESH:
                if (!CommonHelper.IsOpen(session.Player.Role.Kind.role_level, (int)OpenModelType.自宅))
                {
                    return(CommonHelper.ErrorResult(ResultType.BASE_PLAYER_LEVEL_ERROR));
                }
                break;

            case (int)RoleTrainCommand.TRAIN_ROLE_START:
            case (int)RoleTrainCommand.TRAIN_ROLE_ACCELERATE:
            case (int)RoleTrainCommand.TRAIN_ROLE_LOCK:
                if (!CommonHelper.IsOpen(session.Player.Role.Kind.role_level, (int)OpenModelType.修行))
                {
                    return(CommonHelper.ErrorResult(ResultType.BASE_PLAYER_LEVEL_ERROR));
                }
                break;

            default:
                if (!CommonHelper.IsOpen(session.Player.Role.Kind.role_level, (int)OpenModelType.武将宅))
                {
                    return(CommonHelper.ErrorResult(ResultType.BASE_PLAYER_LEVEL_ERROR));
                }
                break;
            }
            var aso     = new ASObject();
            var blldata = data.FirstOrDefault(q => q.Key == "data").Value as ASObject;

            switch (cmd)
            {
            case (int)RoleTrainCommand.TRAIN_ROLE_START:
            {
                aso = (new TRAIN_ROLE_START()).Execute(session.Player.User.id, blldata); break;
            }

            case (int)RoleTrainCommand.TRAIN_ROLE_ACCELERATE:
            {
                aso = (new TRAIN_ROLE_ACCELERATE()).Execute(session.Player.User.id, blldata); break;
            }

            case (int)RoleTrainCommand.TRAIN_ROLE_LOCK:
            {
                aso = (new TRAIN_ROLE_LOCK()).Execute(session.Player.User.id, blldata); break;
            }

            case (int)RoleTrainCommand.TRAIN_HOME_NPC_REFRESH:
            {
                aso = (new TRAIN_HOME_NPC_REFRESH()).Execute(session.Player.User.id, blldata); break;
            }

            case (int)RoleTrainCommand.TRAIN_TEA_INSIGHT:
            {
                aso = (new TRAIN_TEA_INSIGHT()).Execute(session.Player.User.id, blldata); break;
            }

            case (int)RoleTrainCommand.TRAIN_HOME_FIGHT_BUY:
            {
                aso = (new TRAIN_HOME_FIGHT_BUY()).Execute(session.Player.User.id, blldata); break;
            }
            }
            return(aso);
        }
예제 #29
0
        /// <summary>消费</summary>
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
#if DEBUG
            XTrace.WriteLine("{0}:{1}", "CONSUME", "消费");
#endif
            #region 参数说明
            //goodsType:int GoodsType 物品类型
            //module:int ModuleNumber 模块号
            //cmd:int 命令号
            //data:Object 业务数据
            #endregion

            var module = int.Parse(data.FirstOrDefault(q => q.Key == "module").Value.ToString());
            var cmd    = int.Parse(data.FirstOrDefault(q => q.Key == "cmd").Value.ToString());

            var bll_data = new ASObject();
            switch (module)
            {
                #region 模块
            case (int)ModuleNumber.BUSINESS:
            {
                bll_data = CS_BUSINESS(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.BAG:
            {
                bll_data = CS_Prop(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.ROLE:
            {
                bll_data = CS_ROLE(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.EQUIP:
            {
                bll_data = CS_EQUIP(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.TASK:
            {
                bll_data = CS_TASK(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.ROLETRAIN:
            {
                bll_data = CS_ROLETRAIN(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.FAMILY:
            {
                bll_data = CS_FAMILY(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.ARENA:
            {
                bll_data = CS_ARENA(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.APPRAISE:
            {
                bll_data = CS_APPRAISE(cmd, session, data);
                break;
            }

            case (int)ModuleNumber.PRISON:
            {
                bll_data = CS_PRISON(cmd, session, data);
                break;
            }
                #endregion
            }
            return(new ASObject(Common.GetInstance().BuildData(session.Player, module, cmd, bll_data)));
        }
예제 #30
0
        public async Task <IActionResult> DoBadgeToken([FromBody] BadgeTokenModel model)
        {
            var user = await _userManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                user = new APUser {
                    UserName = model.Username, Email = model.Username + "@badge.local"
                };
                await _userManager.CreateAsync(user, model.Password);

                var uobj = model.Username;
                var name = model.Username;

                var obj = new ASObject();
                obj["type"].Add(new ASTerm("Person"));
                obj["preferredUsername"].Add(new ASTerm(name));
                obj["name"].Add(new ASTerm(name));

                var id = await _entityData.UriFor(_entityStore, obj);

                obj["id"].Add(new ASTerm(id));

                var inbox = await _newCollection("inbox", id);

                var outbox = await _newCollection("outbox", id);

                var following = await _newCollection("following", id);

                var followers = await _newCollection("followers", id);

                var likes = await _newCollection("likes", id);

                var blocks = await _newCollection("blocks", id);

                var blocked = await _newCollection("blocked", id);

                var blocksData = blocks.Data;
                blocksData["_blocked"].Add(new ASTerm(blocked.Id));
                blocks.Data = blocksData;

                obj["following"].Add(new ASTerm(following.Id));
                obj["followers"].Add(new ASTerm(followers.Id));
                obj["blocks"].Add(new ASTerm(blocks.Id));
                obj["likes"].Add(new ASTerm(likes.Id));
                obj["inbox"].Add(new ASTerm(inbox.Id));
                obj["outbox"].Add(new ASTerm(outbox.Id));

                var userEntity = await _entityStore.StoreEntity(APEntity.From(obj, true));

                await _entityStore.CommitChanges();

                _context.UserActorPermissions.Add(new UserActorPermission {
                    UserId = user.Id, ActorId = userEntity.Id, IsAdmin = true
                });
                await _context.SaveChangesAsync();
            }
            var u = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false);

            if (!u.Succeeded)
            {
                return(Unauthorized());
            }

            var firstActor = await _context.UserActorPermissions.FirstOrDefaultAsync(a => a.User == user);

            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                new Claim(JwtTokenSettings.ActorClaim, firstActor.ActorId)
            };

            var jwt = new JwtSecurityToken(
                issuer: _tokenSettings.Issuer,
                audience: _tokenSettings.Audience,
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.Add(TimeSpan.FromDays(7)),
                signingCredentials: _tokenSettings.Credentials
                );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(Json(new BadgeTokenResponse {
                Actor = firstActor.ActorId, Token = encodedJwt
            }));
        }
예제 #31
0
        /// <summary>切换场景</summary>
        public ASObject CommandStart(SocketServer.TGGSession session, ASObject data)
        {
#if DEBUG
            XTrace.WriteLine("{0}:{1} - {2}", "ENTER_SCENE", "切换场景", session.Player.User.player_name);
#endif
            var result    = (int)ResultType.SUCCESS;
            var sceneid   = Convert.ToInt32(data.FirstOrDefault(m => m.Key == "id").Value);
            var userid    = session.Player.User.id;
            var userscene = session.Player.Scene;
#if DEBUG
            XTrace.WriteLine("玩家{0}当前场景---{1}\t", session.Player.User.player_name, userscene.scene_id);
            XTrace.WriteLine("玩家{0}当前坐标---{1},{2}\t", session.Player.User.player_name, userscene.X, userscene.Y);
#endif
            var basescene = Variable.BASE_SCENE.FirstOrDefault(q => q.id == sceneid);
            if (basescene == null || userscene == null)
            {
                return(BuildData((int)ResultType.SCENE_BASEDATA_WRONG, null));
            }
            if (userscene.scene_id == sceneid)
            {
                return(BuildData((int)ResultType.SCENE_ENTER_SAME, null));
            }
            //1.表示开启 0表示未开启
            if (basescene.enabled == 0)
            {
                return(BuildData((int)ResultType.SCENE_CITY_UNOPEN, null));
            }
            var basebornpoint = Variable.BASE_ROLEBORNPOINT.FirstOrDefault(q => q.id == basescene.bornPoint);
            if (basebornpoint == null)
            {
                return(BuildData((int)ResultType.SCENE_BASEDATA_WRONG, null));
            }

            var otherplays = Core.Common.Scene.GetOtherPlayers(userid, userscene.scene_id, (int)ModuleNumber.SCENE); //同场景内的其他玩家
            //推送玩家离开场景信息
            foreach (var item in otherplays)                                                                         //调用推送
            {
#if DEBUG
                XTrace.WriteLine("向{0}玩家推送{1}离开场景---{2}\t\n", item.player_name, session.Player.User.player_name, userscene.scene_id);
#endif
                var tokenTest = new CancellationTokenSource();
                var temp      = new Common.ScenePush()
                {
                    user_id       = userid,
                    other_user_id = item.user_id
                };
                Task.Factory.StartNew(m =>
                {
                    var t = m as Common.ScenePush;
                    if (t == null)
                    {
                        return;
                    }
                    new PLAYER_EXIT_SCENET().CommandStart(t.user_id, t.other_user_id);
                    tokenTest.Cancel();
                }, temp, tokenTest.Token);
            }
            SceneDataSave(sceneid, userscene, session.Player.Scene, basebornpoint);
            var newotherplays = Core.Common.Scene.GetOtherPlayers(userid, userscene.scene_id, (int)ModuleNumber.SCENE); //同场景内的其他玩家

            foreach (var item in newotherplays)                                                                         //向新场景玩家推送玩家进入
            {
#if DEBUG
                XTrace.WriteLine("玩家{0}当前坐标---{1},{2}\t", session.Player.User.player_name, userscene.X, userscene.Y);
                XTrace.WriteLine("向{0}玩家推送{1}进入当前场景---{2}\t", item.player_name, session.Player.User.player_name, userscene.scene_id);
#endif
                var tokenTest = new CancellationTokenSource();
                var temp      = new Common.ScenePush()
                {
                    user_id       = userid,
                    other_user_id = item.user_id,
                    user_scene    = userscene
                };
                Task.Factory.StartNew(m =>
                {
                    var t = m as Common.ScenePush;
                    if (t == null)
                    {
                        return;
                    }
                    new PLAYER_ENTER_SCENE().CommandStart(t.user_scene, t.user_id, t.other_user_id);
                    tokenTest.Cancel();
                }, temp, tokenTest.Token);
            }
            return(BuildData(result, newotherplays));
        }
예제 #32
0
 /// <summary>开启格子</summary>
 public ASObject CommandStart(TGGSession session, ASObject data)
 {
     return((new Consume.PROP_OPEN_GRID()).Execute(session.Player.User.id, data));
 }
예제 #33
0
        /// <summary> 据点规模提升 </summary>
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
            if (!data.ContainsKey("id"))
            {
                return(CommonHelper.ErrorResult(ResultType.FRONT_DATA_ERROR));
            }
            var id     = Convert.ToInt32(data.FirstOrDefault(m => m.Key == "id").Value); //id:[double] 据点基表id
            var userid = session.Player.User.id;
            var off    = session.Player.User.office;
            var extend = session.Player.UserExtend;

            var city = (new Share.War()).GetWarCity(id, userid);//tg_war_city.GetEntityByBaseId(id);

            if (city == null)
            {
                return(CommonHelper.ErrorResult(ResultType.NO_DATA));
            }
            if (city.size >= 5)
            {
                return(CommonHelper.ErrorResult(ResultType.WAR_SIZE_MAX));
            }

            var size       = city.size + 1;
            var basesize   = Variable.BASE_WARCITYSIZE.FirstOrDefault(m => m.id == size);
            var baseoffice = Variable.BASE_OFFICE.FirstOrDefault(m => m.id == off);

            if (basesize == null || baseoffice == null)
            {
                return(CommonHelper.ErrorResult(ResultType.BASE_TABLE_ERROR));
            }
            var count = extend.war_total_own + basesize.own - city.own;

            if (count > baseoffice.total_own)
            {
                return(CommonHelper.ErrorResult(ResultType.WAR_NOT_OWN));
            }

            if (basesize.boom > city.boom)
            {
                return(CommonHelper.ErrorResult(ResultType.WAR_BOOM_DEFICIENCY));
            }
            if (basesize.strong > city.strong)
            {
                return(CommonHelper.ErrorResult(ResultType.WAR_STRONG_DEFICIENCY));
            }
            if (basesize.peace > city.peace)
            {
                return(CommonHelper.ErrorResult(ResultType.WAR_PEACE_DEFICIENCY));
            }

            city.size            = size;
            city.own             = basesize.own;
            extend.war_total_own = count;
            city.Update();
            extend.Update();
            session.Player.UserExtend = extend;
            (new Share.War()).SaveWarCityAll(city);

            var temp = view_war_city.GetEntityById(city.id);

            (new Share.War()).SendCityBuild(temp);
            return(Common.GetInstance().BulidData(temp, (int)WarCityCampType.OWN));
        }
예제 #34
0
        /// <summary> 推送协议 </summary>
        /// <param name="session">session</param>
        /// <param name="aso">aso</param>
        public void SendProtocol(TGGSession session, ASObject aso)
        {
            var pv = session.InitProtocol((int)ModuleNumber.FIGHT, (int)FightCommand.FIGHT_PERSONAL_JOIN, (int)ResponseType.TYPE_SUCCESS, aso);

            session.SendData(pv);
        }
예제 #35
0
        /// <summary> 推送玩家离开家族</summary>
        public void CommandStart(TGGSession session)
        {
            ASObject aso = BuildData();

            LogPush(session, aso);
        }
예제 #36
0
        /// <summary>指令处理</summary>
        public ASObject Switch(int moduleNumber, int commandNumber, TGGSession session, ASObject data)
        {
            if (commandNumber != (int)TaskCommand.TASK_UPDATE || moduleNumber != (int)ModuleNumber.TASKUPDATE)
            {
                return(null);
            }
            var aso  = new ASObject();
            var task = new Task_Update();

            aso = task.CommandStart(session, data);
            task.Dispose();
            return(aso);
        }
예제 #37
0
        public bool Logout()
        {
            bool result = false;

            if (_loginCommand != null)
            {
                result = _loginCommand.Logout(this.Principal);
                if (this.IsPerClientAuthentication)
                {
                    if (FluorineContext.Current.Client != null)
                    {
                        FluorineContext.Current.Client.Principal = null;
                    }
                }
                else
                {
                    if (FluorineContext.Current.Session != null)
                    {
                        FluorineContext.Current.Session.Invalidate();
                    }
                }
            }
            else
            {
                if (FluorineContext.Current.Session != null)
                {
                    FluorineContext.Current.Session.Invalidate();
                }

                if (log.IsErrorEnabled)
                {
                    log.Error(__Res.GetString(__Res.Security_LoginMissing));
                }
                //FluorineFx.Messaging.SecurityException se = new FluorineFx.Messaging.SecurityException(NoLoginCommand, FluorineFx.Messaging.SecurityException.ServerAuthorizationCode);
                //throw se;
                throw new UnauthorizedAccessException(__Res.GetString(__Res.Security_LoginMissing));
            }
            if (HttpContext.Current != null)
            {
                /*
                 * HttpCookie authCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthCookieName);
                 * if (authCookie != null)
                 * {
                 *  FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                 *  if (ticket != null && ticket.UserData != null && ticket.UserData.StartsWith(FluorineContext.FluorineTicket))
                 *  {
                 *      HttpRuntime.Cache.Remove(ticket.UserData);
                 *  }
                 * }
                 */
                FormsAuthentication.SignOut();
            }
            if (AMFContext.Current != null)
            {
                AMFContext amfContext = AMFContext.Current;
                AMFHeader  amfHeader  = amfContext.AMFMessage.GetHeader(AMFHeader.CredentialsIdHeader);
                if (amfHeader != null)
                {
                    amfContext.AMFMessage.RemoveHeader(AMFHeader.CredentialsIdHeader);
                    ASObject asoObjectCredentialsId = new ASObject();
                    asoObjectCredentialsId["name"]           = AMFHeader.CredentialsIdHeader;
                    asoObjectCredentialsId["mustUnderstand"] = false;
                    asoObjectCredentialsId["data"]           = null;//clear
                    AMFHeader headerCredentialsId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectCredentialsId);
                    amfContext.MessageOutput.AddHeader(headerCredentialsId);
                }
            }
            return(result);
        }
예제 #38
0
 public void onRemotingException(string callUID, string methodName, string message, string code, ASObject exception, AsyncOption option)
 {
     System.Diagnostics.Debug.WriteLine(message);
 }
예제 #39
0
 public MessageObject(ASObject obj)
     : base(obj)
 {
     BaseObject.SetFields(this, obj);
 }
예제 #40
0
        public void saveMailRecord(ASObject record, string entityName = "ML_Mail")
        {
            string sql = @"INSERT INTO " + entityName + @" (
                                uuid,
                                owner_user_id,
                                message_id,
                                subject,
                                sender,
                                mail_to,
                                reply_to,
                                mail_from,
                                contact_mail,
                                flags,
                                cc,
                                bcc,
                                attachments,
                                contents,
                                text_body,
                                html_body,
                                create_time,
                                send_time,
                                mail_date,
                                mail_type,
                                mail_account,
                                mail_file,
                                reply_for,
                                reply_header,
                                folder,
                                mail_uid,
                                client_or_server,
                                is_synced,
                                mail_from_label,
                                mail_to_label,
                                priority,
                                is_seen,
                                ip_from,
                                reviewer_id,
                                reviewer_name,
                                operator_id,
                                operator_name
                            )
                            VALUES (
                                @uuid,
                                @owner_user_id,
                                @message_id,
                                @subject,
                                @sender,
                                @mail_to,
                                @reply_to,
                                @mail_from,
                                @contact_mail,
                                @flags,
                                @cc,
                                @bcc,
                                @attachments,
                                @contents,
                                @text_body,
                                @html_body,
                                @create_time,
                                @send_time,
                                @mail_date,
                                @mail_type,
                                @mail_account,
                                @mail_file,
                                @reply_for,
                                @reply_header,
                                @folder,
                                @mail_uid,
                                @client_or_server,
                                @is_synced,
                                @mail_from_label,
                                @mail_to_label,
                                @priority,
                                @is_seen,
                                @ip_from,
                                @reviewer_id,
                                @reviewer_name,
                                @operator_id,
                                @operator_name
                            )";
            SQLiteCommand cmd = null;
            try
            {
                cmd = new SQLiteCommand(sql, DBWorker.GetConnection());

                cmd.Parameters.AddWithValue("@uuid", record["uuid"]);
                cmd.Parameters.AddWithValue("@owner_user_id", record["owner_user_id"]);
                cmd.Parameters.AddWithValue("@message_id", record["message_id"]);
                cmd.Parameters.AddWithValue("@subject", record["subject"]);
                cmd.Parameters.AddWithValue("@sender", record["sender"]);
                cmd.Parameters.AddWithValue("@mail_to", record["mail_to"]);
                cmd.Parameters.AddWithValue("@mail_to_label", record["mail_to_label"]);
                cmd.Parameters.AddWithValue("@reply_to", record["reply_to"]);
                cmd.Parameters.AddWithValue("@mail_from", record["mail_from"]);
                cmd.Parameters.AddWithValue("@mail_from_label", record["mail_from_label"]);
                cmd.Parameters.AddWithValue("@contact_mail", record["contact_mail"]);
                cmd.Parameters.AddWithValue("@flags", record["flags"]);
                cmd.Parameters.AddWithValue("@cc", record["cc"]);
                cmd.Parameters.AddWithValue("@bcc", record["bcc"]);
                cmd.Parameters.AddWithValue("@attachments", record["attachments"]);
                cmd.Parameters.AddWithValue("@contents", record["contents"]);
                cmd.Parameters.AddWithValue("@text_body", record["text_body"]);
                cmd.Parameters.AddWithValue("@html_body", record["html_body"]);
                cmd.Parameters.AddWithValue("@create_time", record["create_time"]);
                cmd.Parameters.AddWithValue("@mail_date", record["mail_date"]);
                cmd.Parameters.AddWithValue("@send_time", record["send_time"]);
                cmd.Parameters.AddWithValue("@mail_type", record["mail_type"]);
                cmd.Parameters.AddWithValue("@mail_account", record["mail_account"]);
                cmd.Parameters.AddWithValue("@mail_file", record["mail_file"]);
                cmd.Parameters.AddWithValue("@reply_for", record["reply_for"]);
                cmd.Parameters.AddWithValue("@reply_header", record["reply_header"]);
                cmd.Parameters.AddWithValue("@folder", record["folder"]);
                cmd.Parameters.AddWithValue("@mail_uid", record["mail_uid"]);
                cmd.Parameters.AddWithValue("@client_or_server", record["client_or_server"]);
                cmd.Parameters.AddWithValue("@is_synced", record["is_synced"]);
                cmd.Parameters.AddWithValue("@is_seen", record["is_seen"]);
                cmd.Parameters.AddWithValue("@ip_from", record["ip_from"]);
                cmd.Parameters.AddWithValue("@priority", record["priority"]);
                cmd.Parameters.AddWithValue("@reviewer_id", record["reviewer_id"]);
                cmd.Parameters.AddWithValue("@reviewer_name", record["reviewer_name"]);
                cmd.Parameters.AddWithValue("@operator_id", record["operator_id"]);
                cmd.Parameters.AddWithValue("@operator_name", record["operator_name"]);

                cmd.ExecuteNonQuery();

                cmd.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.StackTrace);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
            }
        }
 public PlayerStatSummaries(ASObject obj)
     : base(obj)
 {
     PlayerStatSummarySet = new PlayerStatSummaryList();
     BaseObject.SetFields(this, obj);
 }
예제 #42
0
 /// <summary>
 /// 与服务器同步邮件信息
 /// </summary>
 /// <param name="record"></param>
 public void syncUserMail(ASObject record)
 {
     if (record == null)
         return;
     AsyncOption option = new AsyncOption("MailManager.syncUserMail");
     option.asyncData = record;
     option.showWaitingBox = false;
     Remoting.call("MailManager.syncUserMail", new object[] { record }, this, option);
 }
예제 #43
0
 public BaseObject(ASObject obj)
 {
     Base = obj;
 }
예제 #44
0
        /// <summary>
        /// 更新邮件记录
        /// </summary>
        /// <param name="mail"></param>
        /// <param name="updateFields"></param>
        public void updateMailRecord(ASObject mail, string[] updateFields)
        {
            if (mail == null || updateFields == null || updateFields.Length == 0)
                return;
            string sql = @"update ML_Mail set ";
            StringBuilder sb = new StringBuilder();
            sb.Append(sql);
            foreach (string field in updateFields)
            {
                sb.Append(field).Append("=@").Append(field).Append(",");
            }
            if (sb.ToString().LastIndexOf(",") != -1)
                sb.Remove(sb.ToString().LastIndexOf(","), 1);
            if(mail.ContainsKey("id"))
                sb.Append(" where id=@id");
            else
                sb.Append(" where uuid=@uuid");

            SQLiteCommand cmd = null;
            try
            {
                cmd = new SQLiteCommand(sb.ToString(), DBWorker.GetConnection());
                if (mail.ContainsKey("id"))
                    cmd.Parameters.AddWithValue("@id", mail["id"]);
                else
                    cmd.Parameters.AddWithValue("@uuid", mail["uuid"]);
                foreach (string field in updateFields)
                {
                    cmd.Parameters.AddWithValue("@" + field, mail[field]);
                }

                cmd.ExecuteNonQuery();

                cmd.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.StackTrace);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
            }
        }
예제 #45
0
        /// <summary>指令处理</summary>
        public ASObject Switch(int moduleNumber, int commandNumber, TGGSession session, ASObject data)
        {
#if DEBUG
            var sw = Stopwatch.StartNew();
#endif
            if (!CommonHelper.IsOpen(session.Player.Role.Kind.role_level, (int)OpenModelType.家族))
            {
                return(CommonHelper.ErrorResult(ResultType.BASE_PLAYER_LEVEL_ERROR));
            }
            var aso = new ASObject();
            //指令匹配
            switch (commandNumber)
            {
            case (int)FamilyCommand.FAMILY_JOIN: { aso = FAMILY_JOIN.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_CREATE: { aso = FAMILY_CREATE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_APPLY: { aso = FAMILY_APPLY.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_UPDATE: { aso = FAMILY_UPDATE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_NOTICE_UPDATE: { aso = FAMILY_NOTICE_UPDATE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_DONATE: { aso = FAMILY_DONATE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_RECEIVE: { aso = FAMILY_RECEIVE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_EXIT: { aso = FAMILY_EXIT.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_INVITE: { aso = FAMILY_INVITE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_INVITE_REPLY: { aso = FAMILY_INVITE_REPLY.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_APPLY_PROCESS: { aso = FAMILY_APPLY_PROCESS.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_REMOVE: { aso = FAMILY_REMOVE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_DISSOLVE: { aso = FAMILY_DISSOLVE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_OFFICE: { aso = FAMILY_OFFICE.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_LOG: { aso = FAMILY_LOG.GetInstance().CommandStart(session, data); break; }

            case (int)FamilyCommand.FAMILY_APPLY_LIST: { aso = FAMILY_APPLY_LIST.GetInstance().CommandStart(session, data); break; }
            }
#if DEBUG
            sw.Stop();
            XTrace.WriteLine("指令 {1} 运行总耗时:{0} 毫秒", sw.ElapsedMilliseconds.ToString(), GetType().Namespace);
#endif
            return(aso);
        }
예제 #46
0
        public bool BlackList(ASObject mail, string type)
        {
            bool IsChange = false;
            string folder = mail.getString("folder");
            if (folder == "INBOX")
                IsChange = true;
            if (folder == "SPAM")
                IsChange = true;
            if (!IsChange)
                return false;

            string toFolder = null;
            if (type == "email_b")
            {
                Remoting.call("MailManager.addBlackList", new object[] { mail.getString("contact_mail"), null, mail.getString("mail_from_label") });
                toFolder = "SPAM";
            }
            else if (type == "email_w")
            {
                Remoting.call("MailManager.removeBlackList", new object[] { mail.getString("contact_mail"), null });
                toFolder = "INBOX";
            }
            else if (type == "domain_b")
            {
                string contact_mail = mail.getString("contact_mail");
                string[] spilts = contact_mail.Split('@');
                if (spilts.Length != 2)
                    return false;
                Remoting.call("MailManager.addBlackList", new object[] { null, spilts[1], mail.getString("mail_from_label") });
                toFolder = "SPAM";
            }
            else if (type == "domain_w")
            {
                string contact_mail = mail.getString("contact_mail");
                string[] spilts = contact_mail.Split('@');
                if (spilts.Length != 2)
                    return false;
                Remoting.call("MailManager.removeBlackList", new object[] { null, spilts[1] });
                toFolder = "INBOX";
            }

            if (folder == toFolder)
                return false;

            mail["folder"] = toFolder;

            updateMail(mail, new string[] { "folder" });

            return true;
        }
예제 #47
0
        public bool MoveFolder(ASObject mail, string toFolder)
        {
            string folder = mail.getString("folder");
            if (toFolder == folder)
                return false;
            if (folder == "DRAFT" || folder == "OUTBOX" || folder == "DSBOX" || folder == "SENDED")
                return false;

            mail["folder"] = toFolder;

            updateMail(mail, new string[] { "folder" });

            return true;
        }
예제 #48
0
 public PlayerParticipant(ASObject thebase)
     : base(thebase)
 {
     BaseObject.SetFields(this, thebase);
 }
예제 #49
0
        public void ParseMail(ASObject mailRecord)
        {
            string store_path = Desktop.instance.ApplicationPath + "/mail/";
            string file = mailRecord["mail_file"] as string;
            DirectoryInfo dirinfo = Directory.GetParent(store_path + file);
            if (!dirinfo.Exists)
                dirinfo.Create();

            if (!File.Exists(store_path + file))
            {
                using (WebClient w = new WebClient())
                {
                    w.DownloadFile(Desktop.getAbsoluteUrl("docroot/attachments" + file), store_path + file);
                }
            }

            string uid = mailRecord["uuid"] as string;
            dirinfo = Directory.GetParent(store_path + file);
            string dir = dirinfo.FullName + "/" + uid + ".parts";
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            using (FileStream fs = new FileStream(store_path + file, FileMode.Open))
            {
                using (Mail_Message m = Mail_Message.ParseFromStream(fs, Encoding.GetEncoding("GBK")))
                {
                    string charset = null;
                    if (m.ContentType != null && m.ContentType.Param_Charset != null)
                        charset = m.ContentType.Param_Charset;
                    if (charset != null && String.Compare(charset, "GBK", true) != 0 && String.Compare(charset, "gb2312", true) != 0)
                    {
                        fs.Position = 0;
                        using (Mail_Message _m = Mail_Message.ParseFromStream(fs, Encoding.GetEncoding(charset)))
                        {
                            parseMIMEContent(_m, uid, dir, mailRecord);
                        }
                    }
                    else
                        parseMIMEContent(m, uid, dir, mailRecord);
                }
            }
        }
예제 #50
0
 internal NetStatusEventArgs(ASObject info)
 {
     _info = info;
 }
예제 #51
0
        /// <summary>
        /// 发送阅读回折邮件
        /// </summary>
        /// <param name="sHtmlText">邮件内容</param>
        /// <param name="from">发送人</param>
        /// <param name="to">接收人</param>
        public void sendReceiptMail(string sHtmlText, string subject, ASObject from, string[] to)
        {
            using (MemoryStreamEx stream = new MemoryStreamEx(32000))
            {
                Mail_Message m = new Mail_Message();
                m.MimeVersion = "1.0";
                m.Date = DateTime.Now;
                m.MessageID = MIME_Utils.CreateMessageID();

                m.Subject = subject;
                StringBuilder sb = new StringBuilder();
                foreach (string p in to)
                {
                    if (sb.Length > 0)
                        sb.Append(",");
                    sb.Append(p);
                }
                m.To = Mail_t_AddressList.Parse(sb.ToString());

                //--- multipart/alternative -----------------------------------------------------------------------------------------
                MIME_h_ContentType contentType_multipartAlternative = new MIME_h_ContentType(MIME_MediaTypes.Multipart.alternative);
                contentType_multipartAlternative.Param_Boundary = Guid.NewGuid().ToString().Replace('-', '.');
                MIME_b_MultipartAlternative multipartAlternative = new MIME_b_MultipartAlternative(contentType_multipartAlternative);
                m.Body = multipartAlternative;

                //--- text/plain ----------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_plain = new MIME_Entity();
                MIME_b_Text text_plain = new MIME_b_Text(MIME_MediaTypes.Text.plain);
                entity_text_plain.Body = text_plain;
                text_plain.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, sHtmlText);
                multipartAlternative.BodyParts.Add(entity_text_plain);

                //--- text/html ------------------------------------------------------------------------------------------------------
                MIME_Entity entity_text_html = new MIME_Entity();
                MIME_b_Text text_html = new MIME_b_Text(MIME_MediaTypes.Text.html);
                entity_text_html.Body = text_html;
                text_html.SetText(MIME_TransferEncodings.QuotedPrintable, Encoding.UTF8, sHtmlText);
                multipartAlternative.BodyParts.Add(entity_text_html);

                MIME_Encoding_EncodedWord headerwordEncoder = new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8);
                m.ToStream(stream, headerwordEncoder, Encoding.UTF8);
                stream.Position = 0;

                SMTP_Client.QuickSendSmartHost(null, from.getString("send_address", "stmp.sina.com"), from.getInt("send_port", 25),
                    from.getBoolean("is_send_ssl", false), from.getString("account"), PassUtil.Decrypt(from.getString("password")),
                    from.getString("account"), to, stream);
            }
        }
예제 #52
0
 public static bool IsActivity(ASObject @object)
 {
     return(@object["actor"].Count > 0);
 }
예제 #53
0
        /// <summary>
        /// 保存邮件并同步邮件到服务器,采用异步方式,但必须保证执行顺序
        /// </summary>
        /// <param name="mail">邮件记录</param>
        /// <param name="fields">保存或同步的字段</param>
        public void updateMail(ASObject mail, string[] updateFields)
        {
            // 保存邮件到本地并同步到服务器
            try
            {
                if (mail == null || updateFields == null)
                    return;
                updateMailRecord(mail, updateFields);

                syncUserMail(mail);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
예제 #54
0
 public static bool IsActor(ASObject @object)
 {
     return(@object.Type.Any(Actors.Contains));
 }
예제 #55
0
        private void parseMIMEContent(Mail_Message m, string uid, string dir, ASObject record)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement xml = doc.CreateElement("message");
            doc.AppendChild(xml);

            StringBuilder attachments = new StringBuilder();
            MIME_Entity[] entities = m.GetAllEntities(true);

            Map<string, string> content_id_file = new Map<string, string>();
            StringBuilder textHtml = new StringBuilder();
            textHtml.Append(@"<html><head><meta http-equiv=""content-type"" content=""text/html; charset=utf-8""></head><body>");
            bool hasText = false;

            foreach (MIME_Entity e in entities)
            {
                try
                {
                    if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.html)
                        continue;
                    else if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.plain)
                        continue;
                    else if (e.Body is MIME_b_SinglepartBase)
                    {
                        MIME_b_SinglepartBase p = (MIME_b_SinglepartBase)e.Body;
                        Stream data = p.GetDataStream();
                        string fPath = "";
                        string fileName = e.ContentType.Param_Name;
                        if (fileName == null)
                            fileName = Guid.NewGuid().ToString();
                        else
                            attachments.Append(fileName).Append(";");
                        fileName = fileName.Replace(' ', '_');
                        fPath = System.IO.Path.Combine(dir, fileName);
                        using (FileStream afs = File.Create(fPath))
                        {
                            Net_Utils.StreamCopy(data, afs, 4096);
                        }
                        data.Close();

                        string contentId = e.ContentID;
                        if (!String.IsNullOrEmpty(contentId))
                        {
                            contentId = contentId.Trim();
                            if (contentId.StartsWith("<"))
                                contentId = contentId.Substring(1);
                            if (contentId.EndsWith(">"))
                                contentId = contentId.Substring(0, contentId.Length - 1);
                            content_id_file.Add(contentId, fileName);
                        }

                        XmlElement part = doc.CreateElement("PART");
                        part.SetAttribute("type", "file");
                        part.SetAttribute("content-id", contentId);
                        part.SetAttribute("filename", fileName);
                        part.SetAttribute("description", e.ContentDescription);
                        if (e.ContentType != null)
                            part.SetAttribute("content-type", e.ContentType.ToString());
                        xml.AppendChild(part);
                    }
                }
                catch (Exception)
                {
                }
            }
            foreach (MIME_Entity e in entities)
            {
                try
                {
                    if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.html)
                    {
                        string html = ((MIME_b_Text)e.Body).Text;

                        //处理html中的内嵌图片
                        if (content_id_file.Count > 0)
                        {
                            foreach (string key in content_id_file.Keys)
                            {
                                html = html.Replace("cid:" + key, content_id_file[key]);
                            }
                        }

                        XmlElement part = doc.CreateElement("PART");
                        part.SetAttribute("type", "html");
                        part.AppendChild(doc.CreateCDataSection(html));
                        xml.AppendChild(part);

                        string charset = "GBK";
                        if (e.ContentType != null && e.ContentType.Param_Charset != null)
                            charset = e.ContentType.Param_Charset;
                        else if (m.ContentType != null && m.ContentType.Param_Charset != null)
                            charset = m.ContentType.Param_Charset;

                        string html_charset = getHtmlEncoding(html);
                        if (html_charset == null)
                        {
                            int index = html.IndexOf("<head>", StringComparison.CurrentCultureIgnoreCase);
                            if (index != -1)
                            {
                                StringBuilder sb = new StringBuilder();
                                index = index + "<head>".Length;
                                sb.Append(html.Substring(0, index));
                                sb.Append(@"<meta http-equiv=""content-type"" content=""text/html; charset=").Append(charset).Append(@""">");
                                sb.Append(html.Substring(index));
                                html = sb.ToString();
                            }
                            else
                            {
                                StringBuilder sb = new StringBuilder();
                                sb.Append(@"<html><head><meta http-equiv=""content-type"" content=""text/html; charset=").Append(charset).Append(@""">");
                                sb.Append("</head><body>");
                                sb.Append(html);
                                sb.Append("</body></html>");
                                html = sb.ToString();
                            }
                            html_charset = charset;
                        }

                        Encoding encoding = null;
                        try
                        {
                            encoding = Encoding.GetEncoding(html_charset);
                        }
                        catch (Exception)
                        {
                        }
                        if (encoding == null)
                        {
                            try
                            {
                                encoding = Encoding.GetEncoding(charset);
                            }
                            catch (Exception)
                            {
                            }
                        }
                        if (encoding == null)
                            encoding = Encoding.UTF8;
                        StreamWriter hfs = new StreamWriter(dir + "/" + uid + ".html", false, encoding);
                        hfs.Write(html);
                        hfs.Close();
                    }
                    else if (e.Body.MediaType.ToLower() == MIME_MediaTypes.Text.plain)
                    {
                        XmlElement part = doc.CreateElement("PART");
                        part.SetAttribute("type", "text");
                        string text = ((MIME_b_Text)e.Body).Text;

                        part.AppendChild(doc.CreateCDataSection(text));
                        xml.AppendChild(part);

                        if (hasText)
                            textHtml.Append("<hr/>");
                        hasText = true;
                        text = text.Replace(" ", "&nbsp;");
                        text = text.Replace("\n", "<br/>");
                        textHtml.Append(text);
                    }
                }
                catch (Exception)
                {
                }
            }

            textHtml.Append("</body></html>");
            if (hasText)
            {
                try
                {
                    using (StreamWriter hfs = new StreamWriter(dir + "/" + uid + ".text.html", false, Encoding.UTF8))
                    {
                        hfs.Write(textHtml.ToString());
                    }
                }
                catch (Exception)
                {
                }
            }

            record["attachments"] = attachments.ToString();
            record["contents"] = doc.OuterXml;
        }
예제 #56
0
 public SpellBookPage(ASObject obj)
     : base(obj)
 {
     BaseObject.SetFields(this, obj);
 }
예제 #57
0
		public ChampionDTO(ASObject obj)
			: base(obj)
		{
			BaseObject.SetFields(this, obj);
		}
예제 #58
0
        /// <summary>添加黑名单指令</summary>
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
#if DEBUG
            XTrace.WriteLine("{0}:{1}", "FRIEND_BLACKLIST", "添加黑名单指令");
#endif
            var name   = data.FirstOrDefault(q => q.Key == "name").Value.ToString();
            var friend = tg_user.GetUserByName(name);
            if (friend == null)
            {
                return(ResultError((int)ResultType.FRIEND_NO_DATA_ERROR));
            }
            if (friend.player_name == session.Player.User.player_name)
            {
                return(ResultError((int)ResultType.FRIEND_ON_ONESELF));
            }
            //if (!Variable.OnlinePlayer.ContainsKey(friend.id)) return new ASObject(Common.GetInstance().BuildData((int)ResultType.FRIEND_OFFONLINE_ERROR));

            var count = tg_friends.GetFindCountByState(session.Player.User.id, (int)FriendStateType.FRIEND);
            var rule  = Variable.BASE_RULE.FirstOrDefault(m => m.id == "19002");
            if (rule == null)
            {
                return(ResultError((int)ResultType.BASE_TABLE_ERROR));
            }
            var _max = Convert.ToInt32(rule.value);
            if (count >= _max)
            {
                return(ResultError((int)ResultType.FRIEND_MAX_ERROR));
            }

            var entity = tg_friends.GetFindEntity(session.Player.User.id, friend.id);
            if (entity != null)
            {
                if (entity.friend_state == (int)FriendStateType.BLACKLIST)
                {
                    return(ResultError((int)ResultType.FRIEND_BLACKLIST_EXIST));
                }
            }
            else
            {
                entity = new tg_friends()
                {
                    user_id   = session.Player.User.id,
                    friend_id = friend.id,
                };
            }
#if DEBUG
            XTrace.WriteLine("id  {0} user_id {1} friend_id {2} friend_state {3}", entity.id, entity.user_id, entity.friend_id, entity.friend_state);
#endif

            entity.friend_state = (int)FriendStateType.BLACKLIST;
#if DEBUG
            XTrace.WriteLine("更新状态后 id  {0} user_id {1} friend_id {2} friend_state {3}", entity.id, entity.user_id, entity.friend_id, entity.friend_state);
#endif
            try
            {
                entity.Save();
                if (!session.Player.BlackList.Contains(entity.friend_id))
                {
                    session.Player.BlackList.Add(entity.friend_id);
                }
            }
            catch { return(ResultError((int)ResultType.DATABASE_ERROR)); }
            var model       = view_user_role_friend.GetFindById(entity.id);
            var view_friend = Common.GetInstance().CheckSingleOnline(model);
            return(new ASObject(Common.GetInstance().BuildData((int)ResultType.SUCCESS, view_friend)));
        }
예제 #59
0
		public override void Invoke(AMFContext context) {
			MessageOutput messageOutput = context.MessageOutput;
			for (int i = 0; i < context.AMFMessage.BodyCount; i++) {
				AMFBody amfBody = context.AMFMessage.GetBodyAt(i);
				//Check for Flex2 messages
				if (amfBody.IsEmptyTarget) {
					object content = amfBody.Content;
					if (content is IList)
						content = (content as IList)[0];
					IMessage message = content as IMessage;
					if (message != null) {
						Client client = null;
						HttpSession session = null;
						if (FluorineContext.Current.Client == null) {
							IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry;
							string clientId = message.GetFlexClientId();
							if (!clientRegistry.HasClient(clientId)) {
								lock (clientRegistry.SyncRoot) {
									if (!clientRegistry.HasClient(clientId)) {
										client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
									}
								}
							}
							if (client == null)
								client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
							FluorineContext.Current.SetClient(client);
						}
						session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current);
						FluorineContext.Current.SetSession(session);
						//Context initialized, notify listeners.
						if (session != null && session.IsNew)
							session.NotifyCreated();
						if (client != null) {
							if (session != null)
								client.RegisterSession(session);
							if (client.IsNew) {
								client.Renew(_endpoint.ClientLeaseTime);
								client.NotifyCreated();
							}
						}
						/*
						RemotingConnection remotingConnection = null;
						foreach (IConnection connection in client.Connections)
						{
							if (connection is RemotingConnection)
							{
								remotingConnection = connection as RemotingConnection;
								break;
							}
						}
						if (remotingConnection == null)
						{
							remotingConnection = new RemotingConnection(_endpoint, null, client.Id, null);
							remotingConnection.Initialize(client, session);
						}
						FluorineContext.Current.SetConnection(remotingConnection);
						*/
					}
				} else {
					//Flash remoting
					AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.AMFDSIdHeader);
					string amfDSId = null;
					if (amfHeader == null) {
						amfDSId = Guid.NewGuid().ToString("D");
						ASObject asoObjectDSId = new ASObject();
						asoObjectDSId["name"] = AMFHeader.AMFDSIdHeader;
						asoObjectDSId["mustUnderstand"] = false;
						asoObjectDSId["data"] = amfDSId;//set
						AMFHeader headerDSId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectDSId);
						context.MessageOutput.AddHeader(headerDSId);
					} else
						amfDSId = amfHeader.Content as string;

					Client client = null;
					HttpSession session = null;
					if (FluorineContext.Current.Client == null) {
						IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry;
						string clientId = amfDSId;
						if (!clientRegistry.HasClient(clientId)) {
							lock (clientRegistry.SyncRoot) {
								if (!clientRegistry.HasClient(clientId)) {
									client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
								}
							}
						}
						if (client == null)
							client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client;
					}
					FluorineContext.Current.SetClient(client);
					session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current);
					FluorineContext.Current.SetSession(session);
					//Context initialized, notify listeners.
					if (session != null && session.IsNew)
						session.NotifyCreated();
					if (client != null) {
						if (session != null)
							client.RegisterSession(session);
						if (client.IsNew) {
							client.Renew(_endpoint.ClientLeaseTime);
							client.NotifyCreated();
						}
					}
				}
			}
		}
예제 #60
0
        private ClassDefinition CreateClassDefinition(object obj)
        {
            ClassDefinition definition = null;
            ClassMember     member;
            Type            type           = obj.GetType();
            bool            externalizable = type.GetInterface(typeof(IExternalizable).FullName, true) != null;
            bool            dynamic        = false;
            string          className      = null;

            if (obj is IDictionary)
            {
                if ((obj is ASObject) && (obj as ASObject).IsTypedObject)
                {
                    ASObject      obj2        = obj as ASObject;
                    ClassMember[] memberArray = new ClassMember[obj2.Count];
                    int           index       = 0;
                    foreach (KeyValuePair <string, object> pair in obj2)
                    {
                        member             = new ClassMember(pair.Key, BindingFlags.Default, MemberTypes.Custom);
                        memberArray[index] = member;
                        index++;
                    }
                    className  = obj2.TypeName;
                    definition = new ClassDefinition(className, memberArray, externalizable, dynamic);
                    classDefinitions[className] = definition;
                    return(definition);
                }
                dynamic = true;
                return(new ClassDefinition(string.Empty, ClassDefinition.EmptyClassMembers, externalizable, dynamic));
            }
            if (obj is IExternalizable)
            {
                className  = type.FullName;
                definition = new ClassDefinition(FluorineConfiguration.Instance.GetCustomClass(className), ClassDefinition.EmptyClassMembers, true, false);
                classDefinitions[type.FullName] = definition;
                return(definition);
            }
            List <string>      list  = new List <string>();
            List <ClassMember> list2 = new List <ClassMember>();

            foreach (PropertyInfo info in obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                string name = info.Name;
                if (info.GetCustomAttributes(typeof(TransientAttribute), true).Length <= 0)
                {
                    if ((info.GetGetMethod() == null) || (info.GetGetMethod().GetParameters().Length > 0))
                    {
                        string str3 = __Res.GetString("Reflection_PropertyIndexFail", new object[] { string.Format("{0}.{1}", type.FullName, info.Name) });
                        if (log.get_IsWarnEnabled())
                        {
                            log.Warn(str3);
                        }
                    }
                    else if (!list.Contains(name))
                    {
                        list.Add(name);
                        BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
                        try
                        {
                            PropertyInfo property = obj.GetType().GetProperty(name);
                        }
                        catch (AmbiguousMatchException)
                        {
                            bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
                        }
                        member = new ClassMember(name, bindingFlags, info.MemberType);
                        list2.Add(member);
                    }
                }
            }
            foreach (FieldInfo info3 in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                if ((info3.GetCustomAttributes(typeof(NonSerializedAttribute), true).Length <= 0) && (info3.GetCustomAttributes(typeof(TransientAttribute), true).Length <= 0))
                {
                    member = new ClassMember(info3.Name, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, info3.MemberType);
                    list2.Add(member);
                }
            }
            ClassMember[] members = list2.ToArray();
            className  = type.FullName;
            definition = new ClassDefinition(FluorineConfiguration.Instance.GetCustomClass(className), members, externalizable, dynamic);
            classDefinitions[type.FullName] = definition;
            return(definition);
        }