Trying to fix this error as I mentioned in title but cant figure it out. I am not comparing anything why I get this I don't know. I tried to change strings to float but no success. Maybe I should change StringTools but not sure what use instead of that.
package com.bykd.output;
#:final class DateOutput
{
public static inline var HOUR : String = "%h";
public static inline var MONTH : String = "%m";
public static inline var SECOND : String = "%s";
public static inline var MINUTE : String = "%i";
public static inline var DAY : String = "%d";
public static inline var YEAR : String = "%y";
public function new()
{
//super();
}
public static function formatDate(date : Date, format : String) : String
{
var output : String = null;
output = format;
output = StringTools.replace(output, DAY, leadZero(date.getDay));
output = StringTools.replace(output, MONTH, leadZero(date.getMonth));
output = StringTools.replace(output, YEAR, date.getFullYear);
return output;
}
public static function formatTime(date : Date, format : String) : String
{
var output : String = null;
output = format;
output = StringTools.replace(output, HOUR, leadZero(date.getHours));
output = StringTools.replace(output, MINUTE, leadZero(date.getMinutes));
output = StringTools.replace(output, SECOND, leadZero(date.getSeconds));
return output;
}
public static function leadZero(num : Float) : String
{
return Std.string("00" + num).substr(-2, 2);
}
}
Related
My View consists of multiple tables, and I am looking to Export multiple tables from View in Excel file. My current function only helps me to export 1 table.
Can any one help me to complete this code so that multiple tables can be exported?
Report VM
public class ReportVM
{
public string ScenName { get; set; }
public int Count { get; set; }
public string CreateTickYes { get; set; }
public int TickYes { get; set; }
public string RegionName { get; set; }
public int RegionCount { get; set; }
public string UserName { get; set; }
public int ChatCountUser { get; set; }
}
Action Method to export
public FileContentResult DownloadReport(DateTime start, DateTime end)
{
//var uName = User.Identity.Name;
var fileDownloadName = String.Format("Report.xlsx");
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// Pass your ef data to method
ExcelPackage package = GenerateExcelFile(db.Chats.Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) >= start && System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) <= end)
.GroupBy(a => a.ScenarioList).Select(b => new ReportVM()
{
ScenName = b.Key,
Count = b.Count()
}).ToList());
var fsr = new FileContentResult(package.GetAsByteArray(), contentType);
fsr.FileDownloadName = fileDownloadName;
return fsr;
}
private static ExcelPackage GenerateExcelFile(IEnumerable<ReportVM> datasource)
{
ExcelPackage pck = new ExcelPackage();
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1");
// Sets Headers
ws.Cells[1, 1].Value = "Scenario";
ws.Cells[1, 2].Value = "No.Of Chats";
// Inserts Data
for (int i = 0; i < datasource.Count(); i++)
{
ws.Cells[i + 2, 1].Value = datasource.ElementAt(i).ScenName;
ws.Cells[i + 2, 2].Value = datasource.ElementAt(i).Count;
}
//Sheet2
// Format Header of Table
using (ExcelRange rng = ws.Cells["A1:B1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Gold); //Set color to DarkGray
rng.Style.Font.Color.SetColor(Color.Black);
}
return pck;
}
So, now it export data for Table GroubBy = ScenarioList. I want to also include another column in groupBy = Username. So when Export data, Excel file should contain 2 Sheets. 1 for Table ScenarioList, and 2nd for Table Username.
Help is much appreciated. Thank you in advance.
You need create div/table under which put all tables and then by using below javascript function. Please call this javascript function on button click on same page which have all data. This is working for me which I already used in my project.
function DownloadToExcel() {
var htmls = $("#compareBodyContent")[0].innerHTML; // this main element under which
//all you data
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
};
var ctx = {
worksheet: 'Worksheet',
table: '<table>' + htmls + '</table>'
}
var compareLink = document.createElement("a");
compareLink.download = "Compare_Test.xls";
compareLink.href = uri + base64(format(template, ctx));
compareLink.click();
}
Hope this will help you. Let me know if you have any question on this.
I have the codeblock like this and I am trying to get rid of the Float should be Int and Missing Return errors.
package com.bykd.dev;
#:final class Version
{
public static inline var SPLIT_CHAR : String = ".";
public static var revisionKeyword : String = "Revision";
private var _tag : String;
private var _numbers : Array<Dynamic>;
public static function create(pfx : String, rev : String = null, sfx : String = null) : Version
{
var nums : Array<Dynamic> = null;
nums = pfx.split(SPLIT_CHAR);
if (rev != null)
{
nums.push(trimRevision(rev));
}
return new Version(nums, sfx);
private static function trimRevision(rev : String) : String
{
var beg : Float = Math.NaN;
var end : Float = Math.NaN;
beg = Std.string("$" + revisionKeyword + ": ").length;
end = rev.lastIndexOf(" $");
return rev.substring(beg, end);
}
}
Errors are in the last lines :
end = rev.lastIndexOf(" $");
return rev.substring(beg, end);
Any help would be highly appreciated.
Why use Float?
var beg : Int = 0;
var end : Int = 0;
Also avoid Dynamic when possible
var nums : Array<String> = null;
nums = pfx.split(SPLIT_CHAR);
Please could you help me here? I need to understand how to convert a String into an Int, Float or Double! This problem occurs when I'm trying to get the value from an UITextField and need this type of conversion!
I used to do it like this:
var myValue : Float = myTextField.text.bridgeToObjectiveC().floatValue
but since Xcode 6 beta 6 it doesn't seem to work anymore!
I've tried also like this:
var str = "3.14"
// Conversion from StringValue to an Int
var intValue : Int = str.toInt()!
// Other converstion from StringValue to an Int
var intOtherValue : Int = Int(str)
// Converstion from StringValue to a Float
var floatValue : Float = str.bridgeToObjectiveC().floatValue
// Converstion from StringValue to a Double
var doubleValue : Double = Double(str)
Please help me or tell me where I can find the answer! Many thanks!
Convert String to NSString and Use convenience methods:
var str = "3.1"
To Int
var intValue : Int = NSString(string: str).integerValue // 3
To Float
var floatValue : Float = NSString(string: str).floatValue // 3.09999990463257
To Double
var doubleValue : Double = NSString(string: str).doubleValue // 3.1
Reference
var doubleValue: Double { get }
var floatValue: Float { get }
var intValue: Int32 { get }
#availability(OSX, introduced=10.5)
var integerValue: Int { get }
#availability(OSX, introduced=10.5)
var longLongValue: Int64 { get }
#availability(OSX, introduced=10.5)
Use:
Int(string:String)
Double(string:String)
Float(string:String)
Which return an optional which is nil if it fails to parse the string.
For example:
var num = 0.0
if let unwrappedNum = Double("5.0") {
num = unwrappedNum
} else {
print("Error converting to Double")
}
Of course you can force unwrap if you are sure:
var foo = Double("5.0")!
Extending String
If you are doing this in more than a few places, and want error handling to be handled the same everywhere then you may want to extend String with conversion methods:
For example:
extension String {
func toDouble() -> Double {
if let unwrappedNum = Double(self) {
return unwrappedNum
} else {
// Handle a bad number
print("Error converting \"" + self + "\" to Double")
return 0.0
}
}
}
and then to use it:
let str = "4.9"
var num = str.toDouble()
public extension String {
public func toFloat() -> Float? {
return Float.init(self)
}
public func toDouble() -> Double? {
return Double.init(self)
}
}
var holdTextFieldToStringValue = myTextField.text
//convert from string to Int
var holdIntValue = holdTextFieldToStringValue.toInt()!
//convert from string to Double
var holdDoubleValue = Double((holdTextFieldToStringValue as NSString).doubleValue)
let strValue = "14.03"
let result = (strValue as NSString).floatValue
I have a studentDto. I want to determine the number
of characters for LastName. If number of characters is greater
than 8, I want to return the last name of 8 characters with two asterisk thus
cutting off the other characters
e.g Abumadem**
Here is how I started.I am unable to get it to work. Can you please assist?
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
int count=0;
List<char> storeStrings = new List<char>();
if (checkLength > 8)
{
foreach (var c in LastName)
{
storeStrings.Add(c);
if ()
{
}
count++;
}
}
}
}
}
Here is new attempt and no luck yet.
public class StudentDto
{
public string Firstname { get; set; }
public string EmailAddress { get; set; }
public string LastName
{
get
{
var checkLength = LastName.Length;
string First8Chars = string.Empty;
if (checkLength > 8)
{
First8Chars = LastName.Substring(0, 7) + "**";
return First8Chars;
}
}
set { }
}
}
Just do it like this:
string _backingFieldLastName;
public string LastName
{
get
{
return _backingFieldLastName == null || backingFieldLastName.Length <=8 ?
_backingFieldLastName :
_backingFieldLastName.Substring(0,8) +"**"; // second parameter of substring is count of chars from the start index (first parameter)
}
set
{
_backingFieldLastName = value;
}
}
If you cant use library functions for some reason:
private string _lastName = "";
public string LastName
{
get
{
var checkLength = _lastName.Length;
string First8Chars = string.Empty;
string storeStrings = "";
if (checkLength > 8)
{
foreach (var c in _lastName)
{
storeStrings += c;
if (storeStrings.Length == 8)
{
storeStrings += "**";
return storeStrings;
}
}
}
return storeStrings;
}
set { _lastName = value; }
}
One thing I noticed is your use of LastName in the LastName property getter, a big no no, its causing recursion and you probably are getting a stack overflow exception
This could be written more concise, but I'll leave that as an exercise for you
The Linq way:
var lastname = "Abumademal";
var formatted = (new string(lastname.Take(8).ToArray())).PadRight(lastname.Length, '*');
// will yield "Abumadem**"
"Take 8 chars and create a new string from this array, then pad it with as many * as needed."
full implementation:
private string lastname;
public string LastName
{
get
{
if (null == this.lastname)
{
return null;
}
char[] firsteight = this.lastname.Take(8).ToArray();
string tmp = new string(firsteight);
// padding this way wasn't the actual requirement ...
string result = tmp.PadRight(this.lastname.Length, '*');
return result;
}
set
{
this.lastname = value;
}
}
I have some public const strings in c# console application as shown below:
//Account one
public const string POP_USER1 = "abc#abcd.com";
public const string POP_PWD1 = "abc";
//Account two
public const string POP_USER2 = "xyz#abcd.com";
public const string POP_PWD2 = "xyz";
//Account three
public const string POP_USER3 = "pqr#abcd.com";
public const string POP_PWD3 = "pqr;
We are using c# MailMan to retrieve emails present in those accounts.
I simply wrote a for loop 3 times:
for (int i = 1; i <= 3; i++)
{
eEmails obj = new eEmails (i);
}
In the constructor of eEmails, I am writing the below logic:
public eEmails (int counter)
{
MailMan obj = new MailMan()
obj.PopUsername = "POP_USER" + counter;
obj.PopPassword = "POP_PWD" + counter;
}
The lines where I am assigning user name and passwords, I need to fetch the exact const variable (i.e., POP_USER1, POP_USER2, POP_USER3 etc.,)
However I am not able to get the variable dynamically.
I can simply write 3 if blocks in eEmails (int counter), but I didnt like that way.
can somebody advise a better way of handling this situation without using separate if blocks for each user??
Use a class instead of strings, then your code becomes more redable and maintainable and it'll also be less error-prone. Here is an example using a List<PopServerAccount> as container:
public class PopServerAccount
{
public string Username {get;set;}
public string Password {get;set;}
public override bool Equals(object obj)
{
PopServerAccount p2 = obj as PopServerAccount;
if (p2 == null) return false;
return Username == p2.Username;
}
public override int GetHashCode()
{
return Username.GetHashCode();
}
public override string ToString()
{
return Username;
}
}
now change the signature of your method:
public eEmails (PopServerAccount pop)
{
MailMan obj = new MailMan()
obj.PopUsername = pop.Username;
obj.PopPassword = pop.Password;
}
Sample data:
var myPopServers = new List<PopServerAccount>
{
new PopServerAccount{ Username = "abc#abcd.com", Password = "abc"},new PopServerAccount{ Username = "xyz#abcd.com", Password = "xyz"}
};
Use a loop and call your method:
foreach (PopServerAccount pop in myPopServers)
{
eEmails(pop);
}