protected override List<MessagePart> CaseLeaf(MessagePart messagePart) { if(messagePart == null) throw new ArgumentNullException("messagePart"); // Maximum space needed is one List<MessagePart> leafAnswer = new List<MessagePart>(1); if (messagePart.IsText) leafAnswer.Add(messagePart); return leafAnswer; }
public static string GetMimeString(MessagePart Parts) { var Body = ""; if (Parts.Parts != null) { foreach (var part in Parts.Parts) { Body = string.Format("{0}\n{1}", Body, GetMimeString(part)); } } else if (Parts.Body.Data != null && Parts.Body.AttachmentId == null) // && Parts.MimeType == "text/plain") { string codedBody = Parts.Body.Data.Replace("-", "+"); codedBody = codedBody.Replace("_", "/"); byte[] data = Convert.FromBase64String(codedBody); Body = Encoding.UTF8.GetString(data); } return Body; }
private Task <bool> FetchEmailsAndForward() { List <Message> msg_list = null; try { msg_list = email_service.FetchUnseenMessages(PopServerHost, port, true, username, password, seenUids); //List<Message> msg_list = email_service.FetchUnseenMessages(PopServerHost, port, true, username, password, seenUids); //List<Message> msg_list = email_service.FetchAllMessages(); //lvSendLog.Items.Clear(); //log file info string fpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); string fname = "email.log"; // This file will have a new line at the end. FileInfo info = new FileInfo(fpath + "\\" + fname); if (msg_list.Count == 0) { return(Task <bool> .Factory.StartNew(() => false)); } foreach (Message msg in msg_list) { FromUserEmail = msg.Headers.From.Address; if (!(msg.Headers.From.Address.Contains("@hyt.com") || msg.Headers.From.Address.Equals("*****@*****.**"))) { continue; } StringBuilder builder = new StringBuilder(); string strEmailInfo = string.Empty; strEmailInfo += msg.Headers.Date; strEmailInfo += CRLF; strEmailInfo += msg.Headers.From.Address; strEmailInfo += CRLF; strEmailInfo += msg.MessagePart.Body; strEmailInfo += CRLF; MessagePart plainText = msg.FindFirstPlainTextVersion(); if (plainText != null) { // We found some plaintext! builder.Append(plainText.GetBodyAsText()); } else { // Might include a part holding html instead MessagePart html = msg.FindFirstHtmlVersion(); if (html != null) { // We found some html! builder.Append(html.GetBodyAsText()); } } //save email into log file using (StreamWriter writer = info.AppendText()) { //writer.WriteLine(tbSendText.Text); writer.WriteLine(strEmailInfo); } sendlog_items.Add(new SendLog() { FromName = msg.Headers.From.DisplayName + msg.Headers.From.Address, ReceivedDatetime = msg.Headers.Date, MailSubject = msg.Headers.Subject, MailBody = Regex.Replace(builder.ToString(), @"^\s*$\n|\r", "", RegexOptions.Multiline).TrimEnd() //MailBody = msg.MessagePart.Body == null ? "" : msg.MessagePart.Body.ToString() }); AddSendItem(new SendLog() { FromName = msg.Headers.From.ToString(), //FromName = msg.Headers.Sender == null ? "" : msg.Headers.Sender.ToString(), ReceivedDatetime = msg.Headers.Date, MailSubject = msg.Headers.Subject, MailBody = Regex.Replace(builder.ToString(), @"^\s*$\n|\r", "", RegexOptions.Multiline).TrimEnd() }); string tmp = builder.ToString(); FromUserEmail = tmp.Substring(tmp.IndexOf("Email:") + 7, tmp.IndexOf("Telephone") - tmp.IndexOf("Email:") - 8); } // delete message loop doesn't overlap with message handling loop // in order to avoid read/delete conflict on server foreach (Message msg in msg_list) { //delete email after fetch, otherwise will be fetched next time if (email_service.DeleteMessageByMessageId(msg.Headers.MessageId)) { //MessageBox.Show("The message " + msg.Headers.MessageId + " has been deleted"); } } } // Catch these exceptions but don't do anything catch (PopServerLockedException psle) { return(Task <bool> .Factory.StartNew(() => false)); } catch (PopServerNotAvailableException psnae) { return(Task <bool> .Factory.StartNew(() => false)); } catch (PopServerException psle) { return(Task <bool> .Factory.StartNew(() => false)); } //send to mobile #region send_to_mobile if (_channelCollection.Count <= 0) { //MessageBox.Show("No channel!"); AutoClosingMessageBox msgBox = new AutoClosingMessageBox("No channel available!", "UTech Demo", 2000); return(Task <bool> .Factory.StartNew(() => false)); } try { foreach (Message msg in msg_list) { TextMessageRequest textMsg = new TextMessageRequest(); StringBuilder builder = new StringBuilder(); MessagePart plainText = msg.FindFirstPlainTextVersion(); if (plainText != null) { // We found some plaintext! builder.Append(plainText.GetBodyAsText()); } else { // Might include a part holding html instead MessagePart html = msg.FindFirstHtmlVersion(); if (html != null) { // We found some html! builder.Append(html.GetBodyAsText()); } } textMsg._msg = builder.ToString(); //should be from email somewhere textMsg._targetID = 20; //hardcode OptionCode messageOpcode = new OptionCode(); messageOpcode = OptionCode.TMP_PRIVATE_NEED_ACK_REQUEST; uint channelId = GetChannel(1).channelId; int requestID = _adk.GetService(ServiceType.TMP).SendCommand(textMsg, messageOpcode, channelId); if (requestID == -1) { return(Task <bool> .Factory.StartNew(() => false)); } if (_msgRequesetIdMsgItemInfoDict.ContainsKey((uint)requestID)) { return(Task <bool> .Factory.StartNew(() => false)); } _msgRequesetIdMsgItemInfoDict.Add((uint)requestID, textMsg._targetID.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.Message, "UTech Demo", MessageBoxButton.OK, MessageBoxImage.Error); } #endregion return(Task <bool> .Factory.StartNew(() => true)); }
protected internal override void VisitMessagePart(MessagePart entity) { MessagePart++; base.VisitMessagePart(entity); }
public void TestDoValidateCollectionItem(MessagePart objectToValidate, object currentTarget, string key, ValidationResults validationResults) { this.DoValidateCollectionItem(objectToValidate, currentTarget, key, validationResults); }
private void updateData() { suara[0] = 0; suara[1] = 0; suara[2] = 0; suara[3] = 0; suara[4] = 0; lblCalon[0] = lblCalon1; //lblCalon[1] = lblCalon2; lblCalon[2] = lblCalon3; //lblCalon[3] = lblCalon4; lblCalon[4] = lblCalon5; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect("pop.gmail.com", 995, true); pop3Client.Authenticate("*****@*****.**", passEMAIL); int count = pop3Client.GetMessageCount(); progressBar1.Maximum = count; int success = 0; int fail = 0; for (int i = count; i >= 1; i -= 1) { // Check if the form is closed while we are working. If so, abort if (IsDisposed) { return; } // Refresh the form while fetching emails // This will fix the "Application is not responding" problem Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); String pesan; if (message.MessagePart.IsText) { pesan = message.MessagePart.GetBodyAsText(); } else { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { pesan = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { pesan = textVersions[0].GetBodyAsText(); } else { pesan = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } if (message.Headers.Subject == "2SUARA KAHIM") { //MessageBox.Show("IBM"); String[] komponen = pesan.Split('|'); if (komponen.Count() == 4) { if (komponen[0] == "COMBODUO") { if (!kupon.Contains(komponen[2])) { int pilihan = 0; if (Int32.TryParse(komponen[3], out pilihan)) { kupon.Add(komponen[2]); textBox1.AppendText(komponen[2] + " " + komponen[3] + "\n"); suara[pilihan - 1] += 1; lblCalon[pilihan - 1].Text = suara[pilihan - 1].ToString(); chart1.Series.Clear(); chart1.Series.Add(""); chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie; chart1.Series[0].Points.Add(0); chart1.Series[0].Points.Add(0); chart1.Series[0].Points.Add(0); //chart1.Series[0].Points.Add(0); //chart1.Series[0].Points.Add(0); chart1.Series[0].Points[0].IsValueShownAsLabel = true; chart1.Series[0].Points[0].Label = "Joshua Belzalel A"; chart1.Series[0].Points[0].SetValueY(suara[0]); //chart1.Series[0].Points[1].IsValueShownAsLabel = true; //chart1.Series[0].Points[1].Label = "Farid Fadhil H"; //chart1.Series[0].Points[1].SetValueY(suara[1]); chart1.Series[0].Points[1].IsValueShownAsLabel = true; chart1.Series[0].Points[1].Label = "Aryya Dwisatya W"; chart1.Series[0].Points[1].SetValueY(suara[2]); //chart1.Series[0].Points[3].IsValueShownAsLabel = true; //chart1.Series[0].Points[3].Label = "Vidia Anindhita"; //chart1.Series[0].Points[3].SetValueY( suara[3] ); chart1.Series[0].Points[2].IsValueShownAsLabel = true; chart1.Series[0].Points[2].Label = "Abstain"; chart1.Series[0].Points[2].SetValueY(suara[4]); progressBar1.Value++; } } } } } //MessageBox.Show(message.Headers.Subject + "\n\n" + pesan); success++; } catch (Exception ex) { MessageBox.Show(ex.Message); DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + ex.Message + "\r\n" + "Stack trace:\r\n" + ex.StackTrace); fail++; } //progressBar.Value = (int)(((double)(count - i) / count) * 100); } //MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); if (fail > 0) { //MessageBox.Show(this, ""); } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception ex) { MessageBox.Show(this, "Error occurred retrieving mail. " + ex.Message, "POP3 Retrieval"); } progressBar1.Value = progressBar1.Maximum; MessageBox.Show("Selesai, selamat untuk yang menang :)", "", MessageBoxButtons.OK, MessageBoxIcon.Information); }
public static List <MessagePart> Get(MessagePart messagePart) { return(getSingleMessagePart(messagePart)); }
/// <summary> /// Reflects over some <see cref="IMessage"/>-implementing type /// and prepares to serialize/deserialize instances of that type. /// </summary> private void ReflectMessageType() { this.mapping = new Dictionary<string, MessagePart>(); Type currentType = this.MessageType; do { foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) { if (member is PropertyInfo || member is FieldInfo) { MessagePartAttribute partAttribute = (from a in member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>() orderby a.MinVersionValue descending where a.MinVersionValue <= this.MessageVersion where a.MaxVersionValue >= this.MessageVersion select a).FirstOrDefault(); if (partAttribute != null) { MessagePart part = new MessagePart(member, partAttribute); if (this.mapping.ContainsKey(part.Name)) { Logger.Messaging.WarnFormat( "Message type {0} has more than one message part named {1}. Inherited members will be hidden.", this.MessageType.Name, part.Name); } else { this.mapping.Add(part.Name, part); } } } } currentType = currentType.BaseType; } while (currentType != null); BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; this.Constructors = this.MessageType.GetConstructors(flags); }
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; if (listMessages.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag; if (selectedMessagePart.IsText) { messageTextBox.Text = selectedMessagePart.GetBodyAsText(); } else { messageTextBox.Text = "This part of the email is not text"; } } else { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { messageTextBox.Text = plainTextPart.GetBodyAsText(); } listAttachments.Nodes.Clear(); List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName)); addedNode.Tag = attachment; } DataSet dataSet = new DataSet(); DataTable table = dataSet.Tables.Add("Headers"); table.Columns.Add("Header"); table.Columns.Add("Value"); DataRowCollection rows = table.Rows; foreach (RfcMailAddress cc in message.Headers.Cc) { rows.Add(new object[] { "Cc", cc }); } foreach (RfcMailAddress bcc in message.Headers.Bcc) { rows.Add(new object[] { "Bcc", bcc }); } foreach (RfcMailAddress to in message.Headers.To) { rows.Add(new object[] { "To", to }); } rows.Add(new object[] { "From", message.Headers.From }); rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo }); rows.Add(new object[] { "Date", message.Headers.Date }); rows.Add(new object[] { "Subject", message.Headers.Subject }); gridHeaders.DataMember = table.TableName; gridHeaders.DataSource = dataSet; } }
/// <summary> /// Invokes the subscriber. /// </summary> /// <param name="msg">A reference to the subscribed message.</param> /// <param name="session">The current <see cref="VocollectSession"/> object.</param> /// <exception cref="WarehouseAdapterException"> /// </exception> /// <exception cref="MessageEngineException"> /// </exception> public override void Invoke(MultiPartMessage msg, VocollectSession session) { MultiPartMessage responseMsg = CreateResponseMessage(msg); try { CorrelationContext context; if (!string.IsNullOrEmpty(session.ReadAsString("PBROWID"))) { /* Refresh rows in status Registrated before the shorts pass */ MultiPartMessage refreshMsg = CreateRequestMessage("wlvoicepick", "refresh_pickorderrows", session); refreshMsg.Properties.Write("TERID_I", session.ReadAsString("TERID")); refreshMsg.Properties.Write("PBHEADID_I", session.ReadAsString("PBHEADID")); refreshMsg.Properties.Write("EMPID_I", session.ReadAsString("EMPID")); refreshMsg.Properties.Write("ALMID_O", ""); MessageEngine.Instance.TransmitRequestMessage(refreshMsg, refreshMsg.MessageId, out context); } MultiPartMessage whMsg = CreateRequestMessage("wlvoicepick", "get_mt_pbrow", session); whMsg.Properties.Write("TERID_I", session.ReadAsString("TERID")); whMsg.Properties.Write("PBHEADID_I", session.ReadAsString("PBHEADID")); whMsg.Properties.Write("NLANGCOD_I", session.ReadAsString("NLANGCOD")); whMsg.Properties.Write("PBROW_Cur_O", new object()); whMsg.Properties.Write("ALMID_O", ""); MessageEngine.Instance.TransmitRequestMessage(whMsg, whMsg.MessageId, out context); PropertyCollection properties = context.ResponseMessages[0].Parts[0].Properties; string prevContainer = ""; string prevLocation = ""; int rowCount = 0; foreach (MessagePart part in context.ResponseMessages[0].Parts) { string status = null; double pickQty = 0; if ((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Finished) && (part.Properties.ReadAsDouble("PICKQTY") < part.Properties.ReadAsDouble("ORDQTY"))) { rowCount++; status = "G"; //Go back for shortage pickQty = part.Properties.ReadAsDouble("ORDQTY") - part.Properties.ReadAsDouble("PICKQTY"); } else if (((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Started) || (part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Registrated)) && (!string.IsNullOrEmpty(session.ReadAsString("PBROWID")))) { rowCount++; status = "S"; //Skipped pickQty = part.Properties.ReadAsDouble("ORDQTY"); } else if ((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Started) || (part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Registrated)) { rowCount++; status = "N"; //Not picked pickQty = part.Properties.ReadAsDouble("ORDQTY"); } else { status = "P"; //Picked } MessagePart responsePart = new VocollectMessagePart(); responsePart.Properties.Write("Status", status); responsePart.Properties.Write("BaseItem", "0"); responsePart.Properties.Write("Sequence", part.Properties.Read("PBROWID")); /* Check if multiple picks for same location and pick load carrier */ if ((prevLocation == part.Properties.ReadAsString("PPKEY")) && (prevContainer == part.Properties.ReadAsString("SEQNUM")) && (session.ReadAsInt("NOCARS") == 1)) { /* Append PBROWID to make location unique to prevent terminal from merging the lines */ responsePart.Properties.Write("LocationId", string.Format("{0}|{1}|{2}", part.Properties.Read("PPKEY"), part.Properties.ReadAsString("ITEID"), part.Properties.Read("PBROWID"))); } else { /*Append PAKID to make location unique for each pick package. Will prevent terminal from merging different pick packages*/ responsePart.Properties.Write("LocationId", string.Format("{0}|{1}|{2}", part.Properties.Read("PPKEY"), part.Properties.ReadAsString("ITEID"), part.Properties.Read("PAKID"))); } responsePart.Properties.Write("Region", "0"); /* VOICEPICK013 = 'Go to area {0}' */ string preAisle = GetCachedAlarmText("VOICEPICK013", session); preAisle = string.Format(preAisle, part.Properties.ReadAsString("WSNAME").PadRight(35, ' ')); responsePart.Properties.Write("PreAisleDirection", preAisle); responsePart.Properties.Write("Aisle", part.Properties.ReadAsString("AISLE").PadRight(3, ' ')); responsePart.Properties.Write("PostAisleDirection", ""); string slot = part.Properties.ReadAsString("WPADR"); string itemLoadId = part.Properties.ReadAsString("ITEID"); if (!string.IsNullOrEmpty(itemLoadId)) { if (itemLoadId.Length > session.ReadAsInt("VOICE_DIGITS_ITEID")) { itemLoadId = itemLoadId.Substring(itemLoadId.Length - session.ReadAsInt("VOICE_DIGITS_ITEID"), session.ReadAsInt("VOICE_DIGITS_ITEID")); } } if ((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Registrated) || (((part.Properties.ReadAsString("ITEVERIFY") == "1") || (part.Properties.ReadAsString("ITETRACE") == "1")) && (string.IsNullOrEmpty(part.Properties.ReadAsString("ITEID"))))) { /* No item load found */ slot += "," + GetCachedAlarmText("VOICEPICK010", session); } else if (part.Properties.ReadAsString("ITEVERIFY") == "1") { /* Append verify item load id to slot */ slot += string.Format("," + GetCachedAlarmText("VOICEPICK008", session), itemLoadId); } else if (part.Properties.ReadAsString("ITEVERIFY") == "2") { /* Append verify lot to slot */ string lot = part.Properties.ReadAsString("PRODLOT"); if (!string.IsNullOrEmpty(lot)) { if (lot.Length > session.ReadAsInt("VOICE_CHARS_PRODLOT")) { lot = lot.Substring(lot.Length - session.ReadAsInt("VOICE_CHARS_PRODLOT"), session.ReadAsInt("VOICE_CHARS_PRODLOT")); } } slot += string.Format("," + GetCachedAlarmText("VOICEPICK017", session), lot); } else if (!string.IsNullOrEmpty(part.Properties.ReadAsString("ITEID"))) { /* Append item load id to slot */ slot += string.Format("," + GetCachedAlarmText("VOICEPICK009", session), itemLoadId); } responsePart.Properties.Write("Slot", slot.PadRight(64, ' ')); responsePart.Properties.Write("QuantityToPick", pickQty); responsePart.Properties.Write("UnitOfMeasure", part.Properties.ReadAsString("PAKNAME").Replace('"', ' ')); responsePart.Properties.Write("ItemNumber", part.Properties.Read("ARTID")); responsePart.Properties.Write("VariableWeight", part.Properties.Read("MEASURE")); /* Convert weight tolerances from per LUM to per package */ double baseQty = part.Properties.ReadAsDouble("BASEQTY"); if (string.IsNullOrEmpty(part.Properties.ReadAsString("MEASQTYLOTOL"))) { responsePart.Properties.Write("VariableWeightMinimum", "000000.0000"); } else { double weightMinimum = part.Properties.ReadAsDouble("MEASQTYLOTOL") * baseQty; responsePart.Properties.Write("VariableWeightMinimum", weightMinimum); } if (string.IsNullOrEmpty(part.Properties.ReadAsString("MEASQTYUPTOL"))) { responsePart.Properties.Write("VariableWeightMaximum", "999999.0000"); } else { double weightMaximum = part.Properties.ReadAsDouble("MEASQTYUPTOL") * baseQty; responsePart.Properties.Write("VariableWeightMaximum", weightMaximum); } responsePart.Properties.Write("QuantityPicked", "".PadLeft(5, '0')); #region Check digits, product verification id and item load id string checkDigits = part.Properties.ReadAsString("PPCODE"); if (part.Properties.ReadAsString("ITEVERIFY") == "1") { /* Verify pick location by item load id */ string verifyItemLoadId = part.Properties.ReadAsString("ITEID"); if (!string.IsNullOrEmpty(verifyItemLoadId)) { if (verifyItemLoadId.Length > session.ReadAsInt("VOICE_MIN_DIGITS_ITEVERIFY")) { verifyItemLoadId = verifyItemLoadId.Substring(verifyItemLoadId.Length - session.ReadAsInt("VOICE_MIN_DIGITS_ITEVERIFY"), session.ReadAsInt("VOICE_MIN_DIGITS_ITEVERIFY")); } } if ((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Registrated) || ((part.Properties.ReadAsString("ITEVERIFY") == "1") && (string.IsNullOrEmpty(part.Properties.ReadAsString("ITEID"))))) { responsePart.Properties.Write("CheckDigits", ""); responsePart.Properties.Write("ScanProductId", part.Properties.ReadAsString("ITEID")); responsePart.Properties.Write("SpokenProductId", "00000"); } else { responsePart.Properties.Write("CheckDigits", "0"); responsePart.Properties.Write("ScanProductId", part.Properties.ReadAsString("ITEID")); responsePart.Properties.Write("SpokenProductId", verifyItemLoadId); } } else if (part.Properties.ReadAsString("ITEVERIFY") == "2") { /* Verify pick location by lot */ string verifyLot = part.Properties.ReadAsString("PRODLOT"); if (!string.IsNullOrEmpty(verifyLot)) { if (verifyLot.Length > session.ReadAsInt("VOICE_MIN_CHARS_PRODLOTVERIFY")) { verifyLot = verifyLot.Substring(verifyLot.Length - session.ReadAsInt("VOICE_MIN_CHARS_PRODLOTVERIFY"), session.ReadAsInt("VOICE_MIN_CHARS_PRODLOTVERIFY")); } } responsePart.Properties.Write("CheckDigits", "0"); responsePart.Properties.Write("ScanProductId", part.Properties.ReadAsString("PRODLOT")); responsePart.Properties.Write("SpokenProductId", verifyLot); } else if ((part.Properties.ReadAsString("PPVERIFY") == PPVERIFY_ARTID) || (part.Properties.ReadAsString("PPVERIFY") == PPVERIFY_EANDUN)) { /* Verify pick location by ARTID or EANDUN */ if (!string.IsNullOrEmpty(checkDigits)) { if (checkDigits.Length > session.ReadAsInt("VOICE_MIN_DIGITS_PPCODE")) { checkDigits = checkDigits.Substring(checkDigits.Length - session.ReadAsInt("VOICE_MIN_DIGITS_PPCODE"), session.ReadAsInt("VOICE_MIN_DIGITS_PPCODE")); } } responsePart.Properties.Write("CheckDigits", "0"); /* If the system hasn't found any item load dont verify anything */ if ((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Registrated) && (string.IsNullOrEmpty(part.Properties.ReadAsString("ITEID")))) { responsePart.Properties.Write("CheckDigits", ""); } responsePart.Properties.Write("ScanProductId", checkDigits); responsePart.Properties.Write("SpokenProductId", checkDigits); } else { /* Verify pick location by pick location code */ if (!string.IsNullOrEmpty(checkDigits)) { if (checkDigits.Length > session.ReadAsInt("VOICE_MIN_DIGITS_PPCODE")) { checkDigits = checkDigits.Substring(checkDigits.Length - session.ReadAsInt("VOICE_MIN_DIGITS_PPCODE"), session.ReadAsInt("VOICE_MIN_DIGITS_PPCODE")); } long temp; if (!long.TryParse(checkDigits, out temp)) { checkDigits = ""; } } responsePart.Properties.Write("CheckDigits", checkDigits); responsePart.Properties.Write("ScanProductId", ""); responsePart.Properties.Write("SpokenProductId", ""); /* If the system hasn't found any item load dont verify anything */ if (((part.Properties.ReadAsString("PBROWSTAT") == PBROWSTAT_Registrated) || (part.Properties.ReadAsString("ITETRACE") == "1")) && (string.IsNullOrEmpty(part.Properties.ReadAsString("ITEID")))) { responsePart.Properties.Write("CheckDigits", ""); responsePart.Properties.Write("ScanProductId", part.Properties.ReadAsString("ITEID")); responsePart.Properties.Write("SpokenProductId", "00000"); } } #endregion responsePart.Properties.Write("Description", part.Properties.ReadAsString("ARTNAME1").Replace('"', ' ')); responsePart.Properties.Write("Size", ""); if (part.Properties.ReadAsString("PPVERIFY") == PPVERIFY_EANDUN) { responsePart.Properties.Write("UniversalProductCode", part.Properties.Read("PPCODE")); } else { responsePart.Properties.Write("UniversalProductCode", ""); } responsePart.Properties.Write("WorkId", "1"); responsePart.Properties.Write("DeliveryLocation", ""); responsePart.Properties.Write("Dummy", ""); responsePart.Properties.Write("Store", ""); responsePart.Properties.Write("CaseLabelCheckDigit", ""); responsePart.Properties.Write("TargetContainer", part.Properties.ReadAsString("SEQNUM").PadLeft(session.ReadAsInt("VOICE_MIN_DIGITS_CARCODE"), '0')); if (part.Properties.ReadAsString("SERIAL") == "1") { responsePart.Properties.Write("CaptureLot", "1"); responsePart.Properties.Write("LotText", GetCachedAlarmText("VOICEPICK006", session)); } else if ((part.Properties.ReadAsString("PRODLOT_VER") == "1") && (string.IsNullOrEmpty(part.Properties.ReadAsString("PRODLOTREQ")))) { responsePart.Properties.Write("CaptureLot", "1"); responsePart.Properties.Write("LotText", GetCachedAlarmText("VOICEPICK004", session)); } else { responsePart.Properties.Write("CaptureLot", "0"); responsePart.Properties.Write("LotText", ""); } responsePart.Properties.Write("PickMessage", part.Properties.ReadAsString("INSTRUCTIONS")); string verifyLocation = "0"; if (session.ReadAsString("VOICE_VERIFY_PP_BALANCE") == "1") { verifyLocation = "1"; } else if ((session.ReadAsString("VOICE_VERIFY_PP_BALANCE") == "2") && (status == "G")) { verifyLocation = "1"; } responsePart.Properties.Write("VerifyLocation", verifyLocation); responsePart.Properties.Write("CycleCount", "0"); responsePart.Properties.Write("CustomerId", PrTaskLUTContainer.GetCotainerHashCode(part)); if (part.Properties.ReadAsString("SERIAL") == "1") { responsePart.Properties.Write("PutLotPrompt", GetCachedAlarmText("VOICEPICK005", session)); } else if (part.Properties.ReadAsString("PRODLOT_VER") == "1") { responsePart.Properties.Write("PutLotPrompt", GetCachedAlarmText("VOICEPICK003", session)); } else { responsePart.Properties.Write("PutLotPrompt", ""); } responsePart.Properties.Write("ErrorCode", VocollectErrorCodeNoError); responsePart.Properties.Write("Message", ""); responseMsg.Parts.Add(responsePart); prevLocation = part.Properties.ReadAsString("PPKEY"); prevContainer = part.Properties.ReadAsString("SEQNUM"); } //Reset session values session.Write("PBROW_COUNT", rowCount); session.Write("SPLIT_PBROWID", ""); session.Write("SPLIT_STATUS", "0"); session.Write("PREV_PPKEY", ""); session.Write("RESTCOD", ""); session.Write("PRODLOT", ""); session.Write("PRODLOTQTY", 0d); } catch (WarehouseAdapterException ex) { responseMsg.Parts.Clear(); MessagePart part = CreateEmptyMessagePart(35); part.Properties.Write("ErrorCode", WarehouseAlarm); part.Properties.Write("Message", ex.Message); responseMsg.Parts.Add(part); throw; } catch (Exception) { responseMsg.Parts.Clear(); MessagePart part = CreateEmptyMessagePart(35); part.Properties.Write("ErrorCode", VocollectErrorCodeCritialError); part.Properties.Write("Message", GetCriticalErrorMessageText(msg)); responseMsg.Parts.Add(part); throw; } finally { TransmitResponseMessage(responseMsg, session); } }
public void Remove (MessagePart messagePart) { List.Remove (messagePart); }
public void Insert (int index, MessagePart messagePart) { List.Insert (index, messagePart); }
public int IndexOf (MessagePart messagePart) { return List.IndexOf (messagePart); }
public void CopyTo (MessagePart[] array, int index) { List.CopyTo (array, index); }
public bool Contains (MessagePart messagePart) { return List.Contains (messagePart); }
/// <summary> /// Adds default messages and namespaces as well as the default targetNamespace to a WSDL ServiceDescription and writes it to target location. /// </summary> /// <param name="collaborationRoleName">The collaborationRolename retrieved from the UMM model.</param> private void finalizeAndWriteServiceDescription(string collaborationRoleName) { //Imports var defaultMessagesImport = new Import { Namespace = "http://bas", Location = "bas.xsd" }; serviceDescription.Imports.Add(defaultMessagesImport); if (!containsInnerXML) { foreach (RetrievedMessage message in targetXSDs.Items) { if (!message.filePath.Equals(string.Empty)) { serviceDescription.Imports.Add(new Import { Namespace = message.targetNamespace, Location = message.filePath }); } } } //Messages var ackReceiptMessagePart = new MessagePart { Name = "parameters", Element = new XmlQualifiedName("Acknowledgement", "http://bas") }; var ackReceiptMessage = new Message { Name = "Acknowledgement" }; ackReceiptMessage.Parts.Add(ackReceiptMessagePart); serviceDescription.Messages.Add(ackReceiptMessage); var controlFailureMessagePart = new MessagePart { Name = "parameters", Element = new XmlQualifiedName("ControlFailure", "http://bas") }; var controlFailureMessage = new Message { Name = "BusinessSignalControlFailure" }; controlFailureMessage.Parts.Add(controlFailureMessagePart); serviceDescription.Messages.Add(controlFailureMessage); //TargetNamespace serviceDescription.TargetNamespace = "http://" + collaborationRoleName; //Namespaces serviceDescription.Namespaces.Add("wsdl", "http://schemas.xmlsoap.org/wsdl/"); serviceDescription.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema"); serviceDescription.Namespaces.Add("soap", "http://schemas.xmlsoap.org/wsdl/soap/"); serviceDescription.Namespaces.Add("bas", "http://bas"); serviceDescription.Namespaces.Add("tns", "http://" + collaborationRoleName); if (!containsInnerXML) { var i = 1; foreach (RetrievedMessage message in targetXSDs.Items) { if (!message.filePath.Equals(string.Empty)) { if (message.prefix.Equals(string.Empty)) { message.prefix = "xsd" + i; } serviceDescription.Namespaces.Add(message.prefix, message.targetNamespace); i++; } } } else { serviceDescription.Namespaces.Add("il", "http://inline"); } serviceDescription.Write(outputDirectory + "\\" + collaborationRoleName + ".wsdl"); }
private static List <MessagePart> CreateMessageParts(Packet message, int mtuSize, RaknetSession session) { Memory <byte> encodedMessage = message.Encode(); if (encodedMessage.IsEmpty) { return(new List <MessagePart>(0)); } if (message.IsMcpe) { Log.Error($"Got bedrock message in unexpected place {message.GetType().Name}"); } int maxPayloadSizeNoSplit = mtuSize - RaknetHandler.UdpHeaderSize - 4 - GetHeaderSize(message.ReliabilityHeader, false); bool split = encodedMessage.Length >= maxPayloadSizeNoSplit; List <(int @from, int length)> splits = ArraySplit(encodedMessage.Length, mtuSize - RaknetHandler.UdpHeaderSize - 4 /*datagram header*/ - GetHeaderSize(message.ReliabilityHeader, split)); int count = splits.Count; if (count == 0) { Log.Warn("Got zero parts back from split"); } if (count <= 1) { var messagePart = MessagePart.CreateObject(); messagePart.ReliabilityHeader.Reliability = message.ReliabilityHeader.Reliability; messagePart.ReliabilityHeader.ReliableMessageNumber = Interlocked.Increment(ref session.ReliableMessageNumber); messagePart.ReliabilityHeader.OrderingChannel = 0; messagePart.ReliabilityHeader.OrderingIndex = message.ReliabilityHeader.OrderingIndex; messagePart.ReliabilityHeader.HasSplit = false; messagePart.Buffer = encodedMessage; return(new List <MessagePart>(1) { messagePart }); } // Stupid but scared to change it .. remove the -100 when i feel "safe" if (session.SplitPartId > short.MaxValue - 100) { Interlocked.CompareExchange(ref session.SplitPartId, 0, short.MaxValue); } if (message.ReliabilityHeader.Reliability == Reliability.Unreliable) { message.ReliabilityHeader.Reliability = Reliability.Reliable; } int index = 0; short splitId = (short)Interlocked.Increment(ref session.SplitPartId); var messageParts = new List <MessagePart>(count); foreach ((int from, int length)span in splits) { var messagePart = MessagePart.CreateObject(); messagePart.ReliabilityHeader.Reliability = message.ReliabilityHeader.Reliability; messagePart.ReliabilityHeader.ReliableMessageNumber = Interlocked.Increment(ref session.ReliableMessageNumber); messagePart.ReliabilityHeader.OrderingChannel = 0; messagePart.ReliabilityHeader.OrderingIndex = message.ReliabilityHeader.OrderingIndex; messagePart.ReliabilityHeader.HasSplit = count > 1; messagePart.ReliabilityHeader.PartCount = count; messagePart.ReliabilityHeader.PartId = splitId; messagePart.ReliabilityHeader.PartIndex = index++; messagePart.Buffer = encodedMessage.Slice(span.@from, span.length); messageParts.Add(messagePart); } return(messageParts); }
private void Tasking_Click(object sender, EventArgs e) { SqlConnection connection; int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode); Message message = messages[messageNumber]; MessagePart plainTextPart = message.FindFirstPlainTextVersion(); String connetionString = GetConnectionString(); connection = new SqlConnection(connetionString); int maxId = 0; //reader try { //open connection connection.Open(); //command1 String sqlGetMaxId = "select MAX(Id) from Emails"; SqlCommand command1 = new SqlCommand(sqlGetMaxId, connection); using (SqlDataReader rdr = command1.ExecuteReader()) { while (rdr.Read()) { if (!rdr.IsDBNull(0)) { maxId = rdr.GetInt32(0); } } } command1.Dispose(); //command2 String sqlInsertEmail = "Insert into Emails(EmailSubject, Body, EmailFrom, EmailReplyTo, EmailDate) Values('" + message.Headers.Subject + "','" + plainTextPart.GetBodyAsText() + "','" + message.Headers.From + "','" + message.Headers.ReplyTo + "','" + message.Headers.Date + "')"; SqlCommand command2 = new SqlCommand(sqlInsertEmail, connection); command2.ExecuteNonQuery(); command2.Dispose(); //command3 List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { String sqlInsertAttachment = "Insert into Attachments(EmailId, AttachmentName) Values('" + (maxId + 1) + "','" + attachment.FileName + "')"; SqlCommand command3 = new SqlCommand(sqlInsertAttachment, connection); command3.ExecuteNonQuery(); command3.Dispose(); } //close connection connection.Close(); if (listMessages.SelectedNode != null) { listMessages.SelectedNode.BackColor = Color.Yellow; } } catch (Exception ex) { MessageBox.Show("Error while saving data to DB! "); } }
/// <summary> /// For a concrete implementation an answer must be returned for a leaf <see cref="MessagePart"/>, which are /// MessageParts that are not <see cref="MessagePart.IsMultiPart">MultiParts.</see> /// </summary> /// <param name="messagePart">The message part which is a leaf and thereby not a MultiPart</param> /// <returns>An answer</returns> protected abstract TAnswer CaseLeaf(MessagePart messagePart);
/// <summary> /// Invokes the subscriber. /// </summary> /// <param name="msg">A reference to the subscribed message.</param> /// <param name="session">The current <see cref="VocollectSession"/> object.</param> /// <exception cref="WarehouseAdapterException"> /// </exception> /// <exception cref="MessageEngineException"> /// </exception> public override void Invoke(MultiPartMessage msg, VocollectSession session) { MultiPartMessage responseMsg = CreateResponseMessage(msg); try { using (TransactionScope transactionScope = new TransactionScope()) { CorrelationContext context; if (!string.IsNullOrEmpty(session.ReadAsString("TUID"))) { MultiPartMessage tuMsg = CreateRequestMessage("wlvoicepick", "disconnect_ter_from_pt", session); tuMsg.Properties.Write("TERID_I", session.ReadAsString("TERID")); tuMsg.Properties.Write("TUID_I", session.ReadAsString("TUID")); tuMsg.Properties.Write("KEEP_ONLINE_I", "0"); tuMsg.Properties.Write("ALMID_O", ""); MessageEngine.Instance.TransmitRequestMessage(tuMsg, tuMsg.MessageId, out context); } MultiPartMessage whMsg = CreateRequestMessage("wlvoicepick", "connect_ter_to_pt", session); whMsg.Properties.Write("TUID_I", msg.Properties.ReadAsString("VehicleId")); whMsg.Properties.Write("TERID_I", session.ReadAsString("TERID")); whMsg.Properties.Write("PBHEADID_I", session.ReadAsString("PBHEADID")); whMsg.Properties.Write("TUID_O", ""); whMsg.Properties.Write("ALMID_O", ""); MessageEngine.Instance.TransmitRequestMessage(whMsg, whMsg.MessageId, out context); MessagePart responsePart = new VocollectMessagePart(); responsePart.Properties.Write("SafetyCheck", ""); responsePart.Properties.Write("ErrorCode", VocollectErrorCodeNoError); responsePart.Properties.Write("Message", ""); responseMsg.Parts.Add(responsePart); session.Write("TUID", context.ResponseMessages[0].Properties.ReadAsString("TUID_O")); session.Write("UPDATE_PBCAR", "1"); transactionScope.Complete(); } } catch (WarehouseAdapterException ex) { responseMsg.Parts.Clear(); MessagePart part = CreateEmptyMessagePart(3); part.Properties.Write("ErrorCode", WarehouseAlarm); part.Properties.Write("Message", ex.Message); responseMsg.Parts.Add(part); throw; } catch (Exception) { responseMsg.Parts.Clear(); MessagePart part = CreateEmptyMessagePart(3); part.Properties.Write("ErrorCode", VocollectErrorCodeCritialError); part.Properties.Write("Message", GetCriticalErrorMessageText(msg)); responseMsg.Parts.Add(part); throw; } finally { TransmitResponseMessage(responseMsg, session); } }
public static bool Delete(MessagePart messagePart) { return(deleteMessagePart(messagePart)); }
public void ReadMail() { try { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(emailaccount.POP3, Convert.ToInt32(emailaccount.POP3port), emailaccount.IsSecured); pop3Client.Authenticate(emailaccount.emailid, emailaccount.password); // int MessageNum; int count = pop3Client.GetMessageCount(); var Emails = new List <POPEmail>(); int counter = 0; for (int i = count; i >= 1; i--) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); POPEmail email = new POPEmail() { // MessageNumber = i, MessageNumber = message.Headers.MessageId, // message.Headers.Received. //MessageNum=MessageNumber, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address, //From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstPlainTextVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } InsertEmailMessages(email.MessageNumber, email.Subject, email.DateSent, email.From, email.Body); Emails.Add(email); counter++; //if (counter > 2) //{ // break; //} } var emails = Emails; } catch (Exception ex) { // continue; throw ex; } }
public int Add (MessagePart messagePart) { Insert (Count, messagePart); return (Count - 1); }
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { // Fetch out the selected message Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; // If the selected node contains a MessagePart and we can display the contents - display them if (listMessages.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag; if (selectedMessagePart.IsText) { // We can show text MessageParts messageTextBox.Text = selectedMessagePart.GetBodyAsText(); } else { // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...) messageTextBox.Text = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>"; } } else { // If the selected node is not a subnode and therefore does not // have a MessagePart in it's Tag property, we genericly find some content to show // Find the first text/plain version MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one messageTextBox.Text = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { messageTextBox.Text = textVersions[0].GetBodyAsText(); } else { messageTextBox.Text = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } // Clear the attachment list from any previus shown attachments listAttachments.Nodes.Clear(); // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { // Add the attachment to the list of attachments TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName)); // Keep a reference to the attachment in the Tag property addedNode.Tag = attachment; } // Only show that attachmentPanel if there is attachments in the message bool hadAttachments = attachments.Count > 0; attachmentPanel.Visible = hadAttachments; // Generate header table DataSet dataSet = new DataSet(); DataTable table = dataSet.Tables.Add("Headers"); table.Columns.Add("Header"); table.Columns.Add("Value"); DataRowCollection rows = table.Rows; // Add all known headers rows.Add(new object[] { "Content-Description", message.Headers.ContentDescription }); rows.Add(new object[] { "Content-Id", message.Headers.ContentId }); foreach (string keyword in message.Headers.Keywords) { rows.Add(new object[] { "Keyword", keyword }); } foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo) { rows.Add(new object[] { "Disposition-Notification-To", dispositionNotificationTo }); } foreach (Received received in message.Headers.Received) { rows.Add(new object[] { "Received", received.Raw }); } rows.Add(new object[] { "Importance", message.Headers.Importance }); rows.Add(new object[] { "Content-Transfer-Encoding", message.Headers.ContentTransferEncoding }); foreach (RfcMailAddress cc in message.Headers.Cc) { rows.Add(new object[] { "Cc", cc }); } foreach (RfcMailAddress bcc in message.Headers.Bcc) { rows.Add(new object[] { "Bcc", bcc }); } foreach (RfcMailAddress to in message.Headers.To) { rows.Add(new object[] { "To", to }); } rows.Add(new object[] { "From", message.Headers.From }); rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo }); foreach (string inReplyTo in message.Headers.InReplyTo) { rows.Add(new object[] { "In-Reply-To", inReplyTo }); } foreach (string reference in message.Headers.References) { rows.Add(new object[] { "References", reference }); } rows.Add(new object[] { "Sender", message.Headers.Sender }); rows.Add(new object[] { "Content-Type", message.Headers.ContentType }); rows.Add(new object[] { "Content-Disposition", message.Headers.ContentDisposition }); rows.Add(new object[] { "Date", message.Headers.Date }); rows.Add(new object[] { "Date", message.Headers.DateSent }); rows.Add(new object[] { "Message-Id", message.Headers.MessageId }); rows.Add(new object[] { "Mime-Version", message.Headers.MimeVersion }); rows.Add(new object[] { "Return-Path", message.Headers.ReturnPath }); rows.Add(new object[] { "Subject", message.Headers.Subject }); // Add all unknown headers foreach (string key in message.Headers.UnknownHeaders) { string[] values = message.Headers.UnknownHeaders.GetValues(key); if (values != null) { foreach (string value in values) { rows.Add(new object[] { key, value }); } } } // Now set the headers displayed on the GUI to the header table we just generated gridHeaders.DataMember = table.TableName; gridHeaders.DataSource = dataSet; }
public async void load(int numberMail) { IProgress <int> progress = new Progress <int>(value => { progressBar1.Value = value; }); progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Step = 1; Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); var client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate("recent:[email protected]", "vnfkfkxlcgpnebra"); List <string> uids = client.GetMessageUids(); List <OpenPop.Mime.Message> AllMsgReceived = new List <OpenPop.Mime.Message>(); SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alexandre\Source\Repos\MailApplication\MailManager\DB\database1.mdf;Integrated Security=True"); ManageDB.RemoveMail(con); List <string> seenUids = new List <string>(); int messageCount = client.GetMessageCount(); progressBar1.Maximum = numberMail; await Task.Run(() => { firstkeer = false; for (int i = messageCount; i >= (messageCount - numberMail); i--) { progress.Report(messageCount - i); OpenPop.Mime.Message unseenMessage = client.GetMessage(i); AllMsgReceived.Add(unseenMessage); } var mails = new List <Mail>(); MessagePart plainTextPart = null, HTMLTextPart = null; string pattern = @"[A-Za-z0-9]*[@]{1}[A-Za-z0-9]*[.\]{1}[A-Za-z]*"; int a = 0; foreach (var msg in AllMsgReceived) { //Check you message is not null if (msg != null) { plainTextPart = msg.FindFirstPlainTextVersion(); //HTMLTextPart = msg.FindFirstHtmlVersion(); //mail.Html = (HTMLTextPart == null ? "" : HTMLTextPart.GetBodyAsText().Trim()); //ajouter au serveur //mails.Add(new Mail { From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim()), Attachment = msg.FindAllAttachments() }); ManageDB.AddMailToDB( new Mail { From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim()), Attachment = msg.FindAllAttachments(), Reference = a += 1 }, con); } } ManageDB.AddNewContact(con); //LoadApp.mail = mails; successLoad = true; }); label1.Text = ""; button1.Show(); }
// Methods public int Add(MessagePart messagePart) {}
protected override void VisitMessage(MessagePart entity) { Message++; base.VisitMessage(entity); }
public void Insert(int index, MessagePart messagePart) {}
protected override void VisitMessagePart(MessagePart entity) { // treat message/rfc822 parts as attachments handleAttachment(entity, null); }
public int IndexOf(MessagePart messagePart) {}
public static void Main() { try { ServiceDescription myDescription = ServiceDescription.Read("Operation_2_Input_CS.wsdl"); Binding myBinding = new Binding(); myBinding.Name = "Operation_2_ServiceHttpPost"; XmlQualifiedName myQualifiedName = new XmlQualifiedName("s0:Operation_2_ServiceHttpPost"); myBinding.Type = myQualifiedName; HttpBinding myHttpBinding = new HttpBinding(); myHttpBinding.Verb="POST"; // Add the 'HttpBinding' to the 'Binding'. myBinding.Extensions.Add(myHttpBinding); OperationBinding myOperationBinding = new OperationBinding(); myOperationBinding.Name = "AddNumbers"; HttpOperationBinding myHttpOperationBinding = new HttpOperationBinding(); myHttpOperationBinding.Location="/AddNumbers"; // Add the 'HttpOperationBinding' to 'OperationBinding'. myOperationBinding.Extensions.Add(myHttpOperationBinding); InputBinding myInputBinding = new InputBinding(); MimeContentBinding myPostMimeContentbinding = new MimeContentBinding(); myPostMimeContentbinding.Type="application/x-www-form-urlencoded"; myInputBinding.Extensions.Add(myPostMimeContentbinding); // Add the 'InputBinding' to 'OperationBinding'. myOperationBinding.Input = myInputBinding; OutputBinding myOutputBinding = new OutputBinding(); MimeXmlBinding myPostMimeXmlbinding = new MimeXmlBinding(); myPostMimeXmlbinding .Part="Body"; myOutputBinding.Extensions.Add(myPostMimeXmlbinding); // Add the 'OutPutBinding' to 'OperationBinding'. myOperationBinding.Output = myOutputBinding; // Add the 'OperationBinding' to 'Binding'. myBinding.Operations.Add(myOperationBinding); // Add the 'Binding' to 'BindingCollection' of 'ServiceDescription'. myDescription.Bindings.Add(myBinding); Port myPostPort = new Port(); myPostPort.Name = "Operation_2_ServiceHttpPost"; myPostPort.Binding = new XmlQualifiedName("s0:Operation_2_ServiceHttpPost"); HttpAddressBinding myPostAddressBinding = new HttpAddressBinding(); myPostAddressBinding.Location = "http://localhost/Operation_2/Operation_2_Service.cs.asmx"; // Add the 'HttpAddressBinding' to the 'Port'. myPostPort.Extensions.Add(myPostAddressBinding); // Add the 'Port' to 'PortCollection' of 'ServiceDescription'. myDescription.Services[0].Ports.Add(myPostPort); PortType myPostPortType = new PortType(); myPostPortType.Name = "Operation_2_ServiceHttpPost"; Operation myPostOperation = new Operation(); myPostOperation.Name = "AddNumbers"; OperationMessage myPostOperationInput = (OperationMessage)new OperationInput(); myPostOperationInput.Message = new XmlQualifiedName("s0:AddNumbersHttpPostIn"); OperationMessage myPostOperationOutput = (OperationMessage)new OperationOutput(); myPostOperationOutput.Message = new XmlQualifiedName("s0:AddNumbersHttpPostout"); myPostOperation.Messages.Add(myPostOperationInput); myPostOperation.Messages.Add(myPostOperationOutput); // Add the 'Operation' to 'PortType'. myPostPortType.Operations.Add(myPostOperation); // Adds the 'PortType' to 'PortTypeCollection' of 'ServiceDescription'. myDescription.PortTypes.Add(myPostPortType); Message myPostMessage1 = new Message(); myPostMessage1.Name="AddNumbersHttpPostIn"; MessagePart myPostMessagePart1 = new MessagePart(); myPostMessagePart1.Name = "firstnumber"; myPostMessagePart1.Type = new XmlQualifiedName("s:string"); MessagePart myPostMessagePart2 = new MessagePart(); myPostMessagePart2.Name = "secondnumber"; myPostMessagePart2.Type = new XmlQualifiedName("s:string"); // Add the 'MessagePart' objects to 'Messages'. myPostMessage1.Parts.Add(myPostMessagePart1); myPostMessage1.Parts.Add(myPostMessagePart2); Message myPostMessage2 = new Message(); myPostMessage2.Name = "AddNumbersHttpPostout"; MessagePart myPostMessagePart3 = new MessagePart(); myPostMessagePart3.Name = "Body"; myPostMessagePart3.Element = new XmlQualifiedName("s0:int"); // Add the 'MessagePart' to 'Message'. myPostMessage2.Parts.Add(myPostMessagePart3 ); // Add the 'Message' objects to 'ServiceDescription'. myDescription.Messages.Add(myPostMessage1); myDescription.Messages.Add(myPostMessage2); // Write the 'ServiceDescription' as a WSDL file. myDescription.Write("Operation_2_Output_CS.wsdl"); Console.WriteLine(" 'Operation_2_Output_CS.wsdl' file created Successfully"); // <Snippet1> // <Snippet2> string myString = null ; Operation myOperation = new Operation(); myDescription = ServiceDescription.Read("Operation_2_Input_CS.wsdl"); Message[] myMessage = new Message[ myDescription.Messages.Count ] ; // Copy the messages from the service description. myDescription.Messages.CopyTo( myMessage, 0 ); for( int i = 0 ; i < myDescription.Messages.Count; i++ ) { MessagePart[] myMessagePart = new MessagePart[ myMessage[i].Parts.Count ]; // Copy the message parts into a MessagePart. myMessage[i].Parts.CopyTo( myMessagePart, 0 ); for( int j = 0 ; j < myMessage[i].Parts.Count; j++ ) { myString += myMessagePart[j].Name; myString += " " ; } } // Set the ParameterOrderString equal to the list of // message part names. myOperation.ParameterOrderString = myString; string[] myString1 = myOperation.ParameterOrder; int k = 0 ; Console.WriteLine("The list of message part names is as follows:"); while( k<5 ) { Console.WriteLine( myString1[k] ); k++; } // </Snippet2> // </Snippet1> } catch( Exception e ) { Console.WriteLine( "The following Exception is raised : " + e.Message ); } }
public bool Contains(MessagePart messagePart) {}
///<summary> /// Parses the given string and converts all the messages into ValidationMessage objects. ///</summary> /// <remarks> /// Messages must be separated by <see cref="ValidationMessage.Separator"/> and may be /// marked with a severity marker prefix like <see cref="ValidationMessage.ErrorMarker"/> /// </remarks> public static IEnumerable <ValidationMessage> ParseMultiple(string value) { return (from MessagePart in value.Split(ValidationMessage.Separator[0]) select ValidationMessage.Parse(MessagePart.Trim())); }
public void Remove(MessagePart messagePart) {}
private void listMessages_AfterSelect(object sender, TreeViewEventArgs e) { listAttachements.Nodes.Clear(); nodeIndex = e.Node.Index; //Get From address txFrom.Text = messages[e.Node.Index].Headers.From.ToString(); //Get To address if (messages[e.Node.Index].Headers.To.Count == 0) { txTo.Text = string.Empty; } else { for (int i = 0; i < messages[e.Node.Index].Headers.To.Count; i++) { txTo.Text += messages[e.Node.Index].Headers.To[i].ToString(); } } //Get CC address if (messages[e.Node.Index].Headers.Cc.Count == 0) { txCC.Text = string.Empty; } else { for (int i = 0; i < messages[e.Node.Index].Headers.Cc.Count; i++) { txCC.Text += messages[e.Node.Index].Headers.Cc[i].ToString(); } } //Get Bcc address if (messages[e.Node.Index].Headers.Bcc.Count == 0) { txBCC.Text = string.Empty; } else { for (int i = 0; i < messages[e.Node.Index].Headers.Bcc.Count; i++) { txBCC.Text += messages[e.Node.Index].Headers.Bcc[i].ToString(); } } //Get Body text MessagePart body = messages[e.Node.Index].FindFirstPlainTextVersion(); if (body != null) { bodyAsText = body.GetBodyAsText(); txMessage.Text = bodyAsText; } else { txMessage.Text = "No text ! "; } //Get attachements foreach (MessagePart attachement in messages[e.Node.Index].FindAllAttachments()) { listAttachements.Nodes.Clear(); listAttachements.Nodes.Add(attachement.FileName); } }
public void CopyTo(MessagePart[] array, int index) {}
void cargar_Correo_Entrada() { try { try { string mensajError = ""; mail_Cuentas_Correo_Bus bus_correo = new mail_Cuentas_Correo_Bus(); List <mail_Cuentas_Correo_Info> lista_Correo = new List <mail_Cuentas_Correo_Info>(); lista_Correo = bus_correo.consultar(ref mensajError); var itemCuenta = lista_Correo.FirstOrDefault(q => q.direccion_correo == correo); IdCuenta = itemCuenta.IdCuenta; Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(itemCuenta.ServidorCorreoEntrante, itemCuenta.port_entrada, true); pop3Client.Authenticate(itemCuenta.direccion_correo, itemCuenta.Password); int count = pop3Client.GetMessageCount(); // int counter = 0; for (int i = count; i >= 1; i -= 1) { string MessageId = pop3Client.GetMessageHeaders(i).MessageId; if (Bus_Mensaje.Verifica_codMensajeId(MessageId) == false) { var itemIdMensaje = listaMensajes.FirstOrDefault(q => q.codMensajeId == MessageId); if (itemIdMensaje == null) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); //Para listPara = new List <string>(); foreach (var item in message.Headers.To.ToList()) { listPara.Add(item.Address); } //con copia list_concopia = new List <string>(); foreach (var item in message.Headers.Cc.ToList()) { list_concopia.Add(item.Address); } //texto mensaje selectedMessagePart = message.FindFirstPlainTextVersion(); if (selectedMessagePart != null) { if (selectedMessagePart.IsText) { valida = selectedMessagePart.GetBodyAsText(); } } Email email = new Email() { MessageNumber = i, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, Prioridad = Convert.ToString(message.Headers.Importance), // From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), // From = message.Headers.From.DisplayName, MessageId = message.Headers.MessageId, Para = para, Texto_mensaje = valida, CC = CC, To = listPara, conCopia = list_concopia }; List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } listaMail.Add(email); } } } if (listaMail.Count() == 0) { MessageBox.Show("No existen Correos de Entrada Nuevos"); return; } // gridControl2.DataSource = listaMail1; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public static void Main() { ServiceDescription myDescription = ServiceDescription.Read("AddNumbers1.wsdl"); // Create the 'Binding' object. Binding myBinding = new Binding(); myBinding.Name = "Service1HttpPost"; XmlQualifiedName qualifiedName = new XmlQualifiedName("s0:Service1HttpPost"); myBinding.Type = qualifiedName; // <Snippet1> // <Snippet2> // Create the 'HttpBinding' object. HttpBinding myHttpBinding = new HttpBinding(); myHttpBinding.Verb = "POST"; // Add the 'HttpBinding' to the 'Binding'. myBinding.Extensions.Add(myHttpBinding); // </Snippet2> // </Snippet1> // Create the 'OperationBinding' object. OperationBinding myOperationBinding = new OperationBinding(); myOperationBinding.Name = "AddNumbers"; HttpOperationBinding myOperation = new HttpOperationBinding(); myOperation.Location = "/AddNumbers"; // Add the 'HttpOperationBinding' to 'OperationBinding'. myOperationBinding.Extensions.Add(myOperation); // Create the 'InputBinding' object. InputBinding myInput = new InputBinding(); MimeContentBinding postMimeContentbinding = new MimeContentBinding(); postMimeContentbinding.Type = "application/x-www-form-urlencoded"; myInput.Extensions.Add(postMimeContentbinding); // Add the 'InputBinding' to 'OperationBinding'. myOperationBinding.Input = myInput; // Create the 'OutputBinding' object. OutputBinding myOutput = new OutputBinding(); MimeXmlBinding postMimeXmlbinding = new MimeXmlBinding(); postMimeXmlbinding.Part = "Body"; myOutput.Extensions.Add(postMimeXmlbinding); // Add the 'OutPutBinding' to 'OperationBinding'. myOperationBinding.Output = myOutput; // Add the 'OperationBinding' to 'Binding'. myBinding.Operations.Add(myOperationBinding); // Add the 'Binding' to 'BindingCollection' of 'ServiceDescription'. myDescription.Bindings.Add(myBinding); // Create a 'Port' object. Port postPort = new Port(); postPort.Name = "Service1HttpPost"; postPort.Binding = new XmlQualifiedName("s0:Service1HttpPost"); // <Snippet3> // <Snippet4> // Create the 'HttpAddressBinding' object. HttpAddressBinding postAddressBinding = new HttpAddressBinding(); postAddressBinding.Location = "http://localhost/Service1.asmx"; // Add the 'HttpAddressBinding' to the 'Port'. postPort.Extensions.Add(postAddressBinding); // </Snippet4> // </Snippet3> // Add the 'Port' to 'PortCollection' of 'ServiceDescription'. myDescription.Services[0].Ports.Add(postPort); // Create a 'PortType' object. PortType postPortType = new PortType(); postPortType.Name = "Service1HttpPost"; Operation postOperation = new Operation(); postOperation.Name = "AddNumbers"; OperationMessage postInput = (OperationMessage) new OperationInput(); postInput.Message = new XmlQualifiedName("s0:AddNumbersHttpPostIn"); OperationMessage postOutput = (OperationMessage) new OperationOutput(); postOutput.Message = new XmlQualifiedName("s0:AddNumbersHttpPostOut"); postOperation.Messages.Add(postInput); postOperation.Messages.Add(postOutput); // Add the 'Operation' to 'PortType'. postPortType.Operations.Add(postOperation); // Adds the 'PortType' to 'PortTypeCollection' of 'ServiceDescription'. myDescription.PortTypes.Add(postPortType); // Create the 'Message' object. Message postMessage1 = new Message(); postMessage1.Name = "AddNumbersHttpPostIn"; // Create the 'MessageParts'. MessagePart postMessagePart1 = new MessagePart(); postMessagePart1.Name = "firstnumber"; postMessagePart1.Type = new XmlQualifiedName("s:string"); MessagePart postMessagePart2 = new MessagePart(); postMessagePart2.Name = "secondnumber"; postMessagePart2.Type = new XmlQualifiedName("s:string"); // Add the 'MessagePart' objects to 'Messages'. postMessage1.Parts.Add(postMessagePart1); postMessage1.Parts.Add(postMessagePart2); // Create another 'Message' object. Message postMessage2 = new Message(); postMessage2.Name = "AddNumbersHttpPostOut"; MessagePart postMessagePart3 = new MessagePart(); postMessagePart3.Name = "Body"; postMessagePart3.Element = new XmlQualifiedName("s0:int"); // Add the 'MessagePart' to 'Message' postMessage2.Parts.Add(postMessagePart3); // Add the 'Message' objects to 'ServiceDescription'. myDescription.Messages.Add(postMessage1); myDescription.Messages.Add(postMessage2); // Write the 'ServiceDescription' as a WSDL file. myDescription.Write("AddNumbers.wsdl"); Console.WriteLine("WSDL file with name 'AddNumber.Wsdl' file created Successfully"); }
protected override void VisitMessagePart(MessagePart entity) { // treat message/rfc822 parts as attachments attachments.Add(entity); }
protected abstract void ImportPartsBySchemaElement(QName qname, List <MessagePartDescription> parts, Message msg, MessagePart part);
public static MessagePart PostUpdate(MessagePart messagePart) { return(postUpdateMessagePart(messagePart)); }
protected override void ImportPartsBySchemaElement(QName qname, List <MessagePartDescription> parts, Message msg, MessagePart part) { XmlSchemaElement element = (XmlSchemaElement)schema_set_in_use.GlobalElements [qname]; if (element == null) { //FIXME: What to do here? throw new Exception("Could not resolve : " + qname.ToString()); } var ct = element.ElementSchemaType as XmlSchemaComplexType; if (ct == null) // simple type { parts.Add(CreateMessagePart(element, msg, part)); } else // complex type { foreach (var elem in GetElementsInParticle(ct.ContentTypeParticle)) { parts.Add(CreateMessagePart(elem, msg, part)); } } }
private void ReceiveCallBack(IAsyncResult asyncResult) { Socket client = (Socket)asyncResult.AsyncState; if (!client.Connected) { Runing = false; return; } if (Runing) { int bytesRead = 0; try { bytesRead = client.EndReceive(asyncResult); if (bytesRead == 0) { Runing = false; this.Disconnect(); return; } List <Tuple <MessagePart, NetworkMessage> > messages = new List <Tuple <MessagePart, NetworkMessage> >(); byte[] data = new byte[bytesRead]; Array.Copy(receiveBuffer, data, bytesRead); buffer = new BigEndianReader(data); REDO_PACKET: ThreatBuffer(); var messagePart = new MessagePart(DataReceivedEventArgs.Data); NetworkMessage message = MessageReceiver.BuildMessage(messagePart.MessageId.Value, new BigEndianReader(messagePart.Data)); messages.Add(new Tuple <MessagePart, NetworkMessage>(messagePart, message)); if (buffer.BytesAvailable > 4) { goto REDO_PACKET; } foreach (var packet in messages) { if (packet.Item1.MessageId == 2000) { //Keep alive the connection if the player continue; } if (packet.Item2 == null) { if (!SimpleServer.PacketsSkipToShow.Contains(packet.Item1.MessageId.Value) && packet.Item1.Length.Value < 1000) { logger.Warn(string.Format($"[{serverConnected}] Received Unknown PacketId : {IP} -> {packet.Item1.MessageId}")); Console.WriteLine($" Body [len:{packet.Item1.Length - 5}] : [{BitConverter.ToString(packet.Item1.Data)}] {Environment.NewLine} [{Encoding.UTF8.GetString(packet.Item1.Data)}]"); } } else { if (!packet.Item2.ServerEnum.Contains(serverConnected)) { throw new Exception($"Sended Packet (Id:{packet.Item1.MessageId}) for server {packet.Item2.ServerEnum} but {serverConnected} received it !"); } if (!SimpleServer.PacketsSkipToShow.Contains(packet.Item1.MessageId.Value)) { ConsoleUtils.WriteMessageInfo(string.Format($"[RCV : {serverConnected}] {IP} -> {packet.Item2}")); Console.WriteLine($" Body [len:{packet.Item1.Length - 5}] : [{BitConverter.ToString(packet.Item1.Data)}] {Environment.NewLine} [{Encoding.UTF8.GetString(packet.Item1.Data)}]"); } PacketManager.ParseHandler(this, packet.Item2); } } if (!client.Connected) { Runing = false; return; } client.BeginReceive(receiveBuffer, 0, bufferLength, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); } catch (System.Exception ex) { logger.Error($"Message : {ex.Message} {Environment.NewLine} StackTrace : {ex.StackTrace}"); this.Disconnect(); } } else { logger.Warn("Receive data but not running"); } }
protected override void ImportPartsBySchemaElement(QName qname, List <MessagePartDescription> parts, Message msg, MessagePart msgPart) { if (schema_set_cache != schema_set_in_use) { schema_set_cache = schema_set_in_use; var xss = new XmlSchemas(); foreach (XmlSchema xs in schema_set_cache.Schemas()) { xss.Add(xs); } schema_importer = new XmlSchemaImporter(xss); if (ccu.Namespaces.Count == 0) { ccu.Namespaces.Add(new CodeNamespace()); } var cns = ccu.Namespaces [0]; code_exporter = new XmlCodeExporter(cns, ccu); } var part = new MessagePartDescription(qname.Name, qname.Namespace); part.XmlSerializationImporter = this; var mbrNS = msg.ServiceDescription.TargetNamespace; var xmm = schema_importer.ImportMembersMapping(qname); code_exporter.ExportMembersMapping(xmm); // FIXME: use of ElementName is a hack! part.CodeTypeReference = new CodeTypeReference(xmm.ElementName); parts.Add(part); Console.Error.WriteLine("CodeNamespace {1} in CCU {2} now contains {0} types.", ccu.Namespaces [0].Types.Count, ccu.Namespaces [0].GetHashCode(), ccu.GetHashCode()); }
/// <summary> /// Creates an <see cref="InterfaceContract"/> object by loading the contents in a specified /// WSDL file. /// </summary> /// <param name="wsdlFileName">Path of the WSDL file to load the information from.</param> /// <returns>An instance of <see cref="InterfaceContract"/> with the information loaded from the WSDL file.</returns> /// <remarks> /// This method first loads the content of the WSDL file to an instance of /// <see cref="System.Web.Services.Description.ServiceDescription"/> class. Then it creates an /// instance of <see cref="InterfaceContract"/> class by loading the data from that. /// This method throws <see cref="WsdlLoadException"/> in case of a failure to load the WSDL file. /// </remarks> public static InterfaceContract GetInterfaceContract(string wsdlFileName) { // Try to load the service description from the specified file. LoadWsdl(wsdlFileName); // Validate the WSDL before proceeding. CheckIfWsdlIsUsableForRoundtripping(); // Start building the simplified InterfaceContract object from the // .Net Fx ServiceDescription we created. InterfaceContract simpleContract = new InterfaceContract(); // Initialize the basic meta data. simpleContract.ServiceName = srvDesc.Name; simpleContract.ServiceNamespace = srvDesc.TargetNamespace; simpleContract.ServiceDocumentation = srvDesc.Documentation; // Try to get the service namespace from the service description. // If it was not found in the service description. Then try to get it from the // service. If it is not found their either, then try to get it from binding. if (simpleContract.ServiceName == null || simpleContract.ServiceName == "") { if (srvDesc.Services.Count > 0 && srvDesc.Services[0].Name != null && srvDesc.Services[0].Name != "") { simpleContract.ServiceName = srvDesc.Services[0].Name; } else { simpleContract.ServiceName = srvDesc.Bindings[0].Name; } } // Set the http binding property. simpleContract.IsHttpBinding = isHttpBinding; // Initialize the imports. foreach (XmlSchema typeSchema in srvDesc.Types.Schemas) { foreach (XmlSchemaObject schemaObject in typeSchema.Includes) { XmlSchemaImport import = schemaObject as XmlSchemaImport; if (import != null) { SchemaImport simpleImport = new SchemaImport(); simpleImport.SchemaNamespace = import.Namespace; simpleImport.SchemaLocation = import.SchemaLocation; simpleContract.Imports.Add(simpleImport); } } } // Initialize the types embedded to the WSDL. simpleContract.SetTypes(GetSchemaElements(srvDesc.Types.Schemas, srvDesc.TargetNamespace)); // Initialize the operations and in/out messages. PortType ptype = srvDesc.PortTypes[0]; if (ptype != null) { foreach (FxOperation op in ptype.Operations) { // Create the Operation. Operation simpleOp = new Operation(); simpleOp.Name = op.Name; simpleOp.Documentation = op.Documentation; if (op.Messages.Input != null) { FxMessage inMessage = srvDesc.Messages[op.Messages.Input.Message.Name]; if (inMessage == null) { // WSDL modified. throw new WsdlModifiedException("Could not find the message"); } MessagePart part = inMessage.Parts[0]; if (part != null) { // Create the input message. Message simpleInMessage = new Message(); simpleInMessage.Name = inMessage.Name; simpleInMessage.Element.ElementName = part.Element.Name; simpleInMessage.Element.ElementNamespace = part.Element.Namespace; simpleInMessage.Documentation = inMessage.Documentation; simpleOp.MessagesCollection.Add(simpleInMessage); simpleOp.Input = simpleInMessage; } else { // WSDL is modified. throw new WsdlModifiedException("Could not find the message part"); } } if (op.Messages.Output != null) { FxMessage outMessage = srvDesc.Messages[op.Messages.Output.Message.Name]; if (outMessage == null) { // WSDL is modified. throw new WsdlModifiedException("Could not find the message"); } MessagePart part = outMessage.Parts[0]; if (part != null) { // Create the output message. Message simpleOutMessage = new Message(); simpleOutMessage.Name = outMessage.Name; simpleOutMessage.Element.ElementName = part.Element.Name; simpleOutMessage.Element.ElementNamespace = part.Element.Namespace; simpleOutMessage.Documentation = outMessage.Documentation; simpleOp.MessagesCollection.Add(simpleOutMessage); simpleOp.Output = simpleOutMessage; } else { // WSDL is modified. throw new WsdlModifiedException("Could not find the message part"); } // Set the message direction. simpleOp.Mep = Mep.RequestResponse; } else { simpleOp.Mep = Mep.OneWay; } // Finally add the Operation to Operations collection. simpleContract.Operations.Add(simpleOp); } } else { // WSDL is modified. throw new WsdlModifiedException("Could not find the portType"); } // Initialize the message headers and header messages. System.Web.Services.Description.Binding binding1 = srvDesc.Bindings[0]; if (binding1 != null) { // Find the corresponding Operation in the InterfaceContract, for each OperationBinding // in the binding1.Operations collection. foreach (OperationBinding opBinding in binding1.Operations) { foreach (Operation simpleOp in simpleContract.Operations) { if (simpleOp.Name == opBinding.Name) { if (opBinding.Input != null) { // Enumerate the message headers for the input message. foreach (ServiceDescriptionFormatExtension extension in opBinding.Input.Extensions) { SoapHeaderBinding inHeader = extension as SoapHeaderBinding; if (inHeader != null) { // Create the in header and add it to the headers collection. MessageHeader simpleInHeader = new MessageHeader(); FxMessage inHeaderMessage = srvDesc.Messages[inHeader.Message.Name]; if (inHeaderMessage == null) { // WSDL modified. throw new WsdlModifiedException("Could not find the message"); } simpleInHeader.Name = inHeaderMessage.Name; simpleInHeader.Message = inHeaderMessage.Name; simpleOp.MessagesCollection[0].HeadersCollection.Add(simpleInHeader); // Create the in header message and put it to the Operation's messeages collection. MessagePart part = inHeaderMessage.Parts[0]; if (part != null) { Message simpleInHeaderMessage = new Message(); simpleInHeaderMessage.Name = inHeaderMessage.Name; simpleInHeaderMessage.Element.ElementName = part.Element.Name; simpleInHeaderMessage.Element.ElementNamespace = part.Element.Namespace; simpleOp.MessagesCollection.Add(simpleInHeaderMessage); } else { // WSDL is modified. throw new WsdlModifiedException("Could not find the message part"); } } } } else { // WSDL modified. throw new WsdlModifiedException("Could not find the operation binding"); } if (simpleOp.Mep == Mep.RequestResponse && opBinding.Output != null) { // Enumerate the message headers for the output message. foreach (ServiceDescriptionFormatExtension extension in opBinding.Output.Extensions) { SoapHeaderBinding outHeader = extension as SoapHeaderBinding; if (outHeader != null) { // Create the in header and add it to the headers collection. MessageHeader simpleOutHeader = new MessageHeader(); FxMessage outHeaderMessage = srvDesc.Messages[outHeader.Message.Name]; if (outHeaderMessage == null) { // WSDL is modified. throw new WsdlModifiedException("Could not find the message"); } simpleOutHeader.Name = outHeaderMessage.Name; simpleOutHeader.Message = outHeaderMessage.Name; simpleOp.MessagesCollection[1].HeadersCollection.Add(simpleOutHeader); // Create the out header message and put it to the Operation's messeages collection. MessagePart part = outHeaderMessage.Parts[0]; if (part != null) { Message simpleOutHeaderMessage = new Message(); simpleOutHeaderMessage.Name = outHeaderMessage.Name; simpleOutHeaderMessage.Element.ElementName = part.Element.Name; simpleOutHeaderMessage.Element.ElementNamespace = part.Element.Namespace; simpleOp.MessagesCollection.Add(simpleOutHeaderMessage); } else { // WSDL is modified. throw new WsdlModifiedException("Could not find the message part"); } } } } else if (simpleOp.Mep == Mep.RequestResponse) { // WSDL modified. throw new WsdlModifiedException("Could not find the operation binding"); } } } } } // Check for the "Generate service tags" option. if (srvDesc.Services.Count == 1) { simpleContract.NeedsServiceElement = true; } // Turn on the SOAP 1.2 binding if available. foreach (System.Web.Services.Description.Binding binding in srvDesc.Bindings) { if (binding.Extensions.Find(typeof(Soap12Binding)) != null) { simpleContract.Bindings |= InterfaceContract.SoapBindings.Soap12; } } return(simpleContract); }
/// <summary> /// Constructs a message from a byte array.<br/> /// <br/> /// The headers are always parsed, but if <paramref name="parseBody"/> is <see langword="false"/>, the body is not parsed. /// </summary> /// <param name="rawMessageContent">The byte array which is the message contents to parse</param> /// <param name="parseBody"><see langword="true"/> if the body should be parsed, <see langword="false"/> if only headers should be parsed out of the <paramref name="rawMessageContent"/> byte array</param> public MailMessage(byte[] rawMessageContent, bool parseBody) { RawMessage = rawMessageContent; // Find the headers and the body parts of the byte array MessageHeader headersTemp; byte[] body; HeaderExtractor.ExtractHeadersAndBody(rawMessageContent, out headersTemp, out body); // Set the Headers property Headers = headersTemp; // Should we also parse the body? if (parseBody) { // Parse the body into a MessagePart MessagePart = new MessagePart(body, this.Headers); } }