public void Call<T>(string command, Responder<T> responder, params object[] arguments) { try { TypeHelper._Init(); Uri uri = new Uri(_gatewayUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.ContentType = ContentType.AMF; request.Method = "POST"; #if !(SILVERLIGHT) request.CookieContainer = _netConnection.CookieContainer; #endif AMFMessage amfMessage = new AMFMessage((ushort)_netConnection.ObjectEncoding); AMFBody amfBody = new AMFBody(command, responder.GetHashCode().ToString(), arguments); amfMessage.AddBody(amfBody); foreach (KeyValuePair<string, AMFHeader> entry in _netConnection.Headers) { amfMessage.AddHeader(entry.Value); } AmfRequestData amfRequestData = new AmfRequestData(request, amfMessage, null, null, responder); request.BeginGetRequestStream(BeginRequestFlashCall, amfRequestData); } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
public void Call(string command, IPendingServiceCallback callback, params object[] arguments) { try { TypeHelper._Init(); Uri requestUri = new Uri(this._gatewayUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); request.ContentType = "application/x-amf"; request.Method = "POST"; request.CookieContainer = this._netConnection.CookieContainer; AMFMessage amfMessage = new AMFMessage((ushort)this._netConnection.ObjectEncoding); AMFBody body = new AMFBody(command, callback.GetHashCode().ToString(), arguments); amfMessage.AddBody(body); foreach (KeyValuePair <string, AMFHeader> pair in this._netConnection.Headers) { amfMessage.AddHeader(pair.Value); } PendingCall call = new PendingCall(command, arguments); RequestData state = new RequestData(request, amfMessage, call, callback); request.BeginGetRequestStream(new AsyncCallback(this.BeginRequestFlashCall), state); } catch (Exception exception) { this._netConnection.RaiseNetStatus(exception); } }
/// <summary> /// Сериализует объект в буффер AMF. /// </summary> /// <param name="sourceObject">Исходный объект.</param> /// <param name="version">Версия AMF.</param> /// <returns></returns> public static byte[] SerializeToAmf(this object sourceObject, ushort version) { using (MemoryStream memoryStream = new MemoryStream()) // Открываем поток для записи данных в буфер. using (AMFSerializer amfSerializer = new AMFSerializer(memoryStream)) // Инициализируем сериализатор для AMF. { AMFMessage amfMessage = new AMFMessage(version); // Создаём сообщение для передачи серверу с заданным номером версии AMF. AMFBody amfBody = new AMFBody(AMFBody.OnResult, null, GenerateType(sourceObject)); // Создаём тело для сообщения AMF. amfMessage.AddBody(amfBody); // Добавляем body для сообщения AMF. amfSerializer.WriteMessage(amfMessage); // Сериализуем сообщение. return(memoryStream.ToArray()); // Преобразовывает поток памяти в буфер и возвращает. } }
public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments) { if (this._netConnection.ObjectEncoding == ObjectEncoding.AMF0) { throw new NotSupportedException("AMF0 not supported for Flex RPC"); } try { TypeHelper._Init(); Uri requestUri = new Uri(this._gatewayUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); request.ContentType = "application/x-amf"; request.Method = "POST"; request.CookieContainer = this._netConnection.CookieContainer; AMFMessage amfMessage = new AMFMessage((ushort)this._netConnection.ObjectEncoding); RemotingMessage message2 = new RemotingMessage { clientId = Guid.NewGuid().ToString("D"), destination = destination, messageId = Guid.NewGuid().ToString("D"), timestamp = 0L, timeToLive = 0L }; message2.SetHeader("DSEndpoint", endpoint); if (this._netConnection.ClientId == null) { message2.SetHeader("DSId", "nil"); } else { message2.SetHeader("DSId", this._netConnection.ClientId); } message2.source = source; message2.operation = operation; message2.body = arguments; foreach (KeyValuePair <string, AMFHeader> pair in this._netConnection.Headers) { amfMessage.AddHeader(pair.Value); } AMFBody body = new AMFBody(null, null, new object[] { message2 }); amfMessage.AddBody(body); PendingCall call = new PendingCall(source, operation, arguments); RequestData state = new RequestData(request, amfMessage, call, callback); request.BeginGetRequestStream(new AsyncCallback(this.BeginRequestFlexCall), state); } catch (Exception exception) { this._netConnection.RaiseNetStatus(exception); } }
private AMFMessage ReadMessage(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) { throw new JsonReaderException("AMFMessage must be a JSON Object"); } AMFMessage message = new AMFMessage(); for (reader.Read(); reader.TokenType != JsonToken.EndObject; reader.Read()) { if (reader.TokenType != JsonToken.PropertyName) { throw new JsonReaderException("JSON format error, JSON Object must have property"); } string propertyName = (string)reader.Value; switch (propertyName) { case "Version": reader.Read(); if (reader.TokenType != JsonToken.Integer) { throw new JsonReaderException("AMFMessage 'Version' must be JSON Number"); } message = new AMFMessage(Convert.ToUInt16(reader.Value)); break; case "Bodies": reader.Read(); if (reader.TokenType != JsonToken.StartArray) { throw new JsonReaderException("AMFMessage 'Bodies' must be JSON Array"); } for (reader.Read(); reader.TokenType != JsonToken.EndArray; reader.Read()) { AMFBody body = serializer.Deserialize <AMFBody>(reader); message.AddBody(body); } break; default: throw new NotSupportedException("AMFMessage dont support property " + propertyName + ", please report this"); break; } } return(message); }
public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments) { if (_netConnection.ObjectEncoding == ObjectEncoding.AMF0) { throw new NotSupportedException("AMF0 not supported for Flex RPC"); } try { TypeHelper._Init(); Uri uri = new Uri(_gatewayUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.ContentType = ContentType.AMF; request.Method = "POST"; #if !(SILVERLIGHT) request.CookieContainer = _netConnection.CookieContainer; #endif AMFMessage amfMessage = new AMFMessage((ushort)_netConnection.ObjectEncoding); RemotingMessage remotingMessage = new RemotingMessage(); remotingMessage.clientId = Guid.NewGuid().ToString("D"); remotingMessage.destination = destination; remotingMessage.messageId = Guid.NewGuid().ToString("D"); remotingMessage.timestamp = 0; remotingMessage.timeToLive = 0; remotingMessage.SetHeader(MessageBase.EndpointHeader, endpoint); remotingMessage.SetHeader(MessageBase.FlexClientIdHeader, _netConnection.ClientId ?? "nil"); //Service stuff remotingMessage.source = source; remotingMessage.operation = operation; remotingMessage.body = arguments; foreach (KeyValuePair <string, AMFHeader> entry in _netConnection.Headers) { amfMessage.AddHeader(entry.Value); } AMFBody amfBody = new AMFBody(null, null, new object[] { remotingMessage }); amfMessage.AddBody(amfBody); PendingCall call = new PendingCall(source, operation, arguments); AmfRequestData amfRequestData = new AmfRequestData(request, amfMessage, call, callback, null); request.BeginGetRequestStream(BeginRequestFlexCall, amfRequestData); } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
/// <summary> /// This method supports the Fluorine infrastructure and is not intended to be used directly from your code. /// </summary> /// <returns></returns> public AMFMessage ReadAMFMessage() { // Version stored in the first two bytes. var version = ReadUInt16(); var message = new AMFMessage(version); // Read header count. int headerCount = ReadUInt16(); for (var i = 0; i < headerCount; i++) { message.AddHeader(ReadHeader()); } // Read header count. int bodyCount = ReadUInt16(); for (var i = 0; i < bodyCount; i++) { var amfBody = ReadBody(); if (amfBody != null) //not failed message.AddBody(amfBody); } return message; }
private async void sendBtn_Click(object sender, EventArgs e) { object[] arguments = { Convert.ToInt32(textBox1.Text) }; AMFMessage _amf = new AMFMessage(3); _amf.AddHeader(new AMFHeader("id", false, Hash.createChecksum(arguments))); _amf.AddHeader(new AMFHeader("needClassName", false, true)); _amf.AddBody(new AMFBody("MovieStarPlanet.WebService.UserSession.AMFUserSessionService.GetActorNameFromId", "/1", arguments)); MemoryStream mStream = new MemoryStream(); AMFSerializer serialize = new AMFSerializer(mStream); serialize.WriteMessage(_amf); HttpClient client = new HttpClient(); byte[] AMFBytes = Encoding.Default.GetBytes(Encoding.Default.GetString(mStream.ToArray())); ///Set referer to send AMF without 404 error Uri referer = new Uri("https://assets.mspcdns.com/msp/91.0.2/Main_20200728_110605.swf"); client.DefaultRequestHeaders.Referrer = referer; try { string gateway = "https://ws-" + comboBox1.Text + ".mspapis.com/msp/91.0.6/Gateway.aspx?method=MovieStarPlanet.WebService.UserSession.AMFUserSessionService.GetActorNameFromId"; var AMFHttpClientByteArray = new ByteArrayContent(AMFBytes); AMFHttpClientByteArray.Headers.ContentType = new MediaTypeHeaderValue("application/x-amf"); var response = await client.PostAsync(gateway, AMFHttpClientByteArray); //Response string responseString = response.Content.ReadAsStringAsync().Result; string final = JsonConvert.SerializeObject(responseString); MessageBox.Show(final); } catch (WebException exception) { MessageBox.Show("Error!" + exception); } }
/// <summary> /// 用户认证 /// </summary> /// <returns></returns> private byte[] AuthenticateUser(string userID, string psd, string responseNo) { RemotingMessage rtMsg = new RemotingMessage(); rtMsg.source = null; rtMsg.operation = "authenticateUser"; rtMsg.clientId = Guid.NewGuid().ToString().ToUpper(); rtMsg.messageId = Guid.NewGuid().ToString().ToUpper(); rtMsg.destination = "userRO"; rtMsg.timestamp = 0; rtMsg.timeToLive = 0; rtMsg.headers.Add(RemotingMessage.FlexClientIdHeader, Guid.NewGuid().ToString().ToUpper()); rtMsg.headers.Add(RemotingMessage.EndpointHeader, "my-amf"); List <object> bodys = new List <object>(); bodys.Add(userID); bodys.Add(psd); rtMsg.body = bodys.ToArray(); AMFMessage _amf3 = new AMFMessage(3);// 创建 AMF List <RemotingMessage> lstR = new List <RemotingMessage>(); lstR.Add(rtMsg); AMFBody _amfbody = new AMFBody("null", "/" + responseNo, lstR.ToArray()); _amf3.AddBody(_amfbody); MemoryStream _Memory = new MemoryStream(); //内存流 AMFSerializer _Serializer = new AMFSerializer(_Memory); //序列化 _Serializer.WriteMessage(_amf3); //将消息写入 return(_Memory.ToArray()); }
private AMFMessage LoadBinMessageIntoAmfMessage(byte[] encodedMessage) { AMFMessage message = null; byte[] buffer = encodedMessage; MemoryStream stream = new MemoryStream(buffer); try { message = new AMFDeserializer(stream).ReadAMFMessage(); } catch (DecoderFallbackException) { stream.Position = 0; object content = new AMFReader(stream) { FaultTolerancy = true }.ReadAMF3Data(); message = new AMFMessage(3); message.AddBody(new AMFBody(string.Empty, string.Empty, content)); } return(message); }
private AMFMessage ReadMessage(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) throw new JsonReaderException("AMFMessage must be a JSON Object"); AMFMessage message = new AMFMessage(); for (reader.Read(); reader.TokenType != JsonToken.EndObject; reader.Read()) { if (reader.TokenType != JsonToken.PropertyName) throw new JsonReaderException("JSON format error, JSON Object must have property"); string propertyName = (string)reader.Value; switch (propertyName) { case "Version": reader.Read(); if (reader.TokenType != JsonToken.Integer) throw new JsonReaderException("AMFMessage 'Version' must be JSON Number"); message = new AMFMessage(Convert.ToUInt16(reader.Value)); break; case "Bodies": reader.Read(); if (reader.TokenType != JsonToken.StartArray) throw new JsonReaderException("AMFMessage 'Bodies' must be JSON Array"); for (reader.Read(); reader.TokenType != JsonToken.EndArray; reader.Read()) { AMFBody body = serializer.Deserialize<AMFBody>(reader); message.AddBody(body); } break; default: throw new NotSupportedException("AMFMessage dont support property " + propertyName + ", please report this"); break; } } return message; }
object ProcessMessage(AMFMessage amfMessage) { // Apply AMF-based operation selector /* Dictionary<string, string> operationNameDictionary = new Dictionary<string, string>(); foreach (OperationDescription operation in _endpoint.Contract.Operations) { try { operationNameDictionary.Add(operation.Name.ToLower(), operation.Name); } catch (ArgumentException) { throw new Exception(String.Format("The specified contract cannot be used with case insensitive URI dispatch because there is more than one operation named {0}", operation.Name)); } } */ //SessionMode, CallbackContract, ProtectionLevel AMFMessage output = new AMFMessage(amfMessage.Version); for (int i = 0; i < amfMessage.BodyCount; i++) { AMFBody amfBody = amfMessage.GetBodyAt(i); object content = amfBody.Content; if (content is IList) content = (content as IList)[0]; IMessage message = content as IMessage; if (message != null) { //WCF should not assign client id for Flex... if (message.clientId == null) message.clientId = Guid.NewGuid().ToString("D"); //IMessage resultMessage = _endpoint.ServiceMessage(message); IMessage responseMessage = null; CommandMessage commandMessage = message as CommandMessage; if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation) { responseMessage = new AcknowledgeMessage(); responseMessage.body = true; } else { RemotingMessage remotingMessage = message as RemotingMessage; string operation = remotingMessage.operation; //TODO: you could use an alias for a contract to expose a different name to the clients in the metadata using the Name property of the ServiceContract attribute string source = remotingMessage.source; Type serviceType = TypeHelper.Locate(source); Type contractInterface = serviceType.GetInterface(_endpoint.Contract.ContractType.FullName); //WCF also lets you apply the ServiceContract attribute directly on the service class. Avoid using it. //ServiceContractAttribute serviceContractAttribute = ReflectionUtils.GetAttribute(typeof(ServiceContractAttribute), type, true) as ServiceContractAttribute; if (contractInterface != null) { object instance = Activator.CreateInstance(serviceType); IList parameterList = remotingMessage.body as IList; MethodInfo mi = MethodHandler.GetMethod(contractInterface, operation, parameterList, false, false); //MethodInfo mi = MethodHandler.GetMethod(serviceType, operation, parameterList, false, false); if (mi != null) { //TODO OperationContract attribute to alias it to a different publicly exposed name OperationContractAttribute operationContractAttribute = ReflectionUtils.GetAttribute(typeof(OperationContractAttribute), mi, true) as OperationContractAttribute; if (operationContractAttribute != null) { //mi = MethodHandler.GetMethod(serviceType, operation, parameterList, false, false); ParameterInfo[] parameterInfos = mi.GetParameters(); object[] args = new object[parameterInfos.Length]; parameterList.CopyTo(args, 0); TypeHelper.NarrowValues(args, parameterInfos); object result = mi.Invoke(instance, args); if (!(result is IMessage)) { responseMessage = new AcknowledgeMessage(); responseMessage.body = result; } else responseMessage = result as IMessage; } else responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of an service contract")); } else responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of an service contract")); } else responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException(String.Format("The specified contract {0} cannot be used with the source named {1} and operation named {2}", _endpoint.Contract.ContractType.Name, source, operation))); } if (responseMessage is AsyncMessage) { ((AsyncMessage)responseMessage).correlationId = message.messageId; } responseMessage.destination = message.destination; responseMessage.clientId = message.clientId; ResponseBody responseBody = new ResponseBody(amfBody, responseMessage); output.AddBody(responseBody); } } return output; }
object ProcessMessage(AMFMessage amfMessage) { // Apply AMF-based operation selector /* * Dictionary<string, string> operationNameDictionary = new Dictionary<string, string>(); * foreach (OperationDescription operation in _endpoint.Contract.Operations) * { * try * { * operationNameDictionary.Add(operation.Name.ToLower(), operation.Name); * } * catch (ArgumentException) * { * throw new Exception(String.Format("The specified contract cannot be used with case insensitive URI dispatch because there is more than one operation named {0}", operation.Name)); * } * } */ //SessionMode, CallbackContract, ProtectionLevel AMFMessage output = new AMFMessage(amfMessage.Version); for (int i = 0; i < amfMessage.BodyCount; i++) { AMFBody amfBody = amfMessage.GetBodyAt(i); object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message != null) { //WCF should not assign client id for Flex... if (message.clientId == null) { message.clientId = Guid.NewGuid().ToString("D"); } //IMessage resultMessage = _endpoint.ServiceMessage(message); IMessage responseMessage = null; CommandMessage commandMessage = message as CommandMessage; if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation) { responseMessage = new AcknowledgeMessage(); responseMessage.body = true; } else { RemotingMessage remotingMessage = message as RemotingMessage; string operation = remotingMessage.operation; //TODO: you could use an alias for a contract to expose a different name to the clients in the metadata using the Name property of the ServiceContract attribute string source = remotingMessage.source; Type serviceType = TypeHelper.Locate(source); Type contractInterface = serviceType.GetInterface(_endpoint.Contract.ContractType.FullName); //WCF also lets you apply the ServiceContract attribute directly on the service class. Avoid using it. //ServiceContractAttribute serviceContractAttribute = ReflectionUtils.GetAttribute(typeof(ServiceContractAttribute), type, true) as ServiceContractAttribute; if (contractInterface != null) { object instance = Activator.CreateInstance(serviceType); IList parameterList = remotingMessage.body as IList; MethodInfo mi = MethodHandler.GetMethod(contractInterface, operation, parameterList, false, false); //MethodInfo mi = MethodHandler.GetMethod(serviceType, operation, parameterList, false, false); if (mi != null) { //TODO OperationContract attribute to alias it to a different publicly exposed name OperationContractAttribute operationContractAttribute = ReflectionUtils.GetAttribute(typeof(OperationContractAttribute), mi, true) as OperationContractAttribute; if (operationContractAttribute != null) { //mi = MethodHandler.GetMethod(serviceType, operation, parameterList, false, false); ParameterInfo[] parameterInfos = mi.GetParameters(); object[] args = new object[parameterInfos.Length]; parameterList.CopyTo(args, 0); TypeHelper.NarrowValues(args, parameterInfos); object result = mi.Invoke(instance, args); if (!(result is IMessage)) { responseMessage = new AcknowledgeMessage(); responseMessage.body = result; } else { responseMessage = result as IMessage; } } else { responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of an service contract")); } } else { responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of an service contract")); } } else { responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException(String.Format("The specified contract {0} cannot be used with the source named {1} and operation named {2}", _endpoint.Contract.ContractType.Name, source, operation))); } } if (responseMessage is AsyncMessage) { ((AsyncMessage)responseMessage).correlationId = message.messageId; } responseMessage.destination = message.destination; responseMessage.clientId = message.clientId; ResponseBody responseBody = new ResponseBody(amfBody, responseMessage); output.AddBody(responseBody); } } return(output); }
private AMFMessage LoadBinMessageIntoAmfMessage(byte[] encodedMessage) { AMFMessage message = null; byte[] buffer = encodedMessage; MemoryStream stream = new MemoryStream(buffer); try { message = new AMFDeserializer(stream).ReadAMFMessage(); } catch (DecoderFallbackException) { stream.Position = 0; object content = new AMFReader(stream) { FaultTolerancy = true }.ReadAMF3Data(); message = new AMFMessage(3); message.AddBody(new AMFBody(string.Empty, string.Empty, content)); } return message; }