I have the following code that loops around and is supposed to send a single email per requested order list. So it sends multiple separated order emails for each customer rather than just the one email order list.
public ActionResult SaveOrder(string name, Order[] order)
{
string result = "Error! Order Is Not Complete!";
if (name != null && address != null && email != null && order != null)
{
var cutomerId = Guid.NewGuid();
Customer model = new Customer();
model.CustomerId = cutomerId;
model.Name = name;
model.Address = address;
model.OrderDate = DateTime.Now;
model.Email = email;
db.Customers.Add(model);
foreach (var item in order)
{
var orderId = Guid.NewGuid();
Order O = new Order();
O.OrderId = orderId;
O.ProductName = item.ProductName;
O.Quantity = item.Quantity;
O.Price = item.Price;
O.Amount = item.Amount;
O.CustomerId = cutomerId;
db.Orders.Add(O);
var customername = model.Name;
if (model.Name != null)
{
//Send Email to User
SendVerificationLinkEmail(model.Email, model.Name, O.ProductName);
}
}
db.SaveChanges()
result = "Success! Order Is Complete!";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
[NonAction]
public void SendVerificationLinkEmail(string email, string name, string productname)
{
var fromEmail = new MailAddress("test#test.com", "Laundry");
var toEmail = new MailAddress(email);
var fromEmailPassword = "xxxxx"; // Replace with actual password
string subject = "Your " + productname + " order request has been scheduled ";
string body = "";
using (StreamReader reader = new StreamReader(Server.MapPath("~/HtmlPage1.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{name}", name);
body = body.Replace("{emailID}", email);
body = body.Replace("{productname}", productname);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
Changing this:
foreach (var item in order)
{
var orderId = Guid.NewGuid();
... // code removed for clarity
if (model.Name != null)
{
//Send Email to User
SendVerificationLinkEmail(model.Email, model.Name, O.ProductName);
}
}
to this: (take the if statement out of the foreach loop)
foreach (var item in order)
{
var orderId = Guid.NewGuid();
... // code removed for clarity
}
if (model.Name != null)
{
//Send Email to User
SendVerificationLinkEmail(model.Email, model.Name, O.ProductName);
}
will send one email per customer order, instead of one email per order item. (Although you're passing o.ProductName to the SendVerificationLinkEmail method, so the email will presumably only contain the last ProductName since that appears to be different for each line item.)
Related
We have created a code that loops in to CosmosDb records and inserts values to Sql db. But in the process, the data insertion perfomance is very slow. please help with suggestions, here is the code. This process is taking more than 4 hours for inserting a data of 4000 rows.
namespace PushNotificationUserInsert
{
class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
#region Variables
var endpoint = ConfigurationManager.AppSettings["DocDbEndpoint"];
var masterKey = ConfigurationManager.AppSettings["DocDbMasterKey"];
var connetionString = ConfigurationManager.AppSettings["SQL_connetionString"].ToString();
// var useremail = "\"\"";
string path = #"xxxx.txt";
string[] useremails = File.ReadAllLines(path);
List<string> It = useremails.ToList();
var newIt = It.Distinct().ToList();
var channel = "\"msteam\"";
var cnn = new SqlConnection(connetionString);
var cnnInsert = new SqlConnection(connetionString);
string query = null;
cnn.Open();
foreach (var email in newIt)
{
query = "SELECT * FROM c where c.document.bot_js.mail = \"" + email + "\" AND CONTAINS(c.id," + channel + ", true)";
dynamic responses = "";
JSONModel.Rootobject records = null;
string conversationId = "";
//string email = "";
#endregion
#region Reading data from SQL
// cnn.Open();
SqlDataReader dataReader;
String Output = "";
SqlCommand command = new SqlCommand(#"SELECT [ConversatonReferenceJson] FROM [dbo].[ConversationReferences] where emailid like ''", cnn);
//command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = dataReader.GetValue(0).ToString();
records = JsonConvert.DeserializeObject<JSONModel.Rootobject>(Output);
}
dataReader.Close();
dataReader.Dispose();
#endregion
string[] readText = File.ReadAllLines(path);
//List<string> It = readText.ToList();
//var newIt = It.Distinct().ToList();
//foreach (string email in newIt)
//{
Console.WriteLine(email);
try
{
#region reading data from Consmos DB
using (var client = new DocumentClient(new Uri(endpoint), masterKey))
{
responses = client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri("Cosmosdbname", "cosmosdbtablebame"), query).ToList();
}
#endregion
#region Looping throught each cosmos DB records and insert value in SQL
foreach (var response in responses)
{
conversationId = response.id.Remove(0, 26);
records.conversation.id = conversationId;
cnnInsert.Open();
SqlCommand commInsert = new SqlCommand("INSERT INTO [ConversationReferences] VALUES " +
"(#ChannelId, #UserId, #ConverJson, #ID, #EmailID)", cnnInsert);
commInsert.Parameters.AddWithValue("#ChannelId", "xxxx");
commInsert.Parameters.AddWithValue("#UserId", "tobedeleted");
commInsert.Parameters.AddWithValue("#ConverJson", JsonConvert.SerializeObject(records));
commInsert.Parameters.AddWithValue("#ID", "tobedeleted");
commInsert.Parameters.AddWithValue("#EmailID", email);
commInsert.ExecuteNonQuery();
cnnInsert.Close();
Console.WriteLine("records updated for " + email);
}
#endregion
}
catch (Exception ex)
{
cnnInsert.Close();
throw;
}
finally
{ cnnInsert.Close(); }
Console.ReadKey();
}
}).Wait();
}
}
I want to send image files to SQL Server using C#.
The below code is working and saving files and their paths into the database. I need the same data in my API endpoint's response. I've created a custom response class, called RegistrationResponse.
I'm beginner in this so I'm looking for help.
public async Task<RegistrationResponse> PostFormData(HttpRequestMessage request)
{
object data = "";
NameValueCollection col = HttpContext.Current.Request.Form;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/images");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
//read file data
foreach (MultipartFileData dataItem in provider.FileData)
{
try
{
string description = string.Empty;
string userId = string.Empty;
String fileName = string.Empty;
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.ToString().ToLower() == "userid")
{
userId = val;
}
else if (key.ToString().ToLower() == "description")
{
description = val;
}
}
}
String name = dataItem.Headers.ContentDisposition.FileName.Replace("\"", "");
fileName = userId + Path.GetExtension(name);
File.Move(dataItem.LocalFileName, Path.Combine(root, fileName));
using (var db = new AlumniDBEntities())
{
//saving path and data in database table
Post userPost = new Post();
userPost.Files = fileName;
userPost.Description = description;
userPost.UserID = Convert.ToInt32(userId);
userPost.CreatedDate = DateTime.Now;
db.Posts.Add(userPost);
db.SaveChanges();
data = db.Posts.Where(x => x.PostID ==
userPost.PostID).FirstOrDefault();
string output = JsonConvert.SerializeObject(data);
}
}
catch (Exception ex)
{
return Request.CreateResponse(ex);
}
}
return Request.CreateResponse(HttpStatusCode.Created);
});
var response = new RegistrationResponse
{
success = true,
status = HttpStatusCode.OK,
message = "Success",
data = data
};
return response;
}
I have been using this code because there is an error:
Execution of authentication request returned unexpected result: 404
DataSet ds = new DataSet();
ds.Tables.Add("GmailContact");
ds.Tables[0].Columns.Add("EmailId");
RequestSettings rs = new RequestSettings("GetGmailContact", txtUsername.Text, txtPassword.Text);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
foreach (Contact t in f.Entries)
{
foreach (EMail email in t.Emails)
{
DataRow row = ds.Tables[0].NewRow();
row["EmailId"] = email.Address.ToString();
ds.Tables[0].Rows.Add(row);
}
}
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
lblStatus.Text = "Total Contact For" + txtUsername.Text + ":" + ds.Tables[0].Rows.Count.ToString();
Step
1 Go to https://console.developers.google.com/project and create project.
2 Select project, select APIs & auth from top left corner menu.
3 Select Credentials
4 Create OAuth with button Create new Client ID (Application type - Installed Aplication.
5 Fill field Product Name
6 Save
After that you got Client ID for native application with: Client ID, Client secret, Redirect URIs
Install Google.Apis.Auth from NuGet
Code
string clientId = null; // https://console.developers.google.com/project/xxx
string clientSecret = null; // https://console.developers.google.com/project/xxx
string accessCode = null; // You will get this code after GetAccessToken method
string redirectUri = null; // https://console.developers.google.com/project/xxx
string applicationName = null; // https://console.developers.google.com/project/xxx
// Scopes https://support.google.com/a/answer/162106?hl=en
string scopes = null; // put your scope like https://www.google.com/m8/feeds/
string accessType = "offline";
string tokenType = "refresh";
OAuth2Parameters parameters = new OAuth2Parameters
{
ClientId = clientId,
ClientSecret = clientSecret,
RedirectUri = redirectUri,
Scope = scopes,
AccessType = accessType,
TokenType = tokenType
};
if (accessCode == null)
{
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
// Start webbrowser
Process.Start(url);
// Load code from web via popup, etc.
parameters.AccessCode = accessCodeFromWeb;
}
// Check accessToken and refreshToken
// After first acceess with GetAccessToken you will get that information
if (accessToken == null || refreshToken == null)
{
OAuthUtil.GetAccessToken(parameters);
// Save yours accessToken and refreshToken for next connection
accessToken = parameters.AccessToken;
refreshToken = parameters.RefreshToken;
}
else
{
// Restore your token from config file, etc.
parameters.AccessToken = accessToken;
parameters.RefreshToken = refreshToken;
}
RequestSettings rs = new RequestSettings(applicationName, parameters);
return new ContactsRequest(rs);
I have implemented Citrus Payment gatway request/Response pages I am struck with Enquiry API integration,Where i have to implement it in code ?what is the page name i have to give ?
this is the guide given to me by citrus to implement enquiry api ..
http://developers.citruspay.com/api/miscellaneous/Enquiry.html#/
Request.aspx page code -
{
string formPostUrl = "https://sandbox.citruspay.com/sslperf/xyzdoman";
string secret_key = "xxxxxxxxxxxxxxx";
//Need to change with your Vanity URL Key from the citrus panel
string vanityUrl = "xxxxxyy";
//Should be unique for every transaction
string merchantTxnId = System.DateTime.Now.ToString("yyyyMMddHHmmssffff");
//Need to change with your Order Amount
string orderAmount = "10";
string currency = "INR";
string data = vanityUrl + orderAmount + merchantTxnId + currency;
//Need to change with your Return URL
string returnURL = "http://www.xxxxxyy.com/Response.aspx";
//Need to change with your Notify URL
string notifyUrl = "http://www.xxxxxyy.com/Response.aspx";
System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
string securitySignature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
%>
Response.aspx page code
{
string secret_key = "xxxxxxxxxxxxxxxxxxxxx";
string data="";
string txnId=Request["TxId"];
string txnStatus=Request["TxStatus"];
string amount=Request["amount"];
string pgTxnId=Request["pgTxnNo"];
string issuerRefNo=Request["issuerRefNo"];
string authIdCode=Request["authIdCode"];
string firstName=Request["firstName"];
string lastName=Request["lastName"];
string pgRespCode=Request["pgRespCode"];
string zipCode=Request["addressZip"];
string resSignature=Request["signature"];
bool flag = true;
if (txnId != null) {
data += txnId;
}
if (txnStatus != null) {
data += txnStatus;
}
if (amount != null) {
data += amount;
}
if (pgTxnId != null) {
data += pgTxnId;
}
if (issuerRefNo != null) {
data += issuerRefNo;
}
if (authIdCode != null) {
data += authIdCode;
}
if (firstName != null) {
data += firstName;
}
if (lastName != null) {
data += lastName;
}
if (pgRespCode != null) {
data += pgRespCode;
}
if (zipCode != null) {
data += zipCode;
}
System.Security.Cryptography.HMACSHA1 myhmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(secret_key));
System.IO.MemoryStream stream = new System.IO.MemoryStream(Encoding.ASCII.GetBytes(data));
string signature = BitConverter.ToString(myhmacsha1.ComputeHash(stream)).Replace("-", "").ToLower();
if(resSignature !=null && !signature.Equals(resSignature)) {
flag = false;
}
if (flag) {
%>
Your Unique Transaction/Order Id : <%=txnId%><br/>
Transaction Status : <%=txnStatus%><br/>
<% } else { %>
<label width="125px;">Citrus Response Signature and Our (Merchant) Signature Mis-Mactch</label>
<% } %>
I know there are lots of methods already given in stackoverflow but in my case all of them taking too long time. I post a method which takes less time but still it is too long to implement. Please help me so that it takes less execution time. Also take consideration that i am using .net 2.0 framework.
try
{
List<string> lstEmails = new List<string>();
string filter1 = string.Format("(anr={0})", "groupname");
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = filter1;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("mail");
IEnumerable res = (IEnumerable)searcher.FindOne().GetDirectoryEntry().Invoke("members");
//IEnumerable<string> rest = (IEnumerable<string>)res;
if (res != null)
{
try
{
int index = 0;
foreach (IEnumerable resl in res)
{
DateTime start = DateTime.Now;
DirectoryEntry dr = new DirectoryEntry(resl);
string strEmail = null;
if (dr.Properties["mail"].Value != null)
{
strEmail = dr.Properties["mail"].Value.ToString();
Console.WriteLine(strEmail);
DateTime stop = DateTime.Now;
Console.WriteLine((stop - start).TotalMinutes.ToString());
index++;
Console.WriteLine(index.ToString());
}
if (!string.IsNullOrEmpty(strEmail))
{
// groupMemebers.Add("sam",strEmail);
}
}
}
catch { }
}
}
catch { }
This is your suggested method Daro..
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domain, "domainname" + strLDAPUserName, strLDAPPassword);
DomainController controller = DomainController.FindOne(context);
DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}",controller.Domain), strLDAPUserName, strLDAPPassword, AuthenticationTypes.Secure);
List<string> userList = new List<string>();
DateTime StartTime = DateTime.Now;
using (DirectorySearcher ds = new DirectorySearcher(entry))
{
ds.PropertiesToLoad.Add("mail");
ds.PageSize = 10000;
string DistingushiedName = "CN=" + groupName + ",OU=Users,dc=CompanyName,dc=com";
ds.Filter = "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:="+DistingushiedName+"))";
ds.SearchScope = SearchScope.Subtree;
try
{
foreach (SearchResult user in ds.FindAll())
{
try
{
userList.Add(user.Path);//.Properties["mail"][0].ToString());
}
catch (Exception E)
{
throw new Exception(E.Message);
}
}
}
catch(Exception E)
{
throw new Exception(E.Message);
}
DateTime EndTime = DateTime.Now;
TimeSpan Dif = EndTime.Subtract(StartTime);
}
Here is your solution:-
string[] email = new string[0];
DirectoryEntry entry = new DirectoryEntry("LDAP://OU=Users,dc=me,dc=com", username, password);
string groupName = "GroupName";//Group NAme
DirectorySearcher groupSearch = new DirectorySearcher(entry);
groupSearch.Filter = "(SAMAccountName=" + groupName + ")";
groupSearch.PropertiesToLoad.Add("member");
SearchResult groupResult = groupSearch.FindOne(); // getting the members who belongs to the concern groupname
if (groupResult != null)
{
email = new string[groupResult.Properties["member"].Count]; //creatign an array to store all the email address
for (int iSearchLoop = 0; iSearchLoop < groupResult.Properties["member"].Count; iSearchLoop++)
{
string userName = groupResult.Properties["member"][iSearchLoop].ToString();
int index = userName.IndexOf(',');
userName = userName.Substring(0, index).Replace("CN=", "").ToString(); // the name of the user will be fetched.
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(name=" + userName + ")";
search.PropertiesToLoad.Add("mail");
SearchResult result = search.FindOne(); //finding the mail id
if (result != null)
{
email[iSearchLoop] = result.Properties["mail"][0].ToString(); //assigning the mail id to an array....
}
}
}
Hope this helps you
Easy enough (if your AD is 2003 R2 or higher):
List<string> userList = new List<string>();
DateTime StartTime = DateTime.Now;
using (DirectorySearcher ds = new DirectorySearcher(new DirectoryEntry ("GC://DC=YourDomain,DC=com")))
{
ds.PropertiesToLoad.Add("mail");
ds.PageSize = 10000;
ds.Filter = "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:=YOUR_GROUP'S DN))";
ds.SearchScope = SearchScope.Subtree;
try
{
foreach (SearchResult user in ds.FindAll())
{
try
{
userList.Add(user.Path);//.Properties["mail"][0].ToString());
}
catch (Exception E)
{
throw new Exception(E.Message);
}
}
}
catch(Exception E)
{
throw new Exception(E.Message);
}
DateTime EndTime = DateTime.Now;
TimeSpan Dif = EndTime.Subtract(StartTime);
}
Replace YOUR_GROUP'S DN with the distiguished name of your group...
memberof:1.2.840.113556.1.4.1941:= is the "new" LDAP_MATCHING_RULE_IN_CHAIN operator, and retrieves all group members. Look here to see if your AD is ready and get more information.
Edit:
I gave you an answer, but an explanation might help further.
In general you should avoid ANR searches because they expand to large wildcard OR queries. Use them only if you have no idea which property contains the name you are searching for. They are much slower than explicit AND searches.
Secondly if you have more than one domain, you should turn off referral chasing unless you want to search through all domains until you get a hit. In this case it would be better to do a GC:// than a LDAP:// search to find the object you’re looking for, than do an LDAP search on that object. Depending on what you are looking for the GC query could well be enough
Edit 2:
Modified the code to give more error information and get the user path instead of E-Mail.
Hey this is the correct way...
try
{
List<string> ReturnArray = new List<string>();
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, domainName, domainName + "\\" + UserName, Password);
DomainController controller = DomainController.FindOne(context);
string LDAPAddress = string.Format("LDAP://{0}", controller.Domain);
DirectoryEntry deDirEntry = new DirectoryEntry(LDAPAddress, UserName, Password);
deDirEntry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher mySearcher = new DirectorySearcher(deDirEntry);
mySearcher.PropertiesToLoad.Add("distinguishedName");
string sFilter = String.Format("(&(objectcategory=group)(cn=" + GroupName + "))");
mySearcher.Filter = sFilter;
mySearcher.Sort.Direction = SortDirection.Ascending;
mySearcher.Sort.PropertyName = "cn";
SearchResult result;
DirectoryEntry ResultEntry;
result = mySearcher.FindOne();
ResultEntry = result.GetDirectoryEntry();
GroupName = ResultEntry.Properties["distinguishedName"].Value.ToString();
mySearcher = new DirectorySearcher(deDirEntry);
mySearcher.PropertiesToLoad.Add("cn");
mySearcher.PropertiesToLoad.Add("mail");
sFilter = String.Format("(&(objectClass=person)(memberOf={0}))", GroupName);
mySearcher.Filter = sFilter;
mySearcher.Sort.Direction = SortDirection.Ascending;
mySearcher.Sort.PropertyName = "cn";
SearchResultCollection results;
results = mySearcher.FindAll();
foreach (SearchResult resEnt in results)
{
ResultPropertyCollection propcoll = resEnt.Properties;
foreach (string key in propcoll.PropertyNames)
{
if (key == "mail")
{
foreach (object values in propcoll[key])
{
if (!String.IsNullOrEmpty(values.ToString()))
{
ReturnArray.Add(values.ToString());
Console.WriteLine(values.ToString());
}
}
}
}
}
return ReturnArray;
}
catch
{
return null;
}
Thanks everyone for your valuable suggesstion