C # – Export record to Excel asp.net

I have created a program to export a dataset that can be exported at runtime via Response. When you open the file, however, a message appears indicating that the file format is incompatible with the file extension.

The following code:

DataTable dt = new DataTable ();
DataSet ds = new DataSet ();

int CompanyID = this.Master.UserID CompanyID.
UpQuestionBLL uqr = new UpQueitoRespostaBLL ();
list lstOpcoesRespuestas = uqr.ListOpcoesRespuestasByCompany (IdEmpresa);
int qtdeResponses = LstOpcoesRequests.FirstOrDefault (). Answers.Count ();

dt.Columns.Add ("question");
dt.Columns.Add ("area");
dt.Columns.Add ("Cargo");
dt.Columns.Add ("Weight");
for (int i = 1; i <= qtdeResponses; i ++)
{
dt.Columns.Add ("Value_" + i);
dt.Columns.Add ("Reply_" + i);
}
foreach (var or in lstOptionsResponses)
{
DataRow line = dt.NewRow ();
line[0] = resp.DsQuesito.ToString ();
line[1] = resp.DsArea.ToString ();
line[2] = resp.DsCargo.ToString ();
line[3] = resp.Peso.ToString ();
int j = 3;
for (int i = 0; i <qtdeResponses; i ++)
{
line[j + 1] = resp. reply[i].Valor.ToString ();
line[j + 2] = resp. reply[i].DsResposta.ToString ();
j + = 2;
}
dt.Rows.Add (line);
}

ds.Tables.Add (dt);

StringWriter sw = DataSetToExcel (ds);

