|
I have a couple of toggle switches: one with Yes/No option and the other with Delivery/Purchase option. I know that you can use the ControlName.Checked but that just inserts True or False. How do I do this when these are the options.
Here are my toggle switch code for Purchase/Delivery:
<label class="switch">
<input class="switch-input" type="checkbox" id="orderselection" name="orderselection" runat="server" />
</label>
and Yes/No:
<label for="exampleOrderNumber">Are Redelegations Authorized?<label for="exampleInputCity">:</label>
<label class="switch">
<input class="switch-input" type="checkbox" id="authredelegation" name="authredelegation" runat="server" />
</label>
|
|
|
|
|
Use the ternary operator:
C#:
command.Parameters.AddWithValue("@OrderSelection", orderselection.Checked ? "Purchase" : "Delivery");
VB:
command.Parameters.AddWithValue("@OrdersSelection", If(orderselection.Checked, "Purchase", "Delivery"))
NB: For "yes/no" options, it's best to stick with the boolean value. Just declare your database column as a bit .
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Greetings gurus,
I have a requirement to collect information from users by presenting a form to them.
Upon completing the form and hitting the submit button, the content of their submission is stored in the db and at the same time sent as an email attachment all at once.
Is this possible?
If yes, does anyone know what I need to modify in the code below?
The code is not fully cooked but I need some guidance on how to submit the record and at same time sending the contents of the record as an attachment via email.
Thanks for your awesome help.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim table As New DataTable()
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("PersonnelPolicyDB").ConnectionString)
Using cmd = New SqlCommand("usp_AddABCD", con)
Using da = New SqlDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@oderno", "orderno.text")
cmd.Parameters.AddWithValue("@orderdate", "orderdate.text")
da.Fill(table)
End Using
End Using
End Using
End Sub
Dim table As New DataTable()
Using con = New SqlConnection(ConfigurationManager.ConnectionStrings("PersonnelPolicyDB").ConnectionString)
Using cmd = New SqlCommand("usp_GetABCD", con)
Using da = New SqlDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@orderno", "orderno.text")
da.Fill(table)
End Using
End Using
End Using
End Sub
Private Sub SendPDFEmail(dt As DataTable)
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
Dim companyName As String = "my Company"
Dim orderNo As Integer = 2303
Dim sb As New StringBuilder()
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>")
sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'>Order Sheet</td></tr>")
sb.Append("<tr><td colspan = '2'></td></tr>")
sb.Append("<tr><td>Order No:")
sb.Append(orderNo)
sb.Append("</td><td>Date: ")
sb.Append(DateTime.Now)
sb.Append(" </td></tr>")
sb.Append("<tr><td colspan = '2'>Company Name : ")
sb.Append(companyName)
sb.Append("</td></tr>")
sb.Append("</table>")
sb.Append("<br />")
sb.Append("<table border = '1'>")
sb.Append("<tr>")
For Each column As DataColumn In dt.Columns
sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>")
sb.Append(column.ColumnName)
sb.Append("</th>")
Next
sb.Append("</tr>")
For Each row As DataRow In dt.Rows
sb.Append("<tr>")
For Each column As DataColumn In dt.Columns
sb.Append("<td>")
sb.Append(row(column))
sb.Append("</td>")
Next
sb.Append("</tr>")
Next
sb.Append("</table>")
Dim sr As New StringReader(sb.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
Using memoryStream As New MemoryStream()
Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, memoryStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Dim bytes As Byte() = memoryStream.ToArray()
memoryStream.Close()
Dim mm As New MailMessage("NoReply@domain.com", "myemail@domain.com")
mm.Subject = "iTextSharp PDF"
mm.Body = "iTextSharp PDF Attachment"
mm.Attachments.Add(New Attachment(New MemoryStream(bytes), "iTextSharpPDF.pdf"))
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "myhostname"
smtp.EnableSsl = False
Dim NetworkCred As New System.Net.NetworkCredential()
NetworkCred.UserName = "myusername"
NetworkCred.Password = "mypassword"
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 25
smtp.Send(mm)
End Using
End Using
End Using
End Sub
|
|
|
|
|
It's rather easy. Write code to save to the database and then write code to send it as an email. There are samples of both online all over the place.
Where are you stuck?
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Man, RyanDev, it is beginning to sound like you just sit on my posts so you can tell me how easy it is and where to go get it.
I know how to google.
But my question is NOT strictly about how to save data and send email.
If you really wanted to help, you would have read my post completely.
What I would like to do is save the user's data and AT SAME TIME send the data a user just entered as A .PDF ATTACHMENT.
They are not asking to click to save the records and then click to send the records just inserted as an attachment.
They want it done in ONE click.
|
|
|
|
|
samflex wrote: They want it done in ONE click. I understood that from the beginning. Why is this hard for you. In one click, save the data to the database and then send the email. We all do this all the time. It is pretty standard. We won't write the code for you so you have to explain where you are stuck.
Just saying, "I want to..." does not mean anything. So, if you know how to google, do it then. It is like you call your mechanic on the phone and say, "I want to drive my car to the store." What in the world do you think the mechanic will say?
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Please do me a favor Ryan.
Next time you see a post from me please avoid commenting on.
How can you say, "we wont write the code for you?
How many lines of code I did I post?
Besides, I asked for ideas.
I have never seen you suggest a solution since I have been coming here.
There are just annoying so called experts like you who feels big by making people feel little.
Even your simple-minded suggestion of saving data and emailing it once again suggests you have no clue what issues I am having.
I know how to save data and email the contents. I am not sure you know what it means to convert user's contents into pdf and email them as attachments.
|
|
|
|
|
samflex wrote: you have no clue what issues I am having. I agree.
There are only 10 types of people in the world, those who understand binary and those who don't.
|
|
|
|
|
Ryandev is great at help if your question is very specific.
It may sound easy to do, but after time when the customer complains, you'll find yourself refining your code more and more to be 100% error free.
I'd start with writing several classes that is ...
- dedicated to updating the database
- dedicated to generating the PDF
- dedicated to sending emails
and then join the 3 together in your click function.
Then you can smooth out the process by making #2 & #3 async, sort of multitask in the background and quickly give the page back to the user while the email sends off.
I was going to post some code for you but my stuff is so customized now, it would be hard for you to follow. You won't be able to paste and go, but just look at it and wonder how it works.
I don't have anything generic anymore, that was years ago.
This is my send engine that I wrote. Years of evolution involved here for me.
Imports System.Net.Mail
Imports System.Threading.Tasks
Imports CO_Standard.Models
Imports System.Net
Imports System.Net.Security
Imports System.Configuration
Public Class sendEngineAsync
Public Shared Function Create_SMTPClient(ByVal smtpC As hx5.common.structure_smtp_connector) As SmtpClient
Dim smtpClient As New SmtpClient()
smtpClient.UseDefaultCredentials = False
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network
Select Case smtpClient.Port
Case 587
smtpClient.EnableSsl = False
Case 443
smtpClient.EnableSsl = True
Case 25
smtpClient.EnableSsl = False
Case Else
smtpClient.EnableSsl = False
End Select
Dim smtpCredentials = New Net.NetworkCredential
smtpCredentials.UserName = smtpC.Credentials_LoginID
smtpCredentials.Password = smtpC.Credentials_Password
smtpClient.Credentials = smtpCredentials
smtpClient.Host = smtpC.Connector_ServerAddress
smtpClient.Port = smtpC.Connector_SMTP_PortNum
smtpClient.Timeout = 250000
Return smtpClient
End Function
Public Shared Async Function SendEmailAsync( _
ByVal smtpClient As SmtpClient,
ByVal message As MailMessage,
ByVal retryCount As Integer) As Task(Of SendEmailCompletedEventArgs)
Dim currentTry As Integer = 0
While currentTry < retryCount
Try
Await smtpClient.SendMailAsync(message)
Return New SendEmailCompletedEventArgs(Nothing, False, Nothing, currentTry)
Catch ex As Exception
currentTry += 1
If currentTry >= retryCount Then
Return New SendEmailCompletedEventArgs(ex, True, Nothing, currentTry)
End If
End Try
End While
Return New SendEmailCompletedEventArgs(Nothing, True, Nothing, currentTry)
End Function
This is sort of how you use the sendengine
Dim mailMessage As New MailMessage()
mailMessage.From = New MailAddress(smtpC.Options_WebsiteName & " < " & smtpC.Options_SentFrom & " >")
mailMessage.ReplyToList.Add(New MailAddress(smtpC.Options_ReplyTo))
mailMessage.To.Add(New MailAddress(names.firstName & " " & names.lastName & "<" & p.Email_Destination & ">"))
mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mailMessage.IsBodyHtml = True
mailMessage.BodyEncoding = System.Text.Encoding.UTF8
mailMessage.Priority = MailPriority.High
mailMessage.Subject = m_Subject & " - " & DateTime.Now.ToLongTimeString()
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8
Using SmtpClient As SmtpClient = sendEngine.Create_SMTPClient(smtpC)
Dim result As SendEmailCompletedEventArgs = sendEngine.SendEmail(SmtpClient, mailMessage, p.retryCount)
sendEngineAsync.ProcessSendResult(model, result, pValue)
End Using
smtpC is a model that stores credentials for sending the email message, you would have to make your own model.
|
|
|
|
|
Thank you
I am actually working on a new assumption I made a few minutes after my initial post.
1, code the button_Click sub - this inserts records into the db
2, code getRecords sub - this grabs all the records just inserted by user
3, code the email sub - this includes the bit that converts contents to pdf
Now, if I call the email sub on both the getRecords sub and insertRecords sub, I think everything fires on one click.
I will let you know if this works.
About this Ryan guy, you understood what I was asking for, didn't you?
Your suggested approach suggests that my question is specific enough for you to understand it and provide whatever you could.
What is so complicated about asking how to save records to the db and generate and send a pdf attachment via email?
Understand that he does this every single time I post a question here.
Then someone else, just like you provides a perfect solution based on same "non specific" question I ask.
If he can stay away from my posts, I will appreciate it.
|
|
|
|
|
samflex wrote: What is so complicated about asking how to save records to the db and generate and send a pdf attachment via email?
I was a beginner like you years ago and I got lots of help from the crew here at Code Project. I'll be honest, answering questions like yours is hard because I have no clue what version of .net your using and the level of detail your looking for because I have no history of your work, gained from looking at your code examples.
As far as your thoughts go on 1,2,3 I find it not efficient.
I use MVC and lots of models which are classes. Once you populate a class to hold your data, you just use that class over and over. In other words,
- you send the class to a function to write the data,
- then send the class to a function to generate your pdf,
- then send the class to a function to send the email.
Writing the data and reading it back is a waste of time, and can result in a long wait for the database server to finish. Writes take longer than reads.
Now you can get real fancy and efficient here with .Net 4.5+
You can say or think,
Task, Async
while the database write occurs, I will task creating the PDF,
I will wait for 1 and 2 to complete and send the email in the background and return control to the user.
|
|
|
|
|
My gripe is not with you at all.
I don't mind constructive criticisms at all.
I have made several posts here, some asp.net and some JavaScript.
Each time that guy gets involved, he never offers any sort constructive criticisms at least with me any way.
He always tells you how easy it is and where to go get it.
Then he turns around and says I don't understand what you are asking.
Again, you don't need to make someone look small just because it helps you look and feel big.
someone has to start somewhere.
|
|
|
|
|
I'm sure he's aware now.
Guess overall, perhaps it's the way you crafted your question. it did sort of sounded like you wanted code written. But I read through that and realized you needed interpretation and design.
I was in the same boat as well, started using this site back in 2011 pretty heavy, asked lots of questions for years, and then took the time to help others as a way to pay for the help given to me. But I learned how to better craft my questions, and if I need code written I just ask flat out.
Now I spend more time on Focus Fanatics because I'm in the process of restoring my car and will add a turbo to it next year, parts built from scratch using 3D CAD and casting from 3D printer output after creating a negative of the printed part.
Even on a car forum, you get the same thing, "Oh that's easy and a you tube link"; but others offer tech info you would of never thought of.
|
|
|
|
|
That's very nice of you giving back.
Back in the day, I was very awesome with classic asp.
But I started perhaps as an aweful newbie and it took folks like you to help a newbie.
Then I started giving back too at experts-exchange. It feels better to give than to ask.
In any case, I was not asking for interpretation.
I have found the transition from classic asp to asp.net a bit harder than I had envisioned but it gets better every day.
The code I posted worked pretty good if you just wanted to enter stuff in markup and email as pdf attachment.
The only area I needed help on was to extend it so I can save user's entry in the db and at same time grab it, convert to pdf and email it, all on the fly.
I have figured it out.
It may not be the best approach but it works and I am fine with the design.
So, as I have it now, I use stored procedure to insert records into the db and while the record is being inserted, grab the data as they are being entered by the user, convert them to pdf and email.
Thanks for everything.
|
|
|
|
|
There is such a condition:
To download the content of Outbox from the server of EIS demonstrator films sends a request to the address on the Internet: https://ekinobilet.ru/ekbs/upload.aspx via HTTPS Protocol, method: POST, MIME-type: multipart/form-data in accordance with RFC1867 (http://www.ietf.org/rfc/rfc1867.txt). The request must contain three parameters:
1) login (string username);
2) password (string PASSWORD);
3) get (list | all | <file_name>,<file_name>,...).
Quite a lot of time I suffer over this task, after having tried different options without success. It is necessary that when you open the page, the controller has made a request to the web service and displays the list in the View. I will be very grateful for the help of the community.
|
|
|
|
|
|
 The first problem was solved this way
