本文整理汇总了C#中Message.Close方法的典型用法代码示例。如果您正苦于以下问题:C# Message.Close方法的具体用法?C# Message.Close怎么用?C# Message.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Message
的用法示例。
在下文中一共展示了Message.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CompressMessage
public Message CompressMessage(Message sourceMessage)
{
byte[] buffer;
MessageBuffer messageBuffer = sourceMessage.CreateBufferedCopy(int.MaxValue);
sourceMessage.Close();
sourceMessage = messageBuffer.CreateMessage();
using (XmlDictionaryReader reader1 = sourceMessage.GetReaderAtBodyContents())
{
buffer = Encoding.UTF8.GetBytes(reader1.ReadOuterXml());
}
if (buffer.Length < this.MinMessageSize)
{
sourceMessage.Close();
return messageBuffer.CreateMessage();
}
byte[] compressedData = DataCompressor.Compress(buffer);
string copressedBody = CreateCompressedBody(compressedData);
XmlTextReader reader = new XmlTextReader(new StringReader(copressedBody), new NameTable());
Message compressedMessage = Message.CreateMessage(sourceMessage.Version, null, (XmlReader)reader);
compressedMessage.Headers.CopyHeadersFrom(sourceMessage);
compressedMessage.Properties.CopyProperties(sourceMessage.Properties);
compressedMessage.AddCompressionHeader(this.DataCompressor.Algorithm);
sourceMessage.Close();
return compressedMessage;
}
示例2: CompressMessage
public Message CompressMessage(Message toCompress)
{
if (Level == CompressionLevel.NoCompression)
{
return toCompress;
}
byte[] buffer = ExtractMessageBody(toCompress);
if (buffer.Length == 0)
{
Message emptyMessage = CopyMessageAndReplaceContent(toCompress);
toCompress.Close();
return emptyMessage;
}
byte[] compressedBuf = DataCompressor.Compress(buffer, Algorithm, Level);
var newMessageXml = new StringWriter();
using (XmlWriter xmlWriter = XmlWriter.Create(newMessageXml))
{
WriteCompressedBody(xmlWriter, compressedBuf);
}
Message newMsg = CopyMessageAndReplaceContent(toCompress, newMessageXml.ToString());
newMsg.Headers.Add(new CompressionMessageHeader(Algorithm, Level));
toCompress.Close();
return newMsg;
}
示例3: SerializeMessage
public static Message SerializeMessage(JObject json, Message previousMessage)
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms))
{
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
json.WriteTo(jtw);
jtw.Flush();
sw.Flush();
Message result = Message.CreateMessage(MessageVersion.None, null, new RawBodyWriter(ms.ToArray()));
if (previousMessage != null)
{
result.Properties.CopyProperties(previousMessage.Properties);
result.Headers.CopyHeadersFrom(previousMessage.Headers);
previousMessage.Close();
}
result.Properties[JsonRpcConstants.JObjectMessageProperty] = json;
return result;
}
}
}
}
示例4: CompressMessage
public Message CompressMessage(Message sourceMessage)
{
byte[] buffer;
//using (XmlDictionaryReader reader1 = sourceMessage.GetReaderAtBodyContents())
//{
// buffer = Encoding.UTF8.GetBytes(reader1.ReadOuterXml());
//}
MemoryStream ms = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8);
sourceMessage.WriteBodyContents(writer);
writer.Flush();
buffer = ms.ToArray();
if (buffer.Length == 0)
{
Message emptyMessage = Message.CreateMessage(sourceMessage.Version, (string)null);
sourceMessage.Headers.CopyHeadersFrom(sourceMessage);
sourceMessage.Properties.CopyProperties(sourceMessage.Properties);
emptyMessage.Close();
return emptyMessage;
}
byte[] compressedData = DataCompressor.Compress(buffer, this.Algorithm);
string copressedBody = CompressionUtil.CreateCompressedBody(compressedData);
XmlTextReader reader = new XmlTextReader(new StringReader(copressedBody), new NameTable());
Message message2 = Message.CreateMessage(sourceMessage.Version, null, (XmlReader)reader);
message2.Headers.CopyHeadersFrom(sourceMessage);
message2.Properties.CopyProperties(sourceMessage.Properties);
message2.AddCompressionHeader(this.Algorithm);
sourceMessage.Close();
return message2;
}
示例5: Base64BodyMessage
private Message Base64BodyMessage(Message ora_msg)
{
MemoryStream ms = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8);
ora_msg.WriteBodyContents(writer);
writer.Flush();
string body = System.Text.Encoding.UTF8.GetString(ms.GetBuffer());
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(body);
body = Convert.ToBase64String(buffer);
Message msg = Message.CreateMessage(ora_msg.Version, ora_msg.Headers.Action, new MyBodyWriter(body));
ora_msg.Close();
return msg;
}
示例6: SizeOfTextMessage
static int SizeOfTextMessage(Message message)
{
// Create a text encoder
MessageEncodingBindingElement element = new TextMessageEncodingBindingElement();
MessageEncoderFactory factory = element.CreateMessageEncoderFactory();
MessageEncoder encoder = factory.Encoder;
// Write the message and return its length
MemoryStream stream = new MemoryStream();
encoder.WriteMessage(message, stream);
int size = (int)stream.Length;
message.Close();
stream.Close();
return size;
}
示例7: BeginSend
public IAsyncResult BeginSend(object registrant, Message message, Uri via,
ITransportFactorySettings settings, TimeSpan timeout, AsyncCallback callback, object state, SecurityProtocol securityProtocol)
{
PeerFlooder localFlooder;
int factoryMaxReceivedMessageSize;
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
MessageBuffer messageBuffer = null;
Message securedMessage = null;
ulong hopcount = PeerTransportConstants.MaxHopCount;
PeerMessagePropagation propagateFlags = PeerMessagePropagation.LocalAndRemote;
int messageSize = (int)-1;
byte[] id;
SendAsyncResult result = new SendAsyncResult(callback, state);
AsyncCallback onFloodComplete = Fx.ThunkCallback(new AsyncCallback(result.OnFloodComplete));
try
{
lock (ThisLock)
{
ThrowIfNotOpen();
localFlooder = flooder;
}
// we know this will fit in an int because of our MaxReceivedMessageSize restrictions
factoryMaxReceivedMessageSize = (int)Math.Min(maxReceivedMessageSize, settings.MaxReceivedMessageSize);
Guid guid = ProcessOutgoingMessage(message, via);
SecureOutgoingMessage(ref message, via, timeout, securityProtocol);
if ((message is SecurityAppliedMessage))
{
ArraySegment<byte> buffer = encoder.WriteMessage(message, int.MaxValue, bufferManager);
securedMessage = encoder.ReadMessage(buffer, bufferManager);
id = (message as SecurityAppliedMessage).PrimarySignatureValue;
messageSize = (int)buffer.Count;
}
else
{
securedMessage = message;
id = guid.ToByteArray();
}
messageBuffer = securedMessage.CreateBufferedCopy(factoryMaxReceivedMessageSize);
string contentType = settings.MessageEncoderFactory.Encoder.ContentType;
if (this.messagePropagationFilter != null)
{
using (Message filterMessage = messageBuffer.CreateMessage())
{
propagateFlags = ((IPeerNodeMessageHandling)this).DetermineMessagePropagation(filterMessage, PeerMessageOrigination.Local);
}
}
if ((propagateFlags & PeerMessagePropagation.Remote) != PeerMessagePropagation.None)
{
if (hopcount == 0)
propagateFlags &= ~PeerMessagePropagation.Remote;
}
// flood it out
IAsyncResult ar = null;
if ((propagateFlags & PeerMessagePropagation.Remote) != 0)
{
ar = localFlooder.BeginFloodEncodedMessage(id, messageBuffer, timeoutHelper.RemainingTime(), onFloodComplete, null);
if (DiagnosticUtility.ShouldTraceVerbose)
{
TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerChannelMessageSent, SR.GetString(SR.TraceCodePeerChannelMessageSent), this, message);
}
}
else
{
ar = new CompletedAsyncResult(onFloodComplete, null);
}
if (ar == null)
{
Fx.Assert("SendAsyncResult must have an Async Result for onFloodComplete");
}
// queue up the pre-encoded message for local channels
if ((propagateFlags & PeerMessagePropagation.Local) != 0)
{
using (Message msg = messageBuffer.CreateMessage())
{
int i = msg.Headers.FindHeader(SecurityJan2004Strings.Security, SecurityJan2004Strings.Namespace);
if (i >= 0)
{
msg.Headers.AddUnderstood(i);
}
using (MessageBuffer clientBuffer = msg.CreateBufferedCopy(factoryMaxReceivedMessageSize))
{
DeliverMessageToClientChannels(registrant, clientBuffer, via, message.Headers.To, contentType, messageSize, -1, null);
}
}
}
result.OnLocalDispatchComplete(result);
}
finally
{
message.Close();
if (securedMessage != null)
securedMessage.Close();
if (messageBuffer != null)
//.........这里部分代码省略.........
示例8: OnLocalFault
public void OnLocalFault(Exception e, Message faultMessage, RequestContext context)
{
if (this.channel.Aborted ||
this.channel.State == CommunicationState.Faulted ||
this.channel.State == CommunicationState.Closed)
{
if (faultMessage != null)
faultMessage.Close();
if (context != null)
context.Abort();
return;
}
lock (this.ThisLock)
{
if (this.faulted != SessionFaultState.NotFaulted)
return;
this.faulted = SessionFaultState.LocallyFaulted;
this.terminatingFault = faultMessage;
this.replyFaultContext = context;
}
this.FaultCore();
this.channel.Fault(e);
this.UnblockChannelIfNecessary();
}
示例9: SendMail
/// <summary>
/// 发送邮件到网络
/// </summary>
public static void SendMail(string UserName, string PassWord, string SMTPServer, string Subject, string body, string FromEmail, string ToEmail,string FuJianList)
{
try
{
Message Jmail = new Message();
DateTime t = DateTime.Now;
//Slient属性:如果设置为true,Jmail不会抛出例外错误,Jmail.Send()会根据操作结果返回True或False
Jmail.Silent = false;
//Jmail创建的日志,提前loging属性设置为True
Jmail.Logging = true;
//字符集,缺省为"US-ASCII";
Jmail.Charset = "GB2312";
//信件的ContentType,缺省为"Text/plain",字符串如果你以Html格式发送邮件,改为"Text/Html"即可。
//Jmail.ContentType = "text/html";
//添加收件人
Jmail.AddRecipient(ToEmail, "", "");
Jmail.From = FromEmail;
//发件人邮件用户名
Jmail.MailServerUserName = UserName;
//发件人邮件密码
Jmail.MailServerPassWord = PassWord;
//设置邮件标题
Jmail.Subject = Subject;
//邮件添加附件(多附件的话,可以再加一条Jmail.AddAttachment("c:\test.jpg",true,null);就可以搞定了。
//注意:为了添加附件,要把上面的Jmail.ContentType="text/html";删掉,否则会在邮件里出现乱码
string[] FuJian = FuJianList.Split('|');
for (int kk = 0; kk < FuJian.Length; kk++)
{
if (FuJian[kk].Trim().Length > 0)
{
Jmail.AddAttachment(System.Web.HttpContext.Current.Request.MapPath("../UploadFile") + "\\" + FuJian[kk].ToString(), true, null);
}
}
//邮件内容
Jmail.Body = body + t.ToString();
//Jmail发送的方法
Jmail.Send(SMTPServer, false);
Jmail.Close();
}
catch (Exception e)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('" + e.Message.ToString() + "');</script>");
}
}
示例10: BeforeSendReply
/// <summary>
/// Check if we have unexpected error occurred during the service call. If so, Create a new fault message that indicates the client the call has failed.
/// </summary>
/// <param name="reply"></param>
/// <param name="correlationState"></param>
public void BeforeSendReply(ref Message reply, object correlationState)
{
string errorCode;
string errorReason;
string methodName;
// gets the current service base
var serviceBase = OperationContext.Current.InstanceContext.GetServiceInstance() as WcfServiceBase;
if (serviceBase != null && serviceBase.HasError)
{
if (serviceBase.UnknownError is ExceptionBase)
{
// convert to business exception
ExceptionBase exception = serviceBase.UnknownError as ExceptionBase;
// get method name
methodName = GetServiceMethod(exception);
// get unknown error code
errorCode = ((exception.HResult)).ToString();
// get the associated error code
//2010-3-9, by Danny, Exception message need to be used in web page. so, message shouldn't be wrapped.
//errorReason = string.Format("{0} failed in executing business logic. Message: {1}", methodName, exception.Message);
errorReason = exception.Message;
}
else
{
// get the service name and method name
string[] headers = reply.Headers.Action.Split('/');
methodName = string.Format("{0}.{1}", headers[headers.Length - 2], headers[headers.Length - 1]);
// get unknown error code
errorCode = (serviceBase.UnknownError.HResult).ToString();
// get unknown error reason
//errorReason = string.Format("{0} failed when committing the transaction. Message: {1}", methodName, serviceBase.UnknownError.Message);
errorReason = string.Format("出错: {0}", serviceBase.UnknownError.Message);
// logs error for failing in committing the transaction
Log4NetHelper.Error(LoggerType.ServiceExceptionLog, errorReason, serviceBase.UnknownError);
// LoggerManager.ServiceLogger.Error(errorReason, serviceBase.UnknownError);
}
// create fault exception
var fe = new FaultException(
string.Format(errorReason.Replace("{", "{{").Replace("}", "}}"),
methodName,
serviceBase.UnknownError.Message),
new FaultCode(errorCode));
MessageFault fault = fe.CreateMessageFault();
Message newMsg = Message.CreateMessage(reply.Version, fault, null);
// Preserve the headers of the original message
newMsg.Headers.CopyHeadersFrom(reply);
foreach (string propertyKey in reply.Properties.Keys)
{
newMsg.Properties.Add(propertyKey, reply.Properties[propertyKey]);
}
// Close the original message and return new message
reply.Close();
reply = newMsg;
}
}
示例11: EncodeMessage
// Address the Message and serialize it into a byte array.
ArraySegment<byte> EncodeMessage(Message message)
{
try
{
this.RemoteAddress.ApplyTo(message);
return encoder.WriteMessage(message, maxBufferSize, bufferManager);
}
finally
{
// we've consumed the message by serializing it, so clean up
message.Close();
}
}
示例12: SetMessage
internal void SetMessage(Message message, Exception requestException)
{
if ((message == null) && (requestException == null))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new ProtocolException(SR.GetString(SR.MessageXmlProtocolError),
new XmlException(SR.GetString(SR.MessageIsEmpty))));
}
this.TraceHttpMessageReceived(message);
if (requestException != null)
{
base.SetRequestMessage(requestException);
message.Close();
}
else
{
message.Properties.Security = (this.securityProperty != null) ? (SecurityMessageProperty)this.securityProperty.CreateCopy() : null;
base.SetRequestMessage(message);
}
}
示例13: RebuildMessage
private static void RebuildMessage(ref Message message, string messageBody)
{
if (message.IsFault || message.IsEmpty)
{
return;
}
var bodyDoc = new XmlDocument();
bodyDoc.LoadXml(messageBody);
// Create new message
if (bodyDoc.DocumentElement == null)
{
return;
}
Message replacementMessage = Message.CreateMessage(
message.Version, null, new XmlNodeReader(bodyDoc.DocumentElement));
replacementMessage.Headers.CopyHeadersFrom(message);
foreach (string propertyKey in message.Properties.Keys)
{
replacementMessage.Properties.Add(propertyKey, message.Properties[propertyKey]);
}
message.Close();
message = replacementMessage;
}
示例14: FaultException
/// <summary>
/// Deserializes the message into requests parameters. Also parses query parameters
/// from the request and stores the results in the original message.
/// </summary>
/// <param name="message">The incoming message to deserialize.</param>
/// <param name="parameters">The parameters that are passed to the query operation.
/// </param>
void IDispatchMessageFormatter.DeserializeRequest(Message message, object[] parameters)
{
Message originalMessage = message;
var isPost = MessageUtility.IsHttpPOSTMethod(message.Properties);
// If user tried to GET a query with side-effects then fail
// Note: This should never ever happen since it would fail earlier in the WCF pipeline since the method should be "POST"-only
if (_queryHasSideEffects && !isPost)
throw new FaultException("Must use POST to for queries with side effects");
if (isPost)
{
// If the HTTP Method is POST, get the query from the message body instead from the URL
ServiceQuery serviceQuery = MessageUtility.GetServiceQuery(ref message);
if (serviceQuery != null)
{
// Since a new message is returned by the GetServiceQueryFromMessageBody, the OperationContext does not find the property
// if set on the new message. So we set the property directly on the current OperationContext IncomingMessageProperties.
OperationContext.Current.IncomingMessageProperties[ServiceQuery.QueryPropertyName] = serviceQuery;
}
}
else if (!String.IsNullOrEmpty(message.Properties.Via.Query))
{
string query = HttpUtility.UrlDecode(message.Properties.Via.Query);
string fullRequestUrl = HttpUtility.UrlDecode(HttpContext.Current.Request.RawUrl);
message.Properties[ServiceQuery.QueryPropertyName] = DomainServiceWebHttpBehavior.GetServiceQuery(query, fullRequestUrl);
}
try
{
this._innerDispatchMessageFormatter.DeserializeRequest(message, parameters);
}
finally
{
// The original message belongs to the service model pipeline. We cannot
// dispose it. On the other hand we could have just created a new message. If
// that is the case we are responsible for disposing the new message.
if (message != originalMessage)
{
message.Properties.Clear();
message.Headers.Clear();
message.Close();
}
}
}
示例15: SelectOperation
/// <summary>
/// Selects the service operation to call.
/// </summary>
/// <param name="message">The <c>Message</c> object sent to invoke a service operation.</param>
/// <returns>The name of the service operation to call.</returns>
public string SelectOperation(ref Message message)
{
AmfPacket packet;
//Read AMF packet from the message
try
{
packet = message.GetBody<AmfPacket>(_context.AmfSerializer);
}
finally
{
message.Close();
}
//Batch request
if (packet.Messages.Count > 1)
{
message = new AmfBatchMessage(packet.Headers, packet.Messages);
return AmfOperationKind.Batch;
}
//Regular request
var amfMessage = new AmfGenericMessage(packet.Headers, packet.Messages[0]);
message = amfMessage;
//Check if it is a Flex message.
//Due to the nature of NetConnection.call(), RPC arguments
//are sent in an array. But in case of AMFX, an array is not used
//if there is only one argument.
var arraybody = amfMessage.AmfMessage.Data as object[];
AbstractMessage flexmessage;
if (arraybody != null && arraybody.Length > 0)
flexmessage = arraybody[0] as AbstractMessage;
else
flexmessage = amfMessage.AmfMessage.Data as AbstractMessage;
//It is a Flex message after all
if (flexmessage != null)
{
amfMessage.AmfMessage.Data = flexmessage;
var type = flexmessage.GetType();
//An RPC operation
if (type == typeof(RemotingMessage))
{
var operation = ((RemotingMessage)flexmessage).Operation;
return EndpointHasOperation(_context.ServiceEndpoint, operation)
? operation
: AmfOperationKind.Fault;
}
//A Flex command message
if (type == typeof(CommandMessage))
{
return AmfOperationKind.Command;
}
}
//If it's not a Flex message, then do it the old way
return EndpointHasOperation(_context.ServiceEndpoint, amfMessage.AmfMessage.Target)
? amfMessage.AmfMessage.Target
: AmfOperationKind.Fault;
}