Connect IIS on different server - c#

I'm having an IIS on a different machine that I need to connect and I'm not able to do so.
How is it possible to do?
My add pool function:
private string addPool(string companyName, string serverName)
{
string errorMsg = string.Empty;
string result = run_AC("add apppool /name:" + companyName, serverName);
if (result.EndsWith("added" + Environment.NewLine))
errorMsg = string.Empty;//"Create application pool ... OK";
else if (result.StartsWith("ERROR ( message:Failed to add duplicate collection element"))
errorMsg = "Create application pool ... already exists";
else
errorMsg = "Create application pool ... failed - ";
return errorMsg;
}
</code>
<code>
private string siteCreation(string companyName, string BaseSite, string envirementFolderPath, string serverName)
{
string errorMsg = string.Empty;
string result = run_AC("add app /site.name:\"" + BaseSite + "\" /app.name:" + companyName + " /path:/" + companyName + " \"/physicalPath:" + envirementFolderPath + "\" /applicationPool:" + companyName, serverName);
if (result.EndsWith("added" + Environment.NewLine))
errorMsg += string.Empty;// "Create app ... OK";
else if (result.StartsWith("ERROR ( message:Failed to add duplicate collection element"))
errorMsg += "Create app ... already exists";
else
errorMsg += "Create app ... failed - " + result;
return errorMsg;
}

Related

Try Catch Block not preventing exception

