Microsoft Teams App - pass team's culture to oauth backend provider in Tabs - microsoft-teams

I have build a Teams application on Asp.net core and connected the oauth backend provider. At startup.cs, I dont know the Team's culture yet. Then I ask user to login and get the culture in my cshtml page. But I am not able to find a way to pass Team's cultutre to my oauth backend.The settings goes like this in statup.cs:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieScheme;
options.DefaultChallengeScheme = OAuthScheme;
options.DefaultAuthenticateScheme = CookieScheme;
options.DefaultSignInScheme = CookieScheme;
options.DefaultSignOutScheme = CookieScheme;
})
.AddCookie(CookieScheme, options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.None;
options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
options.SlidingExpiration = false;
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = RefreshTokenIfRequired
};
})
.AddOAuth(OAuthScheme, options =>
{
var settings = JsonConvert.DeserializeObject<OnlineApiSettings>(Configuration["settings"]);
options.ClientId = settings.ClientId;
options.ClientSecret = settings.ClientSecret;
options.AuthorizationEndpoint = settings.AuthEndpoint;
options.TokenEndpoint = settings.TokenEndpoint;
options.CallbackPath = new PathString("/oauth/callback");
options.SaveTokens = true;
});
This is how login page constructed:
<script type="text/javascript">
function loginV1() {
microsoftTeams.app.initialize().then(() => {
microsoftTeams.app.getContext().then((context) => {
login(window.location.origin + "/LoginPopup?culture=" + context.app.locale);
});
});
}
function login(url) {
const urlParams = new URLSearchParams(window.location.search);
const redirectUrl = urlParams.get('redirectPath');
microsoftTeams.authentication.authenticate({
url: url,
width: 600,
height: 535,
successCallback: function (result) {
console.log("Login succeeded: " + result);
window.location.href = "/" + redirectUrl;
},
failureCallback: function (reason) {
console.log("Login failed: " + reason);
window.location.href = "/" + redirectUrl;
}
});
}
</script>
and LoginPopup page is like below:
[Authorize]
public class LoginPopupModel : PageModel
{
private readonly IHttpContextAccessor _httpContext;
public LoginPopupModel(IHttpContextAccessor httpContextAccessor)
{
_httpContext = httpContextAccessor;
}
public async Task<IActionResult> OnGetAsync()
{
if (_httpContext.HttpContext.User.Identity.IsAuthenticated)
{
return RedirectToPage("LoginSuccess");
}
return null;
}
}

Related

Getting Status 400 error while posting data on server in Razor page and AJAX

