I'm trying to check whether numbers are valid using the code below. Will this work?
try
{
TwilioRest.Account account = new TwilioRest.Account(TwilioRest.TwilioConstants.ACCOUNT_SID, TwilioRest.TwilioConstants.ACCOUNT_TOKEN);
string strResponse = account.request(String.Format("/{0}/Accounts/{1}/OutgoingCallerIds", TwilioRest.TwilioConstants.API_VERSION, TwilioRest.TwilioConstants.ACCOUNT_SID), "GET");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
XmlNode root = xmlDoc.DocumentElement.ChildNodes[0];
int cont = 0;
if (root.ChildNodes.Count > 0)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
string ss = root.ChildNodes[i].SelectSingleNode("PhoneNumber").ChildNodes[0].Value;
if (phoneno.Trim() == ss)
{
cont = 1;
break;
}
}
}
if (cont == 0)
{
btnSubmit.Visible = true;
}
}
catch (TwilioRest.TwilioRestException ex)
{
mpValidatePhone.Show();
ucMsgPhone.MessageType = MessageType.Error;
ucMsgPhone.Text = TwilioErrorMessage(ex.ToString());
}
try like this....
string strResponse = account.request(String.Format("/{0}/Accounts/{1}/OutgoingCallerIds",
TwilioRest.TiwlioConstants.API_VERSION, TwilioRest.TiwlioConstants.ACCOUNT_SID), "GET");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
XmlNode root = xmlDoc.DocumentElement.ChildNodes[0];
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes[0])
{
string nodeVal = node.SelectSingleNode("PhoneNumber").ChildNodes[0].Value.ToString();
string fonVal = foneCountryCode + PhoneNumber.Replace("-", "");
//if (node.SelectSingleNode("PhoneNumber").ChildNodes[0].Value == "+" + PhoneNumber.Replace("-", ""))
if(nodeVal == fonVal)
{
result = true;
break;
}
}
Related
I have this ASP.NET project working with Oracle, I have the following code for operating the DB:
public int cmd_Execute_Orcl(string strSql, params OracleParameter[] paramArray)
{
OracleCommand myCmd = new OracleCommand();
try
{
myCmd.Connection = myOrclConn;
myCmd.CommandText = strSql;
foreach (OracleParameter temp in paramArray)
{
myCmd.Parameters.Add(temp);
}
ConnectionManage(true);
int i = myCmd.ExecuteNonQuery();
myCmd.Parameters.Clear();
return i;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
myCmd.Dispose();
ConnectionManage(false);
}
}
"ConnectionManage()" turns on or off the connection, the following code is from data access layer of the program:
public string Edit_DAL(string id, string jh, string jz, string jd, string wd, string gzwz, string qxlx, string sx, string jx, string jb, string cfdd, string zjqssj, string zjzzsj, string bz)
{
string sql = "update JH set jh = :jh, jz = :jz, wd = :wd, jd = :jd, gzwz = :gzwz, qxlx = :qxlx, sx = :sx, jx = :jx, jb = :jb, cfdd = :cfdd, zjqssj = TO_DATE(:zjqssj, 'yyyy-mm-dd hh24:mi:ss'), zjzzsj = TO_DATE(:zjzzsj, 'yyyy-mm-dd hh24:mi:ss'), bz = :bz where ID = :idy";
string result = null;
{
String[] temp1 = zjqssj.Split('/');
String[] temp2 = zjzzsj.Split('/');
string tempString = "";
if (temp1[2].Length < 2)
{
temp1[2] = temp1[2].Insert(0, "0");
}
for (int i = 0; i < temp1.Length; i++)
{
if (i != 0)
{
temp1[i] = temp1[i].Insert(0, "/");
}
tempString += temp1[i].ToString();
}
zjqssj = tempString;
tempString = "";
if (temp2[2].Length < 2)
{
temp2[2] = temp2[2].Insert(0, "0");
}
for (int i = 0; i < temp2.Length; i++)
{
if (i != 0)
{
temp2[i] = temp2[i].Insert(0, "/");
}
tempString += temp2[i].ToString();
}
zjzzsj = tempString;
tempString = "";
}
OracleParameter[] pars ={
new OracleParameter(":idy",id),
new OracleParameter(":jh",jh),
new OracleParameter(":jz",jz),
new OracleParameter(":jd",jd),
new OracleParameter(":wd",wd),
new OracleParameter(":gzwz",gzwz),
new OracleParameter(":qxlx",qxlx),
new OracleParameter(":sx",sx),
new OracleParameter(":jx",jx),
new OracleParameter(":jb",jb),
new OracleParameter(":cfdd",cfdd),
new OracleParameter(":zjqssj",(zjqssj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":zjzzsj",(zjzzsj.Replace('/', '-') + " 00:00:00")),
new OracleParameter(":bz",bz)
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
result = "ok";
}
catch (Exception ex)
{
result = "no" + "=" + ex.Message + "\n" + ex.StackTrace;
}
return result;
}
Here's where the strange thing happens, when I hit this part of the code, there's no exception, it returns 0, no rows affected, all the values of the parameters are normal, with expected value, then I tried to run the command in PL/SQL and it works, the row is correctly updated, delete function is also referencing the same "cmd_Execute_Orcl" method and it works just fine, and for the other object the edit function is working perfectly, I am posting the code below:
public string Edit(string OriginalId, string EditUserAccount, string EditUserName, string EditUserMobile, string EditDeptId, string EditRoleId, string EditRoleName)
{
string sql = "update AuthUser set UserAccount=:EditUserAccount, UserName=:EditUserName, UserMobile=:EditUserMobile, DepartmentId=:EditDeptId, RID=:EditRoleId, RoleName=:EditRoleName where ID=:OriginalId";
OracleParameter[] pars ={
new OracleParameter(":EditUserAccount",EditUserAccount),
new OracleParameter(":EditUserName",EditUserName),
new OracleParameter(":EditUserMobile",EditUserMobile),
new OracleParameter(":EditDeptId",EditDeptId),
new OracleParameter(":EditRoleId",EditRoleId),
new OracleParameter(":EditRoleName",EditRoleName),
new OracleParameter(":OriginalId",OriginalId),
};
try
{
SqlHelper.cmd_Execute_Orcl(sql, pars);
return "ok";
}
catch (Exception ex)
{
string test = ex.Message;
return "no";
}
}
In the expected table, column ID is nvarchar2 with default value of sys_guid(), column ZJQSSJ and column ZJZZSJ is of type date, all other columns are of type varchar2, I have also tried executing "COMMIT" and reformating data for date, but the same problem is still there, plz help...
In my application i want to open gmail attachment with my application, i used intent filter for that,
I am getting URI and i want to use that and copy that attachment to my local device and want to display that with my application .
url = {content://com.google.android.gm.sapi/abc#gmail.com/message_attachment_external/%23thread-f%3A1610966348228029097/%23msg-f%3A1610966348228029097/0.1?account_type=com.google&mimeType=application%2Foctet-stream&rendition=1}
After a days of research and implementation, Here is a final solution for gmail attachment file , to view and down load in our application.
[IntentFilter(new string[] { Intent.ActionView }, Categories = new string[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataScheme = "content", DataMimeType = "application/octet-stream")]
Stream inputsTream = resolver.OpenInputStream(url);
fs = File.Create(fileName);
byte[] buffer = new byte[32768];
int count;
int offset = 0;
while ((count = inputsTream.Read(buffer, offset, buffer.Length)) > 0)
{
fs.Write(buffer, 0, count);
}
fs.Close();
inputsTream.Close();
private fun deepLinkAcceptor(){
var ins: InputStream? = null
var os: FileOutputStream? = null
var fullPath: String? = null
var file: File;
try {
val action = intent.action
if (Intent.ACTION_VIEW != action) {
return
}
val uri = intent.data
val scheme = uri!!.scheme
var name: String? = null
if (scheme == "content") {
val cursor = contentResolver.query(
uri!!, arrayOf(
MediaStore.MediaColumns.DISPLAY_NAME
), null, null, null
)
cursor!!.moveToFirst()
val nameIndex = cursor!!.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
if (nameIndex >= 0) {
name = cursor!!.getString(nameIndex)
}
} else {
return
}
if (name == null) {
return
}
val n = name.lastIndexOf(".")
val fileName: String
val fileExt: String
if (n == -1) {
return
} else {
fileName = name.substring(0, n)
fileExt = name.substring(n)
}
// create full path to where the file is to go, including name/ext
fullPath = ""
val filenm = fileName + fileExt
file = File(cacheDir, filenm)
ins = contentResolver.openInputStream(uri!!)
os = FileOutputStream(file.getPath())
val buffer = ByteArray(4096)
var count: Int
while (ins!!.read(buffer).also { count = it } > 0) {
os!!.write(buffer, 0, count)
}
os!!.close()
ins!!.close()
println("===onfile path: " + file.getAbsolutePath())
println("===onFile name: " + file.readText())
} catch (e: Exception) {
if (ins != null) {
try {
ins.close()
} catch (e1: Exception) {
}
}
if (os != null) {
try {
os.close()
} catch (e1: Exception) {
}
}
if (fullPath != null) {
val f = File(fullPath)
f.delete()
}
}
}
PaymentService.PaymentServiceClient client = new
PaymentService.PaymentServiceClient();
PaymentTransactionDto model = new PaymentTransactionDto();
OrderInvoiceDto invoiceData;
List<ProductRepoDto> products;
List<OrderTaxDto> taxes;
// Check payment status
int chkProduct = 0;
int chkCourse = 0;
int chkProductCourse = 0;
#region Get order details for invoice
var order_details = client.GetOrderDetailsForInvoice(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
invoiceData = new OrderInvoiceDto();
if (order_details != null)
{
invoiceData = AutoMapConverter<PaymentService.OrderInvoiceDto, OrderInvoiceDto>.GetMappedData(order_details);
}
#endregion
#region Get Products list in order
var productList = client.GetOrderItemsByOrderId(Convert.ToInt32(Oid.Rows[0]["OrderId"]));
products = new List<ProductRepoDto>();
if (productList != null && productList.Count() > 0)
{
products = AutoMapConverter<PaymentService.ProductRepoDto, ProductRepoDto>.GetMappedList(productList.ToList());
}
#endregion
#region ADD Taxes
#region check product type
decimal Amount = 0;
foreach (var item in products)
{
if (item.TypeId == 1)
chkCourse = 1;
if (item.TypeId == 2)
chkProduct = 1;
if (chkCourse == 1 && chkProduct == 1)
chkProductCourse = 1;
Amount = Amount + (item.Amount * item.Quantity);
Amount = Amount - item.Discount;
}
#endregion
// Apply taxes
client.AddOrderTaxMappingDetails(Convert.ToInt64(orderid), Amount);
#endregion
#region Get Applied Tax details
var taxesApplied = client.GetOrderAppliedTaxes(Convert.ToInt64(orderid));
taxes = new List<OrderTaxDto>();
if (taxesApplied != null && taxesApplied.Count() > 0)
{
taxes = AutoMapConverter<PaymentService.OrderTaxDto, OrderTaxDto>.GetMappedList(taxesApplied.ToList());
}
#endregion
string pdfbody = System.IO.File.ReadAllText(Server.MapPath("~/Views/Payment/InvoiceView.cshtml"));
Document document = new Document();
string fileName = string.Format("{0}.pdf", invoiceData.OrderNumber);
var fpath = HttpContext.Current.Server.MapPath("~/Document/Payment/Invoice/");
if (!Directory.Exists(fpath))
{
Directory.CreateDirectory(fpath);
}
pdfbody = pdfbody.Replace("$name$", string.Format("{0} {1}", invoiceData.Billing_FirstName, invoiceData.Billing_LastName));
pdfbody = pdfbody.Replace("$address$", invoiceData.Billing_Address);
pdfbody = pdfbody.Replace("$billingCity$", invoiceData.Billing_City);
pdfbody = pdfbody.Replace("$billingPinCode$", invoiceData.Billing_PinCode.ToString());
pdfbody = pdfbody.Replace("$billingState$", invoiceData.Billing_State);
pdfbody = pdfbody.Replace("$billingCountry$", invoiceData.Billing_Country);
//pdfbody = pdfbody.Replace("$netAmt$", invoiceData.NetAmt.ToString());
//pdfbody = pdfbody.Replace("$grossAmt$", invoiceData.GrossAmt.ToString());
//pdfbody = pdfbody.Replace("$discountAmt$", invoiceData.DiscountAmt.ToString());
pdfbody = pdfbody.Replace("$orderNumber$", invoiceData.OrderNumber.Remove(0, 2));
pdfbody = pdfbody.Replace("$orderDate$", CommonFunctions.EpochToIstDate(Convert.ToDouble(invoiceData.OrderDate)));
StringBuilder b = new StringBuilder();
decimal totalAmount = 0;
foreach (var item in products)
{
if (!string.IsNullOrEmpty(item.ActivationKey))
item.ActivationKey = string.Format("Activation Key:{0}", item.ActivationKey);
b.AppendFormat("<tr><td width='60%'>{0}<br/>{1}</td>", item.ProductName, item.ActivationKey);
b.AppendFormat("<td width='10%' align='left'>{0}</td>", item.Quantity);
b.AppendFormat("<td width='30%' align='right'>{0}</td></tr>", (item.Amount * item.Quantity) - item.Discount);
totalAmount = totalAmount + (item.Amount * item.Quantity);
totalAmount = totalAmount - item.Discount;
}
pdfbody = pdfbody.Replace("$OrderDetailsList$", Convert.ToString(b));
if (taxes != null && taxes.Count > 0)
{
b = new StringBuilder();
foreach (var item in taxes)
{
b.AppendFormat("<tr><td width='80%' colspan='2'>{0} ({1}%)</td>", item.TaxName, item.Percentage);
b.AppendFormat("<td width='20%' align='right'>{0}</td></tr>", item.Amount);
}
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", Convert.ToString(b));
}
else
{
pdfbody = pdfbody.Replace("$OrderTaxDetailsList$", "");
}
pdfbody = pdfbody.Replace("$netAmt$", totalAmount.ToString());
pdfbody = pdfbody.Replace("$rupees$", CommonFunctions.ConvertNumbertoWords(Convert.ToInt32((int)Math.Ceiling(totalAmount))));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fpath + fileName, FileMode.Create));
document.Open();
StringReader sr = new StringReader(pdfbody);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
document.Close();
I want to generate pdf invoice.so i am using itextsharp.
but i am getting Index out of bound array at XMLWorkerHelper.
I am using itextsharp.xmlworker.dll, v5.4.5.0
when i try to update itextsharp.xmlworker.dll, v5.4.5.9
this code works fine..but all other modules of my project which use iTextsharp starts getting error.
if this is version problem, then how i add two different dll in bin folder and use it
or it is code related error?
Ok so I am trying to load a CSVStream into an ExcelPackage (I am using EPPlus).
It always fails at line 221482, no matter what option I choose. I am running on x64 and I have in my app.config...
The error given is the one from the title :(
public ExcelPackage ExcelPackageFromCsvStream(Stream csvStream)
{
var excelPackage = new ExcelPackage();
var workSheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] { eDataTypes.String }
};
using (var sr = new StreamReader(csvStream))
{
int i = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
workSheet.Cells["A" + i].LoadFromText(line, csvFormat);
i++;
}
}
return excelPackage;
}
Resolved it by creating multiple ExcelPackages and also I've read the stream in batches (e.g. 200k lines at once)
public List<ExcelPackage> ExcelPackagesFromCsvStream(Stream csvStream, int batchSize)
{
var excelPackages = new List<ExcelPackage>();
int currentPackage = -1; // so that first package will have the index 0
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] {eDataTypes.String}
};
using (var sr = new StreamReader(csvStream))
{
int index = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
if ((index - 1) % batchSize == 0)
{
var excelPackage = new ExcelPackage();
excelPackage.Workbook.Worksheets.Add("Sheet1");
excelPackages.Add(excelPackage);
currentPackage++;
index = 1;
}
excelPackages[currentPackage].Workbook.Worksheets.First().Cells["A" + index].LoadFromText(line, csvFormat);
index++;
}
}
return excelPackages;
}
I basically need to save the output of the stored procedure to a .xls or .xlsx Excel file. I am able to do it to a csv but not to Excel. Can someone help? Please see the code below
var result = DealingContext.PopulateUnitRebateData(true, Convert.ToDateTime("2015-01-16")).ToList();
if (result.Count > 0)
{
string header = #"""Firm ID"",""AccountNumber"",""Portfolio Name"",""Currency"",""Amount"",""Value Date""";
StringBuilder sb = new StringBuilder();
sb.AppendLine(header);
foreach (var i in result)
{
sb.AppendLine(string.Join(",",
string.Format(#"""{0}""", i.FirmID),
string.Format(#"""{0}""", i.AccountNumber),
string.Format(#"""{0}""", i.PortfolioName),
string.Format(#"""{0}""", i.Currency),
string.Format(#"""{0}""", i.Amount),
string.Format(#"""{0}""", i.ValueDate)));
}
HttpContext context = HttpContext.Current;
context.Response.Write(sb.ToString());
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment; filename=TestData.xls");
context.Response.End();
}
The reason you cant save it to excel is because excel is formatted differently than csv.
The best (and easiest) library I have used for saving data to excel is LinqToExcel https://code.google.com/p/linqtoexcel/
Nuget
PM> Install-Package LinqToExcel
you can try to export Data to Excel using Microsoft.Office.Interop.Excel
Pass the DataSet,which has atleast one DataTable and valid fileName with Path.
public void WriteToExcel(DataSet dataSet , string fileNameWithPath)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
try
{
string data = string.Empty;
//Setting up Columns on Excel
for (int i = 0; i < 1; i++)
{
for (int j = 0; j <= dataSet.Tables[0].Columns.Count - 1; j++)
{
data = dataSet.Tables[0].Columns[j].ColumnName.ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
//data Insertion
for (int i = 0; i <= dataSet.Tables[0].Rows.Count - 1; i++)
{
for (int j = 0; j <= dataSet.Tables[0].Columns.Count - 1; j++)
{
xlWorkSheet.Cells[i + 2, j + 1].NumberFormat = "#"; //format as text
data = result.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
Excel.Range range = xlWorkSheet.Range[xlWorkSheet.Cells[1, 1], xlWorkSheet.Cells[1, result.Tables[0].Columns.Count]];
range.Font.Bold = true;
range.Interior.ColorIndex = 15;
range.EntireColumn.AutoFit();
xlWorkSheet.PageSetup.LeftMargin = 0.5;
xlWorkSheet.PageSetup.RightMargin = 0.5;
xlWorkSheet.PageSetup.Zoom = false;
xlWorkSheet.PageSetup.FitToPagesWide = 1;
xlWorkSheet.PageSetup.FitToPagesTall = Math.Ceiling((result.Tables[0].Rows.Count + 1) / 50.0);
xlWorkSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;
xlWorkSheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperLetter;
xlWorkBook.SaveAsfileNameWithPathExcel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
catch (Exception ex)
{
}
finally
{
xlWorkSheet = null;
xlWorkBook = null;
if (xlApp != null)
{
xlApp.Quit();
}
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}