Submitting form item via code not triggering an email notification - kentico-mvc

I am trying to submit a new form item via api on my MVC web app (grabbed the code from form's code tab) but the email notification is not working. It did create a new record except for the email alert. I checked the email queue but no records of the form item. I configured the smtp server settings properly. I checked the event logs as well but I dont see any errors. Am I missing something or this feature is only on portal engine?

Apparently if we do the submission of form manually via code and not using the default mvc form widgets it does not trigger the notification automatically. We also need to send the notifications via code. form data documentation
// Gets the form object representing the 'ContactUs' form on the current site
BizFormInfo formObject = BizFormInfoProvider.GetBizFormInfo("ContactUs", SiteContext.CurrentSiteID);
if (formObject != null)
{
// Gets the class name of the 'ContactUs' form
DataClassInfo formClass = DataClassInfoProvider.GetDataClassInfo(formObject.FormClassID);
string formClassName = formClass.ClassName;
// Creates a new data record for the form
BizFormItem newFormItem = BizFormItem.New(formClassName);
// Sets the values for the form's fields (UserMessage in this case)
newFormItem.SetValue("UserMessage", "This is a message submitted through the API.");
// Saves the new form record into the database
// Set values for all 'Required' fields in the form before calling the Insert method, otherwise an exception will occur
newFormItem.Insert();
// Obtains a factory object used to create a form notification sender service for the given form
IBizFormMailSenderFactory senderFactory = Service.Resolve<IBizFormMailSenderFactory>();
// Creates an instance of the form notification sender for the inserted form item
IBizFormMailSender sender = senderFactory.GetFormMailSender(formObject, newFormItem);
// Sends a notification email to users (as specified on the form's 'Email notification' tab)
sender.SendNotificationEmail();
// Sends a confirmation email to the submitter (based on the form's autoresponder settings)
sender.SendConfirmationEmail();
}

Related

Is it possible to transfer data retrieved using facebook Graph API to a database in ASP.NET?

I have an ASP.net Web project that includes a form and a Database.
When a user register to the site (not from facebook) he has a username, and then when he fills the form, I can add this username to the 'username' column in the database (using User.Identity.Name). When he login using facebook, I can't do it. So I thought to use his facebook ID, since any ID is different, but I can't find a way to do it. I tried to retrieve the ID using response.id, set the value in a Label, and then to get the Label content from the codebehind to transfer it to the DB, but it didn't work. here is the code I tried:
Set the ID into the label:
function testAPI() {
FB.api('/me?fields=name,email,gender,age_range,picture.width(45).height(44),location', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('HiddenFacebookID').innerText = response.id;
});
}
The Label:
<asp:Label ID="HiddenFacebookID" runat="server"></asp:Label>
The code-behind:
conn.Open();
string insertQuery2 = "INSERT INTO UserData (username) values (#username)";
SqlCommand com2 = new SqlCommand(insertQuery2, conn);
com2.Parameters.AddWithValue("#username", HiddenFacebookID.Text);
com2.ExecuteNonQuery();
The Label content is really the facebook-ID, but the database gets NULL. Please Let me know if I wasn't clear.
I will appreciate any help, thanks!
The value you're setting in JavaScript isn't being posted back to the server. Only form values are posted to the server. And an asp:Label doesn't render as a form element.
Use a hidden form field instead:
<asp:Hidden ID="HiddenFacebookID" runat="server"></asp:Hidden>
And set its value in JavaScript:
document.getElementById('HiddenFacebookID').value = response.id;
Basically, regardless of the lies that WebForms has been telling for years, HTML content is not posted to the server when submitting a form :) Only form values are.

Session, Cache OR Cookies which one to use to retain Search Criteria of User? (Posted With Case Study)

