Getting Flash Media Encoder xml Profile using php - youtube-api

I would like to ask about the xml file that is generated after creating a new broadcast on youtube, I need to get this file using PHP without the need to be logged in to youtube,
I already did something like
public function cURLcheckBasicFunctions()
{
if( !function_exists("curl_init") &&
!function_exists("curl_setopt") &&
!function_exists("curl_exec") &&
!function_exists("curl_close") ) return false;
else return true;
}
/*
* Returns string status information.
* Can be changed to int or bool return types.
*/
public function cURLdownload($url, $file)
{
if( !$this->cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
$ch = curl_init();
if($ch)
{
$fp = fopen($file, "w");
if($fp)
{
if( !curl_setopt($ch, CURLOPT_URL, $url) )
{
fclose($fp); // to match fopen()
curl_close($ch); // to match curl_init()
return "FAIL: curl_setopt(CURLOPT_URL)";
}
if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
if( !curl_exec($ch) ) return "FAIL: curl_exec()";
curl_close($ch);
fclose($fp);
return "SUCCESS: $file [$url]";
}
else return "FAIL: fopen()";
}
else return "FAIL: curl_init()";
}
public function testXmlFile(){
$xml= 'https://www.youtube.com/livestreaming?source=primary&itag=33&v=CtAsVo0Mug0&action_fmle_profile=1';
echo $this->cURLdownload($xml, "test.xml");
}
but this always returns empty file , but if i took the URl and past it in the browser while logged in to youtube the file downloads ok

As no one has tried to answer my question , i took the frustrating path and made an xml template for what youtube might generate and inserted the information directly by using smiple_xml
$xml = new simple_xml_ext("youtube_template.xml",false,true);
$name = "";
$width = "";
$height = "";
$datarate = "";
$outputsize = "";
//getting the stream from youtube api and replacing it in the document
$stream = "<![CDATA[".$streamName."]]>";
switch ($broadcast_quality) {
case "1080p":
$name = "YouTube (1080p Stream)";
$xml->children()->preset->name = $name;
$width = "1920";
$xml->children()->capture->video->size->width = $width;
$height = "1080";
$xml->children()->capture->video->size->height = $height;
$datarate = "6000";
$xml->children()->encode->video->datarate = $datarate;
$outputsize = "1920x1080";
$xml->children()->encode->video->outputsize = $outputsize;
break;
case "720p":
$name = "YouTube (720p Stream)";
$xml->children()->preset->name = $name;
$width = "1280";
$xml->children()->capture->video->size->width = $width;
$height = "720";
$xml->children()->capture->video->size->height = $height;
$datarate = "4000";
$xml->children()->encode->video->datarate = $datarate;
$outputsize = "1280x720";
$xml->children()->encode->video->outputsize = $outputsize;
break;
case "480p":
$name = "YouTube (480p Stream)";
$xml->children()->preset->name = $name;
$width = "854";
$xml->children()->capture->video->size->width = $width;
$height = "480";
$xml->children()->capture->video->size->height = $height;
$datarate = "2000";
$xml->children()->encode->video->datarate = $datarate;
$outputsize = "854x480";
$xml->children()->encode->video->outputsize = $outputsize;
break;
case "360p":
$name = "YouTube (360p Stream)";
$xml->children()->preset->name = $name;
$width = "640";
$xml->children()->capture->video->size->width = $width;
$height = "360";
$xml->children()->capture->video->size->height = $height;
$datarate = "1000";
$xml->children()->encode->video->datarate = $datarate;
$outputsize = "640x360";
$xml->children()->encode->video->outputsize = $outputsize;
break;
case "240p":
$name = "YouTube (240p Stream)";
$xml->children()->preset->name = $name;
$width = "426";
$xml->children()->capture->video->size->width = $width;
$height = "240";
$xml->children()->capture->video->size->height = $height;
$datarate = "500";
$xml->children()->encode->video->datarate = $datarate;
$outputsize = "426x240";
$xml->children()->encode->video->outputsize = $outputsize;
break;
default:
return false;
break;
}
$xml->children()->output->rtmp->stream = null;
$xml->children()->output->rtmp->stream->add_cdata($streamName);
$xml->saveXML("xml_file_path.xml");

Related

ROS - Convert Float64MultiArray to PointCloud2

How do you convert a Float64MultiArray message into a PointCloud2 message in ROS?
This is the basic skeleton :
std_msgs::Float64MultiArray map_info;
tf::matrixEigenToMsg(map,map_info );
sensor_msgs::PointCloud2 cloud;
cloud.header.stamp = ros::Time::now();
cloud.width = map_info.end()+1;
cloud.height = 1;
cloud.is_bigendian = false;
cloud.is_dense = false;
sensor_msgs::PointCloud2Modifier modifier(cloud);
modifier.setPointCloud2FieldsByString(1,"xy");
modifier.resize(map_info.end()+1);
sensor_msgs::PointCloud2Iterator<float> out_x(cloud, "x");
sensor_msgs::PointCloud2Iterator<float> out_y(cloud, "y");
for (double i=0;i<map_info.end();i++)
{
*out_x = i;
*out_y = map_info.data[i];
++out_x;
++out_y;
}

Obj-C: NSString crashes with error "Terminating app due to uncaught exception NSInvalidArgumentException"?

For some reason, the following line in my app is returned NULL, and thus, crashes my app:
NSString *address = [session user][#"field_street_address"][#"und"][0][#"safe_value"];
Which, I don't understand, as my console below states that data is returned for field_street_address. Is there something wrong with that line that I'm just not seeing? I've been staring at this for a while and I feel like I'm missing something obvious.
ViewController.m
NSDictionary *userDictInfo = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:#"diosSession"]];
DIOSSession *session = [DIOSSession sharedSession];
[session setUser:userDictInfo];
[session user];
NSString *address = [session user][#"field_street_address"][#"und"][0][#"safe_value"];
Console ([session user] log):
2017-10-06 14:06:22.226970-0700 app[828:193706] {
sessid = "DRY0fOXtO_FZOIeowFVVq8oalaFnKSe";
"session_name" = SESS2bb8896be0f16543ff3c6a;
token = giCdHBuw967IaSxDB34m0Evzf1HI3DIK6;
user = {
access = 1507310936;
created = 1459875505;
data = {
"ckeditor_auto_lang" = t;
"ckeditor_default" = t;
"ckeditor_lang" = en;
"ckeditor_show_toggle" = t;
"ckeditor_width" = "100%";
};
"field_address" = {
und = (
{
format = "<null>";
"safe_value" = "1325 Fake Street";
value = "1325 Fake Street";
}
);
};
"field_childrenunder" = {
und = (
{
format = "<null>";
"safe_value" = No;
value = No;
}
);
};
"field_city" = {
und = (
{
format = "<null>";
"safe_value" = Van;
value = Van;
}
);
};
"field_emergency_facility" = {
und = (
{
format = "<null>";
"safe_value" = Yes;
value = Yes;
}
);
};
"field_first_name" = {
und = (
{
format = "<null>";
"safe_value" = Brittany;
value = Brittany;
}
);
};
"field_last_name" = {
und = (
{
format = "<null>";
"safe_value" = B;
value = B;
}
);
};
"field_phonenumber" = {
und = (
{
format = "<null>";
"safe_value" = 2369893091;
value = 2369893091;
}
);
};
"field_photo_path" = {
und = (
{
format = "<null>";
"safe_value" = "sites/default/files/stored/1507092784.jpg";
value = "sites/default/files/stored/1507092784.jpg";
}
);
};
"field_points_balance" = {
und = (
{
format = "<null>";
"safe_value" = 12;
value = 12;
}
);
};
"field_postal_code" = {
und = (
{
format = "<null>";
"safe_value" = 000000;
value = 000000;
}
);
};
"field_private_message_notify" = {
und = (
{
value = 1;
}
);
};
"field_profile_photo" = {
und = (
{
alt = "";
fid = 237;
"field_file_image_alt_text" = (
);
"field_file_image_title_text" = (
);
filemime = "image/jpeg";
filename = "1507092784.jpg";
filesize = 16084;
height = 296;
metadata = {
height = 296;
width = 300;
};
"rdf_mapping" = (
);
status = 1;
timestamp = 1507108254;
title = "";
type = image;
uid = 47;
uri = "public://stored/1507092784.jpg";
width = 300;
}
);
};
"field_property_type" = {
und = (
{
format = "<null>";
"safe_value" = House;
value = House;
}
);
};
"field_province" = {
und = (
{
format = "<null>";
"safe_value" = BC;
value = BC;
}
);
};
"field_special_skills" = {
und = (
{
format = "<null>";
"safe_value" = "Oral medication";
value = "Oral medication";
}
);
};
"field_star_rating" = {
und = (
{
format = "<null>";
"safe_value" = 1;
value = 1;
}
);
};
"field_street_address" = {
und = (
{
format = "<null>";
"safe_value" = "1325 Fake Street";
value = "1325 Fake Street";
}
);
};
"field_supervision" = {
und = (
{
format = "<null>";
"safe_value" = No;
value = No;
}
);
};
"field_userbio" = {
und = (
{
format = "<null>";
"safe_value" = "Hi my name is Brittany.";
value = "Hi my name is Brittany.";
}
);
};
language = "";
login = 1507320712;
mail = "brittany-b#shaw.ca";
name = Brittany;
picture = "<null>";
"rdf_mapping" = {
homepage = {
predicates = (
"foaf:page"
);
type = rel;
};
name = {
predicates = (
"foaf:name"
);
};
rdftype = (
"sioc:UserAccount"
);
};
roles = {
2 = "authenticated user";
};
signature = "";
"signature_format" = "filtered_html";
status = 1;
theme = "";
timezone = UTC;
uid = 47;
};
}
If the log output in your question is from logging [session user] then you need to first access the #"user" key.
NSString *address = [session user][#"user"][#"field_street_address"][#"und"][0][#"safe_value"];
BTW - for issues like this it really helps to break down the code:
NSDictionary *sessionUser = [session user];
NSDictionary *user = sessionUser[#"user"];
NSDicitonary *streetAddr = user[#"field_street_address"];
// etc.
Then you can see where you start getting nil and look at the previous results to determine where things are going wrong.

how to Update the value if already exists in database, if not then insert new record?

I've created a validation to check the value from excel file if row value it's already in the database. I want to create action if the value already exists then my record update, if not exist on databese then inserted as new record.
Here The full code.
[ValidateAntiForgeryToken]
public ActionResult ImportDataAgens(HttpPostedFileBase excelfileRekn)
{
if (excelfileRekn == null || excelfileRekn.ContentLength == 0)
{
ViewBag.Error = "Please Select File...";
return View("ImportDataAgens");
}
else
{
if (excelfileRekn.FileName.EndsWith("xls") || excelfileRekn.FileName.EndsWith("xlsx"))
{
string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string filename = Path.GetFileName(excelfileRekn.FileName);
string DocFileNames = newFileName + "-" + filename;
string path = System.IO.Path.Combine(Server.MapPath("~/UploadFile/DataAgen/"), DocFileNames);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelfileRekn.SaveAs(path);
//read data from file excel
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<DMInformasiDataAgen> listTempRekn = new List<DMInformasiDataAgen>();
for (int row = 3; row <= range.Rows.Count; row++)
{
DMInformasiDataAgen rk = new DMInformasiDataAgen();
/* var NewUserIDAgent = ((Excel.Range)range.Cells[row, 1]).Text;
var NewNamaAgen = ((Excel.Range)range.Cells[row, 2]).Text;
//rk.NamaAgen = NewNamaAgen;*/
rk.SandiBank = ((Excel.Range)range.Cells[row, 1]).Text;
rk.UserIDAgen = ((Excel.Range)range.Cells[row, 2]).Text;
rk.NamaAgen = ((Excel.Range)range.Cells[row, 3]).Text;
var NewNomorIdentifikasiAgen = ((Excel.Range)range.Cells[row, 4]).Text;
rk.NomorIdentifikasiAgen = NewNomorIdentifikasiAgen;
if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", "Nomor Identifikasi Sudah ada sebelumnya ! Pada baris ke " + hitung + " Pada EXCEL File !");
return View("ImportDataAgens");
}
rk.NomordanTanggalPerjanjian = ((Excel.Range)range.Cells[row, 5]).Text;
rk.TglPelaksanaan = ((Excel.Range)range.Cells[row, 6]).Value;
rk.JenisAgen = ((Excel.Range)range.Cells[row, 7]).Text;
rk.KlasifikasiAgen = ((Excel.Range)range.Cells[row, 8]).Text;
rk.JenisUsahaAgen = ((Excel.Range)range.Cells[row, 9]).Text;
rk.KodePos = ((Excel.Range)range.Cells[row, 10]).Text;
rk.LatitudeLongitudinal = ((Excel.Range)range.Cells[row, 11]).Text;
rk.KabupatenKota = ((Excel.Range)range.Cells[row, 12]).Text;
rk.ElectronicDevice = ((Excel.Range)range.Cells[row, 13]).Text;
rk.JaringanKantorBank = ((Excel.Range)range.Cells[row, 14]).Text;
rk.KategoriJaringanKantorBank = ((Excel.Range)range.Cells[row, 15]).Text;
rk.StatusPerkembanganAgen = ((Excel.Range)range.Cells[row, 16]).Text;
rk.Keterangan = ((Excel.Range)range.Cells[row, 17]).Text;
if (((Excel.Range)range.Cells[row, 18]).Value == null)
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", "Tolong periksa PERIODE Pada baris ke " + hitung + " Pada EXCEL File !");
return View("ImportDataAgens");
}
rk.Periode = ((Excel.Range)range.Cells[row, 18]).Value;
string valueA = System.Web.HttpContext.Current.User.Identity.Name;
rk.CreateBy = valueA;
rk.CreateDate = DateTime.Today;
if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", "The Number Of Agent Already Exist on " + hitung + " the Template EXCEL File !");
return View("ImportDataAgens");
}
if (ModelState.IsValid)
{
listTempRekn.Add(rk);
db.DMInformasiDataAgens.Add(rk);
db.SaveChanges();
var hitung = listTempRekn.Count;
//range.Rows.Count - 2;
TempData["AlertMessage"] = "Import Data Selesai " + hitung + " Records Sudah Tersimpan...";
}
}
return RedirectToAction("Index", "DataAgens");
}
else
{
ViewBag.Error = "File Type is incorrect <br>";
return View("ImportDataAgens");
}
}
}
Here the Code whe I check the already exist Value :
**if (db.DMInformasiDataAgens.Any(ac => ac.NomorIdentifikasiAgen.Equals((rk.NomorIdentifikasiAgen))))
{
int RowNo = row;
var hitung = listTempRekn.Count + 4;
ModelState.AddModelError("", " The Number Of Agent Already Exist on " + hitung + " the Template EXCEL File !");
return View("ImportDataAgens");
}**
How to create action if the value already exists (Number Of Agent) then my record update, if not then insert new record ?
var chkItem = x.firstOrDefault(your condition);
if(chkItem != null)
{
//update your record.
}
else{
//insert into database
}

Bad Request model derivative autodesk api when translating dwg to obj format

I want to use autodesk model derivative api to show DWG file in forge viewer. In
result = _client.Execute(objReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
{
}
I get badrequest.
public virtual ActionResult Index()
{
SetupViewer();
if (_bucketFound)
{
//upload file
RestRequest uploadReq = new RestRequest();
uploadReq.Resource = "oss/v2/buckets/"+_bucketName+"/objects/"+_filepath;
uploadReq.Method = Method.PUT;
uploadReq.AddHeader("Content-Type", _fileContentType);
uploadReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
var result= _client.Execute(uploadReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
String responseString = result.Content;
int len = responseString.Length;
int objectKeyIndex = responseString.IndexOf("\"objectKey\" : \"");
int index = responseString.IndexOf("urn:");
responseString = responseString.Substring(index, objectKeyIndex - index-5).Replace("urn:", "").Trim();
_fileUrn = "urn:"+responseString;
//convert urn to base64
string base64Urn = Base64Convertor.Base64Encode(_fileUrn);
// Remove ending '=' signs
// Use _ instead of /
// Use - insteaqd of +
base64Urn = base64Urn.Replace("=", "");
//translate to SVF format
//RestRequest svfReq = new RestRequest();
//svfReq.Resource = "modelderivative/v2/designdata/job";
//svfReq.Method = Method.POST;
//svfReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
//svfReq.AddParameter("Content-Type", "application/json;charset=utf-8", ParameterType.HttpHeader);
//string body = "{\"input\":{\"urn\":\"" + base64Urn + "\",\"compressedUrn\":true,\"rootFilename\":\""+_filepath+ "\"},\"output\":{\"formats\":[{\"type\":\"svf\",\"views\":[\"2d\"]}]}}";
//svfReq.AddParameter("application/json", body, ParameterType.RequestBody);
// translate to OBJ format
RestRequest objReq = new RestRequest();
objReq.Resource = "modelderivative/v2/designdata/job";
objReq.Method = Method.POST;
objReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
objReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
string body = "{\"input\":{\"urn\":\"" + base64Urn + "\"},\"output\":{\"formats\":[{\"type\":\"obj\"}]}}";
result = _client.Execute(objReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
{
//check the transition complete
RestRequest checkTransitionCompleteGetReq = new RestRequest();
checkTransitionCompleteGetReq.Resource = "modelderivative/v2/designdata/"+base64Urn+"/manifest";
checkTransitionCompleteGetReq.Method = Method.GET;
checkTransitionCompleteGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
var result2 = _client.Execute(checkTransitionCompleteGetReq);
if (result2.StatusCode == System.Net.HttpStatusCode.OK)
{
ViewBag.BucketFound = result.Content;
}
}
}
}
return View();
}
void SetupViewer()
{
// Authentication
bool authenticationDone = false;
RestRequest authReq = new RestRequest();
authReq.Resource = "authentication/v1/authenticate";
authReq.Method = Method.POST;
authReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
authReq.AddParameter("client_id", ConfigurationManager.AppSettings["ClientId"]);
authReq.AddParameter("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
authReq.AddParameter("grant_type", "client_credentials");
authReq.AddParameter("scope", "bucket:create bucket:read data:write data:read");
IRestResponse result = _client.Execute(authReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
String responseString = result.Content;
int len = responseString.Length;
int index = responseString.IndexOf("\"access_token\":\"") + "\"access_token\":\"".Length;
responseString = responseString.Substring(index, len - index - 1);
int index2 = responseString.IndexOf("\"");
_accessToken = responseString.Substring(0, index2);
//Set the token.
RestRequest setTokenReq = new RestRequest();
setTokenReq.Resource = "utility/v1/settoken";
setTokenReq.Method = Method.POST;
setTokenReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
setTokenReq.AddParameter("access-token", _accessToken);
IRestResponse resp = _client.Execute(setTokenReq);
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
authenticationDone = true;
}
}
if (!authenticationDone)
{
ViewData["Message"] = "View and Data client authentication failed !";
_accessToken = String.Empty;
return;
}
RestRequest bucketReq = new RestRequest();
bucketReq.Resource = "oss/v2/buckets";
bucketReq.Method = Method.POST;
bucketReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
bucketReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
//bucketname is the name of the bucket.
string body = "{\"bucketKey\":\"" + _bucketName + "\",\"policyKey\":\"transient\"}";
bucketReq.AddParameter("application/json", body, ParameterType.RequestBody);
result = _client.Execute(bucketReq);
if (result.StatusCode == System.Net.HttpStatusCode.Conflict ||
result.StatusCode == System.Net.HttpStatusCode.OK)
{
// _bucketFound = true;
//Check bucket
RestRequest bucketGetReq = new RestRequest();
bucketGetReq.Resource = "oss/v2/buckets";
bucketGetReq.Method = Method.GET;
bucketGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
bucketGetReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
result = _client.Execute(bucketGetReq);
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
_bucketFound = true;
ViewBag.BucketFound = "Found";
}
else
ViewBag.BucketFound = "NotFound";
}
else
{
ViewData["Message"] = "View and Data bucket could not be accessed !";
_bucketFound = false;
return;
}
}
Could you try this again, we had some down time from our side during that time, but everything should be back up and running for you. In case does not work I will take a look at your request.

through exception in mvc on send email

I want to send email from an excel file.
When It get wrong email address it stop sending.
I want it send all email and at last show me wrong email that isn't able to send.
This my code for read Excel file:
if (!string.IsNullOrWhiteSpace(excel))
{
var src = excel;
DataSet ds = new DataSet();
string fileExtension = System.IO.Path.GetExtension(Server.MapPath("~/") + src);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/") + src;
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/") + src;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
And this is code for send email:
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string excelname = "";
if (lang == "1")
{
excelname = "<div style='text-align:right;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
else
{
excelname = "<div style='text-align:left;'>" + ds.Tables[0].Rows[i][0].ToString() + "<br/>" + ds.Tables[0].Rows[i][1].ToString() + "</div>";
}
exceltotal = excelname + text + newslink + attach;
//sender
message = string.Format(body, img, exceltotal, title, prehead, senderemail);
MailMessage email = new MailMessage();
email.To.Add(ds.Tables[0].Rows[i][2].ToString());
email.From = new MailAddress(senderemail);
email.Subject = maintitle;
email.Body = message + makedelivey(ds.Tables[0].Rows[i][2].ToString(), maintitle);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.IsBodyHtml = true;
SmtpClient ssmtp = new SmtpClient();
ssmtp.Host = server;
ssmtp.Port = port;
ssmtp.UseDefaultCredentials = false;
ssmtp.Credentials = new System.Net.NetworkCredential(senderemail, senderpassword);
ssmtp.EnableSsl = false;
ssmtp.Send(email);
exceltotal = "";
message = "";
}
It read a text file and add some value from excel or database base on user selection.
I couldn't find line of code which sends email. But wherever you are sending the email inside the loop, make sure you enclose that code in try catch block. This ensures even if a mail send operation is failed, the error is handled and goes on with other mails. You can include your consolidate and formatting of failures issues in catch block.
var consolidateErrors = string.Empty;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Try
{
//Mail sending logic here
}
Catch(Exception ex)
{
consolidateErrors += YourErrorDetails;
}
}

Resources