public async void Send(string message, string score, string webHookUrl = null) { if (Simulate) { Console.WriteLine("Simulate message: " + message + " score: " + score); return; } if (webHookUrl == null) { webHookUrl = WebHookUrl; } using (var client = new HttpClient()) { var content = new Attachment(); content.Fallback = $"{message}. The current score is {score}."; content.Fields = new List<Field>(); var messageField = new Field(); messageField.Value = message; messageField.Short = true; content.Fields.Add(messageField); var scoreField = new Field(); scoreField.Title = "Score"; scoreField.Value = score; scoreField.Short = true; content.Fields.Add(scoreField); var contentAsString = JsonConvert.SerializeObject(content); await client.PostAsync(webHookUrl, new StringContent(contentAsString)); } }
public void SendMailList(string to1, string subject, string body, string filename) { try { System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage(); eMail.IsBodyHtml = true; eMail.Body = body; eMail.From = new System.Net.Mail.MailAddress("*****@*****.**", "مسابقة اصغر رجل اعمال-القائمة البريدية"); eMail.To.Add(to1); eMail.Subject = subject; eMail.Priority = MailPriority.High; Attachment attach = new Attachment(filename); eMail.Attachments.Add(attach); System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587)); NetworkCredential Xcred = new NetworkCredential("samercs", "samer2006"); SMTP.Credentials = Xcred; SMTP.Send(eMail); } catch (System.Exception e) { /*Database db = new Database(); db.AddParameter("@msgfrom", "*****@*****.**"); db.AddParameter("@msgto", to1); db.AddParameter("@subject", subject); db.AddParameter("@body", body); db.AddParameter("@ErrorMsg", e.Message); db.ExecuteNonQuery("Insert Into mailError(msgfrom,msgto,subject,body,ErrorMsg) values(@msgfrom,@msgto,@subject,@body,@ErrorMsg)"); */ } }
internal static Attachment AttachmentReference(string filename) { Attachment attachment = new Attachment(filename, null, null, null, false); attachment.Content = null; return attachment; }
// This handles getting the stream for downloading. Luke, you can probably make more sense of this // than I can. // - Sean public static System.IO.Stream DownloadAttachment(MirrorService service, Attachment attachment) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create( new Uri(attachment.ContentUrl)); service.Authenticator.ApplyAuthenticationToRequest(request); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { return response.GetResponseStream(); } else { Console.WriteLine( "An error occurred: " + response.StatusDescription); return null; } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } }
private void SendReturnParent(DirectoryInfo dirInfo) { Attachment subFile = new Attachment(); subFile.Name = "."; subFile.IsReturnParent = true; SendHeader(subFile); }
internal static Attachment AttachmentBytes(string filename) { Attachment attachment = new Attachment(filename, null, null, null, false); attachment.Content = System.IO.File.ReadAllBytes(filename); return attachment; }
void ThreadMail() { email = nameInputField.text; Debug.Log (email); MailMessage mail = new MailMessage("*****@*****.**", email); // MailMessage mail = new MailMessage("*****@*****.**", email); if (Application.platform == RuntimePlatform.IPhonePlayer) { Attachment a = new Attachment (Application.persistentDataPath + "/" + path, MediaTypeNames.Application.Octet); mail.Attachments.Add (a); } else { Attachment a = new Attachment (path, MediaTypeNames.Application.Octet); mail.Attachments.Add (a); } SmtpClient client = new SmtpClient(); client.EnableSsl = true; client.Host = "w0062da6.kasserver.com"; // client.Host = "smtp.gmail.com"; // client.Port = 25; client.Port = 587; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential ("m0399d9f", "3mVEVGT7wKwKDb5X") as ICredentialsByHost; // client.Credentials = new System.Net.NetworkCredential ("*****@*****.**", "okaconf2016") as ICredentialsByHost; ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; mail.Subject = "OKA Configuration"; mail.Body = ""; client.Send (mail); // Debug.Log(a); }
private void SendDirectory(DirectoryInfo dirInfo) { Attachment subFile = new Attachment(); subFile.Name = dirInfo.Name; subFile.IsDirectory = true; SendHeader(subFile); }
private void BtnOKButton_Click(object sender, EventArgs e) { try { if (type == DialogType.Edit) { byte[] file = File.ReadAllBytes(textBoxAttachmentFilePath.Text); Upload uploadedFile = RedmineClientForm.redmine.UploadFile(file); uploadedFile.FileName = Path.GetFileName(textBoxAttachmentFilePath.Text); uploadedFile.Description = textBoxDescription.Text; uploadedFile.ContentType = GetMimeType(Path.GetExtension(textBoxAttachmentFilePath.Text)); issue.Uploads = new List<Upload>(); issue.Uploads.Add(uploadedFile); RedmineClientForm.redmine.UpdateObject<Issue>(issue.Id.ToString(), issue); } else { NewAttachment = new Attachment { ContentUrl = textBoxAttachmentFilePath.Text, Description = textBoxDescription.Text, FileName = Path.GetFileName(textBoxAttachmentFilePath.Text), ContentType = GetMimeType(Path.GetExtension(textBoxAttachmentFilePath.Text)), FileSize = (int)new FileInfo(textBoxAttachmentFilePath.Text).Length, Author = new IdentifiableName { Id = RedmineClientForm.Instance.CurrentUser.Id, Name = RedmineClientForm.Instance.CurrentUser.CompleteName() } }; } DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { MessageBox.Show(String.Format(Lang.Error_Exception, ex.Message), Lang.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
void CheckAttachment(Attachment attachment) { Assert.Equal("application/x-file", attachment.ContentType); Assert.Equal(attachmentId, attachment.Id); Assert.Equal(attachmentDataBuffer.Length, attachment.Length); Assert.Equal(attachmentDataBuffer, ReadStreamToBuffer(attachment.Syncronously.OpenRead())); }
public virtual bool Equals(Attachment other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return base.Equals(other) && Equals(other.FileName, FileName) && Equals(other.ContentType, ContentType) && other.ContentLength == ContentLength; }
public static Guid UploadAttach(FileUpload fu) { if (!fu.HasFile || fu.FileName.Length == 0) { throw new BusinessObjectLogicException("Please select upload file!"); } string path = null; try { string subDirectory = DateTime.Now.ToString("yyyyMM") + Path.DirectorySeparatorChar + DateTime.Now.ToString("dd"); string directory = System.Configuration.ConfigurationManager.AppSettings["File"] + subDirectory; if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); string title = Path.GetFileNameWithoutExtension(fu.FileName); string ext = Path.GetExtension(fu.FileName); path = Path.DirectorySeparatorChar + Path.GetRandomFileName() + ext; fu.SaveAs(directory + path); Attachment attach = new Attachment(UserHelper.UserName); attach.Title = title; attach.Path = subDirectory + path; new AttachmentBl().AddAttach(attach); return attach.UID; } catch { throw new BusinessObjectLogicException("File upload fail!"); } }
private void btnChonFile_Click(object sender, EventArgs e) { //Chọn files OpenFileDialog x = new OpenFileDialog(); x.Multiselect = true; x.ShowDialog(); string[] file_names = x.FileNames; if (file_names.Count() > 0) { //Tạo chứng từ mới //ct = new ChungTu(); //ct.ngay = ServerTimeHelper.getNow(); //ct.sohieu = "mã chứng từ"; //Gán attchment foreach (string file_name in file_names) { Attachment tmp = new Attachment(); tmp.LOCAL_FILE_PATH = file_name; ct.attachments.Add(tmp); } //register event ct.onUploadProgress += new SHARED.Libraries.FTPHelper.UploadProgress(this.onChungTu_Uploading); // do in background //var taskA = new Task(() => ct.upload()); //taskA.ContinueWith(new Action<Task>(this.onUploadFinish)); //taskA.Start(); Task.Factory.StartNew(() => ct.upload().Wait()) .ContinueWith(new Action<Task>(this.onUploadFinish)); } }
public void GetResponseStream_GivenAStream_ReturnsAStreamAsAttachment() { var request = new PortalRequest(); request.Parameters.Add("format", "attachment"); using (var response = new PortalResponse(request)) { request.Stopwatch.Reset(); var memoryStream = new MemoryStream(); var writer = new StreamWriter(memoryStream); var attachment = new Attachment { FileName = "somefile.name", Stream = memoryStream, ContentType = "some content/type", AsAttachment = true }; writer.Write("OK!"); writer.Flush(); response.WriteToOutput(attachment); var stream = new StreamReader(response.GetResponseStream()); Assert.That(stream.ReadToEnd(), Is.EqualTo("OK!")); } }
public void Attachment1() { IAttachment a = new Attachment(); a.FormatType = "application/binary"; a.Data = new byte[] { 1, 2, 3, 4 }; SerializeTest(a, "Attachment1.xml"); }
private static bool IsSignatureRtf(Attachment attachment) { if (attachment.PropertyAccessor.GetProperty(MAPIProxy.MAPIStringDefines.PR_ATTACH_METHOD) == MAPIProxy.MapiDefines.ATTACH_OLE) { // Only allow file types we DON'T clean to be signatures. try { if (attachment.DisplayName == "Picture (Device Independent Bitmap)") return true; if (FileTypeBridge.GetSupportedFileType(attachment.FileName) == FileType.Unknown) { Interop.Logging.Logger.LogInfo(string.Format("Signature {0} on Rtf formatted message", attachment.DisplayName)); return true; } } catch (System.Exception ex) { Interop.Logging.Logger.LogDebug("Caught exception: assuming that when the mail format is rtf you are unable access the filename property of embedded images."); Interop.Logging.Logger.LogDebug(ex); return true; } } return false; }
public static bool PdfMail(Stream stream, string toAddress) { try { MailMessage message = new MailMessage(new MailAddress("*****@*****.**", "Eaztimate Jour"), new MailAddress(toAddress)); message.BodyEncoding = Encoding.GetEncoding("ISO-8859-1"); message.Subject = "Jourrapport"; message.Body = "Här kommer en jourrapport\r\n"; stream.Seek(0, SeekOrigin.Begin); Attachment att = new Attachment(stream, MediaTypeNames.Application.Pdf); att.ContentDisposition.FileName = "Jourrapport.pdf"; message.Attachments.Add(att); message.IsBodyHtml = false; int port = 0; int.TryParse(ConfigurationManager.AppSettings["SMTPPort"], out port); SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"], port); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["AutomatedEMailAddress"], ConfigurationManager.AppSettings["SMTPPassword"]); //client.Credentials = CredentialCache.DefaultNetworkCredentials; client.Send(message); return true; } catch (Exception ex) { ex.ToString(); return false; } }
public WsAttachment(Attachment attachment, WsAttachments parent) { Id = Guid.NewGuid(); _parent = parent; _attachment = attachment; InitializeAttachment(); }
private void OnAttachmentRemove(Attachment Attachment) { if (AttachmentRemove != null) { AttachmentRemove(_wsAttachments.Remove(Attachment)); } }
private void OnAttachmentAdd(Attachment Attachment) { if (AttachmentAdd != null) { AttachmentAdd(_wsAttachments.Add(Attachment)); } }
public void SendEmail() { if ((_strSmtpServer != "") && (_strSmtpServer != null)) { try { MailMessage _objMail = new MailMessage(_strEmailFrom, _strEmailTo); _objMail.Subject = _strEmailSubject; _objMail.Body = _strEmailMessageBody; _objMail.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient(HttpContext.Current.Request.ServerVariables[ConfigurationManager.AppSettings["smtpServer"].ToString()]); smtpClient.Host = ConfigurationManager.AppSettings["smtpServer"].ToString(); smtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["smtpUser"].ToString(), ConfigurationManager.AppSettings["smtpPw"].ToString()); if (!string.IsNullOrEmpty(_strFileName)) { Attachment item = new Attachment(_strFileName); _objMail.Attachments.Add(item); } smtpClient.Send(_objMail); } catch (Exception ex) { new SqlLog().InsertSqlLog(0, "Email.cs", ex); } } }
private void OnBeforeAttachmentRead(Attachment Attachment, ref bool Cancel) { if (BeforeAttachmentRead != null) { // This is needed to ensure that attachments cannot be opened while IP is updating // the attachments; if (LockedForUpdating) { Cancel = true; } using (var attachment = new WsAttachment(Attachment)) { foreach (WsAttachment wsAttachment in _wsAttachments) { if (wsAttachment.RecordKey == attachment.RecordKey && !string.IsNullOrEmpty(wsAttachment.RecordKey)) { BeforeAttachmentRead(wsAttachment, ref Cancel); return; } } } } else Marshal.ReleaseComObject(Attachment); }
public static bool IsCalendar(Attachment attachment) { if (Path.HasExtension(attachment.FileName) && Path.GetExtension(attachment.FileName).ToLower() == ".ics") return true; string loweredFileName = attachment.FileName.ToLower(); if (loweredFileName == "paycal_uparrow.gif") return true; if (loweredFileName == "paycal_line_datepick.gif") return true; if (loweredFileName == "paycal_line_outer_thick.gif") return true; if (loweredFileName == "paycal_line_outer_thin.gif") return true; if (loweredFileName == "paycal_free.gif") return true; if (loweredFileName == "paycal_tent.gif") return true; if (loweredFileName == "paycal_busy.gif") return true; if (loweredFileName == "paycal_oof.gif") return true; if (loweredFileName == "paycal_oowh.gif") return true; if (loweredFileName == "paycal_workingelsewhere.gif") return true; return false; }
public static bool SendMail(string gMailAccount, string password, string to, string subject, string message) { try { NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password); MailMessage msg = new MailMessage(); msg.From = new MailAddress(gMailAccount); msg.To.Add(new MailAddress(to)); msg.Subject = subject; Attachment att1 = new Attachment("Print.doc"); Attachment att2 = new Attachment("Cost_analize.doc"); msg.Attachments.Add(att1); msg.Attachments.Add(att2); msg.Body = message; msg.IsBodyHtml = true; SmtpClient client = new SmtpClient("smtp.gmail.com"); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = loginInfo; client.Send(msg); return true; } catch (Exception) { return false; } }
public bool OpenActualDocumentFromPlaceHolder(Attachment attachment) { try { if (attachment.Size > (1024*5)) { Logger.LogTrace("Returning without doing anything as the file size is > 5k"); return false; } using (var lcfm = new LocalCopyOfFileManager()) { string filename = lcfm.GetLocalCopyOfFileTarget(attachment.FileName); attachment.SaveAsFile(filename); Logger.LogTrace("Saving placeholder file to " + filename); var lah = new LargeAttachmentHelper(filename); if (lah.IsLargeAttachment) { Logger.LogTrace("Opening actual file from" + lah.ActualPath); var startInfo = new ProcessStartInfo(); startInfo.FileName = lah.ActualPath; Process.Start(startInfo); return true; } } return false; } catch (Exception ex) { Logger.LogError(ex); throw; } }
// This is fired when actually retrieving the attachment public override void OnRead(string key, Attachment attachment) { // Get the filename, and make sure its in the returned metadata var filename = AugmentMetadataWithFilename(key, attachment.Metadata); // We can't do anything else without a filename if (filename == null) return; // Add a Content-Type header var contentType = Utils.GetMimeType(filename); if (!string.IsNullOrEmpty(contentType)) attachment.Metadata["Content-Type"] = contentType; // Add a Content-Disposition header // The filename is supposed to be quoted, but it doesn't escape the quotes properly. // http://issues.hibernatingrhinos.com/issue/RavenDB-824 // This was fixed in 2235. For prior versions, don't send the quotes. if (Utils.RavenVersion < Version.Parse("2.0.2235.0")) attachment.Metadata["Content-Disposition"] = string.Format("attachment; filename={0}", filename); else attachment.Metadata["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", filename); }
/// <summary> /// Reads response elements from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadElementsFromXml(EwsServiceXmlReader reader) { base.ReadElementsFromXml(reader); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.Attachments); if (!reader.IsEmptyElement) { reader.Read(XmlNodeType.Element); if (this.attachment == null) { if (string.Equals(reader.LocalName, XmlElementNames.FileAttachment, StringComparison.OrdinalIgnoreCase)) { this.attachment = new FileAttachment(reader.Service); } else if (string.Equals(reader.LocalName, XmlElementNames.ItemAttachment, StringComparison.OrdinalIgnoreCase)) { this.attachment = new ItemAttachment(reader.Service); } } if (this.attachment != null) { this.attachment.LoadFromXml(reader, reader.LocalName); } reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.Attachments); } }
public void Attach(AttachmentType slot, Attachment attachment) { Noise += attachment.NoiseModifier; ClipSize += attachment.ClipSizeModifier; if (attachments.ContainsKey(slot)) attachments.Remove(slot); attachments.Add(slot, attachment); }
/// <summary> /// 取得文件流,判断是否小图片,特殊处理 /// </summary> /// <param name="context"></param> /// <param name="attachment"></param> /// <returns></returns> protected override Stream GetStream(HttpContext context, Attachment attachment) { Stream stream = base.GetStream(context, attachment); stream = MakeThumbnail(context, stream); return stream; }
/// <summary> /// Initializes the event arguments. /// </summary> /// <param name="report">The report.</param> /// <param name="test">The test data.</param> /// <param name="testStepRun">The test step run.</param> /// <param name="attachment">The attachment.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="report"/>, <paramref name="test"/> /// <paramref name="testStepRun"/> or <paramref name="attachment"/> is null.</exception> public TestStepLogAttachEventArgs(Report report, TestData test, TestStepRun testStepRun, Attachment attachment) : base(report, test, testStepRun) { if (attachment == null) throw new ArgumentNullException("attachment"); this.attachment = attachment; }
public async Task CreateAsync(AuctionRegisterModel model, string userId) { AuctionRegistration ar = new AuctionRegistration() { AnnouncementId = model.AnnouncementId, AppliedByCourtEnforcer = model.AppliedByCourtEnforcer, CreatedBy = userId, CreatedOn = DateTime.UtcNow, Deleted = false, IsApproved = model.IsApproved, IsOwner = model.IsOwner, IsOwnerSpouse = model.IsOwnerSpouse, RepresentationType = model.RepresentationType, ResultDeliveryType = model.ResultDeliveryType }; ar.UniqueNumber = GenerateUniqueNumber(); _context.AuctionRegistration.Add(ar); //Add participant if (model.AppliedByCourtEnforcer && string.IsNullOrWhiteSpace(model.ParticipantId)) { var participantPerson = model.Participant.ToPerson(); _context.Person.Add(participantPerson); ar.ParticipantId = participantPerson.UserId; } else { ar.ParticipantId = userId; } //Represented Person/Company if (model.RepresentationType != AuctionRepresentationTypes.PERSONAL.ToString()) { if (model.RepresentedCompany != null) { await MapCompany(ar, model.RepresentedCompany); } else { await MapPerson(ar, model.RepresentedPerson); } } if (model.Attachments != null && model.Attachments.Any()) { foreach (var item in model.Attachments) { Attachment att = new Attachment() { FileName = item.FileName, ContentType = item.ContentType, FileType = item.FileName.Split('.').Last(), Content = item.Content }; _context.Attachment.Add(att); _context.AuctionRegistrationAttachment.Add(new AuctionRegistrationAttachment() { Attachment = att, AuctionRegistration = ar }); } } await _context.SaveChangesAsync(); }
// This is for creating a card with the given data. private Attachment CreateGitHubAdpativeCardAttachment() { var title = dataFromRequest.Title; var id = dataFromRequest.Id; var description = dataFromRequest.Description; var status = dataFromRequest.Status; var createdAt = dataFromRequest.CreatedAt; var updatedAt = dataFromRequest.UpdatedAt; var mentioned = dataFromRequest.Mentions; var comments = dataFromRequest.Comments; AdaptiveCard card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0)); card.Body.Add(new AdaptiveTextBlock() { Text = title, Size = AdaptiveTextSize.ExtraLarge }); card.Body.Add(new AdaptiveFactSet() { Type = "FactSet", Facts = new List <AdaptiveFact>() { new AdaptiveFact() { Title = "Created At", Value = createdAt }, new AdaptiveFact() { Title = "Updated At", Value = updatedAt }, new AdaptiveFact() { Title = "Id", Value = id }, new AdaptiveFact() { Title = "Description", Value = description }, new AdaptiveFact() { Title = "Status", Value = status } } }); card.Actions.Add(new AdaptiveSubmitAction() { Type = "Action.Submit", Title = "Click me for messageBack" }); string jsonObj = card.ToJson(); Attachment attachmentCard = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = JsonConvert.DeserializeObject(jsonObj) }; return(attachmentCard); }
public bool SendMail(string sendTo, string subject, string body, string lang, string file, bool send_cc) { try { string footer = ""; if (lang == "en") { myServerHost = myServerHost_en; myServerPort = myServerPort_en; myEmail = myEmail_en; myEmailName = myEmailName_en; myPassword = myPassword_en; footer = @" <br> <br> <br> <div><img alt=""nutriprog.com"" height=""40"" src=""https://www.nutriprog.com/assets/img/logo.svg"" style=""float:left"" width=""190"" /></div> <br> <br> <br> <div>IG PROG</div> <div><a href=""mailto:[email protected]?subject=Upit"">[email protected]</a></div> <div><a href = ""https://www.nutriprog.com"">www.nutriprog.com</a></div>"; } else { footer = @" <br> <br> <br> <div> <img alt=""ProgramPrehrane.com"" height=""40"" src=""https://www.programprehrane.com/assets/img/logo.svg"" style=""float:left"" width=""190"" /> </div> <br> <br> <br> <div style=""color:gray""> IG PROG - obrt za računalno programiranje<br> Ludvetov breg 5, 51000 Rijeka, HR<br> <a href=""tel:+385 98 330 966"">+385 98 330 966</a><br> <a href=""mailto:[email protected]?subject=Upit"">[email protected]</a><br> <a href=""https://www.programprehrane.com"">www.programprehrane.com</a> </div>"; } MailMessage mail = new MailMessage(); mail.From = new MailAddress(myEmail, myEmailName); mail.To.Add(sendTo); if (send_cc && sendTo != myEmail_cc) { mail.CC.Add(myEmail_cc); } mail.Subject = subject; mail.Body = string.Format(@" {0} {1}", body, footer); mail.IsBodyHtml = true; if (!string.IsNullOrEmpty(file)) { Attachment attachment = new Attachment(Server.MapPath(file.Replace("../", "~/"))); mail.Attachments.Add(attachment); } SmtpClient smtp = new SmtpClient(myServerHost, myServerPort); NetworkCredential Credentials = new NetworkCredential(myEmail, myPassword); smtp.Credentials = Credentials; smtp.EnableSsl = EnableSsl; smtp.Send(mail); return(true); } catch (Exception e) { return(false); } }
public void SendHtmlMessage(string replyto, string from, string to, string cc, string subject, string htmlBody, Attachment attachment) { MailMessage msg = new MailMessage(from, to, subject, htmlBody); if (!string.IsNullOrEmpty(replyto)) { msg.ReplyToList.Add(new MailAddress(replyto)); } if (!string.IsNullOrEmpty(cc)) { msg.CC.Add(new MailAddress(cc)); } if (attachment != null) { msg.Attachments.Add(attachment); } msg.IsBodyHtml = true; SendMessage(msg); }
/** Stores vertices and triangles for a single material. */ private void AddSubmesh(Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh) { int submeshIndex = submeshMaterials.Count; submeshMaterials.Add(material); if (submeshes.Count <= submeshIndex) { submeshes.Add(new Submesh()); } else if (immutableTriangles) { return; } Submesh submesh = submeshes[submeshIndex]; int[] triangles = submesh.triangles; int trianglesCapacity = triangles.Length; if (lastSubmesh && trianglesCapacity > triangleCount) { // Last submesh may have more triangles than required, so zero triangles to the end. for (int i = triangleCount; i < trianglesCapacity; i++) { triangles[i] = 0; } submesh.triangleCount = triangleCount; } else if (trianglesCapacity != triangleCount) { // Reallocate triangles when not the exact size needed. submesh.triangles = triangles = new int[triangleCount]; submesh.triangleCount = 0; } if (!renderMeshes) { // Use stored triangles if possible. if (submesh.firstVertex != firstVertex || submesh.triangleCount < triangleCount) { submesh.triangleCount = triangleCount; submesh.firstVertex = firstVertex; for (int i = 0; i < triangleCount; i += 6, firstVertex += 4) { triangles[i] = firstVertex; triangles[i + 1] = firstVertex + 2; triangles[i + 2] = firstVertex + 1; triangles[i + 3] = firstVertex + 2; triangles[i + 4] = firstVertex + 3; triangles[i + 5] = firstVertex + 1; } } return; } // Store triangles. List <Slot> drawOrder = skeleton.DrawOrder; for (int i = startSlot, triangleIndex = 0; i < endSlot; i++) { Attachment attachment = drawOrder[i].attachment; if (attachment is RegionAttachment) { triangles[triangleIndex] = firstVertex; triangles[triangleIndex + 1] = firstVertex + 2; triangles[triangleIndex + 2] = firstVertex + 1; triangles[triangleIndex + 3] = firstVertex + 2; triangles[triangleIndex + 4] = firstVertex + 3; triangles[triangleIndex + 5] = firstVertex + 1; triangleIndex += 6; firstVertex += 4; continue; } int[] attachmentTriangles; int attachmentVertexCount; if (attachment is MeshAttachment) { MeshAttachment meshAttachment = (MeshAttachment)attachment; attachmentVertexCount = meshAttachment.vertices.Length >> 1; attachmentTriangles = meshAttachment.triangles; } else if (attachment is SkinnedMeshAttachment) { SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment; attachmentVertexCount = meshAttachment.uvs.Length >> 1; attachmentTriangles = meshAttachment.triangles; } else { continue; } for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleIndex++) { triangles[triangleIndex] = firstVertex + attachmentTriangles[ii]; } firstVertex += attachmentVertexCount; } }
/// <summary> /// Setup the test. /// </summary> public AttachmentModelTests() { instance = new Attachment(); }
public bool Send(List <string> To, List <string> Cc, string Subject, string Body, IList <Attachament> Attachaments, byte[] CompanyLogo = null, byte[] SoleraLogo = null) { MemoryStream streamCompanyLogo = new MemoryStream(); MemoryStream streamSoleraLogo = new MemoryStream(); LinkedResource lkcompanyLogo = null; LinkedResource lkSoleraLogo = null; try { #region Mensagem using (MailMessage message = new MailMessage()) { //ADICIONA E-MAIL QUE ENVIARÁ message.From = new MailAddress(this._From); //TÍTULO DO E-MAIL message.Subject = Subject; //CONTEUDO EM HTML message.IsBodyHtml = true; //ADICIONAR DESTINATÁRIOS #region DESTINATÁRIO if (To == null) { throw new Exception("Informar o destinatário"); } foreach (var _to in To) { message.To.Add(new MailAddress(_to)); } #endregion //ADICIONAR CÓPIAS #region CÓPIAS if (Cc != null) { foreach (var _cc in Cc) { message.CC.Add(new MailAddress(_cc)); } } #endregion //LOGOTIPOS #region LOGOS E CORPO //CRIA VISÃO ALTERNATIVA using (AlternateView view = AlternateView.CreateAlternateViewFromString(Body, null, MediaTypeNames.Text.Html)) { //LOGO EMPRESA DE SEGUROS #region LOGOTIPOS if (SoleraLogo != null) { streamSoleraLogo = new MemoryStream(SoleraLogo); lkSoleraLogo = new LinkedResource(streamSoleraLogo); lkSoleraLogo.ContentType.MediaType = MediaTypeNames.Image.Jpeg; lkSoleraLogo.TransferEncoding = TransferEncoding.Base64; lkSoleraLogo.ContentId = "soleraLogo"; view.LinkedResources.Add(lkSoleraLogo); } if (CompanyLogo != null) { streamCompanyLogo = new MemoryStream(CompanyLogo); lkcompanyLogo = new LinkedResource(streamCompanyLogo); lkcompanyLogo.ContentType.MediaType = MediaTypeNames.Image.Jpeg; lkcompanyLogo.TransferEncoding = TransferEncoding.Base64; lkcompanyLogo.ContentId = "companyLogo"; view.LinkedResources.Add(lkcompanyLogo); } #endregion //ADICONA AS IMAGENS E CORPO DO E-MAIL message.AlternateViews.Add(view); #region Attachament foreach (Attachament attachFile in Attachaments) { //MediaTypeNames.Text.Plain ContentType ct = new ContentType(attachFile.MediaTypeNames); Attachment attach = new Attachment(attachFile.File, ct); attach.ContentDisposition.FileName = attachFile.FileName; message.Attachments.Add(attach); } #endregion //ENVIA E-MAIL this._SMTP.Send(message); } #endregion } #endregion return(true); } catch (Exception ex) { throw ex; } finally { streamSoleraLogo.Dispose(); streamSoleraLogo.Flush(); streamSoleraLogo = null; streamCompanyLogo.Dispose(); streamCompanyLogo.Flush(); streamCompanyLogo = null; if (lkcompanyLogo != null) { lkcompanyLogo.Dispose(); } lkcompanyLogo = null; if (lkSoleraLogo != null) { lkSoleraLogo.Dispose(); } lkSoleraLogo = null; } }
internal static string GetAttachment(MailboxSession mailboxSession, StoreObjectId itemId, string attachmentId, Stream outStream, int offset, int count, Unlimited <ByteQuantifiedSize> maxAttachmentSize, bool rightsManagementSupport, out int total) { string result; using (Item item = Item.Bind(mailboxSession, itemId)) { if ("DRMLicense".Equals(attachmentId, StringComparison.OrdinalIgnoreCase)) { total = AttachmentHelper.WriteDrmLicenseToStream(item, outStream, offset, count, maxAttachmentSize); result = "application/x-microsoft-rpmsg-message-license"; } else { if (rightsManagementSupport) { Command.CurrentCommand.DecodeIrmMessage(item, true); } Attachment attachment = null; try { AttachmentCollection attachmentCollection; if (BodyConversionUtilities.IsMessageRestrictedAndDecoded(item)) { attachmentCollection = ((RightsManagedMessageItem)item).ProtectedAttachmentCollection; } else { attachmentCollection = item.AttachmentCollection; } if (attachmentId.Length > 8) { AttachmentId attachmentId2 = EntitySyncItemId.GetAttachmentId(attachmentId); if (attachmentId2 != null) { attachment = attachmentCollection.Open(attachmentId2); } } if (attachment == null) { int num; if (!int.TryParse(attachmentId, NumberStyles.None, CultureInfo.InvariantCulture, out num) || num < 0) { throw new FormatException("Invalid Attachment Index format: " + attachmentId.ToString(CultureInfo.InvariantCulture)); } IList <AttachmentHandle> handles = attachmentCollection.GetHandles(); if (num < handles.Count) { attachment = attachmentCollection.Open(handles[num]); } } if (attachment == null) { throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId)); } if (BodyConversionUtilities.IsMessageRestrictedAndDecoded(item) && AttachmentHelper.IsProtectedVoiceAttachment(attachment.FileName)) { RightsManagedMessageItem rightsManagedMessageItem = item as RightsManagedMessageItem; rightsManagedMessageItem.UnprotectAttachment(attachment.Id); AttachmentId id = attachment.Id; attachment.Dispose(); attachment = rightsManagedMessageItem.ProtectedAttachmentCollection.Open(id); } if (!maxAttachmentSize.IsUnlimited && attachment.Size > (long)maxAttachmentSize.Value.ToBytes()) { throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge); } result = AttachmentHelper.GetAttachmentItself(attachment, outStream, offset, count, out total); } finally { if (attachment != null) { attachment.Dispose(); } if (rightsManagementSupport) { Command.CurrentCommand.SaveLicense(item); } } } } return(result); }
/// <summary> /// Replaces an attachment as an asynchronous operation. /// </summary> /// <param name="client">document client.</param> /// <param name="attachmentsUri">the updated attachment.</param> /// <param name="attachment">the attachment resource.</param> /// <param name="options">the request options for the request.</param> /// <returns>The task object representing the service response for the asynchronous operation.</returns> public static Task <ResourceResponse <Attachment> > ReplaceAttachmentExAsync(this DocumentClient client, Attachment attachment, RequestOptions options = null) { SwapLinkIfNeeded(client, attachment); return(client.ReplaceAttachmentAsync(attachment, options)); }
private static string GetAttachmentItself(Attachment attachment, Stream outStream, int offset, int count, out int total) { string text = string.Empty; total = 0; StreamAttachmentBase streamAttachmentBase = attachment as StreamAttachmentBase; if (streamAttachmentBase != null) { OleAttachment oleAttachment = streamAttachmentBase as OleAttachment; Stream stream = null; try { if (oleAttachment != null) { stream = oleAttachment.TryConvertToImage(ImageFormat.Jpeg); if (stream != null) { text = "image/jpeg"; } } if (stream == null) { stream = streamAttachmentBase.GetContentStream(); } if (string.IsNullOrEmpty(text)) { text = attachment.ContentType; } if (string.IsNullOrEmpty(text)) { text = attachment.CalculatedContentType; } if (stream.Length > 0L) { if ((long)offset >= stream.Length) { throw new ArgumentOutOfRangeException("offset"); } int num = (count == -1) ? ((int)stream.Length) : count; if (num > GlobalSettings.MaxDocumentDataSize) { throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge); } StreamHelper.CopyStream(stream, outStream, offset, num); total = (int)stream.Length; } } finally { if (stream != null) { stream.Dispose(); stream = null; } } return(text); } ItemAttachment itemAttachment = attachment as ItemAttachment; if (itemAttachment != null) { using (Item item = itemAttachment.GetItem(StoreObjectSchema.ContentConversionProperties)) { text = "message/rfc822"; OutboundConversionOptions outboundConversionOptions = AirSyncUtility.GetOutboundConversionOptions(); using (AirSyncStream airSyncStream = new AirSyncStream()) { try { ItemConversion.ConvertItemToMime(item, airSyncStream, outboundConversionOptions); } catch (ConversionFailedException innerException) { throw new FormatException(string.Format(CultureInfo.InvariantCulture, "MIME conversion failed for Attachment {0}!", new object[] { attachment }), innerException); } if (airSyncStream.Length > 0L) { if ((long)offset >= airSyncStream.Length) { throw new ArgumentOutOfRangeException("offset"); } int num2 = (count == -1) ? ((int)airSyncStream.Length) : count; if (num2 > GlobalSettings.MaxDocumentDataSize) { throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge); } StreamHelper.CopyStream(airSyncStream, outStream, offset, num2); total = (int)airSyncStream.Length; } } } return(text); } throw new FormatException(string.Format(CultureInfo.InvariantCulture, "Attachment {0} is of invalid format!", new object[] { attachment })); }
private static string GetAttachmentByUrlCompName(MailboxSession mailboxSession, string attachmentId, Stream outStream, int offset, int count, Unlimited <ByteQuantifiedSize> maxAttachmentSize, out int total) { attachmentId = "/" + attachmentId; int andCheckLastSlashLocation = AttachmentHelper.GetAndCheckLastSlashLocation(attachmentId, attachmentId); string text = attachmentId.Substring(0, andCheckLastSlashLocation); string text2 = attachmentId.Substring(andCheckLastSlashLocation + 1); andCheckLastSlashLocation = AttachmentHelper.GetAndCheckLastSlashLocation(text, attachmentId); string propertyValue = text.Substring(0, andCheckLastSlashLocation); StoreId storeId = null; QueryFilter seekFilter = new ComparisonFilter(ComparisonOperator.Equal, FolderSchema.UrlName, propertyValue); using (Folder folder = Folder.Bind(mailboxSession, mailboxSession.GetDefaultFolderId(DefaultFolderType.Root))) { using (QueryResult queryResult = folder.FolderQuery(FolderQueryFlags.DeepTraversal, AirSyncUtility.XsoFilters.GetHierarchyFilter, null, AttachmentHelper.folderPropertyIds)) { if (queryResult.SeekToCondition(SeekReference.OriginBeginning, seekFilter)) { object[][] rows = queryResult.GetRows(1); storeId = (rows[0][0] as StoreId); } } } if (storeId == null) { throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId)); } AirSyncDiagnostics.TraceDebug <StoreId>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with parentStoreId {0}.", storeId); StoreId storeId2 = null; seekFilter = new ComparisonFilter(ComparisonOperator.Equal, FolderSchema.UrlName, text); using (Folder folder2 = Folder.Bind(mailboxSession, storeId)) { using (QueryResult queryResult2 = folder2.ItemQuery(ItemQueryType.None, null, null, AttachmentHelper.itemPropertyIds)) { if (queryResult2.SeekToCondition(SeekReference.OriginBeginning, seekFilter)) { object[][] rows2 = queryResult2.GetRows(1); storeId2 = (rows2[0][0] as StoreId); } } } if (storeId2 == null) { throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId)); } AirSyncDiagnostics.TraceDebug <StoreId>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with itemStoreId {0}.", storeId2); PropertyTagPropertyDefinition propertyTagPropertyDefinition = PropertyTagPropertyDefinition.CreateCustom("UrlCompName", 284360734U); string attachmentItself; using (Item item = Item.Bind(mailboxSession, storeId2)) { AttachmentCollection attachmentCollection = item.AttachmentCollection; attachmentCollection.Load(new PropertyDefinition[] { propertyTagPropertyDefinition }); AttachmentId attachmentId2 = null; foreach (AttachmentHandle handle in attachmentCollection) { using (Attachment attachment = attachmentCollection.Open(handle)) { if (text2.Equals((string)attachment[propertyTagPropertyDefinition], StringComparison.Ordinal)) { attachmentId2 = attachment.Id; break; } } } if (attachmentId2 == null) { foreach (AttachmentHandle handle2 in attachmentCollection) { using (Attachment attachment2 = attachmentCollection.Open(handle2)) { string str = (string)attachment2[propertyTagPropertyDefinition]; if (text2.EndsWith("_" + str, StringComparison.Ordinal)) { attachmentId2 = attachment2.Id; break; } } } } if (attachmentId2 == null) { throw new ObjectNotFoundException(ServerStrings.MapiCannotOpenAttachmentId(attachmentId)); } AirSyncDiagnostics.TraceDebug <AttachmentId>(ExTraceGlobals.RequestsTracer, null, "Getting attachment with attachment ID {0}.", attachmentId2); using (Attachment attachment3 = attachmentCollection.Open(attachmentId2)) { if (!maxAttachmentSize.IsUnlimited && attachment3.Size > (long)maxAttachmentSize.Value.ToBytes()) { throw new DataTooLargeException(StatusCode.AttachmentIsTooLarge); } attachmentItself = AttachmentHelper.GetAttachmentItself(attachment3, outStream, offset, count, out total); } } return(attachmentItself); }
private static void playSendAlertThread(object parameterObj) { string[] args = (string[])parameterObj; string picName = args[0]; string TriggerDescription = args[1]; string triggerDetails = args[2]; string triggerName = args[3]; // get directory to pictures string projectDirectory = Environment.CurrentDirectory; string filepath = Directory.GetParent(projectDirectory).Parent.FullName; // get Camera picture string[] paths = new string[] { @filepath, "files", picName }; cameraPic = Path.Combine(paths); // get screenshot picture paths = new string[] { @filepath, "files", "snapshot_" + picName }; screenPic = Path.Combine(paths); Thread.Sleep(60000); try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**", "Bsafe ", Encoding.UTF8); Setting settingInstance = Setting.Instance; mail.To.Add(settingInstance.email); mail.Subject = "Alert " + TriggerDescription; switch (triggerName) { case ("typing"): mail.Body = "The user typing word: " + triggerDetails; break; case ("Site"): mail.Body = "The user browse in site: " + triggerDetails; break; case ("Insta"): mail.Body = "The user try install app " + triggerDetails; break; } Attachment attachment; attachment = new Attachment(cameraPic); mail.Attachments.Add(attachment); Debug.WriteLine("add camera pic"); Attachment attachment2; attachment2 = new Attachment(screenPic);//sara mail.Attachments.Add(attachment2); Debug.WriteLine("add screen pic"); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "rcza voco ctyq ptal"); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); mail.Attachments.Dispose(); Thread.Sleep(120000); if (File.Exists(cameraPic)) { File.Delete(cameraPic); } if (File.Exists(screenPic)) { File.Delete(screenPic); } Debug.WriteLine("send email seccess"); } catch (SmtpException ex) { Console.WriteLine("fail send mailllll: \n" + ex); // if no internet - save imadiate alert in DB string date = DateTime.Now.ToString(); DBclient DBInstance = DBclient.Instance; DBInstance.fillReportImmediateTable(triggerName, TriggerDescription, triggerDetails, date); } catch (Exception ex) { Console.WriteLine("fail send mail: \n" + ex); } }
public Attachment getAttachmentFromDialog(CardList card, Activity activity) { ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); Attachment returnAttachment = new Attachment(); string cardDiv = ""; string cardVal = ""; List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); HistoryLog("CARD IMG START"); if (card.imgUrl != null) { HistoryLog("FB CARD IMG " + card.imgUrl); cardImages.Add(new CardImage(url: card.imgUrl)); } HistoryLog("CARD BTN1 START"); if (activity.ChannelId.Equals("facebook") && card.btn1Type == null && !string.IsNullOrEmpty(card.cardDivision) && card.cardDivision.Equals("play") && !string.IsNullOrEmpty(card.cardValue)) { CardAction plButton = new CardAction(); plButton = new CardAction() { Value = card.cardValue, Type = "openUrl", Title = "영상보기" }; cardButtons.Add(plButton); } else if (card.btn1Type != null) { CardAction plButton = new CardAction(); plButton = new CardAction() { Value = card.btn1Context, Type = card.btn1Type, Title = card.btn1Title }; cardButtons.Add(plButton); } if (card.btn2Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN2 START"); plButton = new CardAction() { Value = card.btn2Context, Type = card.btn2Type, Title = card.btn2Title }; cardButtons.Add(plButton); } if (card.btn3Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN3 START"); plButton = new CardAction() { Value = card.btn3Context, Type = card.btn3Type, Title = card.btn3Title }; cardButtons.Add(plButton); } if (card.btn4Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN4 START"); plButton = new CardAction() { Value = card.btn4Context, Type = card.btn4Type, Title = card.btn4Title }; cardButtons.Add(plButton); } if (!string.IsNullOrEmpty(card.cardDivision)) { cardDiv = card.cardDivision; } if (!string.IsNullOrEmpty(card.cardValue)) { //cardVal = priceMediaDlgList[i].cardValue.Replace(); cardVal = card.cardValue; } if (activity.ChannelId.Equals("facebook") && cardButtons.Count < 1 && cardImages.Count < 1) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1"); Activity reply_facebook = activity.CreateReply(); reply_facebook.Recipient = activity.From; reply_facebook.Type = "message"; HistoryLog("facebook card Text : " + card.cardText); reply_facebook.Text = card.cardText; var reply_ment_facebook = connector.Conversations.SendToConversationAsync(reply_facebook); } else { HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1"); HeroCard plCard = new UserHeroCard(); if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(card.cardValue)) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)"); plCard = new UserHeroCard() { Title = card.cardTitle, Images = cardImages, Buttons = cardButtons, Gesture = card.gesture //2018-04-24 : 제스처 추가 }; returnAttachment = plCard.ToAttachment(); } else { HistoryLog("!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)"); if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(card.cardTitle)) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)"); plCard = new UserHeroCard() { Title = "선택해 주세요", Text = card.cardText, Images = cardImages, Buttons = cardButtons, Card_division = cardDiv, Card_value = cardVal, Gesture = card.gesture //2018-04-24 : 제스처 추가 }; returnAttachment = plCard.ToAttachment(); } else { HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)"); plCard = new UserHeroCard() { Title = card.cardTitle, Text = card.cardText, Images = cardImages, Buttons = cardButtons, Card_division = cardDiv, Card_value = cardVal, Gesture = card.gesture //2018-04-24 : 제스처 추가 }; returnAttachment = plCard.ToAttachment(); } } } //HeroCard plCard = new UserHeroCard() //{ // Title = card.cardTitle, // Text = card.cardText, // Images = cardImages, // Buttons = cardButtons, // Card_division = cardDiv, // Card_value = cardVal //}; //returnAttachment = plCard.ToAttachment(); return(returnAttachment); }
/// <summary> /// ДАННЫЙ МЕТОД НЕ РЕАЛИЗОВАН!!! /// </summary> /// <param name="attach"></param> /// <returns></returns> /// <remarks> /// Для вызова этого метода Ваше приложение должно иметь права с битовой маской, содержащей <see cref="Settings.Video"/>. /// Страница документации ВКонтакте <see href="http://vk.com/dev/video.editComment"/>. /// </remarks> public bool EditComment(Attachment attach) { // todo add version with attachment throw new NotImplementedException(); }
public Attachment getAttachmentFromDialog(DialogList dlg, Activity activity) { Attachment returnAttachment = new Attachment(); ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl)); if (dlg.dlgType.Equals(MessagesController.TEXTDLG)) { if (!activity.ChannelId.Equals("facebook")) { UserHeroCard plCard = new UserHeroCard() { Title = dlg.cardTitle, Text = dlg.cardText, Gesture = dlg.gesture }; returnAttachment = plCard.ToAttachment(); } } else if (dlg.dlgType.Equals(MessagesController.MEDIADLG)) { string cardDiv = ""; string cardVal = ""; List <CardImage> cardImages = new List <CardImage>(); List <CardAction> cardButtons = new List <CardAction>(); HistoryLog("CARD IMG START"); if (dlg.mediaUrl != null) { HistoryLog("FB CARD IMG " + dlg.mediaUrl); cardImages.Add(new CardImage(url: dlg.mediaUrl)); } HistoryLog("CARD BTN1 START"); if (activity.ChannelId.Equals("facebook") && dlg.btn1Type == null && !string.IsNullOrEmpty(dlg.cardDivision) && dlg.cardDivision.Equals("play") && !string.IsNullOrEmpty(dlg.cardValue)) { CardAction plButton = new CardAction(); plButton = new CardAction() { Value = dlg.cardValue, Type = "openUrl", Title = "영상보기" }; cardButtons.Add(plButton); } else if (dlg.btn1Type != null) { CardAction plButton = new CardAction(); plButton = new CardAction() { Value = dlg.btn1Context, Type = dlg.btn1Type, Title = dlg.btn1Title }; cardButtons.Add(plButton); } if (dlg.btn2Type != null) { if (!(activity.ChannelId == "facebook" && dlg.btn2Title == "나에게 맞는 모델 추천")) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN2 START"); plButton = new CardAction() { Value = dlg.btn2Context, Type = dlg.btn2Type, Title = dlg.btn2Title }; cardButtons.Add(plButton); } } if (dlg.btn3Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN3 START"); plButton = new CardAction() { Value = dlg.btn3Context, Type = dlg.btn3Type, Title = dlg.btn3Title }; cardButtons.Add(plButton); } if (dlg.btn4Type != null) { CardAction plButton = new CardAction(); HistoryLog("CARD BTN4 START"); plButton = new CardAction() { Value = dlg.btn4Context, Type = dlg.btn4Type, Title = dlg.btn4Title }; cardButtons.Add(plButton); } if (!string.IsNullOrEmpty(dlg.cardDivision)) { cardDiv = dlg.cardDivision; } if (!string.IsNullOrEmpty(dlg.cardValue)) { //cardVal = priceMediaDlgList[i].cardValue.Replace(); cardVal = dlg.cardValue; } HistoryLog("!!!!!FB CARD BTN1 START channelID.Equals(facebook) && cardButtons.Count < 1 && cardImages.Count < 1"); HeroCard plCard = new UserHeroCard(); if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardTitle)) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)"); plCard = new UserHeroCard() { Title = "선택해 주세요", Text = dlg.cardText, Images = cardImages, Buttons = cardButtons, Card_division = cardDiv, Card_value = cardVal }; returnAttachment = plCard.ToAttachment(); } else if (activity.ChannelId == "facebook" && string.IsNullOrEmpty(dlg.cardValue)) { HistoryLog("FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardValue)"); plCard = new UserHeroCard() { Title = dlg.cardTitle, Images = cardImages, Buttons = cardButtons }; returnAttachment = plCard.ToAttachment(); } else { HistoryLog("!!!!!!!!FB CARD BTN1 START channelID.Equals(facebook) && string.IsNullOrEmpty(card.cardTitle)"); plCard = new UserHeroCard() { Title = dlg.cardTitle, Text = dlg.cardText, Images = cardImages, Buttons = cardButtons, Card_division = cardDiv, Card_value = cardVal }; returnAttachment = plCard.ToAttachment(); } } else { Debug.WriteLine("Dialog Type Error : " + dlg.dlgType); } return(returnAttachment); }
public virtual void LateUpdate() { if (!valid) { return; } // Exit early if there is nothing to render if (!meshRenderer.enabled && submeshRenderers.Length == 0) { return; } // Count vertices and submesh triangles. int vertexCount = 0; int submeshTriangleCount = 0, submeshFirstVertex = 0, submeshStartSlotIndex = 0; Material lastMaterial = null; ExposedList <Slot> drawOrder = skeleton.drawOrder; var drawOrderItems = drawOrder.Items; int drawOrderCount = drawOrder.Count; int submeshSeparatorSlotsCount = submeshSeparatorSlots.Count; bool renderMeshes = this.renderMeshes; // Clear last state of attachments and submeshes MeshState.SingleMeshState workingState = meshState.buffer; var workingAttachments = workingState.attachments; workingAttachments.Clear(true); workingState.UpdateAttachmentCount(drawOrderCount); var workingAttachmentsItems = workingAttachments.Items; // Make sure to not add to or remove from ExposedList inside the loop below var workingFlips = workingState.attachmentsFlipState; var workingFlipsItems = workingState.attachmentsFlipState.Items; // Make sure to not add to or remove from ExposedList inside the loop below var workingSubmeshArguments = workingState.addSubmeshArguments; // Items array should not be cached. There is dynamic writing to this object. workingSubmeshArguments.Clear(false); MeshState.SingleMeshState storedState = useMesh1 ? meshState.stateMesh1 : meshState.stateMesh2; var storedAttachments = storedState.attachments; var storedAttachmentsItems = storedAttachments.Items; // Make sure to not add to or remove from ExposedList inside the loop below var storedFlips = storedState.attachmentsFlipState; var storedFlipsItems = storedFlips.Items; // Make sure to not add to or remove from ExposedList inside the loop below bool mustUpdateMeshStructure = storedState.requiresUpdate || // Force update if the mesh was cleared. (prevents flickering due to incorrect state) drawOrder.Count != storedAttachments.Count || // Number of slots changed (when does this happen?) immutableTriangles != storedState.immutableTriangles; // Immutable Triangles flag changed. for (int i = 0; i < drawOrderCount; i++) { Slot slot = drawOrderItems[i]; Bone bone = slot.bone; Attachment attachment = slot.attachment; object rendererObject; // An AtlasRegion in plain Spine-Unity. Spine-TK2D hooks into TK2D's system. eventual source of Material object. int attachmentVertexCount, attachmentTriangleCount; // Handle flipping for normals (for lighting). bool worldScaleIsSameSigns = ((bone.worldScaleY >= 0f) == (bone.worldScaleX >= 0f)); bool flip = frontFacing && ((bone.worldFlipX != bone.worldFlipY) == worldScaleIsSameSigns); // TODO: bone flipX and flipY will be removed in Spine 3.0 workingFlipsItems[i] = flip; workingAttachmentsItems[i] = attachment; mustUpdateMeshStructure = mustUpdateMeshStructure || // Always prefer short circuited or. || and not |=. (attachment != storedAttachmentsItems[i]) || // Attachment order changed. // This relies on the drawOrder.Count != storedAttachments.Count check above as a bounds check. (flip != storedFlipsItems[i]); // Flip states changed. var regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) { rendererObject = regionAttachment.RendererObject; attachmentVertexCount = 4; attachmentTriangleCount = 6; } else { if (!renderMeshes) { continue; } var meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) { rendererObject = meshAttachment.RendererObject; attachmentVertexCount = meshAttachment.vertices.Length >> 1; attachmentTriangleCount = meshAttachment.triangles.Length; } else { var skinnedMeshAttachment = attachment as SkinnedMeshAttachment; if (skinnedMeshAttachment != null) { rendererObject = skinnedMeshAttachment.RendererObject; attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1; attachmentTriangleCount = skinnedMeshAttachment.triangles.Length; } else { continue; } } } #if !SPINE_TK2D Material material = (Material)((AtlasRegion)rendererObject).page.rendererObject; #else Material material = (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject; #endif // Populate submesh when material changes. (or when forced to separate by a submeshSeparator) if ((lastMaterial != null && lastMaterial.GetInstanceID() != material.GetInstanceID()) || (submeshSeparatorSlotsCount > 0 && submeshSeparatorSlots.Contains(slot))) { workingSubmeshArguments.Add( new MeshState.AddSubmeshArguments { material = lastMaterial, startSlot = submeshStartSlotIndex, endSlot = i, triangleCount = submeshTriangleCount, firstVertex = submeshFirstVertex, isLastSubmesh = false } ); submeshTriangleCount = 0; submeshFirstVertex = vertexCount; submeshStartSlotIndex = i; } lastMaterial = material; submeshTriangleCount += attachmentTriangleCount; vertexCount += attachmentVertexCount; } workingSubmeshArguments.Add( new MeshState.AddSubmeshArguments { material = lastMaterial, startSlot = submeshStartSlotIndex, endSlot = drawOrderCount, triangleCount = submeshTriangleCount, firstVertex = submeshFirstVertex, isLastSubmesh = true } ); mustUpdateMeshStructure = mustUpdateMeshStructure || this.sharedMaterials.Length != workingSubmeshArguments.Count || // Material array changed in size CheckIfMustUpdateMeshStructure(workingSubmeshArguments); // Submesh Argument Array changed. // CheckIfMustUpdateMaterialArray (workingMaterials, sharedMaterials) if (!mustUpdateMeshStructure) { // Narrow phase material array check. var workingMaterials = workingSubmeshArguments.Items; for (int i = 0, n = sharedMaterials.Length; i < n; i++) { if (this.sharedMaterials[i] != workingMaterials[i].material) // Bounds check is implied above. { mustUpdateMeshStructure = true; break; } } } // NOT ELSE if (mustUpdateMeshStructure) { this.submeshMaterials.Clear(); var workingSubmeshArgumentsItems = workingSubmeshArguments.Items; for (int i = 0, n = workingSubmeshArguments.Count; i < n; i++) { AddSubmesh(workingSubmeshArgumentsItems[i], workingFlips); } // Set materials. if (submeshMaterials.Count == sharedMaterials.Length) { submeshMaterials.CopyTo(sharedMaterials); } else { sharedMaterials = submeshMaterials.ToArray(); } meshRenderer.sharedMaterials = sharedMaterials; } // Ensure mesh data is the right size. Vector3[] vertices = this.vertices; bool newTriangles = vertexCount > vertices.Length; if (newTriangles) { // Not enough vertices, increase size. this.vertices = vertices = new Vector3[vertexCount]; this.colors = new Color32[vertexCount]; this.uvs = new Vector2[vertexCount]; mesh1.Clear(); mesh2.Clear(); meshState.stateMesh1.requiresUpdate = true; meshState.stateMesh2.requiresUpdate = true; } else { // Too many vertices, zero the extra. Vector3 zero = Vector3.zero; for (int i = vertexCount, n = meshState.vertexCount; i < n; i++) { vertices[i] = zero; } } meshState.vertexCount = vertexCount; // Setup mesh. float zSpacing = this.zSpacing; float[] tempVertices = this.tempVertices; Vector2[] uvs = this.uvs; Color32[] colors = this.colors; int vertexIndex = 0; Color32 color; float a = skeleton.a * 255, r = skeleton.r, g = skeleton.g, b = skeleton.b; Vector3 meshBoundsMin; Vector3 meshBoundsMax; if (vertexCount == 0) { meshBoundsMin = new Vector3(0, 0, 0); meshBoundsMax = new Vector3(0, 0, 0); } else { meshBoundsMin.x = int.MaxValue; meshBoundsMin.y = int.MaxValue; meshBoundsMax.x = int.MinValue; meshBoundsMax.y = int.MinValue; if (zSpacing > 0f) { meshBoundsMin.z = 0f; meshBoundsMax.z = zSpacing * (drawOrderCount - 1); } else { meshBoundsMin.z = zSpacing * (drawOrderCount - 1); meshBoundsMax.z = 0f; } int i = 0; do { Slot slot = drawOrderItems[i]; Attachment attachment = slot.attachment; RegionAttachment regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) { regionAttachment.ComputeWorldVertices(slot.bone, tempVertices); float z = i * zSpacing; float x1 = tempVertices[RegionAttachment.X1], y1 = tempVertices[RegionAttachment.Y1]; float x2 = tempVertices[RegionAttachment.X2], y2 = tempVertices[RegionAttachment.Y2]; float x3 = tempVertices[RegionAttachment.X3], y3 = tempVertices[RegionAttachment.Y3]; float x4 = tempVertices[RegionAttachment.X4], y4 = tempVertices[RegionAttachment.Y4]; vertices[vertexIndex].x = x1; vertices[vertexIndex].y = y1; vertices[vertexIndex].z = z; vertices[vertexIndex + 1].x = x4; vertices[vertexIndex + 1].y = y4; vertices[vertexIndex + 1].z = z; vertices[vertexIndex + 2].x = x2; vertices[vertexIndex + 2].y = y2; vertices[vertexIndex + 2].z = z; vertices[vertexIndex + 3].x = x3; vertices[vertexIndex + 3].y = y3; vertices[vertexIndex + 3].z = z; color.a = (byte)(a * slot.a * regionAttachment.a); color.r = (byte)(r * slot.r * regionAttachment.r * color.a); color.g = (byte)(g * slot.g * regionAttachment.g * color.a); color.b = (byte)(b * slot.b * regionAttachment.b * color.a); if (slot.data.blendMode == BlendMode.additive) { color.a = 0; } colors[vertexIndex] = color; colors[vertexIndex + 1] = color; colors[vertexIndex + 2] = color; colors[vertexIndex + 3] = color; float[] regionUVs = regionAttachment.uvs; uvs[vertexIndex].x = regionUVs[RegionAttachment.X1]; uvs[vertexIndex].y = regionUVs[RegionAttachment.Y1]; uvs[vertexIndex + 1].x = regionUVs[RegionAttachment.X4]; uvs[vertexIndex + 1].y = regionUVs[RegionAttachment.Y4]; uvs[vertexIndex + 2].x = regionUVs[RegionAttachment.X2]; uvs[vertexIndex + 2].y = regionUVs[RegionAttachment.Y2]; uvs[vertexIndex + 3].x = regionUVs[RegionAttachment.X3]; uvs[vertexIndex + 3].y = regionUVs[RegionAttachment.Y3]; // Calculate min/max X if (x1 < meshBoundsMin.x) { meshBoundsMin.x = x1; } else if (x1 > meshBoundsMax.x) { meshBoundsMax.x = x1; } if (x2 < meshBoundsMin.x) { meshBoundsMin.x = x2; } else if (x2 > meshBoundsMax.x) { meshBoundsMax.x = x2; } if (x3 < meshBoundsMin.x) { meshBoundsMin.x = x3; } else if (x3 > meshBoundsMax.x) { meshBoundsMax.x = x3; } if (x4 < meshBoundsMin.x) { meshBoundsMin.x = x4; } else if (x4 > meshBoundsMax.x) { meshBoundsMax.x = x4; } // Calculate min/max Y if (y1 < meshBoundsMin.y) { meshBoundsMin.y = y1; } else if (y1 > meshBoundsMax.y) { meshBoundsMax.y = y1; } if (y2 < meshBoundsMin.y) { meshBoundsMin.y = y2; } else if (y2 > meshBoundsMax.y) { meshBoundsMax.y = y2; } if (y3 < meshBoundsMin.y) { meshBoundsMin.y = y3; } else if (y3 > meshBoundsMax.y) { meshBoundsMax.y = y3; } if (y4 < meshBoundsMin.y) { meshBoundsMin.y = y4; } else if (y4 > meshBoundsMax.y) { meshBoundsMax.y = y4; } vertexIndex += 4; } else { if (!renderMeshes) { continue; } MeshAttachment meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) { int meshVertexCount = meshAttachment.vertices.Length; if (tempVertices.Length < meshVertexCount) { this.tempVertices = tempVertices = new float[meshVertexCount]; } meshAttachment.ComputeWorldVertices(slot, tempVertices); color.a = (byte)(a * slot.a * meshAttachment.a); color.r = (byte)(r * slot.r * meshAttachment.r * color.a); color.g = (byte)(g * slot.g * meshAttachment.g * color.a); color.b = (byte)(b * slot.b * meshAttachment.b * color.a); if (slot.data.blendMode == BlendMode.additive) { color.a = 0; } float[] meshUVs = meshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { float x = tempVertices[ii], y = tempVertices[ii + 1]; vertices[vertexIndex].x = x; vertices[vertexIndex].y = y; vertices[vertexIndex].z = z; colors[vertexIndex] = color; uvs[vertexIndex].x = meshUVs[ii]; uvs[vertexIndex].y = meshUVs[ii + 1]; if (x < meshBoundsMin.x) { meshBoundsMin.x = x; } else if (x > meshBoundsMax.x) { meshBoundsMax.x = x; } if (y < meshBoundsMin.y) { meshBoundsMin.y = y; } else if (y > meshBoundsMax.y) { meshBoundsMax.y = y; } } } else { SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment; if (skinnedMeshAttachment != null) { int meshVertexCount = skinnedMeshAttachment.uvs.Length; if (tempVertices.Length < meshVertexCount) { this.tempVertices = tempVertices = new float[meshVertexCount]; } skinnedMeshAttachment.ComputeWorldVertices(slot, tempVertices); color.a = (byte)(a * slot.a * skinnedMeshAttachment.a); color.r = (byte)(r * slot.r * skinnedMeshAttachment.r * color.a); color.g = (byte)(g * slot.g * skinnedMeshAttachment.g * color.a); color.b = (byte)(b * slot.b * skinnedMeshAttachment.b * color.a); if (slot.data.blendMode == BlendMode.additive) { color.a = 0; } float[] meshUVs = skinnedMeshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { float x = tempVertices[ii], y = tempVertices[ii + 1]; vertices[vertexIndex].x = x; vertices[vertexIndex].y = y; vertices[vertexIndex].z = z; colors[vertexIndex] = color; uvs[vertexIndex].x = meshUVs[ii]; uvs[vertexIndex].y = meshUVs[ii + 1]; if (x < meshBoundsMin.x) { meshBoundsMin.x = x; } else if (x > meshBoundsMax.x) { meshBoundsMax.x = x; } if (y < meshBoundsMin.y) { meshBoundsMin.y = y; } else if (y > meshBoundsMax.y) { meshBoundsMax.y = y; } } } } } } while (++i < drawOrderCount); } // Double buffer mesh. Mesh mesh = useMesh1 ? mesh1 : mesh2; meshFilter.sharedMesh = mesh; mesh.vertices = vertices; mesh.colors32 = colors; mesh.uv = uvs; if (mustUpdateMeshStructure) { int submeshCount = submeshMaterials.Count; mesh.subMeshCount = submeshCount; for (int i = 0; i < submeshCount; ++i) { mesh.SetTriangles(submeshes.Items[i].triangles, i); } // Done updating mesh. storedState.requiresUpdate = false; } Vector3 meshBoundsExtents = meshBoundsMax - meshBoundsMin; Vector3 meshBoundsCenter = meshBoundsMin + meshBoundsExtents * 0.5f; mesh.bounds = new Bounds(meshBoundsCenter, meshBoundsExtents); if (newTriangles && calculateNormals) { Vector3[] normals = new Vector3[vertexCount]; Vector3 normal = new Vector3(0, 0, -1); for (int i = 0; i < vertexCount; i++) { normals[i] = normal; } (useMesh1 ? mesh2 : mesh1).vertices = vertices; // Set other mesh vertices. mesh1.normals = normals; mesh2.normals = normals; if (calculateTangents) { Vector4[] tangents = new Vector4[vertexCount]; Vector3 tangent = new Vector3(0, 0, 1); for (int i = 0; i < vertexCount; i++) { tangents[i] = tangent; } mesh1.tangents = tangents; mesh2.tangents = tangents; } } // Update previous state storedState.immutableTriangles = immutableTriangles; storedAttachments.Clear(true); storedAttachments.GrowIfNeeded(workingAttachments.Capacity); storedAttachments.Count = workingAttachments.Count; workingAttachments.CopyTo(storedAttachments.Items); storedFlips.GrowIfNeeded(workingFlips.Capacity); storedFlips.Count = workingFlips.Count; workingFlips.CopyTo(storedFlips.Items); storedState.addSubmeshArguments.GrowIfNeeded(workingSubmeshArguments.Capacity); storedState.addSubmeshArguments.Count = workingSubmeshArguments.Count; workingSubmeshArguments.CopyTo(storedState.addSubmeshArguments.Items); // Submesh Renderers if (submeshRenderers.Length > 0) { for (int i = 0; i < submeshRenderers.Length; i++) { SkeletonUtilitySubmeshRenderer submeshRenderer = submeshRenderers[i]; if (submeshRenderer.submeshIndex < sharedMaterials.Length) { submeshRenderer.SetMesh(meshRenderer, useMesh1 ? mesh1 : mesh2, sharedMaterials[submeshRenderer.submeshIndex]); } else { submeshRenderer.GetComponent <Renderer>().enabled = false; } } } useMesh1 = !useMesh1; }
public static bool SendMail(EmailHelper email, bool insertQueue = true) { if (insertQueue) { EmailQueueList.Add(email); return(true); } string email_account = ConfigManager.ReadSetting("Email"); string email_admin = ConfigManager.ReadSetting("EmailRecive"); string email_sendas = ConfigManager.ReadSetting("EmailSendAs"); if (email.Receiver == null || email.Receiver.Count == 0) { email.Receiver.Add(email_admin); } if (string.IsNullOrEmpty(email.Sender_Email)) { email.Sender_Email = email_sendas; } if (email.Receiver == null || email.Receiver.Count == 0 || string.IsNullOrEmpty(email.Receiver.FirstOrDefault())) { email.Receiver = new List <string>(); email.Receiver.Add(email_admin); } if (string.IsNullOrEmpty(email.Sender_Name)) { email.Sender_Name = "Photobookmart"; } string password_account = ConfigManager.ReadSetting("Password"); string host = ConfigManager.ReadSetting("Host"); int port = int.Parse(ConfigManager.ReadSetting("Port")); bool enablessl = Convert.ToBoolean(ConfigManager.ReadSetting("EnableSSL")); SmtpClient SmtpServer = new SmtpClient(); SmtpServer.UseDefaultCredentials = false; SmtpServer.Credentials = new System.Net.NetworkCredential(email_account, password_account); SmtpServer.Port = port; SmtpServer.Host = host; SmtpServer.EnableSsl = enablessl; MailMessage mail = new MailMessage(); string emailto = ""; foreach (var s in email.Receiver) { if (emailto != "") { emailto += ","; } emailto += s; } // render before send email.RazorRender(); try { mail.From = new MailAddress(email.Sender_Email, email.Sender_Name, System.Text.Encoding.UTF8); mail.To.Add(emailto); mail.Subject = email.Title; mail.Body = email.Body; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; mail.ReplyToList.Add(email.Sender_Email); //mail.ReplyTo = new MailAddress(email_account); mail.Priority = MailPriority.High; mail.IsBodyHtml = true; // attachment foreach (var file_name in email.Attachment) { if (!File.Exists(file_name)) { continue; } FileStream fileStream = File.OpenRead(file_name); Attachment messageAttachment = new Attachment(fileStream, Path.GetFileName(file_name)); mail.Attachments.Add(messageAttachment); } SmtpServer.Send(mail); return(true); } catch (Exception) { return(false); } }
private void AddSubmesh(MeshState.AddSubmeshArguments submeshArguments, ExposedList <bool> flipStates) //submeshArguments is a struct, so it's ok. { int submeshIndex = submeshMaterials.Count; submeshMaterials.Add(submeshArguments.material); if (submeshes.Count <= submeshIndex) { submeshes.Add(new Submesh()); } else if (immutableTriangles) { return; } Submesh currentSubmesh = submeshes.Items[submeshIndex]; int[] triangles = currentSubmesh.triangles; int triangleCount = submeshArguments.triangleCount; int firstVertex = submeshArguments.firstVertex; int trianglesCapacity = triangles.Length; if (submeshArguments.isLastSubmesh && trianglesCapacity > triangleCount) { // Last submesh may have more triangles than required, so zero triangles to the end. for (int i = triangleCount; i < trianglesCapacity; i++) { triangles[i] = 0; } currentSubmesh.triangleCount = triangleCount; } else if (trianglesCapacity != triangleCount) { // Reallocate triangles when not the exact size needed. currentSubmesh.triangles = triangles = new int[triangleCount]; currentSubmesh.triangleCount = 0; } if (!this.renderMeshes && !this.frontFacing) { // Use stored triangles if possible. if (currentSubmesh.firstVertex != firstVertex || currentSubmesh.triangleCount < triangleCount) //|| currentSubmesh.triangleCount == 0 { currentSubmesh.triangleCount = triangleCount; currentSubmesh.firstVertex = firstVertex; for (int i = 0; i < triangleCount; i += 6, firstVertex += 4) { triangles[i] = firstVertex; triangles[i + 1] = firstVertex + 2; triangles[i + 2] = firstVertex + 1; triangles[i + 3] = firstVertex + 2; triangles[i + 4] = firstVertex + 3; triangles[i + 5] = firstVertex + 1; } } return; } // Iterate through all slots and store their triangles. var drawOrderItems = skeleton.DrawOrder.Items; // Make sure to not modify ExposedList inside the loop below var flipStatesItems = flipStates.Items; // Make sure to not modify ExposedList inside the loop below int triangleIndex = 0; // Modified by loop for (int i = submeshArguments.startSlot, n = submeshArguments.endSlot; i < n; i++) { Attachment attachment = drawOrderItems[i].attachment; bool flip = flipStatesItems[i]; // Add RegionAttachment triangles if (attachment is RegionAttachment) { if (!flip) { triangles[triangleIndex] = firstVertex; triangles[triangleIndex + 1] = firstVertex + 2; triangles[triangleIndex + 2] = firstVertex + 1; triangles[triangleIndex + 3] = firstVertex + 2; triangles[triangleIndex + 4] = firstVertex + 3; triangles[triangleIndex + 5] = firstVertex + 1; } else { triangles[triangleIndex] = firstVertex + 1; triangles[triangleIndex + 1] = firstVertex + 2; triangles[triangleIndex + 2] = firstVertex; triangles[triangleIndex + 3] = firstVertex + 1; triangles[triangleIndex + 4] = firstVertex + 3; triangles[triangleIndex + 5] = firstVertex + 2; } triangleIndex += 6; firstVertex += 4; continue; } // Add (Skinned)MeshAttachment triangles int[] attachmentTriangles; int attachmentVertexCount; var meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) { attachmentVertexCount = meshAttachment.vertices.Length >> 1; // length/2 attachmentTriangles = meshAttachment.triangles; } else { var skinnedMeshAttachment = attachment as SkinnedMeshAttachment; if (skinnedMeshAttachment != null) { attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1; // length/2 attachmentTriangles = skinnedMeshAttachment.triangles; } else { continue; } } if (flip) { for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii += 3, triangleIndex += 3) { triangles[triangleIndex + 2] = firstVertex + attachmentTriangles[ii]; triangles[triangleIndex + 1] = firstVertex + attachmentTriangles[ii + 1]; triangles[triangleIndex] = firstVertex + attachmentTriangles[ii + 2]; } } else { for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleIndex++) { triangles[triangleIndex] = firstVertex + attachmentTriangles[ii]; } } firstVertex += attachmentVertexCount; } }
private bool SendEmail(string email, string name, string subject, string message) { try { using (MailMessage mail = new MailMessage()) { mail.From = new MailAddress(BlogSettings.Instance.Email, name); mail.ReplyToList.Add(new MailAddress(email, name)); mail.To.Add(BlogSettings.Instance.Email); mail.Subject = BlogSettings.Instance.EmailSubjectPrefix + " " + Resources.labels.email.ToLower() + " - " + subject; mail.Body = "<div style=\"font: 11px verdana, arial\">"; mail.Body += Server.HtmlEncode(message).Replace("\n", "<br />") + "<br /><br />"; mail.Body += "<hr /><br />"; mail.Body += "<h3>" + Resources.labels.contactAuthorInformation + "</h3>"; mail.Body += "<div style=\"font-size:10px;line-height:16px\">"; mail.Body += "<strong>" + Resources.labels.name + ":</strong> " + Server.HtmlEncode(name) + "<br />"; mail.Body += "<strong>" + Resources.labels.email + ":</strong> " + Server.HtmlEncode(email) + "<br />"; if (ViewState["url"] != null) { mail.Body += string.Format("<strong>" + Resources.labels.website + ":</strong> <a href=\"{0}\">{0}</a><br />", ViewState["url"]); } if (ViewState["country"] != null) { mail.Body += "<strong>" + Resources.labels.countryCode + ":</strong> " + ((string)ViewState["country"]).ToUpperInvariant() + "<br />"; } if (HttpContext.Current != null) { mail.Body += "<strong>" + Resources.labels.contactIPAddress + ":</strong> " + Utils.GetClientIP() + "<br />"; mail.Body += "<strong>" + Resources.labels.contactUserAgent + ":</strong> " + HttpContext.Current.Request.UserAgent; } if (txtAttachment.HasFile) { Attachment attachment = new Attachment(txtAttachment.PostedFile.InputStream, txtAttachment.FileName); mail.Attachments.Add(attachment); } if (Utils.SendMailMessage(mail).Length > 0) { return(false); } ; } return(true); } catch (Exception ex) { if (Security.IsAuthorizedTo(Rights.ViewDetailedErrorMessages)) { if (ex.InnerException != null) { lblStatus.Text = ex.InnerException.Message; } else { lblStatus.Text = ex.Message; } } return(false); } }
protected virtual void GenerateMethod(Attachment attachment, StreamWriter stream, string indent) { stream.WriteLine("{0}\tprotected:", indent); }
public virtual void LateUpdate() { if (!valid) { return; } // Count vertices and submesh triangles. int vertexCount = 0; int submeshTriangleCount = 0, submeshFirstVertex = 0, submeshStartSlotIndex = 0; Material lastMaterial = null; submeshMaterials.Clear(); List <Slot> drawOrder = skeleton.DrawOrder; int drawOrderCount = drawOrder.Count; bool renderMeshes = this.renderMeshes; for (int i = 0; i < drawOrderCount; i++) { Slot slot = drawOrder[i]; Attachment attachment = slot.attachment; object rendererObject; int attachmentVertexCount, attachmentTriangleCount; if (attachment is RegionAttachment) { rendererObject = ((RegionAttachment)attachment).RendererObject; attachmentVertexCount = 4; attachmentTriangleCount = 6; } else { if (!renderMeshes) { continue; } if (attachment is MeshAttachment) { MeshAttachment meshAttachment = (MeshAttachment)attachment; rendererObject = meshAttachment.RendererObject; attachmentVertexCount = meshAttachment.vertices.Length >> 1; attachmentTriangleCount = meshAttachment.triangles.Length; } else if (attachment is SkinnedMeshAttachment) { SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment; rendererObject = meshAttachment.RendererObject; attachmentVertexCount = meshAttachment.uvs.Length >> 1; attachmentTriangleCount = meshAttachment.triangles.Length; } else { continue; } } // Populate submesh when material changes. Material material = (Material)rendererObject; if ((lastMaterial != material && lastMaterial != null) || slot.Data.name[0] == '*') { AddSubmesh(lastMaterial, submeshStartSlotIndex, i, submeshTriangleCount, submeshFirstVertex, false); submeshTriangleCount = 0; submeshFirstVertex = vertexCount; submeshStartSlotIndex = i; } lastMaterial = material; submeshTriangleCount += attachmentTriangleCount; vertexCount += attachmentVertexCount; } AddSubmesh(lastMaterial, submeshStartSlotIndex, drawOrderCount, submeshTriangleCount, submeshFirstVertex, true); // Set materials. if (submeshMaterials.Count == sharedMaterials.Length) { submeshMaterials.CopyTo(sharedMaterials); } else { sharedMaterials = submeshMaterials.ToArray(); } GetComponent <Renderer>().sharedMaterials = sharedMaterials; // Ensure mesh data is the right size. Vector3[] vertices = this.vertices; bool newTriangles = vertexCount > vertices.Length; if (newTriangles) { // Not enough vertices, increase size. this.vertices = vertices = new Vector3[vertexCount]; this.colors = new Color32[vertexCount]; this.uvs = new Vector2[vertexCount]; mesh1.Clear(); mesh2.Clear(); } else { // Too many vertices, zero the extra. Vector3 zero = Vector3.zero; for (int i = vertexCount, n = lastVertexCount; i < n; i++) { vertices[i] = zero; } } lastVertexCount = vertexCount; // Setup mesh. float[] tempVertices = this.tempVertices; Vector2[] uvs = this.uvs; Color32[] colors = this.colors; int vertexIndex = 0; Color32 color = new Color32(); float zSpacing = this.zSpacing; float a = skeleton.a * 255, r = skeleton.r, g = skeleton.g, b = skeleton.b; for (int i = 0; i < drawOrderCount; i++) { Slot slot = drawOrder[i]; Attachment attachment = slot.attachment; if (attachment is RegionAttachment) { RegionAttachment regionAttachment = (RegionAttachment)attachment; regionAttachment.ComputeWorldVertices(slot.bone, tempVertices); float z = i * zSpacing; vertices[vertexIndex] = new Vector3(tempVertices[RegionAttachment.X1], tempVertices[RegionAttachment.Y1], z); vertices[vertexIndex + 1] = new Vector3(tempVertices[RegionAttachment.X4], tempVertices[RegionAttachment.Y4], z); vertices[vertexIndex + 2] = new Vector3(tempVertices[RegionAttachment.X2], tempVertices[RegionAttachment.Y2], z); vertices[vertexIndex + 3] = new Vector3(tempVertices[RegionAttachment.X3], tempVertices[RegionAttachment.Y3], z); color.a = (byte)(a * slot.a * regionAttachment.a); color.r = (byte)(r * slot.r * regionAttachment.r * color.a); color.g = (byte)(g * slot.g * regionAttachment.g * color.a); color.b = (byte)(b * slot.b * regionAttachment.b * color.a); if (slot.data.additiveBlending) { color.a = 0; } colors[vertexIndex] = color; colors[vertexIndex + 1] = color; colors[vertexIndex + 2] = color; colors[vertexIndex + 3] = color; float[] regionUVs = regionAttachment.uvs; uvs[vertexIndex] = new Vector2(regionUVs[RegionAttachment.X1], regionUVs[RegionAttachment.Y1]); uvs[vertexIndex + 1] = new Vector2(regionUVs[RegionAttachment.X4], regionUVs[RegionAttachment.Y4]); uvs[vertexIndex + 2] = new Vector2(regionUVs[RegionAttachment.X2], regionUVs[RegionAttachment.Y2]); uvs[vertexIndex + 3] = new Vector2(regionUVs[RegionAttachment.X3], regionUVs[RegionAttachment.Y3]); vertexIndex += 4; } else { if (!renderMeshes) { continue; } if (attachment is MeshAttachment) { MeshAttachment meshAttachment = (MeshAttachment)attachment; int meshVertexCount = meshAttachment.vertices.Length; if (tempVertices.Length < meshVertexCount) { tempVertices = new float[meshVertexCount]; } meshAttachment.ComputeWorldVertices(slot, tempVertices); color.a = (byte)(a * slot.a * meshAttachment.a); color.r = (byte)(r * slot.r * meshAttachment.r * color.a); color.g = (byte)(g * slot.g * meshAttachment.g * color.a); color.b = (byte)(b * slot.b * meshAttachment.b * color.a); if (slot.data.additiveBlending) { color.a = 0; } float[] meshUVs = meshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { vertices[vertexIndex] = new Vector3(tempVertices[ii], tempVertices[ii + 1], z); colors[vertexIndex] = color; uvs[vertexIndex] = new Vector2(meshUVs[ii], meshUVs[ii + 1]); } } else if (attachment is SkinnedMeshAttachment) { SkinnedMeshAttachment meshAttachment = (SkinnedMeshAttachment)attachment; int meshVertexCount = meshAttachment.uvs.Length; if (tempVertices.Length < meshVertexCount) { tempVertices = new float[meshVertexCount]; } meshAttachment.ComputeWorldVertices(slot, tempVertices); color.a = (byte)(a * slot.a * meshAttachment.a); color.r = (byte)(r * slot.r * meshAttachment.r * color.a); color.g = (byte)(g * slot.g * meshAttachment.g * color.a); color.b = (byte)(b * slot.b * meshAttachment.b * color.a); if (slot.data.additiveBlending) { color.a = 0; } float[] meshUVs = meshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { vertices[vertexIndex] = new Vector3(tempVertices[ii], tempVertices[ii + 1], z); colors[vertexIndex] = color; uvs[vertexIndex] = new Vector2(meshUVs[ii], meshUVs[ii + 1]); } } } } // Double buffer mesh. Mesh mesh = useMesh1 ? mesh1 : mesh2; meshFilter.sharedMesh = mesh; mesh.vertices = vertices; mesh.colors32 = colors; mesh.uv = uvs; int submeshCount = submeshMaterials.Count; mesh.subMeshCount = submeshCount; for (int i = 0; i < submeshCount; ++i) { mesh.SetTriangles(submeshes[i].triangles, i); } mesh.RecalculateBounds(); if (newTriangles && calculateNormals) { Vector3[] normals = new Vector3[vertexCount]; Vector3 normal = new Vector3(0, 0, -1); for (int i = 0; i < vertexCount; i++) { normals[i] = normal; } (useMesh1 ? mesh2 : mesh1).vertices = vertices; // Set other mesh vertices. mesh1.normals = normals; mesh2.normals = normals; if (calculateTangents) { Vector4[] tangents = new Vector4[vertexCount]; Vector3 tangent = new Vector3(0, 0, 1); for (int i = 0; i < vertexCount; i++) { tangents[i] = tangent; } mesh1.tangents = tangents; mesh2.tangents = tangents; } } useMesh1 = !useMesh1; }
public AttachmentSwitcher(SkeletonAnimation animationController, string slotName, string attachmentName) { _slot = animationController.Skeleton.FindSlot(slotName); _attachment = animationController.Skeleton.GetAttachment(slotName, attachmentName); _initialAttachment = _slot.Attachment; }
public async Task StartAsync(IDialogContext context) { await context.PostAsync("welcome to angkasa pura shopping center, these are our products ?"); Activity replyToConversation = context.MakeMessage() as Activity; replyToConversation.Attachments = new List <Attachment>(); /* * List<CardImage> cardImages = new List<CardImage>(); * cardImages.Add(new CardImage(url: "https://<imageUrl1>")); * * List<CardAction> cardButtons = new List<CardAction>(); * * CardAction plButton = new CardAction() * { * Value = $"https://en.wikipedia.org/wiki/PigLatin", * Type = "openUrl", * Title = "WikiPedia Page" * }; * * cardButtons.Add(plButton); */ List <ReceiptItem> receiptList = new List <ReceiptItem>(); foreach (var item in AirportProduct.GetProducts()) { ReceiptItem lineItem = new ReceiptItem() { Title = $"{item.Name}", Subtitle = $"Product ID: { item.IDProduct}", Text = $"{item.Description}", Image = new CardImage(url: $"{item.UrlImage}"), Price = $"Rp.{item.Harga.ToString("{C:0}")}", Quantity = $"{item.Stock}", Tap = null }; receiptList.Add(lineItem); } ReceiptCard plCard = new ReceiptCard() { Title = "these are our merchant products", //Buttons = cardButtons, Items = receiptList, }; Attachment plAttachment = plCard.ToAttachment(); replyToConversation.Attachments.Add(plAttachment); //send product list await context.PostAsync(replyToConversation); //send confirmation PromptDialog.Confirm( context, AfterShoppingConfirmation, "Do you want to order?", "Oups, I don't understand!", promptStyle: PromptStyle.None); }
protected void Page_Load(object sender, EventArgs e) { try { if (Session["loginVal"].ToString() == "*****@*****.**") { currtst = "€"; } else { currtst = "INR"; } // Generate booking reference number for agent, to find their bookings details.This number is unique for every agent......... string AvailableCash = Session["AvlCash"].ToString(); string bookingref = Session["bookingRef"].ToString(); //Session["bookingRef"] = bookingref; // Complete booking details string....... string BookData = Session["BookData"].ToString().Replace("(HASH)", "#"); string CustomerDetails = BookData.Split('$')[1]; string totpassanger = (CustomerDetails.Split('/')[0].Split(',').Length - 1).ToString(); string agentdetails = CF.CommonFunction.agencydetails(Session["loginVal"].ToString()); string cat = Session["Category"].ToString(); //ftresp //using (var client = new WebClient()) //{ // //string result = client.DownloadString("https://ftcash.com/websdkresponse/responsem.php"); if (Session["HoldBooking"].ToString() == "No") { try { NameValueCollection nvc = Request.Form; if (!string.IsNullOrEmpty(nvc["orderid"])) { ftorderid = nvc["orderid"]; } if (!string.IsNullOrEmpty(nvc["responseDescription"])) { ftresponseDescription = nvc["responseDescription"]; } if (!string.IsNullOrEmpty(nvc["checksum"])) { ftchecksum = nvc["checksum"]; } if (!string.IsNullOrEmpty(nvc["responseCode"])) { ftresponseCode = nvc["responseCode"]; } if (!string.IsNullOrEmpty(nvc["amount"])) { ftamount = nvc["amount"]; } if (!string.IsNullOrEmpty(nvc["mid"])) { ftmid = nvc["mid"]; } if (!string.IsNullOrEmpty(nvc["referenceNumber"])) { ftreferenceNumber = nvc["referenceNumber"]; } string ServerPath = Server.MapPath("~\\FtCash"); string DataFile = bookingref + ".txt"; FileStream fs = new FileStream(ServerPath + "/" + DataFile, FileMode.Create, FileAccess.Write); StreamWriter fp = new StreamWriter(fs, Encoding.UTF8); try { fp.WriteLine(nvc); } catch (Exception Ex) { } finally { fp.Close(); fp = null; } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } } string bookingdetail = BookData + "$" + agentdetails; cls.CommonClass obj = new cls.CommonClass(); string supplier = BookData.Split('$')[0].Split('!')[5]; string bookingresponse = string.Empty; string price = BookData.Split('$')[0].Split('!')[15]; try { if (ftresponseCode == "1") { Response.Redirect("Bankissue.aspx?"); } } catch (Exception ex) { } string ExtraInfo1 = ""; if (BookData.Split('$')[0].Split('!')[5].ToUpper() == "HOTELBEDS") { string[] arr = BookData.Split('$')[0].Split('!'); string response = "", cancellationcharge = ""; string policydet = arr[16] + "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "HOTELBEDS", cat); string deadln = ""; try { if (!string.IsNullOrEmpty(response)) //Parsing cancellation policy....... { XmlDocument doc = CF.CommonFunction.JSONtoXML(response); XmlNodeList cnlplcy = doc.GetElementsByTagName("Cancellationpolicies"); foreach (XmlNode rootnode in cnlplcy) { foreach (XmlNode chnode in rootnode) { cancellationcharge = chnode["Cancellationcharge"].InnerText; ExtraInfo1 = chnode["ExtraInfo1"].InnerText; } } } else { cancellationcharge = "No Cancellation Policy Found. Deadline: " + DateTime.Now.ToString("yyyy-MM-dd"); } // End region of cancellation policy ............... string[] policy = Regex.Split(cancellationcharge, "Deadline: "); string sql1 = "Insert into cancellationPolicy(BookingRef,Policy,Deadline) values("; if (policy.Length > 1) { DateTime daedline = DateTime.ParseExact(policy[1], "dd-MM-yyyy", CultureInfo.InvariantCulture); sql1 += "'" + bookingref + "','" + policy[0] + "','" + daedline.ToString("yyyy-MM-dd") + "')"; deadln = daedline.ToString("yyyy-MM-dd"); } else { sql1 += "'" + bookingref + "','" + policy[0] + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; deadln = DateTime.Now.ToString("yyyy-MM-dd"); } try { DB.CommonDatabase.RunQuery(sql1); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql1, "cancellationPolicy_" + supplier); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } } //End calling cancellation policy........ //Start Calling booking method supplier wise.... string status = ""; string bookingId = ""; try { if (supplier.ToUpper() == "TBO") { bookingresponse = obj.GetHotelBooking(bookingdetail, CustomerDetails, price, totpassanger, supplier); } if (supplier.ToUpper() == "DOTW") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "DESIYA") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "TRAVELBULLZ") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "EZEEGO1") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "," + Session["EzeeGoId"].ToString(), bookingref, supplier); } else if (supplier.ToUpper() == "ABREU") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger, bookingref, supplier); } else if (supplier.ToUpper() == "HOTELBEDS") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "^" + ExtraInfo1, bookingref, supplier); } else if (supplier.ToUpper() == "TRAVSTARZ") { string id = CF.CommonFunction.NewNumber12(); bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "`" + id, bookingref, supplier); } else if (supplier.ToUpper() == "QUANTUM") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "^" + ExtraInfo1, bookingref, supplier); } else if (supplier.ToUpper() == "JACTRAVEL") { bookingresponse = obj.GetHotelBooking(bookingdetail, price, totpassanger + "," + Session["PreBookingToken"].ToString(), bookingref, supplier); } if (supplier.ToUpper() == "DESIYA") { if (bookingresponse.Contains('{') || bookingresponse == "") { } else { Session["bookingdetail"] = bookingdetail; Response.Redirect("pricechange.aspx?oldprice=" + BookData.Split('$')[0].Split('!')[15] + "$" + bookingresponse); } } if (!string.IsNullOrEmpty(bookingresponse)) // Booking Details parsing....... { XmlDocument doc = CF.CommonFunction.JSONtoXML(bookingresponse); XmlNodeList hotelres = doc.GetElementsByTagName("Booking"); foreach (XmlNode hnode in hotelres) { foreach (XmlNode chnode in hnode) { bookingId = chnode["booking_id"].InnerText; status = chnode["confirmation"].InnerText; if (bookingId != "" && status == "") { status = "Confirmed"; } } } } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } //End ............. if (Session["HoldBooking"].ToString() == "Yes") { status = "Hold"; } string sql = ""; string title = ""; string firstname = ""; string lastname = ""; string passport = ""; string GN = ""; for (int i = 0; i < Convert.ToInt16(totpassanger); i++) { title = CustomerDetails.Split('/')[0].Split(',')[i]; firstname = CustomerDetails.Split('/')[1].Split(',')[i]; lastname = CustomerDetails.Split('/')[2].Split(',')[i]; passport = CustomerDetails.Split('/')[3].Split(',')[i]; GN = CustomerDetails.Split('/')[4].Split(',')[i]; sql = "Insert into CustomerDetails(BookingRef, Title, Firstname, Lastname, BookingDate, Passport, GuestNationality) values('" + bookingref + "','" + title + "','" + firstname + "','" + lastname + "','" + DateTime.Now + "','" + passport + "','" + GN + "')"; try { DB.CommonDatabase.RunQuery(sql); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql, "CustomerDetails_" + supplier); } } if (bookingId != "") { // Calling method of cancellation policy.......... string[] arr = BookData.Split('$')[0].Split('!'); string response = ""; string cancellationcharge = ""; if (arr[5].ToUpper() == "TBO") { string policydet = arr[16] + "$" + arr[11]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(policydet, "", "TBO", cat); } else if (arr[5].ToUpper() == "DOTW") { string policydet = "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$"; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "DOTW", cat); } else if (arr[5].ToUpper() == "TRAVELBULLZ") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$" + arr[7] + "~"; cls.CommonClass plcy = new cls.CommonClass(); response = obj.GetCancelPolicy(BookData.Split('$')[2], policydet, "TRAVELBULLZ", cat); } else if (arr[5].ToUpper() == "DESIYA") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[17].Split('*')[1] + "$" + arr[13]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "DESIYA", cat); } else if (arr[5].ToUpper() == "EZEEGO1") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "EZEEGO1", cat); } else if (arr[5].ToUpper() == "ABREU") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7] + "$" + arr[17].TrimEnd('%'); cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "ABREU", "INR"); } else if (arr[5].ToUpper() == "HOTELBEDS") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "HOTELBEDS", cat); } else if (arr[5].ToUpper() == "QUANTUM") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[8] + "$" + arr[13] + "$" + arr[7]; cls.CommonClass plcy = new cls.CommonClass(); response = plcy.GetCancelPolicy(BookData.Split('$')[2], policydet, "QUANTUM", cat); } else if (arr[5].ToUpper() == "JACTRAVEL") { string policydet = arr[16] + "$" + arr[11] + "$" + arr[14] + "$" + arr[5] + "$" + arr[7] + "$" + BookData.Split('$')[0]; cls.CommonClass plcy = new cls.CommonClass(); response = obj.GetCancelPolicy(BookData.Split('$')[2], policydet, "JACTRAVEL", "INR"); } else if (arr[5].ToUpper() == "TRAVSTARZ") { //DateTime dt1 = DateTime.ParseExact(searchparam.Split('^')[0], "dd MMM yyyy", CultureInfo.InvariantCulture); //DateTime dt2 = DateTime.ParseExact(searchparam.Split('^')[1], "dd MMM yyyy", CultureInfo.InvariantCulture); //string formatfromdDate = dt1.ToString("yyyy-MM-dd"); //string formattodDate = dt2.ToString("yyyy-MM-dd"); //string htlid = bookdet.Split('!')[7]; //string rmtype = bookdet.Split('!')[12]; //cls.CommonClass plcy = new cls.CommonClass(); //for (int r = 0; r < rmtype.Split('~').Length; r++) //{ // response += plcy.GetCancelPolicy(htlid, rmtype.Split('~')[r], formatfromdDate, formattodDate); //} //policydet = "$"+arr[11] + "$" + arr[14] + "$" + arr[13] + "$" + arr[7]; //response = obj.GetCancelPolicy(searchparam, policydet, "TRAVSTARZ", cat); // response = bookdet.Split('*')[1];//.Split('~')[0]; } string deadln = ""; try { if (!string.IsNullOrEmpty(response)) //Parsing cancellation policy....... { XmlDocument doc = CF.CommonFunction.JSONtoXML(response); XmlNodeList cnlplcy = doc.GetElementsByTagName("Cancellationpolicies"); foreach (XmlNode rootnode in cnlplcy) { foreach (XmlNode chnode in rootnode) { cancellationcharge = chnode["Cancellationcharge"].InnerText.Replace("'", ""); } } } else { cancellationcharge = "No Cancellation Policy Found. Deadline: " + DateTime.Now.ToString("yyyy-MM-dd"); } // End region of cancellation policy ............... string[] policy = Regex.Split(cancellationcharge, "Deadline: "); sql = "Insert into cancellationPolicy(BookingRef,Policy,Deadline) values("; if (supplier.ToUpper() == "EZEEGO1" || supplier.ToUpper() == "DESIYA") { if (policy.Length > 1) { DateTime daedline = DateTime.Parse(policy[1]); sql += "'" + bookingref + "','" + policy[0] + "','" + daedline.ToString("yyyy-MM-dd") + "')"; deadln = daedline.ToString("yyyy-MM-dd"); } else { sql += "'" + bookingref + "','" + policy[0] + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; deadln = DateTime.Now.ToString("yyyy-MM-dd"); } } else { if (policy.Length > 1) { DateTime daedline; if (supplier == "JACTRAVEL") { daedline = Convert.ToDateTime(policy[1].Split('T')[0]); } else { daedline = DateTime.ParseExact(policy[1], "dd-MM-yyyy", CultureInfo.InvariantCulture); } sql += "'" + bookingref + "','" + policy[0] + "','" + daedline.ToString("yyyy-MM-dd") + "')"; deadln = daedline.ToString("yyyy-MM-dd"); } else { sql += "'" + bookingref + "','" + policy[0] + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "')"; deadln = DateTime.Now.ToString("yyyy-MM-dd"); } } try { DB.CommonDatabase.RunQuery(sql); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql, "cancellationPolicy_" + supplier); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } string HotelName = BookData.Split('$')[0].Split('!')[0]; string chkin = BookData.Split('$')[2].Split('^')[0]; string chkout = BookData.Split('$')[2].Split('^')[1]; string pno = BookData.Split('$')[1].Split('|')[1]; string loginval = Session["loginVal"].ToString(); string emailid = loginval.Split('^')[0]; string address = BookData.Split('$')[0].Split('!')[9]; string ddl = ""; try { ddl = Convert.ToDateTime(deadln).ToString("yyyy-MM-dd"); } catch (Exception) { ddl = ""; } try { sql = "Insert into HotelBookingDetails(BookingReference, BookingId, BkDetails, EmailID, BookingDate, Status, Supplier, CheckIn, CheckOut, HotelName, PhoneNo, Address, Deadline) values("; sql += "'" + bookingref + "',"; sql += "'" + bookingId + "',"; sql += "'" + bookingdetail + "',"; sql += "'" + emailid + "',"; sql += "'" + DateTime.Now.ToString("dd-MM-yyyy") + "',"; sql += "'" + status + "',"; sql += "'" + supplier + "',"; sql += "'" + Convert.ToDateTime(chkin).ToString("yyyy-MM-dd") + "',"; sql += "'" + Convert.ToDateTime(chkout).ToString("yyyy-MM-dd") + "',"; sql += "'" + HotelName + "',"; sql += "'" + pno + "',"; sql += "'" + address + "',"; sql += "'" + ddl + "')"; try { DB.CommonDatabase.RunQuery(sql); } catch (Exception) { cls.CommonClass objnew = new cls.CommonClass(); objnew.LogFailedQuery(sql, "HotelBookingDetails_" + supplier); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } //try //{ // string xml = string.Empty; // xml += "<?xml version='1.0' encoding='utf-8'?>"; // xml += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"; // xml += "<soap:Body>"; // xml += "<InsertHotelDetails xmlns='http://tempuri.org/'>"; // xml += "<ReservationID>" + bookingref + "</ReservationID>"; // xml += "</InsertHotelDetails>"; // xml += "</soap:Body>"; // xml += "</soap:Envelope>"; // string url = "http://bookingapi.theholidaykingdom.com/ApiList.asmx"; // cls.CommonClass obj1 = new cls.CommonClass(); // string responsedata = obj1.PostXml4Min(url, xml); // //SAve Logs // string FileDateTime = Convert.ToString(System.DateTime.Now); // FileDateTime = DateTime.Now.ToString("dd-MM-yyyy HH;mm;ss"); // string ServerPath = Path.Combine(HttpRuntime.AppDomainAppPath, "ExcelReport"); // string DataFileName = "InsertHotelDetails" + "_" + FileDateTime + ".txt"; // try // { // FileStream fs = new FileStream(ServerPath + "/" + DataFileName, FileMode.Create, FileAccess.Write); // StreamWriter fp = new StreamWriter(fs, Encoding.UTF8); // try // { // fp.WriteLine(xml + "****" + responsedata + "****" + url); // fp.Close(); // } // catch (Exception Ex) // { } // finally // { } // } // catch (Exception Ex) // { } // //SAve Logs end //} //catch (Exception ex) //{ // //SAve Logs // string FileDateTime = Convert.ToString(System.DateTime.Now); // FileDateTime = DateTime.Now.ToString("dd-MM-yyyy HH;mm;ss"); // string ServerPath = Path.Combine(HttpRuntime.AppDomainAppPath, "ExcelReport"); // string DataFileName = "InsertHotelDetails" + "_" + FileDateTime + ".txt"; // try // { // FileStream fs = new FileStream(ServerPath + "/" + DataFileName, FileMode.Create, FileAccess.Write); // StreamWriter fp = new StreamWriter(fs, Encoding.UTF8); // try // { // fp.WriteLine(ex.ToString()); // fp.Close(); // } // catch (Exception Ex) // { } // finally // { } // } // catch (Exception Ex) // { } // //SAve Logs end} //} if (bookingId != "" || bookingId != null) { try { if (supplier.ToUpper() == "TRAVELBULLZ") { bookingId = bookingId.Split('#')[0]; } string username = string.Empty; string password = string.Empty; string email = CustomerDetails.Split('|')[4]; var data = bookingdetail.Split('$'); string roomtype = data[0].Split('!')[12] + " (" + data[0].Split('!')[17].Split('%')[0] + ")"; decimal servicetaxval = Convert.ToDecimal(data[0].Split('!')[15]) * ((Convert.ToDecimal(data[0].Split('!')[2].Split('`')[1])) / 100); string price1 = currtst + " " + (Convert.ToDecimal(data[0].Split('!')[15]) + servicetaxval); string city = data[2].Split('^')[4].Split('@')[1]; string totroom = (data[2].Split('~').Length - 1).ToString(); string totnyt = data[2].Split('^')[2]; string PaxName = string.Empty; int totpax = data[1].Split('/')[0].Split(',').Length - 1; for (int i = 0; i < totpax; i++) { PaxName += data[1].Split('/')[0].Split(',')[i] + " " + data[1].Split('/')[1].Split(',')[i] + " " + data[1].Split('/')[2].Split(',')[i] + "<br />"; } string Emails = email + "," + Session["loginVal"] + "," + "*****@*****.**"; if (email != null || email != "") { MailMessage mm = new MailMessage(); mm.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]); mm.Subject = "Booking Invoice"; string[] multi = Emails.Split(','); foreach (string multiid in multi) { mm.Bcc.Add(new MailAddress(multiid)); } mm.Body = string.Format("Your Booking Confirmation Details ,<br /><br /><div class='container' align='center'><h2>Hotel Invoice</h2><table style='border: 2px solid navy;' width='750px'><tbody><tr><td style='border: 2px solid gray; padding:10px;'><b>Invoice Number: </b>" + bookingref + "</td><td style='border: 2px solid gray; padding:10px;'><b>Booking Id: </b>" + bookingId + "</td></tr><tr><td style='border: 2px solid gray; padding:10px;'><b>Booking Date: </b>" + DateTime.Now.ToString("dd-MM-yyyy") + "</td><td style='border: 2px solid gray; padding:10px;'><b>Status: </b>" + status + "</td></tr><tr style='height: 10px;'></tr><tr><td colspan='2' align='center'><img src=\"@@IMAGE@@\" alt=\"INLINE attachment\" height='70' width='250' /><br /><font size='2'>(A Unit of Travstarz Holiday & Destinations Pvt.Ltd)</font><br /><font size='2'>61-C 2nd Floor Eagle House Kalu Sarai Sarva Priya Vihar<br />New Delhi - 110016, India<br /><i>Tel No. :</i> 47050000 <i>Mail :</i> [email protected]</font><br /><font size='2'><b>GST No:</b> 07AAHCA9883B1ZI <b>Pan No:</b> AAHCA9883B</font></td></tr><tr style='height: 10px;'></tr><tr><td colspan='2' align='left' style='padding:10px;'><font size='4'>" + data[data.Length - 1].Split('!')[4] + "</font><br /><%=adrs %></td></tr><tr style='height: 15px;'></tr><tr><td style='padding-left:10px; width:50%;'><b>Check In Date: </b>" + chkin + "</td><td style='padding-left:10px;'><b>Check Out Date: </b>" + chkout + "</td></tr><tr><td style='padding-left:10px; width:50%;'><b>Hotel Name: </b>" + HotelName + "</td><td style='padding-left:10px;'><b>City: </b> " + city + "</td></tr><tr><td style='padding-left:10px; width:50%;'><b>No Of Night: </b>" + totnyt + "</td><td style='padding-left:10px;'><b>No Of Room(s): </b>" + totroom + "</td></tr><tr><td style='padding-left:10px; width:50%;'><b>Pax Name: </b>" + PaxName + "</td><td style='padding-left:10px;'><b>Room Type: </b>" + roomtype + "</td></tr><tr style='height: 25px;'></tr><tr><td align='center' colspan='2'><table width='100%' border='1px' cellpadding='10px'><tr><td><b>Amount (Including all Taxes)</b></td><td><b>Grand Total</b></td></tr><tr><td>" + price1 + "</td><td>" + price1 + "</td></tr></table></td><td align='center' colspan='2'></td></tr><tr style='height: 20px;'></tr><tr><td><b>Terms and Conditions</b></td><td align='right' rowspan='2'><b>Receiver's Signature</b></td></tr><tr style='height: 10px;'></tr><tr><td colspan='2' align='center'><b>This is an auto generated invoice hence no signature require.</b></td></tr></tbody></table></div><br /><br />Thank You."); mm.IsBodyHtml = true; string attachmentPath = Server.MapPath("~/new-travel-rez.png"); Attachment inline = new Attachment(attachmentPath); string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); mm.Attachments.Add(inline); mm.Body = mm.Body.Replace("@@IMAGE@@", "cid:" + contentID); SmtpClient smtp = new SmtpClient(); smtp.Host = ConfigurationManager.AppSettings["Host"]; smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); }; NetworkCredential NetworkCred = new NetworkCredential(); NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"]; NetworkCred.Password = ConfigurationManager.AppSettings["Password"]; smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); smtp.Send(mm); } Response.Redirect("HotelBookingConfirmation.aspx"); } catch (Exception) { Response.Redirect("HotelBookingConfirmation.aspx"); } } } else { Response.Redirect("Error.aspx?BookingID" + bookingId); } } catch (Exception ex) { string ServerPath = Server.MapPath("ErrorLogs"); string DataFile1 = "BookAfterPayment" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; FileStream fs1 = new FileStream(ServerPath + "/" + DataFile1, FileMode.Create, FileAccess.Write); StreamWriter fp1 = new StreamWriter(fs1, Encoding.UTF8); try { fp1.WriteLine(ex.Message.ToString()); } catch (Exception Ex) { } finally { fp1.Close(); fp1 = null; } } }
public void Add(Attachment attachment) { _attachments.Add(attachment); }
//private void DepartSent_SMS() //{ // DataTable dtDepartmentSMSSent = new DataTable(); // dtDepartmentSMSSent = DataAccessManager.GetSMSSent( Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtDepartmentSMSSent"] = dtDepartmentSMSSent; // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; //} //protected void rgvDepartmentSent_SortCommand(object sender, GridSortCommandEventArgs e) //{ // this.rgvDepartmentSent.MasterTableView.AllowNaturalSort = true; // this.rgvDepartmentSent.MasterTableView.Rebind(); //} //protected void rgvDepartmentSent_PageIndexChanged(object sender, GridPageChangedEventArgs e) //{ // try // { // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; // } // catch (Exception ex) // { // } //} #endregion public void fetchmail(string DeptID, int CampusID) { try { DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID); if (dtEmailConfig.Rows.Count > 0) { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"])); pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword); if (pop3Client.Connected) { int count = pop3Client.GetMessageCount(); int progressstepno; if (count == 0) { } else { progressstepno = 100 - count; this.Emails = new List <Email>(); for (int i = 1; i <= count; i++) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, messageId = message.Headers.MessageId, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } email.IsAttached = false; this.Emails.Add(email); //Attachment Process List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.IsAttached = true; string FolderName = string.Empty; FolderName = Convert.ToString(Session["CampusName"]); String path = Server.MapPath("~/InboxAttachment/" + FolderName); if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } string ext = attachment.FileName.Split('.')[1]; // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString()); FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString()); attachment.SaveToFile(file); Attachment att = new Attachment(); att.messageId = message.Headers.MessageId; att.FileName = attachment.FileName; attItem.Add(att); } //System.Threading.Thread.Sleep(500); } //Insert into database Inbox table DataTable dtStudentNo = new DataTable(); bool IsReadAndSave = false; foreach (var ReadItem in Emails) { string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty; from = Convert.ToString(ReadItem.From); subj = Convert.ToString(ReadItem.Subject); messId = Convert.ToString(ReadItem.messageId); Ebody = Convert.ToString(ReadItem.Body); if (Ebody != string.Empty && Ebody != null) { Ebody = Ebody.Replace("'", " "); } DateTime date = ReadItem.DateSent; bool IsAtta = ReadItem.IsAttached; //Student Email if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"]))) { dtStudentNo = DyDataAccessManager.GetStudentNo(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } //Leads Email if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false) { dtStudentNo = DyDataAccessManager.GetLeadsID(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } // } //Insert into database Attachment table foreach (var attachItem in attItem) { bool success; string Filname = attachItem.FileName; string MssID = attachItem.messageId; success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname); } Emails.Clear(); // attItem.Clear(); pop3Client.DeleteAllMessages(); //StartNotification(count); } } pop3Client.Disconnect(); } } catch (Exception ex) { } }
public static Skin GetRepackedSkin(this Skin o, string newName, Shader shader, out Material m, out Texture2D t, int maxAtlasSize = 1024, int padding = 2, TextureFormat textureFormat = TextureFormat.RGBA32, bool mipmaps = false, Material materialPropertySource = null) { Dictionary <Skin.AttachmentKeyTuple, Attachment> attachments = o.Attachments; Skin skin = new Skin(newName); Dictionary <AtlasRegion, int> dictionary = new Dictionary <AtlasRegion, int>(); List <int> list = new List <int>(); List <Attachment> list2 = new List <Attachment>(); List <Texture2D> list3 = new List <Texture2D>(); List <AtlasRegion> list4 = new List <AtlasRegion>(); int num = 0; foreach (KeyValuePair <Skin.AttachmentKeyTuple, Attachment> item2 in attachments) { Attachment clone = item2.Value.GetClone(cloneMeshesAsLinked: true); if (IsRenderable(clone)) { AtlasRegion atlasRegion = clone.GetAtlasRegion(); if (dictionary.TryGetValue(atlasRegion, out int value)) { list.Add(value); } else { list4.Add(atlasRegion); list3.Add(atlasRegion.ToTexture()); dictionary.Add(atlasRegion, num); list.Add(num); num++; } list2.Add(clone); } Skin.AttachmentKeyTuple key = item2.Key; skin.AddAttachment(key.slotIndex, key.name, clone); } Texture2D texture2D = new Texture2D(maxAtlasSize, maxAtlasSize, textureFormat, mipmaps); texture2D.mipMapBias = -0.5f; texture2D.anisoLevel = list3[0].anisoLevel; texture2D.name = newName; Rect[] array = texture2D.PackTextures(list3.ToArray(), padding, maxAtlasSize); Material material = new Material(shader); if (materialPropertySource != null) { material.CopyPropertiesFromMaterial(materialPropertySource); material.shaderKeywords = materialPropertySource.shaderKeywords; } material.name = newName; material.mainTexture = texture2D; AtlasPage atlasPage = material.ToSpineAtlasPage(); atlasPage.name = newName; List <AtlasRegion> list5 = new List <AtlasRegion>(); int i = 0; for (int count = list4.Count; i < count; i++) { AtlasRegion atlasRegion2 = list4[i]; AtlasRegion item = UVRectToAtlasRegion(array[i], atlasRegion2.name, atlasPage, atlasRegion2.offsetX, atlasRegion2.offsetY, atlasRegion2.rotate); list5.Add(item); } int j = 0; for (int count2 = list2.Count; j < count2; j++) { Attachment attachment = list2[j]; attachment.SetRegion(list5[list[j]]); } t = texture2D; m = material; return(skin); }
private static bool IsRenderable(Attachment a) { return(a is RegionAttachment || a is MeshAttachment); }
private async Task SendInvoice(Customer customer, Invoice invoice) { StringBuilder body = new StringBuilder(); // top banner body.AppendLine("<htm><body style='width: 1150px; font-family: Arial;'>"); body.AppendLine("<image src='cid:banner.jpg'>"); body.AppendLine("<table style='width: 100%; border: 0px; font-size: 25pt;'><tr>"); body.AppendLine("<td>PITSTOP GARAGE</td>"); body.AppendLine("<td style='text-align: right;'>INVOICE</td>"); body.AppendLine("</tr></table>"); body.AppendLine("<hr>"); // invoice and customer details body.AppendLine("<table style='width: 100%; border: 0px;'><tr>"); body.AppendLine("<td width='150px' valign='top'>"); body.AppendLine("Invoice reference<br/>"); body.AppendLine("Invoice date<br/>"); body.AppendLine("Amount<br/>"); body.AppendLine("Payment due by<br/>"); body.AppendLine("</td>"); body.AppendLine("<td valign='top'>"); body.AppendLine($": {invoice.InvoiceId}<br/>"); body.AppendLine($": {invoice.InvoiceDate.ToString("dd-MM-yyyy")}<br/>"); body.AppendLine($": € {invoice.Amount}<br/>"); body.AppendLine($": {invoice.InvoiceDate.AddDays(30).ToString("dd-MM-yyyy")}<br/>"); body.AppendLine("</td>"); body.AppendLine("<td width='50px' valign='top'>"); body.AppendLine("To:"); body.AppendLine("</td>"); body.AppendLine("<td valign='top'>"); body.AppendLine($"{customer.Name}<br/>"); body.AppendLine($"{customer.Address}<br/>"); body.AppendLine($"{customer.PostalCode}<br/>"); body.AppendLine($"{customer.City}<br/>"); body.AppendLine("</td>"); body.AppendLine("</tr></table>"); body.AppendLine("<hr><br/>"); // body body.AppendLine($"Dear {customer.Name},<br/><br/>"); body.AppendLine("Hereby we send you an invoice for maintenance we executed on your vehicle(s):<br/>"); body.AppendLine("<ol>"); foreach (string specificationLine in invoice.Specification.Split('\n')) { if (specificationLine.Length > 0) { body.AppendLine($"<li>{specificationLine}</li>"); } } body.AppendLine("</ol>"); body.AppendLine($"Total amount : € {invoice.Amount}<br/><br/>"); body.AppendLine("Payment terms : Payment within 30 days of invoice date.<br/><br/>"); // payment details body.AppendLine("Payment details<br/><br/>"); body.AppendLine("<table style='width: 100%; border: 0px;'><tr>"); body.AppendLine("<td width='120px' valign='top'>"); body.AppendLine("Bank<br/>"); body.AppendLine("Name<br/>"); body.AppendLine("IBAN<br/>"); body.AppendLine($"Reference<br/>"); body.AppendLine("</td>"); body.AppendLine("<td valign='top'>"); body.AppendLine(": ING<br/>"); body.AppendLine(": Pitstop Garage<br/>"); body.AppendLine(": NL20INGB0001234567<br/>"); body.AppendLine($": {invoice.InvoiceId}<br/>"); body.AppendLine("</td>"); body.AppendLine("</tr></table><br/>"); // greetings body.AppendLine("Greetings,<br/><br/>"); body.AppendLine("The PitStop crew<br/>"); body.AppendLine("</htm></body>"); MailMessage mailMessage = new MailMessage { From = new MailAddress("*****@*****.**"), Subject = $"Pitstop Garage Invoice #{invoice.InvoiceId}" }; mailMessage.To.Add("*****@*****.**"); mailMessage.Body = body.ToString(); mailMessage.IsBodyHtml = true; Attachment bannerImage = new Attachment(@"Assets/banner.jpg"); string contentID = "banner.jpg"; bannerImage.ContentId = contentID; bannerImage.ContentDisposition.Inline = true; bannerImage.ContentDisposition.DispositionType = DispositionTypeNames.Inline; mailMessage.Attachments.Add(bannerImage); await _emailCommunicator.SendEmailAsync(mailMessage); }
/// <summary> /// ДАННЫЙ МЕТОД НЕ РЕАЛИЗОВАН!!! /// </summary> /// <param name="attach"></param> /// <returns></returns> /// <remarks> /// Для вызова этого метода Ваше приложение должно иметь права с битовой маской, содержащей <see cref="Settings.Video"/>. /// Страница документации ВКонтакте <see href="http://vk.com/dev/video.createComment"/>. /// </remarks> public long CreateComment(Attachment attach) { // todo сделать версию с прикладыванием приложения throw new NotImplementedException(); }