I am developing a Web application which is based on ASP.NET 4.0, JQUERY, AJAX and Javascript. I have a particular search page in which a user can search via multiple factors i.e. either by Date, Name, Code, Category etc.
For e.g.
A) In a SearchProducts form, user can search a product via its unique Number OR Name OR Start Date/End Date OR Category OR etc etc.
B) User can search by either one or all of the parameters which a standard search form should be able to do.
C) If user searches via Start Date and End Date say 1st Dec 2012 to 31st Dec 2012 so for example my Search Results consist of 4 Products i.e. 4 products are purchased from 1st Dec to 31st Dec
D) Results are displayed in the grid and by clicking on the Product Number its redirecting to its View page (selected Product Specific full details) with ProductID via Query string.
E) I have a requirement which enables the user to retain search results which he/she has searched via Back To Search button in View page (selected Product Specific full details) page.
Now, What I have planned is as follows:
1) When a user submits on the Search then I want to store the refference of Search Paramters i.e Date, Name, Category etc which user has entered.
2) I will set a value in query string to differentiate normal request and request Via Back to Search button.
3) code in Search Page:
if (!(IsPostBack))
{
string tempRequestMode = string.Empty;
if (Request.QueryString["requestMode"] != null)
{
tempRequestMode = Request.QueryString["requestMode"].ToString();
if (tempRequestMode == "searchResults")
{
//RestoreValues();
//Fetch results from the database again based on above results
}
}
}
Now, My question is:
I wanted to use ASP.NET Cache for this purpose:
Advantages: its expiration and dependencies
Disadvantages: its has the application scope i.e. its not per user wise as Session is.
Second option is session:
Advantages: its per user wise.
Disadvantages: Session is more memory intensive.
I am confused that what Should I use. Is there any other option to use as Search Criteria is different for different users so want user wise maintenance of data.
You can write all search criteria to QueryString.
When a User clicks the Search Button, run this Javascript:
CLIENT-SIDE
<script type="text/javascript">
var url = "Invoices.aspx?type=__type__&status=__status__&order=__order__";
var type= $("#<%= drpType.ClientID%>").val(); // Type
var status = $("#<%= drpStatus.ClientID %>").val(); // Status Parameter
var order = $("#<%= drpOrder.ClientID %>").val(); // order Parameter
window.location = url.replace("__type__",type).replace("__status__",status).replace("__order__",order).replace(");
</script>
SERVER-SIDE
protected void Page_Load(object cart, EventArgs curt)
{
_type = Request.QueryString["type"];
if (string.IsNullOrEmpty(_type))
_type = Enums.InvoiceUserTypes.RS.ToString(); //Default
_status = Request.QueryString["status"];
if (string.IsNullOrEmpty(_status)) _status = "ALL"; //Default
_order= Request.QueryString["order"];
if (string.IsNullOrEmpty(_order)) _order = "date"; //Default
drpStatus.Value = _status;
drpType.Value = _type;
drpOrder.Value = _order;
RunReport();
}
When user click Back button . Search parameters will be on the URL
I think the best approach to this case is to redo the search using the stored filters once the user gets back to the search page. Any other approaches will bring you a big drawback.
Caches Expire and if you use the default implementation they won't allow your app to scale to multiple machines since they are local.
Using sessions is a bad idea too because they will eat your resources AND won't allow you to scale too.
If you must store the results you should store them serialized (LOB pattern) in a database or another network accessible resource so you could retrieve them in any application server.

Send email with attachment , that attachement will be uploaded in the same FORM where from the mail gets triggered

Send email with attachment,that attachement will be uploaded in the same FORM where from the mail gets triggered.
BACKGROUND:
i.e. I have an FORM that will take name, address etc details from a FROM. After filling the details user would be allowed to a browse and upload an attachment. Onclicking the Upload button the file will get uploaded to the server.
After doing all of the above action when the users clicks on SUBMIT button in this FROM, it should trigger a email with all the details entered in the FORM and With the uploaded file attached in it.
Now, the problem I am facing is : when I click on UPLOAD button, the file is getting uploaed but all the inputs entered gets disappeared.
Any resolution around this will be appreciated.
N.B: We are not using any free ware like for mail functioanlity. Mail is send by a vbscript function.
below is the logic how i/p fields values are getting captured:
ssr_imo = sql_ship_friendly(request.form("ssr_imo"),10)
ssr_ship_name = sql_ship_friendly(request.form("ssr_ship_name"),100)
ssr_ins_nr = sql_ship_friendly(request.form("ssr_ins_nr"),20)
ssr_ins_date = sql_date_friendly(request.form("ssr_ins_date"),30)
port_name = sql_ship_friendly(request.form("port_name"),50)
ssr_port_id = sql_ship_friendly(request.form("ssr_port_id"),20)
opStat = sql_ship_friendly(request.form("opStat"),20)
subEmail = sql_ship_friendly(request.Form("ssr_sub_email"),200)
subName = sql_ship_friendly(request.Form("ssr_sub_name"),70)
ssr_q2 = validate_q_ssr(request.form("ssr_q2"))
ssr_q3 = validate_q_ssr(request.form("ssr_q3"))
debugNote "<b> TEST = </b>" & ssr_q3
ssr_q4 = validate_q_ssr(request.form("ssr_q4"))
ssr_q5 = validate_q_ssr(request.form("ssr_q5"))
ssr_q6 = validate_q_ssr(request.form("ssr_q6"))
ssr_q7 = validate_q_ssr(request.form("ssr_q7"))
ssr_q8 = validate_q_ssr(request.form("ssr_q8"))
ssr_q9 = validate_q_ssr(request.form("ssr_q9"))
ssr_q10 = validate_q_ssr(request.form("ssr_q10"))
ssr_q11 = validate_q_ssr(request.form("ssr_q11"))
ssr_q12 = validate_q_ssr(request.form("ssr_q12"))
ssr_q13 = validate_q_ssr(request.form("ssr_q13"))
ssr_qa = validate_q_ssr(request.form("ssr_qa"))
ssr_qb = validate_q_ssr(request.form("ssr_qb"))
Once you change your form enctype to "multipart/form-data" you can no longer retrieve input values with Request or Request.Form, you have to use the method/function that is part of the upload component or script that you are using.
For example:
In Persit's AspUpload you use obj.Form("inputName") In ChestySoft's
csASPUpload you use obj.Value("inputName")
(In both cases obj is the name of your upload component object instance and inputName is the name of your form element)
Edit: Using the ASP class you are using for uploading you should use Uploader.Form instead of Request.Form to retrieve input values.

Microsoft dynamics CRM 2011: how to generate lead from external contact form

i developed CMS to one of my customers and he wants that when a user fill in the contact form, it will automatically generate lead in his CRM.
what is the easiest way to do that?
by the way, the contact form is ajax and the data is transfered to asmx, so it will be easy to call to CRM webservice or something like that, because i'm already in the server side.
can someone point me to tutorial or some code example?
thanks!
Your best start will be with the SDK available here, which contains example code and the sdk dlls etc...
Here is a page with a quick reference to all the web service endpoints available in the different flavors of CRM 2011.
From the SDK samplepcode\cs\quickstart creating account, but very similar for lead:
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
serverConfig.HomeRealmUri,
serverConfig.Credentials,
serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
// Instaniate an account object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Account account = new Account { Name = "Fourth Coffee" };
// Create an account record named Fourth Coffee.
_accountId = _serviceProxy.Create(account);
Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
// Retrieve the account containing several of its attributes.
ColumnSet cols = new ColumnSet(
new String[] { "name", "address1_postalcode", "lastusedincampaign" });
Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
Console.Write("retrieved, ");
// Update the postal code attribute.
retrievedAccount.Address1_PostalCode = "98052";
// The address 2 postal code was set accidentally, so set it to null.
retrievedAccount.Address2_PostalCode = null;
// Shows use of a Money value.
retrievedAccount.Revenue = new Money(5000000);
// Shows use of a boolean value.
retrievedAccount.CreditOnHold = false;
// Update the account record.
_serviceProxy.Update(retrievedAccount);
Console.WriteLine("and updated.");

How to open new window with streamed document in ASP.NET Web Forms

I have an ASP.NET Web Forms application. I want to have a button to post back to the server that will use my fields on my form (after validation) as parameters to a server process that will generate a document and stream it back to the browser. I want the form to be updated with some status results.
What is the best way to achieve this? Right now, I've got the button click generating the document and streaming it back to the browser (it's a Word document and the dialog pops up, and the Word document can be opened successfully) but the page doesn't get updated.
I have jQuery in my solution, so using js isn't an issue if that is required.
I have a very similar process on one of my servers, and the way I've handled it is to create a temporary document on the server rather than doing a live stream. It requires a bit of housekeeping code to tidy it up, but it does mean that you can return the results of the generation and then do a client-side redirect to the generated document if successful. In my case, I'm using jQuery and AJAX to do the document generation and page update, but the same principle should also apply to a pure WebForms approach.
This was way more difficult to do than I thought. The main issue is with opening a new browser window for a Word document. The window briefly flashes up, then closes - no Word document appears. It seems to be a security issue.
If i click a button on my page, I can stream the Word doc back as the response, and the browser dialog pops up allowing me to Open/Save/Cancel, but of course, my page doesn't refresh.
My final solution to this was to use a client script on the button click to temporarily set the form's target to _blank. This forces the response to the click on the postback to go to a new browser window (which automatically closes after the download dialog is dismissed):
<asp:Button Text="Generate Doc" runat="server" ID="btnGenerateDoc"
onclick="btnGenerateDoc_Click" OnClientClick="SetupPageRefresh()" />
My SetupPageRefresh function is as follows:
function SetupPageRefresh() {
// Force the button to open a new browser window.
form1.target = '_blank';
// Immediately reset the form's target back to this page, and setup a poll
// to the server to wait until the document has been generated.
setTimeout("OnTimeout();", 1);
}
Then my OnTimeout function resets the target for the form, then starts polling a web service to wait until the server process is complete. (I have a counter in my Session that I update once the process has completed.)
function OnTimeout() {
// Reset the form's target back to this page (from _blank).
form1.target = '_self';
// Poll for a change.
Poll();
}
And the Poll function simply uses jQuery's ajax function to poll my web service:
function Poll() {
var currentCount = $("#hidCount").val();
$.ajax({
url: "/WebService1.asmx/CheckCount",
data: JSON.stringify({ currentCount: currentCount }),
success: function (data) {
var changed = data.d;
if (changed) {
// Change recorded, so refresh the page.
window.location = window.location;
}
else {
// No change - check again in 1 second.
setTimeout("Poll();", 1000);
}
}
});
}
So this does a 1 second poll to my web service waiting for the Session's counter to change from the value in the hidden field on the page. This means it doesn't matter how long the server process takes to generate the Word document (and update the database, etc.) the page won't refresh until it's done.
When the web service call comes back with true, the page is refreshed with the window.location = window.location statement.
For completeness, my Web Service looks like this:
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : WebService
{
[WebMethod(EnableSession=true)]
public bool CheckCount(int currentCount)
{
if (Session["Count"] == null)
Session["Count"] = 0;
var count = (int)Session["Count"];
var changed = count != currentCount;
return changed;
}
}
Hopefully that helps somebody else!

Resources