DateTime Not working in Global.asax in c# - asp.net

I am trying to use DateTime in global.asax to give a name to a file but it gives an error. Could you please assist?
The code I am using for the DateTime;
public void callFileCreate()
{
string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string filename = HttpContext.Current.Server.MapPath(path + "\\Log_" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
TraceFilePath = HttpContext.Current.Server.MapPath(path + "\\Scheduler" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
FileStream fs = null, fs1 = null;
fs = File.Create(filename);
fs1 = File.Create(TraceFilePath);
ErrorFilePath = filename;
}

You should use the Path class if you work with paths:
string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string fileName = string.Format("{0}_{1}_{2}.txt"
, "Log"
, DateTime.Today.ToString("dd.MM.yyyy") // change according to your actual culture
, DateTime.Now.ToString("HH_mm_ss"));
string fullPath = Path.Combine(path, fileName);
Not sure if that solves your issue, but it increases readability and avoids careless mistakes anyway.

You don't write what error you get. But here are some hints about how you can simplify your code:
var dir = HttpContext.Current.Server.MapPath(
ConfigurationManager.AppSettings["LogFileFolder"].ToString());
var dt = DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss");
var logFilePath = Path.Combine(dir, string.Format("Log_{0}.txt", dt));
var traceFilePath = Path.Combine(dir, string.Format("Scheduler_{0}.txt", dt));
var fs = File.Create(logFilePath);
var fs1 = File.Create(traceFilePath);
Notes:
if the app-settings entry LogFileFolder already contains an (absolute) filesystem-path such as c:\temp, then you shouldn't call Server.MapPath().
you should call fs.Close() once you no longer need the streams (or put it in a using block). Otherwise, another attempt to create the (same) file will result in an exception.

Related

Write to Spreadsheet in Google sheet from ASP.NET

I have a code, it should write in the Spreadsheet of google sheet. When I run the function, I receive this error:
Message[Requested writing within range ['6/12/2019-20:37'!A1], but
tried writing to column [B]] Location[ - ] Reason[badRequest]
Domain[global]
That its my code:
private void SheetPattern(Item webinar)
{
var valueRange = new ValueRange();
var range = $"{sheet}!A:D";
DateTime dateTime=(DateTime)webinar.webInfo.times[0].startTime;
var date = dateTime.Day+"-"+dateTime.Month+"-"+dateTime.Year;
var hour = dateTime.Hour + ":" + dateTime.Minute;
var webName = webinar.webInfo.subject;
var webDescription = webinar.webInfo.description;
var oblist = new List<object>() { date, hour, webName, webDescription};
valueRange.Values = new List<IList<object>> { oblist };
var appendRequest = service.Spreadsheets.Values.Append(valueRange, SpreadsheetId, range);
Console.WriteLine(appendRequest);
appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
var appendReponse = appendRequest.Execute();
}
I found the problem its a Syntax problem, here:
var hour = dateTime.Hour + ":" + dateTime.Minute;
when I make a new sheet with a new name, google sheet doesn't permit the char : in the sheet name. So I change this code for that code:
var hour = dateTime.Hour + "-" + dateTime.Minute;

Convert string start with 0 to 2 decimal place asp.net?

I have this string:
Dim value as String = "0.11209176170341301"
And tried to use this code to convert the string into decimal with two places:
Dim value as String = "0.11209176170341301"
Dim valueInDecimal As Decimal
If [Decimal].TryParse(value, valueInDecimal) Then
Console.WriteLine(valueInDecimal.ToString("0:0.#"))
End If
I get this result:
11209176170341301D
I need to get this:
0.11
What I'm doing wrong?
I want to get as result a decimal with two placesfrom the string value
You can use basic string operations also:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
decimal d = decimal.Parse(truncatedValue);
string s = d.ToString();
Console.Write(s);
Console.Read();
If you are only needed it as string then you can just truncate it as string then it will be easier like:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
Console.Write(truncatedValue);
Or even you do not convert '.' to ',' then it will be like this:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = string.Join(".",parts[0],floatingPart);
Console.Write(truncatedValue);
Use Math.Round function
var x = "0.11209176170341301";
Console.Write(Math.Round(Convert.ToDecimal(x), 2));

How i can current date Outputfilename Data Extract Arcgis Flex

outputFileName = (configXML.outputfilename[0] || "Dataextracted") + ".zip";
outputFileName = outputFileName.replace(/(\\|\/|:|\?|"|<|>|\|)/g, "");
"Dataextracted" change current date time
replace "Dataextracted" with
new Date()
To format it:
var df:spark.formatters.DateTimeFormatter = new DateTimeFormatter();
df.dateTimePattern = "yyyy-MMM-dd-HHmmss";
trace(df.format(new Date())); //output 2016-Oct-13-095823

How to get a variable replaced with a field name in a LINQ?

string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;
Is there any way to replace the q.CompanyName part of the query with a string variable
so that the field used for filtering be a parametric?
I tried
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q;
Didn't work.
Been trying to let the user choose the columns for the query.
Read more about both below option at : Dynamic query with Linq
you can use one of this
Use Dynamic LINQ library
Example for the the blog below
string strWhere = string.Empty;
string strOrderBy = string.Empty;
if (!string.IsNullOrEmpty(txtAddress.Text))
strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";
if (!string.IsNullOrEmpty(txtEmpId.Text))
{
if(!string.IsNullOrEmpty(strWhere ))
strWhere = " And ";
strWhere = "Id = " + txtEmpId.Text;
}
if (!string.IsNullOrEmpty(txtDesc.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
}
if (!string.IsNullOrEmpty(txtName.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
}
EmployeeDataContext edb = new EmployeeDataContext();
var emp = edb.Employees.Where(strWhere);
Predicate Builder
EXample
var predicate = PredicateBuilder.True<employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
Expression.Equal(
Expression.Property(param, str1),
Expression.Constant(companySize)),
param);
var query = context.Company.Where(exp);
I think the best way to do this is with built in libraries (and PropertyDescriptor type).
using System.ComponentModel;
void Main()
{
Test test = new Test();
test.CompanyName = "ABC";
object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
.Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();
Console.WriteLine(z.ToString());
}
public class Test
{
public string CompanyName { get; set; }
}

GridView to Excel using EPPlus

I'm trying to create an excel sheet using the EPPlus's library.
However, the output excel file does not relate well to cells of representing numbers.
The code I'm using is:
using (var pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(string.IsNullOrEmpty(SpreadsheetName) ? "Report" : SpreadsheetName);
ws.Cells["B2"].LoadFromDataTable(gridViewTable, true, OfficeOpenXml.Table.TableStyles.Light1);
for (int i = 1; i <= gridViewTable.Columns.Count; i++)
{
ws.Column(i).AutoFit();
}
// **************
// HEADER
// **************
//prepare the range for the column headers
string cellRange = "B2:" + Convert.ToChar('B' + gridViewTable.Columns.Count - 1) + 2;
//Format the header for columns
using (ExcelRange rng = ws.Cells[cellRange])
{
rng.Style.WrapText = false;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#007A99"));
rng.Style.Font.Color.SetColor(Color.White);
}
// ************
// DATA
// ************
//prepare the range for the rows
string rowsCellRange = "B3:" + Convert.ToChar('B' + gridViewTable.Columns.Count - 1) + (gridViewTable.Rows.Count + 1);
//Format the rows
using (ExcelRange rng = ws.Cells[rowsCellRange])
{
rng.Style.WrapText = false;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#B2D1F0"));
rng.Style.Font.Color.SetColor(Color.Black);
}
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + (string.IsNullOrEmpty(FileName) ? "Report" : FileName) + ".xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Does anyone might know why is this happening ?
I got it.
If you use the LoadFromDataTable() method, the DataTable object should be typed in its columns, meaning that you should create the columns using
table.Columns.Add(columnName, columnType);

Resources