Send email containing pdf based on items in table - c#

I have a program that I lost the source code to and cannot figure out what I am doing wrong now that we had an IP change. What I am trying to do is step through a table and have it send emails with the corresponding report. Any ideas what is going wrong? I don't get any errors but I also don't get any emails (and yes the SMTP server works).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Web;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace AutomatedReporting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
foreach (var item in dc.reportsSent1s)
{
string matchedCaseNumber = item.CaseNumberKey;
(new MyReportRenderer()).RenderTest(matchedCaseNumber);
}
dc.ExecuteCommand("TRUNCATE TABLE reportsSent1");
}
public class MyReportRenderer
{
private rs2005.ReportingService2005 rs;
private rs2005Execution.ReportExecutionService rsExec;
public void RenderTest(String matchedCaseNumber)
{
string HistoryID = null;
string deviceInfo = null;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
rs2005Execution.Warning[] warnings = null;
string[] streamIDs = null;
rs = new rs2005.ReportingService2005();
rsExec = new rs2005Execution.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://***.***.***.***/ReportServer_DEVELOPMENT/ReportService2005.asmx";
rsExec.Url = "http://***.***.***.***/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";
try
{
// Load the selected report.
rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);
// Set the parameters for the report needed.
rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
parameters[0] = new rs2005Execution.ParameterValue();
parameters[0].Name = "CaseNumberKey";
parameters[0].Value = matchedCaseNumber;
rsExec.SetExecutionParameters(parameters, "en-us");
// get pdf of report
Byte[] results = rsExec.Render("PDF", deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
//pass paramaters for email
DataClasses1DataContext db = new DataClasses1DataContext();
var matchedBRT = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.BRTNumber).SingleOrDefault();
var matchedAdd = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Premises).SingleOrDefault();
var matchedDocument = (from c in db.GetTable<Document>()
where c.DocIDKey == SelectedRow.DocIDKey
select c).SingleOrDefault();
db.Documents.DeleteOnSubmit(matchedDocument);
db.SubmitChanges();
var matchedEmail = (from c in db.GetTable<vw_ProductClientInfo>()
where c.CaseNumberKey == matchedCaseNumber
select c.Email).SingleOrDefault();
//send email with attachment
MailMessage message = new MailMessage("Reports#acmetaxabstracts.com", matchedEmail, "Report for property located at " + matchedAdd, "Attached is the Tax Information Certificate for the above captioned property");
MailAddress copy = new MailAddress("acmetaxabstracts#gmail.com");
message.CC.Add(copy);
SmtpClient emailClient = new SmtpClient("***.***.***.***");
message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}" + matchedBRT + ".pdf", "BRT")));
emailClient.Send(message);
//db.reportsSent1s.DeleteOnSubmit(matchedItem);
//db.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}

Related

Code indicating that the "_edgeKey" object is null when the code tries to access it

