Export to excel losses leading zero in mvc4 - asp.net-mvc

i am working on mvc4 project.I have having issue with export to excel code.I have employee id that is varchar field... and have leading zero ie : 0289707,2909878 etc..
So when i export data to excel it looses leading zero..
So how do i export data as it is ??
Controller code is as below :
public ActionResult ExportToExcel(string strStartDate, string strEndDate)
{
try
{
GridView gridView = new GridView();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "EmployeeReport " + Helper.GetBrazilTime(DateTime.UtcNow).ToString() + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
gridView.AllowPaging = false;
DateTime startDate = Convert.ToDateTime(strStartDate);
DateTime endDate = Convert.ToDateTime(strEndDate);
if (Helper.CurrentCulture == "pt-BR")
{
startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 0, 0, 0, DateTimeKind.Utc);
endDate = new DateTime(endDate.Year, startDate.Month, endDate.Day, 0, 0, 0, DateTimeKind.Utc);
}
gridView.DataSource = ReportExecutor.GetEmployeeReportExportData(startDate, endDate);
gridView.DataBind();
//This will change the header background color
gridView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //
//This will apply style to gridview header cells
for (int index = 0; index < gridView.HeaderRow.Cells.Count; index++)
{
gridView.HeaderRow.Cells[index].Style.Add("background-color", "#778899"); //Light Slate Gray
gridView.HeaderRow.Cells[index].Style.Add("foreground-color", "#ffffff"); // White
}
gridView.HeaderRow.Cells[0].Text = #Resources.Resource.ShopName;
gridView.HeaderRow.Cells[1].Text = #Resources.Resource.MachineName;
gridView.HeaderRow.Cells[2].Text = #Resources.Resource.ProjectIDName;
gridView.HeaderRow.Cells[3].Text = #Resources.Resource.BaseActivity;
gridView.HeaderRow.Cells[4].Text = #Resources.Resource.EmployeeID;
gridView.HeaderRow.Cells[5].Text = #Resources.Resource.EmployeeName;
gridView.HeaderRow.Cells[6].Text = #Resources.Resource.RunTime;
gridView.HeaderRow.Cells[7].Text = #Resources.Resource.SetUp;
gridView.HeaderRow.Cells[8].Text = #Resources.Resource.TearDown;
gridView.HeaderRow.Cells[9].Text = #Resources.Resource.Work;
gridView.HeaderRow.Cells[10].Text = #Resources.Resource.Rework;
gridView.HeaderRow.Cells[11].Text = #Resources.Resource.LunchHours;
gridView.HeaderRow.Cells[12].Text = #Resources.Resource.MaintenanceHours;
gridView.HeaderRow.Cells[13].Text = #Resources.Resource.QualityProblemHours;
gridView.HeaderRow.Cells[14].Text = #Resources.Resource.LOMHours;
gridView.HeaderRow.Cells[15].Text = #Resources.Resource.UDCIdle;
gridView.HeaderRow.Cells[16].Text = #Resources.Resource.UDCOthers;
gridView.HeaderRow.Cells[17].Text = #Resources.Resource.ActualShiftHours;
gridView.HeaderRow.Cells[18].Text = #Resources.Resource.Overtime;
int index2 = 1;
//This will apply style to alternate rows
foreach (GridViewRow gridViewRow in gridView.Rows)
{
//gridViewRow.Attributes.Add("class", "textmode");
gridViewRow.BackColor = Color.White;
if (index2 <= gridView.Rows.Count)
{
if (index2 % 2 != 0)
{
for (int index3 = 0; index3 < gridViewRow.Cells.Count; index3++)
{
gridViewRow.Cells[index3].Style.Add("background-color", "#e6e6fa");// Lavender
//gridViewRow.Cells[index3].Style.Add("class", "textmode");// Apply text style to all rows
}
}
}
index2++;
}
gridView.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
catch
{
}
return null;
}

For i As Integer = 0 To GridView1.Rows.Count - 1
//Apply text style to each Row.cell
//The attribute must be "text" not "textmode" and it must be applied to the cells
For j As Integer = 0 To GridView1.Rows(i).Cells.Count - 1
GridView1.Rows(i).Cells(j).Attributes.Add("class", "text");
Next
Next

Related