String Date = DateTime.Now.ToShortDateString (). Replace ("/", "-"). ToString ();
HttpContext.Current.Response.Clear ();
HttpContext.Current.Response.ContentType = "application / vnd.ms-excel";
HttpContext.Current.Response.AddHeader ("content-disposition", "attachment; filename = ResponsesPerformance" + date + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.End ();

I have already changed the contentType and the extension in the header, but it has not worked.

Is the error in the format or in the way I export?

asp.net mvc 5 – How to set the domain service setting?

I'm new to the code review, I have an ASP.net MVC5 project that includes several domain services, and one of them is Email services the e-mail will be sent when the entity is updated.

public class project {
string ProjectType {get; to adjust;}
String Name {get; to adjust;}
}

public interface IProjectService {
Event invalid EventHandler updated;
}

public interface IEmailLogRepository {
void Insert (EmailLog obj);
}


public class EmailService {

private read-only IEmailLogRepository _repos;

public string SmtpServer {get; set;}
public string SmtpPort {get; set;}
public string SmtpSender {get; set;}
public string SmtpUsername {get; set;}
public string SmtpPassword {get; set;}
......

public string TemplateASubjectFormat {get; set;}
public string TemplateBSubjectFormat {get; set;}
public string TemplateAContentFormat {get; set;}
public string TemplateBContentFormat {get; set;}

public EmailService (IProjectService service, repos for IEmailLogRepository) {
service.Updated + = OnProjectUpdated;
_repos = repos;
}

private void OnProjectUpdated (object sender, ProjectEventArgs arguments) {
if (args.Entity.ProjectType == "A") SendEmailWithTemplateA (args.Entity);
if (args.Entity.ProjectType == "B") SendEmailWithTemplateB (args.Entity);
}

private void SendEmailWithTemplateA (project obj) {
MailMessage mail = new MailMessage ();
mail.Suject = string.Format (TemplateASubjectFormat, obj.Name);
mail.Content = string.Format (TemplateAccentFormat, obj.Name);
......
SendEmail (mail);
}

private void SendEmailWithTemplateB (Project obj) {
MailMessage mail = new MailMessage ();
mail.Suject = string.Format (TemplateBSubjectFormat, obj.Name);
mail.Content = string.Format (TemplateBContentFormat, obj.Name);
......
SendEmail (mail);
}

private void SendEmail (MailMessage Mail) {

EmailLog Log = new EmailLog ();
log.Email = mail.ToAddress;

To attempt{
SmtpClient smtp = new SmtpClient ();
........
smtp.Send (mail);
log.Status = "Success";
_repos.Insert (log);
} catch (exception ex) {
log.Status = string.Format ("Error: {0}", ex.Message);
_repos.Insert (log);
}
}
}

public class ProjectController: Controller
{
private read-only IProjectService _service;
private Readonly EmailService _emailService;

public ProjectController (IDbConnection connection, IProjectService service, IEmailLogRepository emailRepos) {
_service = service;
_emailService = new email service (_service, emailRepos);
dictionary settings = Settings.Load (connection);
_emailService.SmtpServer = Settings["SmtpServer"];
........
_emailService.TemplateASubjectFormat = Settings["TemplateASubjectFormat"];
_emailService.TemplateAContentFormat = Settings["TemplateAContentFormat"];
_emailService.TemplateBSubjectFormat = Settings["TemplateBSubjectFormat"];
_emailService.TemplateBContentFormat = Settings["TemplateBContentFormat"];
........
}
}

In the above code is the Email services contains many settings like SMTP and template information for different project types, these settings are currently in the database (a settings table that stores all settings for different services), and the service properties are assigned in the ASP.net controller constructor.

This type of property assignment has resulted in the constructor containing many lines. Some controllers may require more than one service. Every service in my projects is designed this way. I think it's not a good design. So I can test what the best practice for assigning settings values ​​for assigning settings is?

Many Thanks.

asp.net web api – recovers a value from a web app with Cypress

I'm doing some tests with cypres to the next method of a web api.

[HttpPost]
        [Route("authenticate")]
        
        
        
        authenticate public test response (test test)
{
Test Response test Test Response = new test response ();
testResponse.value = "error";

// TODO: Check credentials Correctly, this code is only for the demo !!
bool isCredentialValid = (test.cadena1 == "123456");
if (isCredentialValid)
{
testResponse.value = test.chain2;
}

Return answer Answer;
}

The class of return is

public class TestAnswer
{
public string value;
}

The question is, I'm making the next call in Cypress

cy.request ({
Method: "POST",
URL: & # 39; http: // localhost: 93 / swagger / ui / index #! / Test / Test_Authenticate & # 39 ;,
Body: {
"string1": "123456",
"string2": "worked"
}
}). then ((answer) => {
// we see that you have the answer)

                                // Weather
cy.log (answer.duration)
cy.log (answer.status)

})

I noticed that neither in the answer nor in the text something points to "value", nor does the string "work" work.

the web api works fine (i get it back when i make a normal http call)

Can you help me please?

Many Thanks

Hide form model data in subsequent RazorPage navigation systems ASP.Net Core

I have a RazorPage with a form that takes on a complex data model.
It has these properties:
recipient address
EmpfängerZip
Delivery city

The page should be shared with an employee. That is, I share with you a link that contains a GUID to fill out your address for a collaboration tool.

The problem is that if the associate navigates to the page after the employee completes the page, the subscriber can see the information entered by the employee. So if I share the page with you, fill it out and navigate back to it. I can see your address, city and zip code.

Not very user friendly, since we are strangers.
Are there any simple techniques for hiding model data in sequence navigation with asp.net core and asp.net core mvc on a razor page?

Many Thanks!

SQL Server – How do I go about removing ASP.NET users whose UserID is bound to records that should be retained even after deleting a user?

I have a website that uses ASP.NET membership, so there are several "aspnet_" tables in our database.

We create a service for the users that allows them to essentially create laboratory testing jobs for an employer. An employer can have multiple users who can order tests.

If someone actually loses access to the service (he or she will be dismissed, terminated, retired, or revoked his / her privileges by his employer), the lab test orders he has created should remain in the system and the user should provide the username. In this way, when a list of all lab orders is displayed, someone knows which user ordered which test for whom.

When a user loses access, we physically remove his user record from the aspnet_users table and the aspnet_membership table. This removes username, email address, profile, password, and so on. This is not possible when creating a relationship between the aspnet_users table and the table containing the lab jobs. When we do this, we either have to:

  • Cascade deletion (deleting user-created jobs)
  • Set the value in the table containing the lab orders to either "NULL" or to a default value. When we do that, we lose all of the user's information, such as the username, etc. that we want to keep.

If we choose a soft-delete approach and mark only one user as unlogged in (unapproved), but keep the user in the aspnet_users and aspnet_membership tables, there is a problem that may occur I can not see that? Security problems? Performance problems?

In general, I think it is wrong to leave user data in a system if the user can not access the system. It leaves a bad taste in my mouth.

What is the best way to store such data that must be retained even if the parent record is removed? Should I not use a relationship and simply copy the user data to another table? If I do that, there is the potential for inconsistent data, and updates would be difficult. I can easily see that it becomes a monster that can not be sustained. There is also the possibility of conflicts when a user name is reused in the future.

Any advice would be very welcome.

asp.net – Testing the .Net Core Identity GetUserAsync

With .NET Core 2.2 I try to test a Razor page with Identity Framework, which starts like this

var user = await _userManager.GetUserAsync (user);

There are many solutions online that can be summarized by this generic class: setting up the UserManager on an IUserStore mock and setting up the user in the PageContext.

public class SetupContext where T: IdentityUser, New()
{
public mock <IUserRoleStore> MockUserStore {get; private set; }

public user manager SetupUserManager ()
{
MockUserStore = new mock <IUserStore> (). As <IUserRoleStore> ();
MockUserStore.Setup (x => x.FindByIdAsync (It.IsAny.)(), It.IsAny())). ReturnsAsync (
(String-ID, CancellationToken-Token) => new T ()
{
Id = Guid.Parse (id),
UserName = "username"
});
Return a new UserManager(MockUserStore.Object, zero, zero, zero, zero, zero, zero, zero, zero);
}

public PageContext SetupPageContext ()
{
var displayName = "username";
var identity = new GenericIdentity (displayName);
Var principle = new ClaimsPrincipal (identity);
var httpContext = new DefaultHttpContext ()
{
User = principle
};
var modelState = new ModelStateDictionary ();
var actionContext = new ActionContext (httpContext, new RouteData (), new PageActionDescriptor (), modelState);
var modelMetadataProvider = new EmptyModelMetadataProvider ();
var viewData = new ViewDataDictionary (modelMetadataProvider, modelState);
var pageContext = new PageContext (actionContext)
{
ViewData = ViewData
};
return pageContext;
}
}