I have a C# code that connects to a set of APIs and retrieves and displays specific data. Initially, the code was written in a way that heavily depended on Internet Explorer (the user had to be logged in to their account only through IE; otherwise, the application couldn't make a connection to the API). Since the IE expired, the code could no longer connect to the API, so I replaced the cookies with edge cookies. I receive no errors; however, the code is not giving the desire outcome. When I debugged, it looks like the exception of "Error:_edgeKey is null" is being thrown. How can I fix this?
I have created a folder named Controllers which includes StaticStrings.cs, WebAPI.cs, WebNav.cs.
StaticStrings.cs includes the set of APIs
WebAPI.cs includes the following code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using WeeklyScheduleModels;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
namespace WeeklySchedule.Contollers
{
class WebAPI
{
public string GetNorderTimeExpensebyNo(string norderNo)
{
return "OK";
}
public string GetNorderDbIDfromNo(string norderNo)
{
return "";
}
public async Task<double> GetBookedHours(string subOrderNo)
//public double GetBookedHours(string subOrderNo)
{
using (var edgeCookie = new EdgeCookie())
{
var cookies = edgeCookie.GetCookies(new Uri(StaticStrings.UrlNCert), false);
var cookieString = new StringBuilder();
foreach (var cookie in cookies)
{
cookieString.Append(cookie.Name + "=" + cookie.Value + "; ");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cookie", cookieString.ToString());
string uri = "";
double totalHours = 0.0;
uri = StaticStrings.NOrderTimeExpenseAPI + subOrderNo;
var response = await client.GetStringAsync(uri);
NCertTimeExpenseMain ntem = JsonConvert.DeserializeObject<NCertTimeExpenseMain>(response);
foreach (OracleHour oh in ntem.oracleHours)
{
totalHours += oh.hours;
}
return totalHours;
}
}
//To get the status of the project from Ncert
public async Task<string> GetOrderStatus(string subOrderNo)
{
using (var edgeCookie = new EdgeCookie())
{
var cookies = edgeCookie.GetCookies(new Uri(StaticStrings.UrlNCert), false);
var cookieString = new StringBuilder();
foreach (var cookie in cookies)
{
cookieString.Append(cookie.Name + "=" + cookie.Value + "; ");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cookie", cookieString.ToString());
string uri = "";
uri = StaticStrings.OrderStatusAPI + subOrderNo + '?';
var response = await client.GetStringAsync(uri);
RootObject status = JsonConvert.DeserializeObject<RootObject>(response);
string currentstatusofproject = status.statusDescription;
return currentstatusofproject;
}
}
public CustomerList GetCustomerListFromPartialName(string partialName)
{
using (var edgeCookie = new EdgeCookie())
{
var cookies = edgeCookie.GetCookies(new Uri(StaticStrings.UrlNCert), false);
var cookieString = new StringBuilder();
foreach (var cookie in cookies)
{
cookieString.Append(cookie.Name + "=" + cookie.Value + "; ");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cookie", cookieString.ToString());
string searchStr = StaticStrings.CustomerSearchAPI + partialName + "&%24format=json&%24top=30&%24filter=status%20eq%20%27Active%27&%24count=true";
var response = client.GetStringAsync(searchStr).Result;
CustomerList cl = JsonConvert.DeserializeObject<CustomerList>(response);
return cl;
}
}
public List<FrameAgreement> GetAgreementsFromCustomerId(string customerId)
{
using (var edgeCookie = new EdgeCookie())
{
var cookies = edgeCookie.GetCookies(new Uri(StaticStrings.UrlNCert), false);
var cookieString = new StringBuilder();
foreach (var cookie in cookies)
{
cookieString.Append(cookie.Name + "=" + cookie.Value + "; ");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cookie", cookieString.ToString());
string searchStr = StaticStrings.CustomerAgreementAPI + customerId;
var response = client.GetStringAsync(searchStr).Result;
List<FrameAgreement> FAList = JsonConvert.DeserializeObject<List<FrameAgreement>>(response);
return FAList;
}
}
public List<Address> GetAddressFromCustomerId(string customerId)
{
using (var edgeCookie = new EdgeCookie())
{
var cookies = edgeCookie.GetCookies(new Uri(StaticStrings.UrlNCert), false);
var cookieString = new StringBuilder();
foreach (var cookie in cookies)
{
cookieString.Append(cookie.Name + "=" + cookie.Value + "; ");
}
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cookie", cookieString.ToString());
string searchStr = StaticStrings.CustomerAddressAPI + customerId + "/survey-address/all";
var response = client.GetStringAsync(searchStr).Result;
List<Address> AddressList = JsonConvert.DeserializeObject<List<Address>>(response);
return AddressList;
}
}
}
}
WebNav.cs Includes the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
namespace WeeklySchedule.Contollers
{
public class EdgeCookie : IDisposable
{
private Microsoft.Win32.RegistryKey _edgeKey = null;
public EdgeCookie()
{
_edgeKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\Main", false);
}
public List<Cookie> GetCookies(Uri uri, bool v)
{
var cookies = new List<Cookie>();
try
{
if (_edgeKey == null)
{
throw new Exception("Error: _edgeKey is null");
}
var sqliteFile = System.IO.Path.Combine(_edgeKey.GetValue("DataPath").ToString(), "Cookies");
using (var conn = new System.Data.SQLite.SQLiteConnection("Data Source=" + sqliteFile + ";Version=3;"))
{
conn.Open();
using (var cmd = new System.Data.SQLite.SQLiteCommand("select host_key, name, encrypted_value, path, expires_utc, secure, httponly from cookies where host_key like '%" + uri.Host + "%'", conn))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var cookie = new Cookie(
reader.GetString(1),
reader.GetString(2),
reader.GetString(3),
reader.GetString(0));
cookie.Expires = DateTime.FromFileTimeUtc(long.Parse(reader.GetString(4)));
cookie.Secure = reader.GetBoolean(5);
cookie.HttpOnly = reader.GetBoolean(6);
cookies.Add(cookie);
}
}
}
}
}
catch
{
throw new Exception("Error reading cookies from Microsoft Edge");
}
return cookies;
}
public void Dispose()
{
if (_edgeKey != null)
{
_edgeKey.Dispose();
_edgeKey = null;
}
}
}
}

System.ArgumentNullException: 'value can't be null Parametre name: source'

I have a program which connects to a site and gets the list of orders using soap api. But i have a really strange issue. When a i try to get the orders of a day which there is no orders and then try get list of orders of a day i get this error. But strange thing is if a put a break point to line where i got the error and evalute the program step by step i don't get any errors. How could that happen. herre is the code.
https://api.n11.com/ws/OrderService.wsdl
using n11.Deneme.Forms.com.n11.api;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace n11.Deneme.Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strStartDate = "18/01/2020";
string strEndDate = "18/01/2020";
long totalCountValue = 50;
int currentPageValue = 0;
int pageCountValue = 1;
int pageSizeValue = 50;
Authentication auth = new Authentication();
auth.appKey = "b891a6b9-cb97-4a7e-9ffb-f7b1e2a593e8";
auth.appSecret = "pHCjYYadxwTG64Ej";
OrderSearchPeriod orderSearchPeriod = new OrderSearchPeriod();
orderSearchPeriod.startDate = strStartDate;
orderSearchPeriod.endDate = strEndDate;
OrderDataListRequest orderDataListRequest = new OrderDataListRequest();
//orderDataListRequest.status = "1";
orderDataListRequest.period = orderSearchPeriod;
//orderDataListRequest.orderNumber = "209524598478";
PagingData pagingData = new PagingData();
pagingData.currentPage = currentPageValue;
pagingData.pageCount = pageCountValue;
pagingData.pageSize = pageSizeValue;
pagingData.totalCount = totalCountValue;
DetailedOrderListRequest request = new DetailedOrderListRequest();
request.auth = auth;
request.pagingData = pagingData;
request.searchData = orderDataListRequest;
OrderServicePortService port = new OrderServicePortService();
DetailedOrderListResponse response = port.DetailedOrderList(request);
List<DetailedOrderData> orderList = response.orderList.ToList();
foreach (var order in orderList)
{
MessageBox.Show(order.totalAmount.ToString() + " - " + order.orderNumber + " - " + order.citizenshipId + " - " + order.createDate);
long orderIdValue = order.id;
OrderDataRequest orderDataRequest = new OrderDataRequest();
orderDataRequest.id = orderIdValue;
OrderDetailRequest orderdetailrequest = new OrderDetailRequest();
orderdetailrequest.auth = auth;
orderdetailrequest.orderRequest = orderDataRequest;
OrderServicePortService port1 = new OrderServicePortService();
OrderDetailResponse orderDetailResponse = port1.OrderDetail(orderdetailrequest);
OrderDetailData orderDetail = orderDetailResponse.orderDetail;
MessageBox.Show(orderDetail.orderNumber);
List<OrderSearchData> orderItemList = orderDetail.itemList.ToList();
foreach (var item in orderItemList)
{
MessageBox.Show(item.shipmentInfo.campaignNumber);
}
}
}
}
}
If you're getting the error on the line:
List<DetailedOrderData> orderList = response.orderList.ToList(); //I GOT THE ERROR ON THIS LINE
then the thing to do is to look at how response.orderList gets a value. In particular, does it do something with threads, tasks, timers, external events, or anything else like that - which could mean that it gets populated shortly after the initial return from DetailedOrderList, which could explain why it works when you debug and step through (adding a crucial delay into things).
You could also simply do:
var tmp = response.orderList;
if (tmp == null) throw new InvalidOperationException(
"hey, response.orderList was null! this is not good!");
List<DetailedOrderData> orderList = tmp.ToList();
return orderList;
which would make it very clear and explicit that this is what is happening. If you don't get this exception, but something else, then: more debugging needed!
if(response.orderList == null)
{
var temp = button1_Click.PerformClick();
return temp;
}
else
{
List<DetailedOrderData> orderList = response.orderList.ToList();
return orderList;
}

