I am unable to upload large files to Sharepoint 2010. I am using Visual Studio 2010 and Language C#. I have tried multiple ways from content I have found online but nothing has worked. I have changed the settings and config files to the maximum allowed upload limits and still nothing. I am using the copy.asmx for small files which works fine and am trying UploadDataAsync when the file is too large and an exception is thrown but this is not working. Please take a look at the code below...
Any/all assistance is greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace ListsService
{
public class UploadDocumentcs
{
public string UploadResult { get; set; }
public string Errors { get; set; }
public UploadDataCompletedEventHandler WebClient_UploadDataCompleted { get; set; }
public byte[] content { get; set; }
public void UploadDocumentToSP(string localFile, string remoteFile)
{
string result = string.Empty;
SPCopyService.CopySoapClient client = new SPCopyService.CopySoapClient();
string sUser = "user";
string sPwd = "pwd";
string sDomain = "dmn";
System.Net.NetworkCredential NC = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential = NC;
try
{
client.Open();
string url = "http://SP/TestLibrary/";
string fileName = localFile.Substring(localFile.LastIndexOf('\\'), (localFile.Length - localFile.LastIndexOf('\\')));
fileName = fileName.Remove(0, 1);
string[] destinationUrl = { url + fileName };
System.IO.FileStream fileStream = new System.IO.FileStream(localFile, System.IO.FileMode.Open);
byte[] content = new byte[(int)fileStream.Length];
fileStream.Read(content, 0, (int)fileStream.Length);
fileStream.Close();
// Description Information Field
SPCopyService.FieldInformation descInfo = new SPCopyService.FieldInformation
{
DisplayName = "Description",
Type = SPCopyService.FieldType.File,
Value = "Test file for upload"
};
SPCopyService.FieldInformation[] fileInfoArray = { descInfo };
SPCopyService.CopyResult[] arrayOfResults;
uint result2 = client.CopyIntoItems(fileName, destinationUrl, fileInfoArray, content, out arrayOfResults);
// Check for Errors
foreach (SPCopyService.CopyResult copyResult in arrayOfResults)
{
string msg = "====================================" +
"SharePoint Error:" +
"\nUrl: " + copyResult.DestinationUrl +
"\nError Code: " + copyResult.ErrorCode +
"\nMessage: " + copyResult.ErrorMessage +
"====================================";
Errors = string.Format("{0};{1}", Errors, msg);
}
UploadResult = "File uploaded successfully";
}
catch (OutOfMemoryException)
{
System.Uri uri = new Uri("http://bis-dev-srv2:300/DNATestLibrary/");
(new System.Net.WebClient()).UploadDataCompleted += new UploadDataCompletedEventHandler(WebClient_UploadDataCompleted);
(new System.Net.WebClient()).UploadDataAsync(uri, content);
}
finally
{
if (client.State == System.ServiceModel.CommunicationState.Faulted)
{
client.Abort();
UploadResult = "Upload aborted due to error";
}
if (client.State != System.ServiceModel.CommunicationState.Closed)
{
client.Close();
}
}
}
void WcUpload_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
if (e != null)
{
UploadResult = "Upload Unuccessful";
}
else
{
UploadResult = "Upload Successful";
//throw new NotImplementedException();
}
}
}
}
Shaun
In order to get this to work, you will have to make changes to the SharePoint configuration to increase the upload limit and the time out. The link below shows the necessary steps to get large file uploads to work.
http://blogs.technet.com/b/sharepointcomic/archive/2010/02/14/sharepoint-large-file-upload-configuration.aspx
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
namespace UploadTester
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnSelectFile_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
byte[] content = GetByteArray();
string filename = Path.GetFileName(openFileDialog1.FileName);
System.Net.WebClient webClient = new System.Net.WebClient();
System.Uri uri = new Uri("http://SP/DNATestLibrary/" + filename);
webClient.Credentials = new NetworkCredential("username", "pwd", "domain");
webClient.UploadData(uri, "PUT", content);
MessageBox.Show("Upload Successful");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
byte[] GetByteArray()
{
FileStream fileStream = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
byte[] content = new byte[(int)fileStream.Length];
fileStream.Read(content, 0, (int)fileStream.Length);
fileStream.Close();
return content;
}
private void btnUploadAsync_Click(object sender, EventArgs e)
{
try
{
byte[] content = GetByteArray();
string filename = Path.GetFileName(openFileDialog1.FileName);
System.Net.WebClient webClient = new System.Net.WebClient();
System.Uri uri = new Uri("http://SP/DNATestLibrary/" + filename);
webClient.UploadDataCompleted += new UploadDataCompletedEventHandler(webClient_UploadDataCompleted);
webClient.Credentials = new NetworkCredential("username", "pwd", "domain");
webClient.UploadDataAsync(uri, "PUT", content);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
void webClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
{
if (e.Error == null)
{
MessageBox.Show("Upload Successful");
}
else
{
MessageBox.Show(e.ToString());
}
}
}
}
Related
I'm stuck with an App that is running on Windows 10 IoT Core. All Classes are working fine, except for the one that is creating a CSV File via JSON and is supposed to send it as an Email.
When the Code reaches the "ReturnToMainPage()" Function the Exception "System.Exception: The application called an interface that was marshalled for a different thread" is thrown.
The "funny" thing is, the Mail is being send and i recieve it but the Program won't switch to back to the Main Page as intendet after sending the Email.
Here is the Code of the Class:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using EASendMail;
namespace PratschZahlstation
{
public sealed partial class MailChoice : Page
{
private TextBlock _headerText;
private ComboBox _mailComboBox;
private Button _execute;
private Button _abort;
private EnDecode _coder = EnDecode.get_EnDecodeSingleton();
private string _mailto = null;
public MailChoice()
{
this.InitializeComponent();
Init();
}
private void Init()
{
_headerText = HeaderText;
_mailComboBox = MailAdresses;
_mailComboBox.Items.Add("---");
_mailComboBox.Items.Add("dummy#mail.com");
_mailComboBox.SelectedIndex = 0;
_execute = DoFunction;
_abort = DoExit;
}
private void DoFunction_Click(object sender, RoutedEventArgs e)
{
string selectedMail = this._mailComboBox.SelectedItem.ToString();
if(selectedMail == "---")
{
_headerText.Text = "Bitte eine Emailadresse aus der Liste auswählen.";
}
else
{
_headerText.Text = "CSV wird erstellt und per Mail versendet!";
_execute.IsEnabled = false;
_abort.IsEnabled = false;
_mailComboBox.IsEnabled = false;
_mailto = selectedMail;
DateTime date = DateTime.Now;
string strippedDate = date.ToString("yyyy-MM-dd") + " 00:00:01";
GetDataForCSV(strippedDate);
}
}
private async void GetDataForCSV(string dateAsString)
{
string correctedDate = "2019-07-01 00:00:01";//dateAsString;
string date = _coder.Base64Encode(correctedDate);
HttpClient _client = new HttpClient();
Uri _uri = new Uri("URI TO JSON-API");
_client.BaseAddress = _uri;
var request = new HttpRequestMessage(HttpMethod.Post, _uri);
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("mode", "10"));
keyValues.Add(new KeyValuePair<string, string>("date", date));
request.Content = new FormUrlEncodedContent(keyValues);
var response = await _client.SendAsync(request);
string sContent = await response.Content.ReadAsStringAsync();
keyValues = null;
if (sContent != null)
{
byte[] bytes = Encoding.UTF8.GetBytes(sContent);
string json = Encoding.UTF8.GetString(bytes);
if (!json.Contains("success"))
{
List<CSV_SQL_Json_Object> _Json = JsonConvert.DeserializeObject<List<CSV_SQL_Json_Object>>(json);
response.Dispose();
request.Dispose();
_client.Dispose();
if (_Json.Count == 0)
{
}
else
{
CreateCSV(_Json);
}
}
else
{
List<JSON_Status> _Json = JsonConvert.DeserializeObject<List<JSON_Status>>(json);
_headerText.Text = "Es ist der Folgender Fehler aufgetreten - Errorcode: \"" + _coder.Base64Decode(_Json[0].success) + "\"\r\nFehlermeldung: \"" + _coder.Base64Decode(_Json[0].message) + "\"";
_Json.Clear();
response.Dispose();
request.Dispose();
_client.Dispose();
}
}
}
private async void CreateCSV(List<CSV_SQL_Json_Object> contentForCSV)
{
DateTime date = DateTime.Now;
string csvName = date.ToString("yyyy-MM-dd") + ".csv";
StorageFolder storageFolder = KnownFolders.MusicLibrary;
StorageFile csvFile = await storageFolder.CreateFileAsync(csvName, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);
await FileIO.WriteTextAsync(csvFile, "Column1;Column2;Column3;Column4;\n");
foreach (var item in contentForCSV)
{
await FileIO.AppendTextAsync(csvFile, _coder.Base64Decode(item.Object1) + ";" + _coder.aesDecrypt(_coder.Base64Decode(item.Object2)) + ";" + _coder.aesDecrypt(_coder.Base64Decode(item.Object3)) + ";" + _coder.aesDecrypt(_coder.Base64Decode(item.Object4)) + "\n");
}
SendEmail(_mailto, csvName);
}
private async void SendEmail(string mailto, string csvName)
{
try
{
SmtpMail oMail = new SmtpMail("Mail");
SmtpClient oSmtp = new SmtpClient();
oMail.From = new MailAddress("noreply#dummy.com");
oMail.To.Add(new MailAddress(mailto));
oMail.Subject = "The Subject";
oMail.HtmlBody = "<font size=5>MailText</font>";
StorageFile file = await KnownFolders.MusicLibrary.GetFileAsync(csvName).AsTask().ConfigureAwait(false);
string attfile = file.Path;
Attachment oAttachment = await oMail.AddAttachmentAsync(attfile);
SmtpServer oServer = new SmtpServer("mail.dummy.com");
oServer.User = "dummyuser";
oServer.Password = "dummypass";
oServer.Port = 587;
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
await oSmtp.SendMailAsync(oServer, oMail);
}
catch (Exception ex)
{
string error = ex.ToString();
_abort.IsEnabled = true;
}
ReturnToMainPage(); //This is where the Error Happens
}
private void ReturnToMainPage()
{
this.Frame.Navigate(typeof(MainPage));
}
private void DoExit_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(MainPage));
}
}
}
This could be an Threading issue. Navigation is only possible on the main-Thread.
You may want to try to marshal the call in:
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// Your UI update code goes here!
}
);
Source:
The application called an interface that was marshalled for a different thread - Windows Store App
Like Tobonaut said, you can use the Dispatcher.RunAsync to call the Navigation, it worked.
But your problem may not be this.
I copied your code and reproduced your problem and found that you have problems with the calls to read and write files:
// Your code
StorageFile csvFile = await storageFolder.CreateFileAsync(csvName, CreationCollisionOption.OpenIfExists).AsTask().ConfigureAwait(false);
StorageFile file = await KnownFolders.MusicLibrary.GetFileAsync(csvName).AsTask().ConfigureAwait(false);
The Navigation will be work if you delete the .AsTask().ConfigureAwait(false).
Best regards.
I have designed a c sharp application which captures an image using the laptop camera,save it ,and sends a copy via an email with the help of Dynamsoft Dynamic .NET TWAIN 5.3 Trial .... when I run the program from the visual studio it works fine,but when I copy and paste the .exe file outside the program directory it does not work and a message saying "program_name has stopped working "appears.and that is my code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Dynamsoft.DotNet.TWAIN.Enums;
using Dynamsoft.DotNet.TWAIN.WebCamera;
using System.Net.Mail;
using System.IO;
using System.Collections;
namespace captureImageOfMyLaptopUser
{
public partial class Form1 : Form
{
string receiverId;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dynamicDotNetTwain1.IfShowUI = true;
dynamicDotNetTwain1.SupportedDeviceType = EnumSupportedDeviceType.SDT_WEBCAM;
dynamicDotNetTwain1.IfThrowException = true;
if (!Directory.Exists("d:\\WhoOpenedMyLaptop\\Images"))
{
Directory.CreateDirectory("d:\\WhoOpenedMyLaptop");
}
string[] filePaths = Directory.GetFiles(#"d:\WhoOpenedMyLaptop");
ArrayList list = new ArrayList();
int num=0;
foreach (string path in filePaths)
{
int l = path.Length;
num = int.Parse(path.Substring(24, l - 28));
list.Add(num);
}
int[] array = list.ToArray(typeof(int)) as int[];
if (array.Length > 0)
{
num = array.Max();
}
else
{
num=0;
}
string fileName = "d:\\WhoOpenedMyLaptop\\pic" + (num + 1).ToString() + ".pdf";
turnOnCamera();
captureImage();
saveImage(fileName);
sendingTheImage(fileName);
}
private void captureImage()
{
try
{
dynamicDotNetTwain1.EnableSource();
}
catch (Exception)
{
MessageBox.Show("error");
}
}
private void turnOnCamera()
{
try
{
dynamicDotNetTwain1.SelectSourceByIndex(0) ;
dynamicDotNetTwain1.SetVideoContainer(pictureBox1);
dynamicDotNetTwain1.OpenSource();
int count = dynamicDotNetTwain1.ResolutionForCamList.Count;
for (int j = 0; j < count; j++)
{
string tempHeight = dynamicDotNetTwain1.ResolutionForCamList[j].Height.ToString();
string tempWidth = dynamicDotNetTwain1.ResolutionForCamList[j].Width.ToString();
string tempResolution = tempWidth + "X" + tempHeight;
comboResolution.Items.Insert(j, tempResolution);
comboResolution.SelectedIndex = 0;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void saveImage(string imagePath)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = imagePath;
saveFileDialog.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
dynamicDotNetTwain1.SaveAllAsPDF(saveFileDialog.FileName);
}
private void sendingTheImage(string path)
{
readEmailIdFromTextFile();
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("seewhoopenedyourlaptop#gmail.com");
mail.To.Add(receiverId);
string date = DateTime.Now.ToString();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(path);
mail.Attachments.Add(attachment);
mail.Subject = "لقد قام هذا الشخص بفتح جهازك ";
mail.Body = "التوقيت : " + date;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("seewhoopenedyourlaptop", "mylaptopcamera");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
// MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void readEmailIdFromTextFile()
{
String line;
StreamReader sr = new StreamReader("C:\\Program Files\\WhoOpenedMyLaptop\\data.txt");
line = sr.ReadLine();
receiverId = line;
sr.Close();
}
}
}
You should copy the executable files together with all dll files since it depends on them. You can go to references and then select all libraries and at the atributes, change to copy always, then cleanup the project and then build the project, do not run, copy all content of the folder to a new location and open the executable file, it should run
I want to send SMS using way2sms. I have tried following code
login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnconnect_Click(object sender, EventArgs e)
{
Session["id"] = txtmobileno.Text;
Session["pw"] = txtpw.Text;
Response.Redirect("/send.aspx");
}
}
}
send.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace WebApplication1
{
public partial class send : System.Web.UI.Page
{
string mbno, mseg, ckuser, ckpass;
private HttpWebRequest req;
private CookieContainer cookieCntr;
private string strNewValue;
public static string responseee;
private HttpWebResponse response;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null && Session["pw"] == null)
{
Server.Transfer("login.aspx");
}
connect();
try
{
lblError.Text = "";
lblError.Visible = false;
if (!(IsPostBack))
{
btnSend.Attributes.Add("onclick", "return Validate('" + txtTo.ClientID + "','" + txtMessage.ClientID + "');");
txtMessage.Attributes.Add("onchange", "TextChange('" + txtMessage.ClientID + "','" + lblLeft.ClientID + "');");
txtMessage.Attributes.Add("onkeyup", "TextChange('" + txtMessage.ClientID + "','" + lblLeft.ClientID + "');");
}
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
mbno = txtTo.Text;
mseg = txtMessage.Text;
sendSms(mbno, mseg);
txtTo.Text = "";
txtMessage.Text = "";
}
catch (Exception ex)
{
lblError.Text = ex.Message;
lblError.Visible = true;
}
}
public void connect()
{
ckuser = Session["id"].ToString();
ckpass = Session["pw"].ToString();
try
{
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com/auth.cl");
this.req.CookieContainer = new CookieContainer();
this.req.AllowAutoRedirect = false;
this.req.Method = "POST";
this.req.ContentType = "application/x-www-form-urlencoded";
this.strNewValue = "username=" + ckuser + "&password=" + ckpass;
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
this.cookieCntr = this.req.CookieContainer;
this.response.Close();
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com//jsp/InstantSMS.jsp?val=0");
this.req.CookieContainer = this.cookieCntr;
this.req.Method = "GET";
this.response = (HttpWebResponse)this.req.GetResponse();
responseee = new StreamReader(this.response.GetResponseStream()).ReadToEnd();
int index = Regex.Match(responseee, "custf").Index;
responseee = responseee.Substring(index, 0x12);
responseee = responseee.Replace("\"", "").Replace(">", "").Trim();
this.response.Close();
pnlsend.Visible = true;
lblErrormsg.Text = "connected";
}
catch (Exception ex)
{
lblErrormsg.Text = "Error connecting to the server...";
Session["error"] = "Error connecting to the server...";
lblError.Text = ex.ToString();
lblError.Text= ex.ToString();
//Server.Transfer("login.aspx");
}
}
public void sendSms(string mbno, string mseg)
{
if ((mbno != "") && (mseg != ""))
{
try
{
this.req = (HttpWebRequest)WebRequest.Create("http://wwwd.way2sms.com//FirstServletsms?custid=");
this.req.AllowAutoRedirect = false;
this.req.CookieContainer = this.cookieCntr;
this.req.Method = "POST";
this.req.ContentType = "application/x-www-form-urlencoded";
this.strNewValue = "custid=undefined&HiddenAction=instantsms&Action=" + responseee + "&login=&pass=&MobNo=" + this.mbno + "&textArea=" + this.mseg;
string msg = this.mseg;
string mbeno = this.mbno;
this.req.ContentLength = this.strNewValue.Length;
StreamWriter writer = new StreamWriter(this.req.GetRequestStream(), Encoding.ASCII);
writer.Write(this.strNewValue);
writer.Close();
this.response = (HttpWebResponse)this.req.GetResponse();
this.response.Close();
lblErrormsg.Text = "Message Sent..... " + mbeno + ": " + msg;
}
catch (Exception)
{
lblErrormsg.Text = "Error Sending msg....check your connection...";
}
}
else
{
lblErrormsg.Text = "Mob no or msg missing";
}
}
protected void btnLogOut_Click(object sender, EventArgs e)
{
Session["id"] = null;
Session["pw"] = null;
Session["error"] = null;
Server.Transfer("login.aspx");
}
}
}
But it doesn't work. Is there any changes in this code that I have to do?
Please tell me any other way to send sms from desktop application or web application
I dont know way2sms but the easiest SMS API I have found is http://cp.bulksmsportal.co.za/sms_default.aspx
Code is really simple as well
public static void sendSMS(string Recepient, string Message)
{
//Recepient is the cellno in string format
StringBuilder sb = new StringBuilder();
sb.Append("http://www.mymobileapi.com/api5/http5.aspx?");
sb.Append("Type=sendparam");
sb.Append("&username={yourusername}");//add your username here
sb.Append("&password={yourpassword}");//add your password here
sb.AppendFormat("&numto={0}", Recepient);
string message = HttpUtility.UrlEncode(Message, ASCIIEncoding.ASCII);
sb.AppendFormat("&data1={0}", message);
try
{
////Create the request and send data to the SMS Gateway Server by HTTP connection
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(sb.ToString());
//Get response from the SMS Gateway Server and read the answer
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
}
catch (Exception ex)
{
}
}
I used this : GSM Communication Library (GSMComm)
I have a c# app (Windows Service) that fires a timer event that reads files in a directory and sends out SMS using the data in the files. Next time the event fires, it tries to move the processed files in the "Processed" directory to a "Completed" directory before processing the new files. I keep getting a "File in use by another process" exception, although I am pretty sure that I dispose of everything that uses the files. If I stop the service and start it again, the files is released. Any ideas?
//Code that fires the timer
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.Timers;
namespace SmsWindowsService
{
public partial class SmsWindowsService : ServiceBase
{
private static System.Timers.Timer aTimer;
public SmsWindowsService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MatterCentreSMSSource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MatterCentreSMSSource", "MatterCentreSMSLog");
}
elMatterCentreSMS.Source = "MatterCentreSMSSource";
elMatterCentreSMS.Log = "MatterCentreSMSLog";
}
protected override void OnStart(string[] args)
{
string logText = string.Empty;
logText = "MatterCentreSMS Service started successfully on " + DateTime.Now;
WriteEventLog(logText);
//Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
//Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
//Set the Interval to 5 minutes.
//aTimer.Interval = 300000;
aTimer.Interval = 60000;
aTimer.Enabled = true;
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
GC.Collect();
}
protected override void OnStop()
{
string logText = string.Empty;
logText = "MatterCentreSMS Service stopped on " + DateTime.Now;
WriteEventLog(logText);
}
private void WriteEventLog(string logText)
{
elMatterCentreSMS.WriteEntry(logText);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
string ex = string.Empty;
SendSms s = new SendSms();
ex = s.ProcessSms();
if (ex.Length > 1)
WriteEventLog(ex);
//ex = RestartService("SmsWindowsService", 60000);
//WriteEventLog(ex);
}
public string RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
return "MatterCentreSMS Service successfully restarted on " + DateTime.Now;
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
}
}
//Code that reads the file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
namespace SmsWindowsService
{
class Message
{
private string filePath;
public Message(string filePath)
{
this.filePath = filePath;
}
public string readSMS(string filePath)
{
const string searchmessage = "[B-->]";
StreamReader smsmessage = new StreamReader(filePath);
try
{
FileInfo filenameinfo = new FileInfo(filePath);
if (filenameinfo.Exists == false)
throw new SMSReaderException(String.Format("SMS Message {0} cannot be found ...", filePath), filePath);
smsmessage = filenameinfo.OpenText();
string smsoutput = smsmessage.ReadToEnd();
int endpos = smsoutput.IndexOf(searchmessage);
smsoutput = smsoutput.Substring(endpos + searchmessage.Length);
smsoutput = smsoutput.Replace("&", "&");
smsoutput = smsoutput.Replace("\"", """);
smsoutput = smsoutput.Replace("'", "'");
filenameinfo = null;
smsmessage.Close();
smsmessage.Dispose();
return smsoutput;
}
catch(Exception e)
{
throw new Exception("Help", e.InnerException);
}
finally
{
smsmessage.Close();
smsmessage.Dispose();
}
}
}
public class SMSReaderException : System.IO.FileNotFoundException
{
public SMSReaderException(string message, string filename)
: base(message, filename)
{
}
}
}
//Code that connects to web service and send sms
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Net;
using System.Configuration;
using SmsWindowsService.EsendexSendSmsService;
namespace SmsWindowsService
{
class SendSms
{
string filePath = string.Empty;
string directoryPath = string.Empty;
string directoryPathProcessing = string.Empty;
string directoryPathCompleted = string.Empty;
string smsLogfileDirectory = string.Empty;
string smsLogfilePath = string.Empty;
string mattercentreSMS = string.Empty;
string messageBody = string.Empty;
string messageId = string.Empty;
string messageStatus = string.Empty;
string dateTodayString = string.Empty;
long mobileNumber;
EsendexSendSmsService.SendService send;
public SendSms()
{
directoryPath = ConfigurationSettings.AppSettings[#"directoryPath"];
directoryPathProcessing = ConfigurationSettings.AppSettings[#"directoryPathProcessing"];
directoryPathCompleted = ConfigurationSettings.AppSettings[#"directoryPathCompleted"];
smsLogfileDirectory = ConfigurationSettings.AppSettings[#"smsLogfileDirectory"];
dateTodayString = DateTime.Now.ToString("yyyy/MM/dd");
smsLogfilePath = smsLogfileDirectory + dateTodayString.Replace(#"/", "_") + ".txt";
send = new EsendexSendSmsService.SendService();
}
public string ProcessSms()
{
string ex = string.Empty;
try
{
DirectoryInfo di = new DirectoryInfo(directoryPathProcessing);
ex = MoveFilesToCompleted(directoryPathProcessing, directoryPathCompleted);
if (ex.Length > 1)
return ex;
ex = MoveFilesToProcessing(directoryPath, directoryPathProcessing);
if (ex.Length > 1)
return ex;
FileInfo[] subFilesProcessing = di.GetFiles();
foreach (FileInfo subFile in subFilesProcessing)
{
filePath = directoryPathProcessing + subFile.Name;
Message sms = new Message(filePath);
mattercentreSMS = sms.readSMS(filePath);
MessageDetails d = new MessageDetails(mattercentreSMS);
mobileNumber = d.GetMobileNumber();
messageBody = d.GetMessageBody();
ex = SetHeader();
if (ex.Length > 1)
return ex;
ex = SetProxy();
if (ex.Length > 1)
return ex;
//Send the message and get the returned messageID and send status
messageId = send.SendMessage(Convert.ToString(mobileNumber), messageBody, EsendexSendSmsService.MessageType.Text);
messageStatus = Convert.ToString(send.GetMessageStatus(messageId));
ex = WriteLogFile(messageId, subFile.Name, messageStatus);
if (ex.Length > 1)
return ex;
send.Dispose();
}
di = null;
subFilesProcessing = null;
return ex;
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
private string MoveFilesToCompleted(string directoryPathProcessing, string directoryPathCompleted)
{
DirectoryInfo din = new DirectoryInfo(directoryPathProcessing);
try
{
FileInfo[] subFiles = din.GetFiles();
foreach (FileInfo subFile in subFiles)
{
subFile.MoveTo(directoryPathCompleted + subFile.Name);
}
subFiles = null;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
finally
{
din = null;
}
}
private string MoveFilesToProcessing(string directoryPath, string directoryPathProcessing)
{
DirectoryInfo din = new DirectoryInfo(directoryPath);
try
{
FileInfo[] subFiles = din.GetFiles();
foreach (FileInfo subFile in subFiles)
{
subFile.MoveTo(directoryPathProcessing + subFile.Name);
}
subFiles = null;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
finally
{
din = null;
}
}
private string SetHeader()
{
try
{
//Setup account details in the header
EsendexSendSmsService.MessengerHeader header = new EsendexSendSmsService.MessengerHeader();
header.Account = ConfigurationSettings.AppSettings[#"smsServiceUrl"];
header.Username = ConfigurationSettings.AppSettings[#"smsServiceUsername"];
header.Password = ConfigurationSettings.AppSettings[#"smsServicePassword"];
// set the SOAP header Authentication values
send.MessengerHeaderValue = header;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
private string SetProxy()
{
try
{
//Create a web proxy object as the proxy server block direct request to esendex
WebProxy myProxy = new WebProxy(ConfigurationSettings.AppSettings[#"proxyaddress"], true);
myProxy.Credentials = new NetworkCredential(ConfigurationSettings.AppSettings[#"username"], ConfigurationSettings.AppSettings[#"password"]);
WebRequest.DefaultWebProxy = myProxy;
send.Proxy = myProxy;
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
private string WriteLogFile(string messageId, string smsFileName, string messageStatus)
{
try
{
if (File.Exists(smsLogfilePath))
{
//file is not empty - append log entry to file
using (StreamWriter writeSmsLog = File.AppendText(smsLogfilePath))
{
writeSmsLog.WriteLine(messageId + " " + smsFileName + " " + DateTime.Now + " " + messageStatus);
writeSmsLog.Close();
}
}
else
{
FileStream fs = File.OpenWrite(smsLogfilePath);
fs.Flush();
fs.Close();
fs.Dispose();
using (StreamWriter writeSmsLog = new StreamWriter(smsLogfilePath, true))
{
writeSmsLog.WriteLine("Message_ID File_Name Date_Sent Status");
writeSmsLog.WriteLine("======================================================================================================================================");
writeSmsLog.WriteLine(messageId + " " + smsFileName + " " + DateTime.Now + " " + messageStatus);
writeSmsLog.Close();
}
}
return "";
}
catch (Exception e)
{
return Convert.ToString(e);
}
}
}
}
Any ideas?
You're running a virus checker in an entirely different process. It is detecting that the file has changed and is locking it momentarily in order to check it to see if the edit you just performed to the file introduced a virus. It'll unlock it in a couple of milliseconds.
Disabling your virus checker is a bad idea. Instead, you're just going to have to live with it; write your code to be robust in a world where there are lots of processes vying for locks on files.
StreamReader smsmessage = new StreamReader(filePath);
try
{
FileInfo filenameinfo = new FileInfo(filePath);
....
smsmessage = filenameinfo.OpenText();
...
You are initializing smsmessage twice, but only disposing one of those instances. The first line constructs a StreamReader, and then you overwrite your reference to that instance with the instance created by filenameinfo.OpenText(). That leaves you with an instance that no longer has any references and hasn't been disposed. That instance might be holding a lock on the file and you have no guarantees on when it will be disposed. Even if it isn't holding a lock, you should still fix this.
I save a pdf file to stream. I want to save the stream to Response stream. But it always throw error:Response is not available in contex.
Here is the code:
using System;
using System.Threading;
using System.IO;
using Spire.Pdf;
namespace SingleThreadTest
{
public partial class Test : System.Web.UI.Page
{
//[STAThread]
protected void Page_Load(object sender, EventArgs e)
{
}
[STAThread]
protected void Button1_Click(object sender, EventArgs e)
{
////new a thread
ThreadStart threadStart = HTMLToPDF;
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
void HTMLToPDF()
{
PdfDocument doc = new PdfDocument();
String url = "http://www.e-iceblue.com/";
doc.LoadFromHTML(url, false, true, true);
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "application/pdf";
using (MemoryStream pdfStream = new MemoryStream())
{
doc.SaveToStream(pdfStream);
using (MemoryStream ms = new MemoryStream())
{
//ms.WriteTo(Response.OutputStream);
Response.OutputStream.Write(pdfStream.ToArray(), 0, pdfStream.ToArray().Length);
}
}
doc.SaveToHttpResponse("Test.pdf", Response, HttpReadType.Save);
doc.Close();
}
}
}
I want to sent client an attachment. How to acheive it??(The above code i use the third component of Spire.PDF).
Thanks in advance.
You are starting new thread to process request, but your original thread likely continues execution and successfully terminates request before your new thread even gets to doing something with the response. You have to wait for completion of the new thread in the original thread (you may be able to creatively use asynchronous pages to not block original thread http://msdn.microsoft.com/en-us/magazine/cc163725.aspx).
I had a similar task. I had a dataset and I needed to return to the client excel file.
I solved with the AXD handler. Add to web config reference to AXD.
See example
<httpHandlers>
<add verb="GET,POST" path="Export.axd" type="YourNameSpace.ExportHandler, YouDLL"/>
</httpHandlers>
See below the code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Spire;
using Spire.Xls;
namespace SD.Reval.Admin.Services
{
public class ExportHandler : IHttpHandler
{
virtual public bool IsReusable
{
get { return true; }
}
virtual public void ProcessRequest(HttpContext context)
{
try
{
Workbook workbook = new Workbook();
Worksheet worksheet;
int counter = 0;
string methodName = HttpContext.Current.Request.QueryString["methodName"];
string fileName = HttpContext.Current.Request.QueryString["fileName"];
string parameters = HttpContext.Current.Request.QueryString["params"];
if (parameters == null)
parameters = HttpContext.Current.Request.Form["params"];
int workSheetCount = workbook.Worksheets.Count;
string tableName = string.Empty ;
if (methodName.Length > 0 && fileName.Length > 0)
{
DataSet dataSet = (DataSet)ServiceInterface.InternalGenericInvoke(methodName, parameters);
foreach (DataTable dt in dataSet.Tables)
{
if (dt.Columns.Count > 0)
{
tableName = dt.TableName ;
if (counter >= workSheetCount)
worksheet=workbook.Worksheets.Add(tableName);
else
{
worksheet = workbook.Worksheets[counter];
worksheet.Name = tableName;
}
worksheet.InsertDataTable(dt, true, 4, 1, -1, -1);
counter++;
worksheet.AllocatedRange.AutoFitColumns();
worksheet.AllocatedRange.AutoFitRows();
worksheet.Pictures.Add(1, 1, SD.Reval.Admin.Services.ResourceFile.logo_reval );
//Sets header style
CellStyle styleHeader = worksheet.Rows[0].Style;
styleHeader.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
styleHeader.Borders[BordersLineType.EdgeRight].LineStyle = LineStyleType.Thin;
styleHeader.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thin;
styleHeader.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;
styleHeader.VerticalAlignment = VerticalAlignType.Center;
styleHeader.KnownColor = ExcelColors.Green;
styleHeader.Font.KnownColor = ExcelColors.White;
styleHeader.Font.IsBold = true;
}
}
fileName = fileName + ".xls";
workbook.SaveToHttpResponse(fileName, context.Response);
context.Response.Buffer = true;
context.Response.ContentType = "application/x-msdownload";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
}
}
catch (Exception ex)
{
Log.WriteLog(ex);
throw new ApplicationException("The epxport process failed", ex);
}
finally
{
}
}
}
}