The problem is that this does not work. GetUserAsync calls GetUserId calling

principal.FindFirstValue (Options.ClaimsIdentity.UserIdClaimType)

This claim is not established, in fact, no ID is set up at any point, so neither the user nor the user ID can be returned. Then I want to later access database data belonging to UserId to test.

I searched for a long time and did not find the solution. I seem to be 90% there, but what else do I need to set up the test properly?

The test I'm going to do is set up that way

private async task SetupModelAsync ()
{
_db = new RemoteHealingTechDbContext (InMemoryDbContextGetTestDbOptions ());
Wait SeedData.Initialize (_db);
var _setup = new SetupContext();
var userManager = _setup.SetupUserManager ();
var pageContext = _setup.SetupPageContext ();
return new FreeTrialModel (_db, userManager)
{
PageContext = pageContext
};
}

asp.net mvc – Do I use the asynchronous task correctly?

Hello,

I am doing an ASP.NET MVC project and wanted to use an asynchronous task.
In my repository I have:

public async task GerarItems (int code)
{
using (var dbTran = dbContext.Database.BeginTransaction ())
{
try it
{
>> VARIOUS SELECTs, UPDATES, INSERTs <<
dbTran.Commit;
Expect Task.FromResult(zero);
}
catch (exception)
{
dbTran.Rollback ();
throw
}
}
}

In my controller I have:

private async task generator items (int code)
{
RepoExample repo = new RepoExample ();
Expect Repo.GerarItems (code);
}

public async task Listing (Int-Code)
{
try it
{
RepoExample repo = new RepoExample ();

Expect GeneratorItems (code);

return view (repo.List (code));
}
catch (exception ex)
{
return view ("Error", ex.Message);
}
}