"404 - File or directory not found" error when logging in to DocuSign API

I am using the code listed below for a c# visual studio project to interface with the DocuSign API. As soon as the code gets to
LoginInformation loginInfo = authApi.Login();
I am getting error message:
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable
Does anyone know why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using DocuSign.eSign.Api;
using DocuSign.eSign.Model;
using DocuSign.eSign.Client;
namespace CoreRecipes
{
class Program
{
private string INTEGRATOR_KEY = "[key]";
static void Main(string[] args)
{
Program recipes = new Program();
recipes.listDocumentsAndDownloadTest();
Console.Read();
}
public void listDocumentsAndDownloadTest()
{
string username = "[username]";
string password = "[password]";
string envelopeId = "envelopid";
//configureApiClient("www.docusign.net/restapi");
//http"s://demo.docusign.net/restapi"
configureApiClient("https://demo.docusign.net/restpi");
string accountId = loginApi(username, password);
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeDocumentsResult docsList = envelopesApi.ListDocuments(accountId, envelopeId);
Console.WriteLine("EnvelopeDocumentsResult:\n{0}", JsonConvert.SerializeObject(docsList));
int docCount = docsList.EnvelopeDocuments.Count;
string filePath = null;
FileStream fs = null;
for (int i = 0; i < docCount; i++)
{
MemoryStream docStream = (MemoryStream)envelopesApi.GetDocument(accountId, envelopeId, docsList.EnvelopeDocuments[i].DocumentId);
filePath = Path.GetTempPath() + Path.GetRandomFileName() + ".pdf";
fs = new FileStream(filePath, FileMode.Create);
docStream.Seek(0, SeekOrigin.Begin);
docStream.CopyTo(fs);
fs.Close();
Console.WriteLine("Envelope Document {0} has been downloaded to: {1}", i, filePath);
}
}
public void configureApiClient(string basePath)
{
ApiClient apiClient = new ApiClient(basePath);
Configuration.Default.ApiClient = apiClient;
}
public string loginApi(string usr, string pwd)
{
ApiClient apiClient = Configuration.Default.ApiClient;
string authHeader = "{\"Username\":\"" + usr + "\", \"Password\":\"" + pwd + "\", \"IntegratorKey\":\"" + INTEGRATOR_KEY + "\"}";
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
string accountId = null;
AuthenticationApi authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
foreach (LoginAccount loginAcct in loginInfo.LoginAccounts)
{
if (loginAcct.IsDefault == "true")
{
accountId = loginAcct.AccountId;
break;
}
}
if (accountId == null)
{
accountId = loginInfo.LoginAccounts[0].AccountId;
}
return accountId;
}
}
}
The issue is with this list:
configureApiClient("https://demo.docusign.net/restpi")
There is a typo in it - as identified by going to https://demo.docusign.net/restpi and seeing that it returned a 404.
I suggest changing it to:
configureApiClient("https://demo.docusign.net/restapi")