I am building a program that will move a bunch of files.
if (line.Contains("INSERT INTO BACKLOGITEM_ATTACHMENT VALUES"))
{
string AttachementID = line.Split(',', ')')[1];
string FileName = AttachementsDictionary[AttachementID];
string BacklogScrumID = BacklogLookupDictionary[AttachementID];
BacklogItem Story = BacklogItemDictionary[BacklogScrumID];
Product Product = ProductDictionary[Story.ProductScrumId];
string FileToCopy = "\\\\dxScrum01v\\ScrumWorksPro\\scrumworks\\data\\attachments\\product" + Story.ProductScrumId + "\\attachement" + AttachementID;
string FileToSave = "C:\\ScrumWorksAttachementExport\\" + Product.ProductName + "\\" + Product.StoryPrefix + "-" + Story.StoryTitle + "\\" + FileName;
//Console.WriteLine(FileToCopy + " >>> " + FileToSave);
try
{
File.Copy(#FileToCopy, #FileToSave);
}
catch (Exception)
{
Console.WriteLine("Failed: " + FileToSave);
throw;
}
}
The issue is that I am getting an exception when running the program. There are times when the file does not exist.
How can I make it so that if it fails it just outputs the failure and keeps going?
Remove throw; if you dont want your application to break, you can handle the exception too

AT commands appearing in the sms in asp.net

I'm trying to develop a sms sending system using asp.net mvc 4 where I'm using HUAWEI USB 3G modem to send sms. Problem is, when I receive sms, most often the text are coming like this,
AT+CMGF=1 AT+CMGS="+8801671234567" Name: Sample Name Amount1: 1000.....
Here are my codes,
public ActionResult SendSms(int RentId=0)
{
AmountInfo BillTable = db.AmountInfoes.Find(RentId);
var GetName = db.AmountInfoes.Where(a => a.serial.Equals(BillTable.serial)).FirstOrDefault();
string getName = GetName.name;
int getAmount1 = GetName.amount1;
int getAmount2 = GetName.amount2;
int getAmount3 = GetName.amount3;
int getAmount4 = GetName.amount4;
int getAmount5 = GetName.amount5;
int getAmount6 = GetName.amount6;
string getNumber = GetName.phone;
try
{
SP.PortName = "COM8";
SP.Close();
SP.Open();
string ph_no;
string the_no = getNumber;
string txt_msg = "Name: " + getName + " Amount1: " + getAmount1 + " Amount2: " + getAmount2 + " Amount3: " + getAmount3 + " Amount4: " + getAmount4 + " Amount5: " + getAmount5 + " Amount6: " + getAmount6;
ph_no = Char.ConvertFromUtf32(34) + the_no + char.ConvertFromUtf32(34);
SP.Write("AT+CMGF=1" + Char.ConvertFromUtf32(13));
SP.Write("AT+CMGS=" + ph_no + Char.ConvertFromUtf32(13));
SP.Write(txt_msg + Char.ConvertFromUtf32(26) + Char.ConvertFromUtf32(13));
SP.Close();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("RentManager");
}
Is there something wrong in my code? How can I fix this problem where AT commands will not appear in my sms? Need this help badly. Thanks.

C# SQL output to text like SSMS message tab

I'm having some trouble finding a way to get the results from updates/inserts/deletes/table creates...
I would like to get it like you see in the SSMS (SQL Server Management Studio) message tab (guess the tool is done_in_proc).
At the moment, I can get the exceptions, and I can capture the prints done in the SQL script.
I already tried ExecuteScalar, ExecuteReader, ExecuteWithResults and got nothing.
Thanks,
Code:
public void conn_InfoMessage(object sender, SqlInfoMessageEventArgs e)
{
foreach (SqlError err in e.Errors)
{
richTextBoxDeployCopy.AppendText("Info : "+err.Message + Environment.NewLine);
}
}
public void ExecSQLScript(string Instance, string Database, string SQLScript, string Username, string Password)
{
if (Application2Deploy == "DUMMY")
{
server = "Server";
}
else
{
server = Instance;
} string sqlConnectionString = #"User ID=" + Username + "; Password = " + Password + ";Persist Security Info=False;Initial Catalog=" + Database + ";Data Source=" + server + "\\" + Instance;
FileInfo file = new FileInfo(SQLScript);
string script = file.OpenText().ReadToEnd();
conn = new SqlConnection(sqlConnectionString);
conn.FireInfoMessageEventOnUserErrors = true;
Server SQLserver = new Server(new ServerConnection(conn));
if (checkBoxDeployCopyTestingScript.Checked)
{
richTextBoxDeployCopy.AppendText("Test: Running SQL Script......" + Environment.NewLine);
LogFile(DateTime.Now + "Test: Running SQL Script......", LogPath);
}
else
{
try
{
SQLserver.ConnectionContext.Connect();
SQLserver.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(conn_InfoMessage);
SQLserver.ConnectionContext.BeginTransaction();
SQLserver.ConnectionContext.ExecuteNonQuery(script);
Error = false;
}
catch (Exception SQLEx)
{
Error = true;
richTextBoxDeployCopy.AppendText("Error executing SQL Script." + Environment.NewLine);
LogFile(DateTime.Now + "Error executing SQL Script", LogPath);
richTextBoxDeployCopy.AppendText("Exception: " + SQLEx.InnerException.Message + Environment.NewLine);
LogFile(DateTime.Now + "Exception: " + SQLEx.InnerException.Message, LogPath);
try
{
SQLserver.ConnectionContext.RollBackTransaction();
}
catch (Exception ex2)
{
richTextBoxDeployCopy.AppendText("Error executing rollback." + Environment.NewLine);
richTextBoxDeployCopy.AppendText("Exception: " + ex2.Message + Environment.NewLine);
}
}
if (Error == false)
{
SQLserver.ConnectionContext.CommitTransaction();
CopyExit("End");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
else
{
CopyExit("Abort");
file.OpenText().Close();
file.OpenText().Dispose();
SQLserver.ConnectionContext.SqlConnectionObject.Close();
//SQLserver.ConnectionContext.ForceDisconnected();
}
}
}

How to attach a file to an email in c#

Hi I believe I am pretty close to figuring out what is wrong with my code, but was hoping someone could help me out or point me in the right direction. I am able to run my program and on the page where the user is going to be uploading a file it gives me the option to choose a file. But when I press submit other information gets sent to me but the file never comes. I think this is because I am having trouble figuring out where to temporarily save the file when it send to my email. Here is my code at the moment:
Also what this code is for is a comment / request page on my website where the user can comment and also add a screen shot.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
My question is where am I going wrong where in this code do I put where I want the file to be saved.
The below part of the code is what I am using to format the email when it is sent. And pick what will be sent in the email.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
File1.f + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
For some reason now nothing is sending in my emails when I press submit. Also I was trying to figure out how to put in the email the time and date the email was sent. Even though obviously my email will have this information, incase the email is delayed for some reason I would like to have the time and date the user pressed the submit button. Where is says File.F in this part of the code this is where i was trying to figure out how to get the file attachment to go to the email, but I'm not sure what syntax should go there in the code.
It looks like you are trying to attach some file from the user's computer to the email you are sending. If that is the case, you need to upload your file first before you call SendMessage.
In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you.
After you upload your file, pass strSavedLocation, which is the file location you saved the file, to your SendMessage() method.
In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage. strAttachment is the path name to your uploaded file:
var attachment = new Attachment(strAttachment);
// Add time stamp information for the file.
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(strAttachment);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(strAttachment);
disposition.ReadDate = System.IO.File.GetLastAccessTime(strAttachment);
mailMsg.Attachments.Add(attachment);
It looks to me like you have the major parts here minus the handy, System.Net.Mail.Attachment.
If I were doing this, I'd move the file upload handling code into the Submit_Click handler, and then just add the Mail.Attachment code.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
System.Net.Mail.MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
/*** Added mail attachment handling ***/
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strAttachment);
mailMsg.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
}
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
/*** Moved from SendMessage function ****/
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
strSaveLocation + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, strSaveLocation, "");
}
catch
{
}
}
As for the note about using StringBuilder, I agree, and I would use it like this:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat("Bug Name: {0}<br/>", txtBugName.Text.Trim());
sb.AppendFormat("Module Name: {0}<br/>", ddlModule.SelectedValue);
Edited To Add:
Also, see Brad's answer above about using ContentDisposition.