Show forum posts

  1. Can I use that? dbtran within a asynchronous task?
  2. If I use that waiting? In my Gera Ritens from repositoryI would use in all my Choose, Appearances, updates?

    2a. For example, if I have to do one choose after one insertonly in this insert I pocketed waitingI have the right result in mine choose?

    2 B. What I understood about this topic (very well spoken), that waiting makes
    the task in the background, so in my example, if the insert
    take your time, my choose does not work with the
    Information that this insert would generate, right?

  3. What return options do I have for a method? TASK? I have the Expect Task.FromResult(zero); because I did not know what to put …

  4. public async task listingIs it right to use this for what I am trying to do?
  5. How do you pass data with ASP.NET Core to a partial view?

    Disclaimer: I'm new to ASP.NET Core, but have read a lot and tried.

    I'm trying to implement my first partial view and submit data to it. From what I've read, this should work, so I'm confused as to where things are heading south.

    My partial view:

                    @Page
    @model int
    @ *
    
    * @
       

    @Model

    My call for partial view:

    @ Html.Partial ("_ ProductCreate", 0);
    

    The C # code for _ProductCreate is the default:

    public class _ProductCreateModel: PageModel
    {
    public void OnGet ()
    {
    
    }
    }
    

    @Model is always zero. In particular, I get the following error:

    NullReferenceException: The object reference was not set to an instance of an object. aspnetcoreapp.Pages.Customers.Pages_Customers__ProductCreate.get_Model ()
    

    How do I get the result of a selection in ASP.NET?

    I have a view that when selected in a as follows:

    @ Html.DropDownListFor (m => m.listClasses, new SelectList (Model.ListClass, "IdClass", "Class"), new {@class = "input form control input-lg", @required = "required"), @style = "height: 40px; font size: 16px"})
    

    I have to get in the same view and without Javascript the value selected to paint the other one.

    I tried to create a hidden field @ Html.HiddenFor and assign the value to the event onChange with something similar to this question, but I did not make it

    How can I get that? IdClase without using javascript and reflecting directly in the html?

    asp.net – The IIS operation aborted by the client logs response code 0 instead of 500 after request header logging

    We have REST-based Web API services hosted on IIS 8.5. The standard logging is the W3C format. The client can cancel the current request and it is logged with status code 500.

    If request headers logging is enabled to capture a request header in the IIS log, the application uses a custom header: Logging -> Log File Format -> Select Fields -> Custom Fields -> Add Field
    Field name: XView
    Source Type: Request Header
    Source: XView (custom request header)

    After this change, the logged IIS log response code is 0 (instead of 500) when the client aborts the operation.

    Fields: Date Time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs (user-agent) cs (referer) sc-status sc-substatus sc-win32-status sc bytes cs bytes time spent
    2019-03-28 08:30:24 10.91.1.183 GET / api / MyTestUri filter = SampleNumber: -2 & itemsPerPage = 25 & pageNumber = 1 65435 UserId 10.91.2.14 – – 500 0 64 0 943 6968

    Fields: Date Time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs (user-agent) cs (referer) sc-status sc-substatus sc-win32-status sc-bytes cs-bytes TimeView XView
    2019-03-28 09:33:26 10.91.1.183 GET / api / MyTestUri filter = SampleNumber: -2 & itemsPerPage = 25 & pageNumber = 1 65435 UserId 10.91.2.14 – – 0 0 64 0 943 6874 –

    The event log still has an exception type: OperationCanceledException as before and the requested request trace in IIS displays the response code as 500 (final status).

    Other threads have discussed when state 0 may occur, e.g. https://stackoverflow.com/q/3825581/987191, but not this specific scenario.

    We need custom headers to be logged to add more context to the IIS log. However, we would like the 500 status to continue to be logged so that we can respond to other errors, such as: This change in behavior due to logging the request headers causes noise in the logs. I could not find enough documentation why the response code is changed. However, if someone has information, this is appreciated.

    Proxy Sites Proxy Tunnels Proxy List Working Proxy Sites Hotproxysite Proxy Sites Proxy Sites Anonymous Proxy Anonymous Proxies Top-Proxies.co.uk http://www.proxysitesnow.com Proxy Servers Free Proxies Free Proxy List Proxy List Zoxy Proxy List PR liste all proxy sites More Proxies netgofree netgofree Hide-MyIp - The Best Proxy List American Proxy List www.proxylisty.com/proxylist Web Proxy Submit Proxies Updated Proxy List Updated Proxy List aproxy.org Bypass Proxy Sites Free Proxies List Evolving Critic Business Web Directory Free Proxy List iShortIt MyProxyList Online Proxies Go Proxies Need Proxies PrivateProxies Proxies4MySchool Proxies4Work Free Proxy List Free Proxy Sites ProxyInside Wiksa Proxy ProxyLister.org Free Proxy List ProxyNoid Proxy List Free Proxy List Proxy Sites Proxy TopList ProxyVille UK Proxy WebProxy List RatedProxy.com - Listing the best Web Proxies Free Proxy List SchoolProxiesList Stay Anonymous Proxy List The Power Of Ninja Proxy List UNubstruct Free proxy sites Free proxy sites