Error while consuming webservice

But it does not create my new record in my crm.
Error: Could not connect to
net.tcp://103.229.5.53:8201/DynamicsAx/Services/ACX_CaseTab leQ. The
connection attempt lasted for a time span of 00:00:21.0658227. TCP
erro r code 10060: A connection attempt failed because the connected
party did not pr operly respond after a period of time, or established
connection failed because connected host has failed to respond
103.229.5.53:8201.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk;
using System.ServiceModel.Discovery;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel.Description;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Program test = new Program();
ClientCredentials cc = new ClientCredentials();
cc.UserName.UserName = "";
cc.UserName.Password = "";
OrganizationServiceProxy service = new OrganizationServiceProxy(new Uri(""), null, cc, null);
string caseid = ""; string casetype = "";
try
{
QueryExpression query1 = new QueryExpression
{
EntityName = "e011_cases",
ColumnSet = new ColumnSet("e011_caseid", "e011_casetype", "e011_casesid"),
Criteria = new FilterExpression()
{
FilterOperator = LogicalOperator.And,
Conditions = {
new ConditionExpression
{
AttributeName ="e011_caseid",
Operator=ConditionOperator.Equal,
Values ={"CRM00000098"}
},
}
}
};
EntityCollection ec = service.RetrieveMultiple(query1);
if(ec.Entities[0].Contains("e011_caseid"))
{
caseid = ec.Entities[0].Attributes["e011_caseid"].ToString();
}
if(ec.Entities[0].Contains("e011_casetype"))
{
EntityReference er = (EntityReference)ec.Entities[0].Attributes["e011_casetype"];
casetype = er.Name.ToString();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); Console.ReadKey();
}
ACX_CaseTableQ.ACX_CaseTableQServiceClient Proxy = new ACX_CaseTableQ.ACX_CaseTableQServiceClient();
ACX_CaseTableQ.CallContext cnx = new ACX_CaseTableQ.CallContext();
cnx.Company = "1100";
Proxy.ClientCredentials.Windows.ClientCredential.UserName = "";
Proxy.ClientCredentials.Windows.ClientCredential.Domain = "";
Proxy.ClientCredentials.Windows.ClientCredential.Password = "";
ACX_CaseTableQ.AxdACX_CaseTableQ ObjCasetableQ = new ACX_CaseTableQ.AxdACX_CaseTableQ(); string objcase =
Convert.ToString(ObjCasetableQ.Acx_CaseTable_1);
ACX_CaseTableQ.AxdEntity_Acx_CaseTable_1 objAxd = new ACX_CaseTableQ.AxdEntity_Acx_CaseTable_1();
string zipcode = objAxd.Zipcode;
string sate = objAxd.State;
objAxd.CaseID = caseid;
objAxd.CaseCategoryId = casetype; ObjCasetableQ.Acx_CaseTable_1 = new ACX_CaseTableQ.AxdEntity_Acx_CaseTable_1[1] { objAxd };
ACX_CaseTableQ.EntityKey[] ReturnKey = Proxy.create(cnx, ObjCasetableQ);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); Console.ReadKey();
}
}
}
}
Problem can be related with CRM Online unavailability to connect with URL that contains IP address. This is system restriction. Try to use domain name instead of IP