public async Task<ActionResult> Test()
{
var parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", ""),
new KeyValuePair<string, string>("password", ""),
};
var data = new FormUrlEncodedContent(parameters);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://ekinobilet.ru/ekbs/upload.aspx");
request.Method = "POST";
byte[] dataArray = await data.ReadAsByteArrayAsync();
request.ContentLength = dataArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
var dataStream = await request.GetRequestStreamAsync();
dataStream.Write(dataArray, 0, dataArray.Length);
dataStream.Close();
var resp = await request.GetResponseAsync();
dataStream = resp.GetResponseStream();
Stream receiveStream = resp.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var responseText = readStream.ReadToEnd();
StringBuilder output = new StringBuilder();
XmlReader reader = XmlReader.Create(new StringReader(responseText));
{
reader.ReadToFollowing("list");
reader.MoveToFirstAttribute();
string count = reader.Value;
output.AppendLine(count);
string size = reader.Value;
output.AppendLine(size);
string file = reader.Value;
output.AppendLine(file);
string name = reader.Value;
output.AppendLine(name);
}
ViewBag.list = output.ToString();
return View(responseText);
|
|
|
|
|
The challenge now is to send an xml file with an operating authorization that was above...
|
|
|
|
|
hi guys,
I have developed a MVC implementation 5, it works perfectly locally
but I published it on IIS and I have had this problem
//
in the controller I
public ActionResult Index ()
{
CatalogModel m = new CatalogModel ();
m.LocalCodeColumn = 1;
m.PriceColumn = 2;
m.SelectedClientList = m.GetClientSelectedItems ();
return View (m);
}
and in the view:
Select Client: @ Html.DropDownListFor (m => m.SelectedClientList, Model.GetClientSelectedItems (), "--Select--", new {@id = "ddlClient"})
and this function :
public IEnumerable<SelectListItem> GetClientSelectedItems()
{
IEnumerable<SelectListItem> listClient = dataServices.GetClients();
return listClient;
}
modified 20-Oct-16 11:13am.
|
|
|
|
|
I made that same mistake when I started writing MVC, and after days of research, I determined that using a dictionary is the best method to use because select list are really just key value pairs.
So when razor goes to construct the dropdownlist, it can consume the dictionary with ease.
Model
public class CatalogModel
{
public int LocalCodeColumn { get; set; }
public Dictionary<string, string> CustomerTypes { get; set; }
}
Controller
public ActionResult Index()
{
CatalogModel m = new CatalogModel();
m.CustomerTypes = SelectListHelper.Get_Customer_Types();
return View(m);
}
SelectHelper Class
public static Dictionary<string, string> Get_Customer_Types()
{
return new Dictionary<string, string>
{
{"Private", "PRIVATE"},
{"Public", "PUBLIC"},
{"Both", "BOTH"}
};
}
View
@Html.DropDownListFor(m => m.CustomerType, new SelectList(Model.select_customerType, "Value", "Key"), "-- Select Customer Type --", new { @class = "form-control" })
|
|
|
|
|
I have a modal popup form and i want to insert/delete into a database and show/remove in a data table. Does anyone know how to do this. Here is the code for the modal:
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!--
<div class="modal-content">
<div class="modal-header">
Point of Contact
</div>
<div class="modal-body">
<div class="name-text-container">
<span id="fname-text">First Name:</span>
<span id="mname-text">MI:</span>
<span id="lname-text">Last name*:</span><br>
</div>
<div class="name-input-container">
<form>
<input id="fname-input" type="text" name="fname" size="15">
<input id="mname-input" type="text" name="mname" maxlength="1" size="1">
<input id="lname-input" type="text" name="lname" size="16"><br>
</form>
</div>
<div class="email-text-container">
<span id="email-text">Email*:</span><br>
</div>
<div class="email-input-container">
<form>
<input id="email-input" type="text" name="email" size="47"><br>
</form>
</div>
<div class="contact-text-container">
<span id="telephone-text">Telephone:</span>
<span id="fax-text">Fax:</span><br>
</div>
<div class="contact-input-container">
<form>
<input id="telephone-input" type="text" name="telephone" size="20">
<input id="fax-input" type="text" name="fax" size="19"><br>
</form>
</div>
</div>
<!--
<div class="modal-footer">
<button type="button" data-dismiss="modal">Cancel</button>
<button type="button" data-dismiss="modal">Save</button>
</div>
|
|
|
|
|
1. Create a jquery function on click event of the on save button.
2. Remove the data-dismiss attribute from the save button.
3. Start writing function in javascript =>
function Save()
{
var Employee = {
fname: $("#fname").val(),
mname: $("#mname").val(),
lname: $("#lname").val()
};
$.ajax({
type:"post",
url:"write url of server method here",
data:JSON.stringify(Employee),
dataType:"json",
success:function(data){
alert("Data saved successfully !");
}
});
}
4. Create server method for save with class as parameter.public string Save(Employee emp).
5. Return the result from that method as string.
6. Get all records on pageload function, your grid will be updated.
7. Similarly for delete create a function and call on the click event of delete button.
|
|
|
|
|
SqlConnection con;
con = new SqlConnection(@"Data Source=SEPEHR;Integrated Security=True;server=(local);Database=TestDatabaseByYall");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO tbl_CustInfo (codemeli,mydate,name,idnasb,iddevice,email,mobile,tel,adress)" + "VALUES (@codemeli,@mydate,@name,@idnasb,@iddevice,@email,@mobile,@tel,@adress)", con);
cmd.Parameters.AddWithValue("@codemeli", txtcodemeli.Text.Trim().ToString());
cmd.Parameters.AddWithValue("@mydate", mydat);
statuse = false;
cmd.Parameters.AddWithValue("@name", txtname.Text);
cmd.Parameters.AddWithValue("@idnasb", dridnasb.SelectedItem.Value);
cmd.Parameters.AddWithValue("@iddevice", drdevice.SelectedItem.Value);
cmd.Parameters.AddWithValue("@email", txtemail.Text.Trim());
cmd.Parameters.AddWithValue("@mobile", txtmobile.Text.Trim().ToString());
cmd.Parameters.AddWithValue("@tel", txttel.Text.Trim().ToString());
cmd.Parameters.AddWithValue("@adress", txtAdress.Text.Trim());
cmd.ExecuteNonQuery();
lblresult.Text = "Successful!";
SqlCommand cmd2;
string vart="1";
string varf="0";
cmd2 = new SqlCommand("INSERT INTO tbl_Customer_Statuse (idcustomer,level1,level2,level3,level4,Complate)" + "VALUES (@codemeli,@level1,@level2,@level3,@level14,@Complate)", con);
cmd2.Parameters.AddWithValue("@codemeli",txtcodemeli.Text.Trim());
cmd2.Parameters.AddWithValue("@level1",vart);
cmd2.Parameters.AddWithValue("@level2",varf);
cmd2.Parameters.AddWithValue("@level3",varf);
cmd2.Parameters.AddWithValue("@level4",varf);
cmd2.Parameters.AddWithValue("@Complate",varf);
cmd2.ExecuteNonQuery();
con.Close();
|
|
|
|
|
Huh?
Well, good luck with that!
|
|
|
|
|
but in second table did not fill
|
|
|
|
|