Using Redemption (Outlook) with a user other than the logged in user - and getting errors

I'm using Redemption dll (http://www.dimastr.com/redemption/) and I've created an exe that accesses my mail box.
I run the exe in Windows Scheduler under my username and it works fine, I get an email sent to me (see below code).
When I change the runas username in Scheduler to someone else and try to access their mail box Profile I get an error. System.IO.FileLoadException
static void Main(string[] args)
{
System.Diagnostics.Debugger.Break();
object oItems;
//string outLookUser = "My Profile Name";
string outLookUser = "Other User Profile Name";
string ToEmailAddress = "abc.email#xyz.com";
string FromEmailAddress = "abc.email#xyz.com";
string outLookServer = "exchangeServer.com";
string sMessageBody =
"\n outLookUser: " + outLookUser +
"\n outLookServer: " + outLookServer +
"\n\n";
RDOSession Session = null;
try
{
rdoDefaultFolders olFolderInbox = rdoDefaultFolders.olFolderInbox;
Session = new RDOSession();
RDOFolder objFolder;
Session.LogonExchangeMailbox(outLookUser, outLookServer);
int mailboxCount = Session.Stores.Count;
string defaultStore = Session.Stores.DefaultStore.Name;
sMessageBody +=
"\n mailboxCount: " + mailboxCount.ToString() +
"\n defaultStore: " + defaultStore +
"\n\n";
//RDOStore rmpMetering = Session.Stores.GetSharedMailbox("Name of another mailbox");
//objFolder = rmpMetering.GetDefaultFolder(olFolderInbox);
objFolder = Session.GetDefaultFolder(olFolderInbox);
oItems = objFolder.Items;
int totalcount = objFolder.Items.Count;
if (totalcount > 10) totalcount = 10;
for (int loopcounter = 1; loopcounter < totalcount; loopcounter++)
{
RDOMail oItem = objFolder.Items[loopcounter];
string attachmentName = string.Empty;
foreach (RDOAttachment attachment in oItem.Attachments)
{
attachmentName += attachment.FileName + " ";
if (attachmentName.Trim() == "Data.csv")
{
attachment.SaveAsFile(#"C:\datafiles\" + attachmentName.Trim());
foreach (RDOFolder archiveFolder in objFolder.Folders)
{
if (archiveFolder.Name == "DataFileArchive")
{
oItem.MarkRead(true);
oItem.Move(archiveFolder);
}
}
}
}
sMessageBody += oItem.Subject + " " + attachmentName + "\n";
if ((oItem.UnRead))
{
//Do whatever you need this for
//sMessageBody = oItem.Body;
//oItem.MarkRead(true);
}
}
System.Web.Mail.SmtpMail.Send(ToEmailAddress,FromEmailAddress
, "Data File Processing-" + DateTime.Now.ToString()
,"" + sMessageBody);
}
catch (Exception ex)
{
Session = null;
System.Web.Mail.SmtpMail.Send(ToEmailAddress, FromEmailAddress, "Error", sMessageBody + " " + ex.Message);
}
finally
{
if ((Session != null))
{
if (Session.LoggedOn)
{
Session.Logoff();
}
}
}
}
When I try to run the same exe on another machine with me logged in I get this error,
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or ass
embly 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken=null
' or one of its dependencies. The system cannot find the file specified.
File name: 'Interop.Redemption, Version=4.7.0.0, Culture=neutral, PublicKeyToken
=null'
at RPMDataFileProcessing.Program.Main(String[] args)
Has anyone got any ideas on what I'm doing wrong, can Redemption be used in this way?
I got this working in the end by ensuring that the user you are logged in as, has 'full mailbox rights' to the mail box you are trying to see.

Categories

Resources