Get Value from Dropdown List in MVC

On submit the contact form sends out an email to the specified email address in the web.config file. However at the moment it is posting the ID of the "Selected Services" - how do i get the value rendering instead of the ID? I've tried going through the list after appending the . to see what is available to me, i can't find value.
The values are already defined in Umbraco using a custom datatype.
Here is the surface controller;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml.XPath;
using Umbraco.Core.Services;
using Umbraco.Web.Mvc;
/// <summary>
/// Summary description for ContactSurfaceController
/// </summary>
namespace LiquidThinker2015
{
public class ContactSurfaceController : SurfaceController
{
public object XPathModeIterator { get; private set; }
public ActionResult ShowForm()
{
ContactModel myModel = new ContactModel();
List<SelectListItem> ListOfServices = new List<SelectListItem>();
XPathNodeIterator iterator = umbraco.library.GetPreValues(1435);
iterator.MoveNext();
XPathNodeIterator preValues = iterator.Current.SelectChildren("preValue", "");
while (preValues.MoveNext())
{
string preValue = preValues.Current.GetAttribute("id", "");
ListOfServices.Add(new SelectListItem
{
Text = preValues.Current.Value,
Value = preValues.Current.GetAttribute("id","")
});
myModel.ListOfServices = ListOfServices;
}
return PartialView("ContactForm", myModel);
}
public ActionResult HandleFormPost(ContactModel model)
{
var newComment = Services.ContentService.CreateContent(model.Name + " - " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"), CurrentPage.Id, "ContactFormula");
//DataTypeService myService = new DataTypeService();
//var SelectedService = myService.GetAllDataTypeDefinitions().First(x => x.Id == 1435);
//int SelectedServicePreValueId = myService.GetPreValuesCollectionByDataTypeId(SelectedService.Id).PreValuesAsDictionary.Where(x => x.Value.Value == model.SelectedService).Select(x => x.Value.Id).First();
newComment.SetValue("contactName", model.Name);
newComment.SetValue("companyName", model.Company);
newComment.SetValue("emailFrom", model.Email);
newComment.SetValue("telephoneNumber", model.Telephone);
newComment.SetValue("dropdownServices", model.SelectedService);
newComment.SetValue("contactMessage", model.Message);
Services.ContentService.SaveAndPublishWithStatus(newComment);
//Send out email
if (ModelState.IsValid)
{
var sb = new StringBuilder();
sb.AppendFormat("<p>Name: {0}</p>", model.Name);
sb.AppendFormat("<p>Company: {0}</p>", model.Company);
sb.AppendFormat("<p>Email: {0}</p>", model.Email);
sb.AppendFormat("<p>Phone: {0}</p>", model.Telephone);
sb.AppendFormat("<p>Service: {0}</p>", model.SelectedService); //THIS LINE HERE
sb.AppendFormat("<p>Message: {0}</p>", model.Message);
SmtpClient smtp = new SmtpClient();
MailMessage message = new MailMessage();
MailAddress ma = new MailAddress(model.Email);
message.Subject = ConfigurationManager.AppSettings["ContactFormSubject"];
message.To.Add(new MailAddress(ConfigurationManager.AppSettings["ContactFormTo"]));
message.CC.Add(new MailAddress(ConfigurationManager.AppSettings["ContactFormCC"]));
message.From = ma;
message.Sender = new MailAddress(model.Email);
message.Body = sb.ToString();
message.IsBodyHtml = true;
try
{
smtp.Send(message);
}
catch (SmtpException smtpEx)
{
// Log or manage your error here, then...
return RedirectToUmbracoPage(1084); // Redirect to homepage.
}
return RedirectToUmbracoPage(1454);
}
return RedirectToUmbracoPage(1454);
}
}
}
Edit:
#co0ke when i do that i get this;
Or should i just try passing in "1435"?
You can use the method on the UmbracoHelper named .GetPreValueAsString(id) and pass in the id of the prevalue.
The UmbracoHelper is available as a property named 'Umbraco' on the PluginController which SurfaceController inherits from.

Categories