I am developing a website related to medical treatment, in which we ask different type of questions from patient actually, my task is, to enter their Email so I can check if he is already registered or not logged in then I redirect the user to the login page else I can register the user and assign a random password to the user and send him a mail on that Email,
so logged in user and if a user is not logged in these flows are working fine but when I'm when I register the user then and come to the next question I'm getting an error of status 400
Code for checking for user:
public async Task<IActionResult> OnGetCheckUserAsync(string Email)
{
if (User.Identity.IsAuthenticated)
{
var UserCred = _userManagmentServices.GetProfileAsync(Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
var user = await _userManager.FindByEmailAsync(Email);
if (user == null)
{
string randomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!##$%^&*";
Random random = new Random();
char[] myPassword = new char[6];
for (int i = 0; i < 6; i++)
{
myPassword[i] = randomString[(int)(35 * random.NextDouble())];
}
var randomPassword = string.Concat(myPassword);
var UserModel = new UserModel()
{
Email = Email,
FirstName = "Mr",
LastName = "Patient",
Password = randomPassword,
PhoneNo = "03000000000",
};
var response = await _userManagmentServices.CreateAsync(UserModel);
if (response.IsSuccessful)
{
var Body = $"Dear {UserModel.FirstName + UserModel.LastName} Your password is auto generated successfull and your password is {UserModel.Password}";
await _mailServices.SendEmailNotificationAsync(UserModel.Email, "Auto Generated Password", Body);
}
if (!response.IsSuccessful)
{
foreach (var Error in response.Errors)
{
ModelState.AddModelError("", Error.ToString());
}
return new JsonResult("Error while creating your account");
}
var UserCred = _userManagmentServices.GetProfileAsync(UserModel.Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
application = new FEApplication();
application.Status = Status.Incomplete;
application.UserEmail = Email;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
var _signinUrl = "../Auth/Signin";
return new JsonResult(_signinUrl);
}
}
}
public async Task<IActionResult> OnPostSubmitAsync(FEApplication? application)
{
if (application.FlowId != null)
{
application.ApplicationType = "Premature Ejaculation";
if (application.DoctorToKnow == "No" || application.ExplainDoctorToKnow != null)
{
application.Status = Status.PaymentDue;
}
else
{
application.Status = Status.Incomplete;
}
await _applicationManagementService.UpdatePEAsync(application.FlowId, application);
}
else
{
if (User.Identity.IsAuthenticated)
{
application.PatientUserName = ProfileModel.DisplayName;
application.ApplicationType = "Premature Ejaculation";
application.Status = Status.Incomplete;
application.UserEmail = User?.Identity?.Name;
ProfileModel = _userManagmentServices.GetProfileAsync(application.UserEmail).Result;
}
else
{
application.PatientUserName = ProfileModel.DisplayName ?? string.Empty;
application.UserEmail = application.UserEmail;
}
application.Status = Status.Incomplete;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
//_application = _applicationManagementService.GetOneById(FlowId);
}
return new JsonResult(application.FlowId);
}
function CheckUserEmail() {
$("#modalspinner").show();
var email = document.getElementById("Email").value;
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
url: "./Start?handler=CheckUser",
type: "GET",
dataType: "json",
data: {
Email: email
},
success: function (response) {
console.log("Success block");
if (response) {
$("#modalspinner").hide();
console.log("response " + response)
if (response == "../Auth/Signin") {
window.location.href = response;
}
else {
if (response.id) {
console.log("if block =" + JSON.stringify(response));
var firstName = JSON.stringify(response.displayName) ?? "";
var lastName = JSON.stringify(response.displayName) ?? "";
var email = JSON.stringify(response.email) ?? "";
var phoneNo = JSON.stringify(response.phone);
var address = JSON.stringify(response.address) ?? "";
var city = JSON.stringify(response.city);
var postalCode = JSON.stringify(response.postalCode) ?? "";
$("#FirstName").val(firstName.replace(/\"/g, ""));
$("#LastName").val(lastName.replace(/\"/g, ""));
$("#Email").val(email.replace(/\"/g, ""));
$("#PhoneNoTextbox").val(phoneNo.replace(/\"/g, ""));
$("#CustomerShippingAddress").val(address.replace(/\"/g, ""));
$("#CustomerCity").val(city.replace(/\"/g, ""));
$("#CustomerPostalCode").val(postalCode.replace(/\"/g, ""));
console.log("response data :" + firstName, lastName, email, phoneNo, address, city, postalCode);
}
else {
$("#modalspinner").hide();
console.log("Error while creating new user" + JSON.stringify(response));
}
}
}
},
error: function (response) {
console.log("Error block =" + JSON.stringify(response));
$("#modalspinner").hide();
$('#EmailMessage').show();
setTimeout(function () { $('#EmailMessage').hide(); }, 5000);
$("#modalspinner").hide();
}
});
}
function SubmitForm() {
/*var flowId = document.getElementById("FlowId").value;*/
var data = $("#ApplicationData").serialize();
console.log("data :" + data);
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
type: "POST",
url: "./Start?handler=Submit",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: data,
success: function (response) {
var res = JSON.stringify(response);
console.log("Application data saved!");
$("#FlowId").val(res.replace(/\"/g, ""));
}
})
}
Please check below with your code:
In the cshtml, add
#Html.AntiForgeryToken()
The Ajax request should send the anti-forgery token in request header to the server.
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
In startup, since the script sends the token in a header called XSRF-TOKEN, configure the antiforgery service to look for the XSRF-TOKEN header:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

google calendar api net api The access token has expired and could not be refreshed. Errors: refresh error, refresh error, refresh error

I'm new to google api. I'm using google .net api, I'm getting the error:
The access token has expired and could not be refreshed. Errors: refresh error, refresh error, refresh error
I'm able to see the login screen, I accept the permissions request, and I got redirected to Index 2 correctly. When the calendar service is going to be used (execute) it crashes with the already mentioned error.
I already set the token as offline in the GOOGLE_AUTH_URL_TEMPLATE variable. That is supposed to be used for long term tokens.
Main Auth Class
public class TestOAuth2
{
private string applicationName = "g calendar test api";
private string clientId = "---";//From Google Developer console https://console.developers.google.com
private string clientSecret = "---";//From Google Developer console https://console.developers.google.com
private string[] scopes = new string[] {
CalendarService.Scope.Calendar, // Manage your calendars
CalendarService.Scope.CalendarReadonly // View your Calendars
};
private UserCredential userCredential;
string GOOGLE_AUTH_URL_TEMPLATE = "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&approval_prompt=force&scope={0}&response_type=code&redirect_uri={1}&client_id={2}&login_hint=";
string clientRedirectUri= "http://localhost:57618/Home/Index2";
private CalendarService calendarService;
public TestOAuth2(string access_token)
{
ClientSecrets clientSecrets = new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
};
GoogleAuthorizationCodeFlow flow = null;
TokenResponse token = new TokenResponse
{
AccessToken = access_token
};
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets,
Scopes = scopes
});
userCredential = new UserCredential(flow, "user", token);
calendarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = userCredential,
ApplicationName = applicationName
});
}
public string GetGoogleOAuthURL()
{
return string.Format(GOOGLE_AUTH_URL_TEMPLATE, String.Join("+", scopes), clientRedirectUri, clientId);
}
private void InitializeCalendarService()
{
calendarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = userCredential,
ApplicationName = applicationName
});
}
public string GetEvents()
{
try
{
if (calendarService == null)
{
InitializeCalendarService();
}
var eventRequest = calendarService.Events.List("primary");
eventRequest.TimeMin = DateTime.Now;
eventRequest.ShowDeleted = false;
eventRequest.SingleEvents = true;
eventRequest.MaxResults = 10;
eventRequest.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
var events = eventRequest.Execute();
string sEvents = "";
foreach (var evt in events.Items)
{
sEvents += evt.Description + "\n<br>";
}
return sEvents;
}
catch (Exception ex)
{
return ex.Message;
}
}
}
Home Controller
public class HomeController : Controller
{
private TestOAuth2 Google;
public string GetGoogleOauthUrl()
{
string temp = "";
try
{
Google = new TestOAuth2(string.Empty);
temp = Google.GetGoogleOAuthURL();
}
catch (Exception ex)
{
temp = ex.Message;
}
return temp;
}
public string GetEvents()
{
string access_token = Request.Headers.Get("access_token");
string temp = "";
try
{
Google = new TestOAuth2(access_token);
temp = Google.GetEvents();
}
catch (Exception ex)
{
temp = ex.Message;
}
return temp;
}
public ActionResult Index()
{
return View();
}
public ActionResult Index2()
{
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
Index View
<html>
<body>
<script>
document.addEventListener('DOMContentLoaded', function (event) {
fetch("http://localhost:57618/Home/GetGoogleOauthUrl", {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.ok) {
response.text().then(myAnswer => {
console.log(myAnswer);
window.open(myAnswer, '_blank');
})
} else {
console.error.log("HTTP-Error: " + response.status);
}
});
});
</script>
Hello! Wait For A New Window!
</body>
</html>
Index 2 View
<html>
<body>
<script>
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
document.addEventListener('DOMContentLoaded', function (event) {
let token = getUrlParameter("code");
fetch("http://localhost:57618/Home/GetEvents", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
"access_token": token
}
})
.then(response => {
if (response.ok) {
response.text().then(myAnswer => {
console.log(myAnswer);
document.write("<br><br><br>");
document.write(myAnswer);
})
} else {
console.error.log("HTTP-Error: " + response.status);
}
});
});
</script>
</body>
</html>
What you want to use is a special token that does not need to be refreshed I believe.
To do that you need to create a project inside GCP and then create a Service Account and Download a json key inside the new Service Account created.
Enable the Calendar API inside the new created project and copy the email of the service account. Go to the calendar you want to give access to your api and add the email you copy from the service account. Now you can use the service account json key to authenticate and it wont have expiration.

Chromecast Reciever App Error : '[goog.net.WebSocket] The WebSocket disconnected unexpectedly: undefined '

While creating a receiver application in chromecast we are getting a problem as :
[goog.net.WebSocket] The WebSocket disconnected unexpectedly: undefined
cast_receiver_framework.js:507 WebSocket connection to 'ws://localhost:8008/v2/ipc' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
Our receiver has simple code as in example provided by CAF receiver in chromecast documentation:
const context = cast.framework.CastReceiverContext.getInstance();
const playerManager = context.getPlayerManager();
const playbackConfig = new cast.framework.PlaybackConfig();
// Customize the license url for playback
playbackConfig.licenseUrl = 'https://wv-keyos.licensekeyserver.com/';
playbackConfig.protectionSystem = cast.framework.ContentProtection.WIDEVINE;
playbackConfig.licenseRequestHandler = requestInfo => {
requestInfo.withCredentials = true;
requestInfo.headers = {
'customdata': '<customdata>'
};
};
context.getPlayerManager().setMediaPlaybackInfoHandler((loadRequest, playbackConfig) => {
if (loadRequest.media.customData && loadRequest.media.customData.licenseUrl) {
playbackConfig.licenseUrl = loadRequest.media.customData.licenseUrl;
}
return playbackConfig;
});
function makeRequest (method, url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(JSON.parse(xhr.response));
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
playerManager.setMessageInterceptor(
cast.framework.messages.MessageType.LOAD,
request => {
castDebugLogger.info('MyAPP.LOG', 'Intercepting LOAD request');
if (request.media && request.media.entity) {
request.media.contentId = request.media.entity;
}
return new Promise((resolve, reject) => {
if(request.media.contentType == 'video/mp4') {
return resolve(request);
}
// Fetch content repository by requested contentId
makeRequest('GET', 'https://tse-summit.firebaseio.com/content.json?orderBy=%22$key%22&equalTo=%22'+ request.media.contentId + '%22')
.then(function (data) {
var item = data[request.media.contentId];
if(!item) {
// Content could not be found in repository
castDebugLogger.error('MyAPP.LOG', 'Content not found');
reject();
} else {
// Adjusting request to make requested content playable
request.media.contentId = item.stream.hls;
request.media.contentType = 'application/x-mpegurl';
castDebugLogger.warn('MyAPP.LOG', 'Playable URL:', request.media.contentId);
// Add metadata
var metadata = new cast.framework.messages.MovieMediaMetadata();
metadata.metadataType = cast.framework.messages.MetadataType.MOVIE;
metadata.title = item.title;
metadata.subtitle = item.author;
request.media.metadata = metadata;
resolve(request);
}
});
});
});
/** Debug Logger **/
const castDebugLogger = cast.debug.CastDebugLogger.getInstance();
// Enable debug logger and show a warning on receiver
// NOTE: make sure it is disabled on production
castDebugLogger.setEnabled(false);
playerManager.addEventListener(
cast.framework.events.category.CORE,
event => {
castDebugLogger.info('ANALYTICS', 'CORE EVENT:', event);
});
// Set verbosity level for custom tags
castDebugLogger.loggerLevelByTags = {
'MyAPP.LOG': cast.framework.LoggerLevel.WARNING,
'ANALYTICS': cast.framework.LoggerLevel.INFO,
};
/** Optimizing for smart displays **/
const playerData = new cast.framework.ui.PlayerData();
const playerDataBinder = new cast.framework.ui.PlayerDataBinder(playerData);
const touchControls = cast.framework.ui.Controls.getInstance();
let browseItems = getBrwoseItems();
function getBrwoseItems() {
let data = '"video": { \
<Encrypted Video>
}, \
"title": "Big Buck Bunny" \
}';
let browseItems = [];
for (let key in data) {
let item = new cast.framework.ui.BrowseItem();
item.entity = key;
item.title = data[key].title;
item.subtitle = data[key].description;
item.image = new cast.framework.messages.Image(data[key].poster);
item.imageType = cast.framework.ui.BrowseImageType.MOVIE;
browseItems.push(item);
}
return browseItems;
}
let browseContent = new cast.framework.ui.BrowseContent();
browseContent.title = 'Up Next';
browseContent.items = browseItems;
browseContent.targetAspectRatio =
cast.framework.ui.BrowseImageAspectRatio.LANDSCAPE_16_TO_9;
playerDataBinder.addEventListener(
cast.framework.ui.PlayerDataEventType.MEDIA_CHANGED,
(e) => {
if (!e.value) return;
// Clear default buttons and re-assign
touchControls.clearDefaultSlotAssignments();
touchControls.assignButton(
cast.framework.ui.ControlsSlot.SLOT_1,
cast.framework.ui.ControlsButton.SEEK_BACKWARD_30
);
// Media browse
touchControls.setBrowseContent(browseContent);
});
context.start({playbackConfig: playbackConfig});
This code takes the input from sender but even if sender has application ID it shows the same message.

Angular2 to Asp.net Core Webapi IFormFile is null

I am using angular2 with asp.net core webapi. Using the following code to send file information. IFormFile is always null. I have used same name in post input and in api method parameter, still no luck. Please help me.
FormData
this.formData.append("file", f,f.name);
Component method
public UploadFiles() {
console.log("Form Data:" + this.formData);
let saved: boolean = false;
this.claimsService
.UploadFiles(this.formData)
.subscribe(data => {
saved = data;
}, error => {
console.log(error)
swal(error);
})
}
Service Method
UploadFiles(data: FormData): Observable<boolean> {
return this.ExecuteFilePost("Upload/Upload", data);
}
Base Service Method:
public ExecuteFilePost(action: string, data: FormData) {
let _body = data;
let headers = new Headers({ 'Content-Type': undefined});
let url = this._baseUrl + action;
let requestoptions: RequestOptions = new RequestOptions({
headers: headers,
});
console.log('req url:' + url);
return this.http.post(url,_body,requestoptions)
.share()
.map((res: Response) => {
if (res.status < 200 || res.status >= 300) {
throw new Error('This request has failed ' + res.status);
}
else {
return res.json();
}
});
}
WebApi Method
[HttpPost]
[ActionName("Upload")]
public async Task Upload(IFormFile file)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
// foreach (var file in files)
// {
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
// }
}
Chrome request screens
enter image description here
I know the post is old, but maybe for others. You can do things like this:
HTML:
<input #fileInput type="file" multiple />
<button (click)="addFile()">Add</button>
Component:
#ViewChild("fileInput") fileInput;
addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files) {
let fileToUpload = fi.files;
this.settingsService
.upload(fileToUpload)
.subscribe(res => {
console.log(res);
});
}
}
Service:
upload(files: any) {
let formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append("files", files[i]);
}
return this.http
.post(fileUploadApi, formData)
.map(response => this.extractData(response as Response))
.catch(error => this.httpErrorHandlerService.responseError(error));
}
Web API
[HttpPost]
[Route("Upload")]
public IActionResult UploadFiless([FromForm] IFormFileCollection files)
{
try
{
return this.Ok();
}
catch (Exception)
{
return this.BadRequest();
}
}

MVC Ajax function call twice

I have a problem with an ajax function. I want to send param to method on controller and this ajax function call method twice.
ajax:
$(document).ready(function () {
$(document).on('click', '.exp', function (e) {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
})
$(".exp").click(function() {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
?
<th>
Start date: #Html.TextBox("start_date", null, new { #class = "dateClass start", id = "StartDate" })
End date: #Html.TextBox("end_date", null, new { #class = "dateClass end", id = "EndDate", #data_toggle = "popover", #data_content = "End date should be greater than Start date. ", #title = "Attention" })
#Html.ActionLink("Export Report", "Report_CLeav", "Reports", new { #class = "IndexButton exp", #style = "text-decoration: none;color:white" })
</th>
"Controller"
public class ReportsController : Controller
{
// GET: Export
public ActionResult Index()
{
return View();
}
public void Report_CLeav(DateTime ?start_date, DateTime ? end_date)
{
string path = HttpContext.Server.MapPath("~/App_Data/reports/Report_LeavingCompanyHCT.xlsx");
Models.Report.Report_CompLeav reportcompleav = new Models.Report.Report_CompLeav();
var fileinfo = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(fileinfo))
{
var currentWorksheet = package.Workbook.Worksheets["HC"];
using (var excelToExport = new ExcelPackage())
{
excelToExport.Workbook.Worksheets.Add(currentWorksheet.Name, currentWorksheet);
var workBook = excelToExport.Workbook.Worksheets["HC"];
try
{
workBook = reportcompleav.exportAllEmployeeDataRRecords(workBook,start_date,end_date);
}
catch (Exception e)
{
ViewBag.IsError = true;
}
excelToExport.Save();
Stream stream = excelToExport.Stream;
var memoryStream = stream as MemoryStream;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats";
Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileinfo.Name);
Response.BinaryWrite(memoryStream.ToArray());
}
}
}
}
}

Resources