I have create one web application where user can send friend request. If there are two users A and B. If A user send friend request to B then one pop up display's on B user dashboard. In that pop up box two buttons are there confirm or ignore.
If user click on confirm button then it takes some time to close that popup box. Because in backgroud it execute code for send email. Once email sent then that popup box close. So I want to close that popup box immediately after clicking on confirm button and then after send mail to that user.
Here is my code for accepting request and sending mail
#region dlUserFriendRequests_ItemCommand
protected void dlUserFriendRequests_ItemCommand(object source, DataListCommandEventArgs e)
{
HtmlTable objDataTable;
//Panel objDataTable;
switch (e.CommandName)
{
case "confirm":
RadioButtonList objRadioButtonList;
int intFriendRelationID = -1;
objRadioButtonList = (RadioButtonList)e.Item.FindControl("rblstFriends");
if (objRadioButtonList != null)
{
intFriendRelationID = UserManagementBL.AcceptUserFriendRequest(Convert.ToInt32(e.CommandArgument), this.LoginSessionDO.UserID, objRadioButtonList.SelectedItem.Text);
if (intFriendRelationID > 0)
{
int SentByUserID = Convert.ToInt32(e.CommandArgument);
DataTable dtbSenderdetails = null;
string SenderEmail = "";
dtbSenderdetails = UserManagementBL.GetUserDetails(SentByUserID);
if (dtbSenderdetails != null)
{
SenderEmail = dtbSenderdetails.Rows[0]["UserName"].ToString();
SendConfirmationMail(SenderEmail);
Response.Redirect("~/Dashboard/Dashboard.aspx",false);
//GetUserFriendRequests();
}
}
}
break;
case "Ignore":
int intFriendRequestID = -1;
intFriendRequestID = UserManagementBL.IgnoreUserFriendRequest(Convert.ToInt32(e.CommandArgument), this.LoginSessionDO.UserID);
GetUserFriendRequests();
break;
}
}
#endregion
#region Send confirmation mail
public void SendConfirmationMail(string email)
{
//DataTable dtblUserDetails = UserManagementBL.GetUserByUserName(email);
//if (dtblUserDetails != null)
//{
//int UserID = Convert.ToInt32(dtblUserDetails.Rows[0]["UserID"]);
//string FirstName = Convert.ToString(dtblUserDetails.Rows[0]["FirstName"]);
//string LastName = Convert.ToString(dtblUserDetails.Rows[0]["LastName"]);
string FirstName = this.LoginSessionDO.FirstName;
string LastName = this.LoginSessionDO.LastName;
var parameters = new System.Collections.Generic.Dictionary<string, string>();
parameters.Add("USER_NAME", string.Format("{0} {1}", FirstName, LastName));
parameters.Add("USER_IMAGE_URL", string.Format(SystemConfiguration.GetSiteURL() + "UserControls/UserPhoto.ashx?UserID={0}", this.LoginSessionDO.UserID));
string ToAddress = email;
string subject = FirstName + " " + LastName + " confirmed you as a friend on Lifetrons.";
CommonFunctions.CommonFunctions.SendEmail(SystemConfiguration.GetEmailSenderAddress(), ToAddress, subject, CommonFunctions.EmailTemplates.AcceptFriendRequest, parameters);
//}
}
#endregion
Here is my pop up box image
So how can I close that pop up box immediately after confirm button click? Is there any changes in my code?
You would do this in JavaScript. I assume you're already using AJAX to perform the Confirm action, otherwise it would just be reloading the page and your popup shouldn't be there anyway (since they're already confirmed?).
If you have jQuery on the frontend, you can use:
$('#confirm-box-id').hide();
Without jQuery, you could use:
document.getElementById('confirm-box-id').style.display = 'none';
Re-reading your message, it seems this is just a long running action. You should note that if you do hide this and don't show any indication of progress using the code above, for example, your user may navigate away or close the browser, which may cause the action to stop processing or be terminated forcefully server-side so the confirmation would never happen.
Related
I am having the hardest time figuring out how to create a pdf and attach it to an automated email. I thought it wouldn't be that hard but have quickly found out that it is much more complex than I imagined. Anyways, what I am doing is I have an order form, and when the customer fills out an order and submits it, I want it to generate a PDF for that order and attach it to an automated confirmation email. I am currently using Rotativa to generate the pdf and if I just ran the action result for generating it, it works perfectly fine which looks something like this:
public ActionResult ProcessOrder(int? id)
{
string orderNum = "FulfillmentOrder" + orderDetail.OrderID + ".pdf";
var pdf = new ActionAsPdf("OrderReportPDF", new { id = orderDetail.OrderID }) { FileName = orderNum };
return pdf;
}
When I added the function to send an automated email after the order form was submitted, that works perfectly fine with just the email by itself. But I can't seem to figure out how to generate the pdf and attach it to the email. The report view that gets the data from the order form is called "OrderReportPDF". My order form is called "Checkout", but the action result I use for this is called "Process Order". I've taken out the code in this function that is for the order form as it is not applicable. The section of my code for sending the email after the form is submitted is:
public ActionResult ProcessOrder(int? id)
{
//Send a confirmation email
var msgTitle = "Order Confirmation #" + orderDetail.OrderID;
var recipient = JohnDoe;
var fileAttach = //This is where I can't figure out how to attach//
var fileList = new string[] { fileAttach };
var errorMessage = "";
var OrderConfirmation = "Your order has been placed and is pending review." +
" Attached is a copy of your order.";
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "abc.net";
WebMail.SmtpPort = 555;
WebMail.UserName = recipient;
WebMail.Password = "12345";
WebMail.From = "orders#samplecode.com";
// Send email
WebMail.Send(to: "orders#samplecode.com",
subject: msgTitle,
body: OrderConfirmation,
filesToAttach: fileList
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
//5. Remove item cart session
Session.Remove(strCart);
return View("OrderSuccess");
}
I have been able to find very few articles on this issue using Rotativa and the ones I have found don't work for what I'm doing. Maybe Rotativa won't work for this, I'm hoping it does because I've designed my pdf report it generates from it, and not sure if doing it another way will screw up my formatting of it or not. As you can see at the bottom of the code, I return the view to an "OrderSuccess" page. When I try to implement the first code into the second code, it won't let me "return pdf" to execute the ActionAsPdf that generates the pdf when I do the "return View("OrderSuccess")". It only lets me do one or the other. If anybody knows how I can accomplish this, I need some help. I appreciate any suggestions or feedback. I'm pretty new to this so please be patient with me if I don't understand something.
Here is the updated code that fixed my problem and created the pdf, then attached it to an automated email once the order form was submitted:
public ActionResult ProcessOrder(int? id)
{
//1. Generate pdf file of order placed
string orderNum = "FulfillmentOrder" + orderDetail.OrderID + ".pdf";
var actionResult = new Rotativa.ActionAsPdf("OrderReportPDF", new { id = orderDetail.OrderID }) { FileName = orderNum };
var PdfAsBytes = actionResult.BuildFile(this.ControllerContext);
//2. Send confirmation email
var msgTitle = "Order Confirmation #" + orderDetail.OrderID;
var OrderConfirmation = "Your order has been placed and is pending review.<br />" +
" Attached is a copy of your order." +
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("orders#samplecode.com");
mail.To.Add("orders#samplecode.com");
mail.Subject = msgTitle;
mail.Body = OrderConfirmation;
mail.IsBodyHtml = true;
//STREAM THE CONVERTED BYTES AS ATTACHMENT HERE
mail.Attachments.Add(new Attachment(new MemoryStream(PdfAsBytes), orderNum));
using (SmtpClient smtp = new SmtpClient("abc.net", 555))
{
smtp.Credentials = new NetworkCredential("orders#samplecode.com", "password!");
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
//3. Remove item cart session
Session.Remove(strCart);
return View("OrderSuccess");
}
Thank you again to the people that helped and got me pointed in the right direction! Also, a quick shout out to #Drewskis who posted this answer in convert Rotativa.ViewAsPdf to System.Mail.Attachment where I was able to use it to solve my issue!
i'm trying to send message to People user name for example my friends username is #...
but no thing happend
no Error
and no send
can i use this library ?
or just with tlsharp?
how can i found apiid and hashid for my bot?
using Telegram.Bot;
and
public partial class Form1 : Form
{
Telegram.Bot. TelegramBotClient bot = new TelegramBotClient("token");
Thread a;
public Form1()
{
InitializeComponent();
}
public void GetUpdates()
{
int offset = 0;
while (true)
{
Telegram.Bot.Types.Update[] updates =
bot.GetUpdatesAsync(offset).Result;
foreach (var update in updates)
{
offset = update.Id + 1;
if (update.Message == null)
continue;
var from = update.Message.From.FirstName;
var text = update.Message.Text;
string chatid = update.Message.Chat.Id;
string username = update.Message.From.Username;
// label1.BeginInvoke(delegate { label1.Text = label1.BeginInvoke(delegate { label1.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid); }); });
// lblshow.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid);
//label1.Text = string.Format("sender:{0}\ntext:{1}\ncatid:{2}", from, text, chatid);
this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate () {textBox1.Text = string.Format("sender:{0}\ntext:{1}\ncusername:{2}", from, text, username); });
bot.SendTextMessageAsync( chatid, "سلام بر شما");
//is this correct for send to people?
bot.SendTextMessageAsync("#Hoda.....", "hi");
}
}
you cant send message to user by user Name.telegram bot API only accept user Id. (except channels).
When you try to send messages to users you must know their chatID (chatID is a long number which is unique for every user in telegram and never changes while username can be changed) or you must have stored their chatIDs in a database or a file or ...
This means a user must have sent at least one message to your bot before this includes the /start command. Then your bot can find out their chatID and using that chatID, you can send whatever you want to that user unless he/she has blocked your bot by pressing Delete and Stop button when trying to delete the conversation between him/her and your bot.
You can but don't pass # symbol, If the username is #me pass "me" to SendTextMessageAsync without passing #.
I am working on an Outlook add-in to handle email attachments by placing them on a server and putting a URL in the email instead.
One problem is that after adding the URL to the end of the email body the user's cursor is reset to the start of the email.
A related problem is that I do not know where the cursor is in the text so I cannot insert my URL into the correct location.
Here is some code showing what I am doing, for simplicity the code is assuming the body is plain text.
private void MyAddIn_Startup(object sender, System.EventArgs e)
{
Application.ItemLoad += new Outlook.ApplicationEvents_11_ItemLoadEventHandler(Application_ItemLoad);
}
void Application_ItemLoad(object Item)
{
currentMailItem = Item as Outlook.MailItem;
((Outlook.ItemEvents_10_Event)currentMailItem).BeforeAttachmentAdd += new Outlook.ItemEvents_10_BeforeAttachmentAddEventHandler(ItemEvents_BeforeAttachmentAdd);
}
void ItemEvents_BeforeAttachmentAdd(Outlook.Attachment attachment, ref bool Cancel)
{
string url = "A URL";
if (currentMailItem.BodyFormat == Outlook.OlBodyFormat.olFormatHTML)
{
// code removed for clarity
}
else if (currentMailItem.BodyFormat == Outlook.OlBodyFormat.olFormatRichText)
{
// code removed for clarity
}
else
currentMailItem.Body += attachment.DisplayName + "<" + url + ">";
Cancel = true;
}
Use Application.ActiveInspector.WordEditor to retrieve the Word Document object. Perform all the changes using Word Object Model.
This seems to do what I want:
using Microsoft.Office.Interop.Word;
void ItemEvents_BeforeAttachmentAdd(Outlook.Attachment attachment, ref bool Cancel)
{
if (attachment.Type == Outlook.OlAttachmentType.olByValue)
{
string url = "A URL";
Document doc = currentMailItem.GetInspector.WordEditor;
Selection objSel = doc.Windows[1].Selection;
object missObj = Type.Missing;
doc.Hyperlinks.Add(objSel.Range, url, missObj, missObj, attachment.DisplayName, missObj);
Cancel = true;
}
}
I am trying to delete message from inbox. Message doesn't have messageId(it's not gmail)
I've found in this topic the solution
MailSystem.Net Delete Message, IndexOnServer Property = 0
However it doesn't work for me.
The code below is simplifed the application works as MVVM light application.
This is how I get emails.
for (int i = 1; i <= mails.MessageCount; ++i)
{
Message msg = fetch.MessageObject(i);
MessageModel tmpMsg = new MessageModel() { messageType = MessageModel.MessageType.INBOX, UID = i, Date = msg.Date, Body = content, Title = msg.Subject, Sender = msg.From.Merged, Receiver = msg.To[0].Merged, IsEncrypted = isEncrypted };
tmpMsg.MessageWasDeleted += tmpMsg_MessageWasDeleted;
InboxMessages.Messages.Add(tmpMsg); //this is observable collection of MessageModel
}
I've tested this code and proper id is added to messageModel object.
Now when I want to delete the message I use this code in model:
var imapClient = new Imap4Client();
imapClient.BeginConnect(ConfigurationManager.AppSettings["mail_smtp_host"], ConfigurationManager.AppSettings["mail_smtp_login"], ConfigurationManager.AppSettings["mail_smtp_password"], new AsyncCallback((res) =>
{
imapClient.EndConnect(res);
//var box = imapClient.AllMailboxes["INBOX"] ;
var box = imapClient.SelectMailbox("INBOX");
Message email = box.Fetch.MessageObject(UID); //this is just to check if proper message is going to be deleted
box.UidDeleteMessage(UID, true);
if (MessageWasDeleted != null) MessageWasDeleted(this, new EventArgs());
}));
This method removes the message based on UID(at least it should do it) but it doesn't. There is no error nothing appears.
Where I could make an error? What's the proper way to delete message using ActiveUpMail?
every night i have a trigger that executes asp.net page with method that first retrieves from DB users with needed details and then emails them with information they need like ie. users that does not have an image in their profile. Once i get data from DB i build large string with encoded HTML and assign it to MailMessage.Body tag. There are about 20000 users per action/night who get the mail. Stored procedures just get users based on criteria i need nothing to optimize there (after proper indexes been made).
How do i optimize it? Can i create sort of queue in ASP.NET that it will be executed all day long without one time action? Maybe i can use async actions to send few emails per time.
Need advice, if you have question about how i perform each action in order to help me don't be afraid to ask, i will answer i just don't know what place in code may interest you.
protected void Page_Load(object sender, EventArgs e)
{
string type = Request.QueryString["type"];
string spName = "";
string message = "";
switch (type)
{
//getUsersWithoutPictures
case "uwp":
spName = "getUsersWithoutPictures";
message = getUsersWithoutPicturesTemplate();
break;
//getUsersWithoutText
case "uwt":
spName = "getUsersWithoutText";
message = getUsersWithoutTextTemplate();
break;
//getUsersWithoutEnteringWebsiteForTwoWeeks
case "uwewftw":
spName = "getUsersWithoutEnteringWebsiteForTwoWeeks";
message = getUsersWithoutEnteringWebsiteForTwoWeeksTemplate();
break;
//getUsersWithoutHobbies
case "uwh":
spName = "getUsersWithoutHobbies";
message = getUsersWithoutHobbiesTemplate();
break;
//getUsersWithoutCharateristics
case "uwc":
spName = "getUsersWithoutCharateristics";
message = getUsersWithoutCharateristicsTemplate();
break;
//getUsersWithoutActivation
case "uwa":
spName = "getUsersWithoutActivation";
message = getUsersWithoutActivationTemplate();
break;
default:
Response.Write("failure");
Response.End();
break;
}
DataTable recipientsList = new DataTable();
using (SqlConnection cn = cms.connect("someconnectionstring"))
{
SqlDataAdapter adp = new SqlDataAdapter(spName, cn);
adp.SelectCommand.CommandType = CommandType.StoredProcedure;
adp.Fill(recipientsList);
}
foreach (DataRow row in recipientsList.Rows)
{
try
{
IPHostEntry emailHost = Dns.GetHostEntry(row["email"].ToString().Remove(0, row["email"].ToString().LastIndexOf("#") + 1));
MailMessage myMessage = new MailMessage(new MailAddress("support#" + row["registratioSite"].ToString()), new MailAddress(row["email"].ToString()));
myMessage.Subject = "";
myMessage.Body = getGenericEmailTemplate(AffDomains.getFullDomain(row["registratioSite"].ToString()), message, row["email"].ToString(), row["usernumber"].ToString(), row["nick"].ToString());
myMessage.IsBodyHtml = true;
SmtpClient mySmtp = new SmtpClient("mysmtp.server.com");
mySmtp.Send(myMessage);
}
catch (Exception)
{
}
}
Response.Write("success");
Response.End();
}
private string getGenericEmailTemplate(string domain, string message, string email, string usernumber, string nick)
{
return "some html";
}
private string getUsersWithoutPicturesTemplate()
{
return "some message";
}
private string getUsersWithoutTextTemplate()
{
return "some message 2";
}
private string getUsersWithoutEnteringWebsiteForTwoWeeksTemplate()
{
return "some message 3";
}
private string getUsersWithoutHobbiesTemplate()
{
return "some message 4";
}
private string getUsersWithoutCharateristicsTemplate()
{
return "some message 5";
}
private string getUsersWithoutActivationTemplate()
{
return "some message 6";
}
Some pointers based on your current implementation:
Do this once per week. Is your site really so important that the users must be tortured every single night?
It looks like you're going to email each user several times, eg if they don't have a picture and haven't entered for two weeks they will get two emails. Combine all the events into one email.
Batch your emails into small groups based on which notifications they ought to receive, eg BCC 5 users at a time who don't have images in their profile.
Return only the data you need from the stored procs.
Move everything you can outside of the main loop eg creation of the EmailHost, MailMessage object and set the relevant properties inside the loop.
If you want this solution to scale way beyond its current limits however, you might want to think about some sort of multithreaded (or distrubuted) producer/consumer queue. I won't elaborate further here - there are plenty of examples on the web.