i have json response but its optional can any one tell me how to unwrap optional json

please tell me how to unwrap this josn response because of optional json i am not able to parse in label
i have tried my best but i am new to swift so i can't get it to unwrap the optional json
response::
Optional(<__NSArrayM 0x600000848340>(
{
contributors = "";
coordinates = "";
"created_at" = "Thu Jul 12 11:49:57 +0000 2018";
entities = {
hashtags = (
);
media = (
{
"display_url" = "pic.twitter.com/IJtq6aLM7K";
"expanded_url" = "";
id = 1017375504448479232;
"id_str" = 1017375504448479232;
indices = (
12,
35
);
"media_url" = "";
"media_url_https" = "";
sizes = {
large = {
h = 1820;
resize = fit;
w = 2048;
};
medium = {
h = 1067;
resize = fit;
w = 1200;
};
small = {
h = 604;
resize = fit;
w = 680;
};
thumb = {
h = 150;
resize = crop;
w = 150;
};
};
type = photo;
url = "";
}
);
symbols = (
);
urls = (
);
"user_mentions" = (
);
};
"extended_entities" = {
media = (
{
"display_url" = "pic.twitter.com/IJtq6aLM7K";
"expanded_url" = "";
id = 1017375504448479232;
"id_str" = 1017375504448479232;
indices = (
12,
35
);
"media_url" = "";
"media_url_https" = "";
sizes = {
large = {
h = 1820;
resize = fit;
w = 2048;
};
medium = {
h = 1067;
resize = fit;
w = 1200;
};
small = {
h = 604;
resize = fit;
w = 680;
};
thumb = {
h = 150;
resize = crop;
w = 150;
};
};
type = photo;
url = "";
}
);
};
"favorite_count" = 0;
favorited = 0;
geo = "";
id = 1017375507174719488;
"id_str" = 1017375507174719488;
"in_reply_to_screen_name" = "";
"in_reply_to_status_id" = "";
"in_reply_to_status_id_str" = "";
"in_reply_to_user_id" = "";
"in_reply_to_user_id_str" = "";
"is_quote_status" = 0;
lang = fr;
place = "";
"possibly_sensitive" = 0;
"retweet_count" = 0;
retweeted = 0;
source = "";
text = "Tweet Tweet ";
truncated = 0;
user = {
"contributors_enabled" = 0;
"created_at" = "Tue Mar 27 05:14:33 +0000 2018";
"default_profile" = 1;
"default_profile_image" = 0;
description = "";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 3;
"follow_request_sent" = 0;
"followers_count" = 1;
following = 0;
"friends_count" = 0;
"geo_enabled" = 1;
"has_extended_profile" = 0;
id = 978500498897563648;
"id_str" = 978500498897563648;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 0;
location = "";
name = Mike;
notifications = 0;
"profile_background_color" = F5F8FA;
"profile_background_image_url" = "";
"profile_background_image_url_https" = "";
"profile_background_tile" = 0;
"profile_image_url" = "";
"profile_image_url_https" = "";
"profile_link_color" = 1DA1F2;
"profile_sidebar_border_color" = C0DEED;
"profile_sidebar_fill_color" = DDEEF6;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = Mike50430315;
"statuses_count" = 13;
"time_zone" = "";
"translator_type" = none;
url = "";
"utc_offset" = "";
verified = 0;
};
}
because of this i am getting nil value in all like name text retweet please tell me how to solve this
var timeline = (FHSTwitterEngine.shared().getTimelineForUser(FHSTwitterEngine.shared().authenticatedUsername, isID: true, count: 10), terminator: "")
from this line i am getting whole response
and then i have on array i create and store in to array like below
var serviceData = [AnyObject]()
let timelinedata = [timeline] as [AnyObject]
serviceData = (timelinedata)
print(serviceData)
In general, anything optional can be unwrapped like so:
let optionalValue: String? = "Hello, this is optional!"
if let noLongerOptional = optionalValue {
print("\(noLongerOptional) no its not! ahah")
}
Edit: more specific example...
Assuming you have a variable 'myJson' which hold your optional value... and you did:
print("\(myJson)")
You can solve this by:
if let validJson = myJson {
print("\(validJson)")
}
Edit 2: ... FHSTwitter... (updated.... this is getting long)
let twitterEngine = FHSTwitterEngine.sharedEngine()
let twitterUser = twitterEngine.authenticatedID
let timeline = twitterEngine.getTimelineForUser(twitterUser, isID: true, count: 10)
According to FHSTwitterEngine docs... getTimelineForUser() will return either a NSError or an array of Tweets.
so...
if let error = timeline as? Error {
print("Oops, looks like something went wrong: \(error)")
} else {
if let tweets = timeline as? [Any] {
for tweet in tweets {
print("This is a tweet: \(tweet)")
}
}
}
If you have any more trouble using FHSTwitterEngine, I suggest you play with: https://github.com/natesymer/FHSTwitterEngine/tree/master/FHSTwitterEngineDemoSwift/Demo-Swift
Or open a support ticket with the FHSTwitterEngine developer(s) at: https://github.com/natesymer/FHSTwitterEngine/issues
Good Luck!

Can you resize images that are passed to UIPrintInteractionController.PrintingItems?

I'm trying to print multiple labels using UIPrintInteractionController.PrintingItems but when the image is loaded it fills the page, is it possible to have multiple images on one page using this method or is there another method that would offer me a better solution? Thanks.
void Print()
{
var printInfo = UIPrintInfo.PrintInfo;
printInfo.OutputType = UIPrintInfoOutputType.General;
printInfo.JobName = "Label Printing";
//UIPrintFormatter formatter = new UIPrintFormatter()
//{
// StartPage = 0,
// ContentInsets = new UIEdgeInsets(72, 72, 72, 72),
// MaximumContentWidth = 6 * 72,
//};
int labelAmount = 10;
int x;
NSObject[] labelItems = new NSObject[labelAmount];
for (x = 0; x < labelAmount; x++)
{
labelItems[x] = UIImage.FromFile("Images/BMcAzurri.png");
}
UIPrintInteractionController printer = UIPrintInteractionController.SharedPrintController;
printer.PrintInfo = printInfo;
//printer.PrintFormatter = formatter;
printer.PrintingItems = labelItems;
printer.ShowsPageRange = true;
printer.Present(true, (handler, completed, err) => {
if (!completed && err != null)
{
Console.WriteLine("error");
}
});
}
There are a few ways to do what you are asking, here is just one using a graphics context to do your print page rendering.
Load your image into a UIImage instance
You might want to pre-scale/re-scale that image
Create a UIView that is large enough to contain all your rows and columns of that image
Create a UIImageView that contains your image for each row/column on your "printed page" and place it at the correct location in this view
Using an Image render context, convert the UIView that contains your images to a UIImage and queue and print as many of those as you need...
Example:
var printInfo = UIPrintInfo.PrintInfo;
printInfo.OutputType = UIPrintInfoOutputType.General;
printInfo.JobName = "Label Printing";
var uiImage = UIImage.FromFile("BingWallpaper-2017-05-04.jpg");
var noColumns = 2;
var noRows = 2;
var gapBetweenImages = 25;
int noOfPages = 2;
NSObject[] labelItems = new NSObject[noOfPages];
for (int x = 0; x < noOfPages; x++)
{
var aPrintView = new UIView
{
Frame = new CGRect(0, 0, (uiImage.Size.Width * noColumns) + ((noColumns + 1) * gapBetweenImages), (uiImage.Size.Height) * noRows + ((noRows + 1) * gapBetweenImages))
};
for (int column = 0; column < noColumns; column++)
{
for (int row = 0; row < noRows; row++)
{
var printImage = new UIImageView(uiImage)
{
Frame = new CGRect((column * gapBetweenImages) + (column * uiImage.Size.Width), (row * gapBetweenImages) + (row * uiImage.Size.Height), uiImage.Size.Width, uiImage.Size.Height)
};
aPrintView.Add(printImage);
}
}
UIGraphics.BeginImageContext(aPrintView.Bounds.Size);
aPrintView.Layer.RenderInContext(UIGraphics.GetCurrentContext());
var aPageImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
labelItems[x] = aPageImage;
}
UIPrintInteractionController printer = UIPrintInteractionController.SharedPrintController;
printer.PrintInfo = printInfo;
printer.PrintingItems = labelItems;
printer.ShowsPageRange = true;
printer.Present(true, (handler, completed, err) =>
{
if (!completed && err != null)
{
Console.WriteLine("error");
}
});
Note: !!! This is not handling the clean up, make sure you Dispose of everything after you are done...
Note: This is just a quick example does not handle the aspect ratio of the image to the paper size, you would need to consider that depending upon what you are printing and to what type of printer/paper...
Note: If you were renderering a number of text fields vs. images, you might want to render to a PDF vs a UIImage and print that instead.

JSON object data to UILabel

How can I populate a few UILabels on a ViewController from the JSON object I receive from a previously passed id parameter? I get the response from the server but, I don't know how to populate the key/value pairs to a UILabel.
The JSON response I get is:
{
product = {
attributes = (
);
"average_rating" = "0.00";
backordered = 0;
"backorders_allowed" = 0;
"button_text" = "";
"catalog_visibility" = visible;
categories = (
);
"created_at" = "2016-02-23T05:00:55Z";
"cross_sell_ids" = (
);
description = "<p>Microsoft Office</p>\n";
dimensions = {
height = "";
length = "";
unit = in;
width = "";
};
"download_expiry" = 0;
"download_limit" = 0;
"download_type" = "";
downloadable = 0;
downloads = (
);
featured = 0;
"featured_src" = "https://qashop.taxometry.com/wordpressv4/wp-content/uploads/2016/02/softwarecontract-150x150.jpg";
"grouped_products" = (
);
id = 15;
images = (
{
alt = "";
"created_at" = "2016-02-23T05:01:35Z";
id = 16;
position = 0;
src = "https://qashop.taxometry.com/wordpressv4/wp-content/uploads/2016/02/softwarecontract-150x150.jpg";
title = "softwarecontract-150×150";
"updated_at" = "2016-02-23T05:01:35Z";
}
);
"in_stock" = 1;
"managing_stock" = 0;
"menu_order" = 0;
"on_sale" = 1;
parent = (
);
"parent_id" = 0;
permalink = "https://qashop.taxometry.com/wordpressv4/product/software-contract/";
price = 25;
"price_html" = "<del><span class=\"amount\">$30.00</span></del> <ins><span class=\"amount\">$25.00</span></ins>";
"product_url" = "";
"purchase_note" = "";
purchaseable = 1;
"rating_count" = 0;
"regular_price" = 30;
"related_ids" = (
);
"reviews_allowed" = 1;
"sale_price" = 25;
"shipping_class" = "";
"shipping_class_id" = "<null>";
"shipping_required" = 1;
"shipping_taxable" = 1;
"short_description" = "";
sku = 2370;
"sold_individually" = 0;
status = publish;
"stock_quantity" = "<null>";
tags = (
);
"tax_class" = "";
"tax_status" = taxable;
taxable = 1;
title = "Software Contract";
"total_sales" = 5;
type = simple;
"updated_at" = "2016-02-23T05:01:41Z";
"upsell_ids" = (
);
variations = (
);
virtual = 0;
visible = 1;
weight = "<null>";
};
}
Try this - > First
then Second

How can i check image contain data or not in this Response

This is my response API. The image data dynamically changes,with more image at a time or else no image at a time. I have check as ([image_array count]==0) but app crash due to empty array.
Error
reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
(
0 CoreFoundation 0x0243edf6 __exceptionPreprocess + 182
API RESPONSE
{
response = {
Details = {
ID = 4;
address = "";
ancestors = (
);
"comment_count" = 0;
"comment_status" = closed;
description = "";
"description_pt" = "";
duration = 2;
"event_address" = "";
"event_location" = ",";
"event_location_option" = "";
"event_place_address" = "";
"event_place_email" = "";
"event_place_location" = "";
"event_place_phone" = "";
"event_place_website" = "";
filter = raw;
guid = "";
images = (
);
"like_count" = 0;
"like_status" = FALSE;
location = "";
"menu_order" = 0;
"ping_status" = closed;
pinged = "";
"place_event_count" = "";
"place_event_id" = "";
"place_id" = "";
"post_author" = 5;
"post_category" = (
);
"post_content" = "";
"post_content_filtered" = "";
"post_date" = "2015-07-31 ";
"post_date_gmt" = "2015-07-31 ";
"post_excerpt" = "";
"post_mime_type" = "";
"post_modified" = "2015-07-31 ";
"post_modified_gmt" = "2015-07-31 ";
"post_name" = 48;
"post_parent" = 0;
"post_password" = "";
"post_status" = publish;
"post_title" = "";
"post_type" = events;
"tags_input" = (
);
time = "17:50:30";
title = "";
"title_pt" = "";
"to_ping" = "";
video = "";
website = "";
};
Message = "Post Details";
httpCode = 10;
};
}
check like this
NSArray *array = [data valueForKey#"images"];
if (![array isKindOfClass:[NSArray class]]) {
//its not array or have null value
}else{
//its real array
}
It will work fine

Issue with Sorting NSMutableArray

I have an NSMutableArray which contains an NSDictionary, I need to sort the array based on certain criteria.
Sorting criteria is
sort based on properties.property.value, suppose if I want to sort based on properties.property.name = Risk value. I want all the elements with Risk value first with the value in Ascending order. That means for the Dictionary which doesn't have
properties.property.name = Risk must come last. Some of the dictionaries don't have these names.
Please help...
finalArr (
{
ViewTag = 101;
"action-taken-date" = {
class = "java.util.GregorianCalendar";
text = "2013-06-03 22:23:28.0 PDT";
};
alarms = 0;
alerts = 0;
application = {
assignee = "Test Name";
completed = false;
"properties" = {
class = "java.util.ArrayList";
property = (
{
label = Risk;
name = Risk;
value = "3 - Low";
},
{
label = "Start Time";
name = "Start Time";
value = "05/09/13 06:00:00";
}
);
};
{
ViewTag = 102;
"date" = {
class = "java.util.GregorianCalendar";
text = "2013-06-03 22:23:28.0 PDT";
};
alarms = 0;
alerts = 0;
application = {
assignee = "Test Name";
completed = false;
"properties" = {
class = "java.util.ArrayList";
property = (
{
label = Risk;
name = Risk;
value = "2 - Low";
},
{
label = "Start Time";
name = "Start Time";
value = "05/09/13 06:00:00";
}
);
};
{
ViewTag = 103;
"date" = {
class = "java.util.GregorianCalendar";
text = "2013-06-03 22:23:28.0 PDT";
};
alarms = 0;
alerts = 0;
application = {
assignee = "Test Name";
completed = false;
"properties" = {
class = "java.util.ArrayList";
property = (
{
label = Status;
name = Status;
value = "Pending Signoffs";
},
{
label = Priority;
name = Priority;
value = 3;
}
);
};
{
ViewTag = 104;
"date" = {
class = "java.util.GregorianCalendar";
text = "2013-06-03 22:23:28.0 PDT";
};
alarms = 0;
alerts = 0;
application = {
assignee = "Test Name";
completed = false;
"properties" = {
property = (
{
label = Priority;
name = priority;
value = 1;
},
{
label = "Start Time";
name = "Start Time";
value = "05/09/13 06:00:00";
}
);
};
{
ViewTag = 103;
"date" = {
class = "java.util.GregorianCalendar";
text = "2013-06-03 22:23:28.0 PDT";
};
alarms = 0;
alerts = 0;
application = {
assignee = "Test Name";
completed = false;
"properties" = {
property = (
{
label = Status;
name = Status;
value = "Pending Signoffs";
},
{
label = Priority;
name = Priority;
value = 2;
}
);
};
)
Try with this
NSString *risk = #"Risk";
[finalArray sortUsingComparator:^NSComparisonResult(NSDictionary * dict1, NSDictionary * dict2) {
NSDictionary *property1 = dict1[#"properties"][#"property"][0];
NSString *name1 = property1[#"name"];
NSDictionary *property2 = dict2[#"properties"][#"property"][0];
NSString *name2 = property2[#"name"];
if ([name1 isEqualToString:name2]) {
//if both names are equal then they are sorted based on value
NSString *value1 = property1[#"value"];
NSString *value2 = property2[#"value"];
return [value1 compare:value2 options:NSNumericSearch];
}else if ([name1 isEqualToString:risk]){
//if name1 is equal to risk it is moved up
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}];
It sounds like you have multiple different requirements (logic) which go into determining the desired sort result. You should write your own comparison logic and use one of the array methods like sortUsingComparator:.

Resources