Our app has the <machineKey> set in the web.config:

<machineKey validation="HMACSHA256" validationKey="some-validationkey" decryption="AES" decryptionKey="some-decryption-key" />

It is used to encrypt/decrypt many things built into ASP.NET including:

  • Forms authentication tickets
  • Anonymous identification module tickets
  • Anti-forgery tokens (in ASP.NET MVC)

If the machine key is compromised, it means an attacker could decrypt all of these things. A security best-practice is to rotate your keys often (or at least when you think it might be compromised). This would require the ability to version each piece of encrypted data so that rotation is possible when needed.

If you change the machine key and re-deploy your site, your existing users that have encrypted data (e.g. cookies, form fields) will most likely trigger exceptions on their next request because the data can no longer be decrypted. For example, the AnonymousIdentificationModule will throw a CryptographicException: Error occurred during a cryptographic operation.. This makes complete sense if the AnonymousIdentificationModule doesn't have the ability to version encryption/decryption.

One method I was thinking of using is implementing custom HashAlgorithm and SymmetricAlgorithm with versioning built-in to delegate to real algorithms. For example:

  1. Registering them with CryptoConfig.AddAlgorithm():

    CryptoConfig.AddAlgorithm(typeof(MyCustomHashAlgorithm), "MyCustomHashAlgorithm");
    CryptoConfig.AddAlgorithm(typeof(MyCustomSymmetricAlgorithm), "MyCustomSymmetricAlgorithm");
  2. Change the <machineKey> to use the custom algorithm:

    <machineKey validation="alg:MyCustomHashAlgorithm" validationKey="some-validationkey" decryption="alg:MyCustom" decryptionKey="some-decryption-key" />

However, I'm concerned about implementing the HashAlgorithm and SymmetricAlgorithm. I do not want to accidentally introducing security holes, and this is an easy place to do this. Also, this feels like a huge hack since it really belongs at the place that uses the algorithm (I think).

Another approach is re-implementing all of the functionality that uses the machine key but add versioning. It's not possible to change the existing .NET classes.

How do you handle this problem in production? I know StackOverflow is written in ASP.NET MVC, so how do they handle it?

Side note: For security reasons, we don't actually store the <machineKey> in the web.config directly (it is outside of source control).

i'm a newbie in ASP.NET programming and I am facing a strange situation. I have an ASP page with a table containing always different rows, dinamically loaded from a MSSQL DB. In each row of the table I have created a Button, called Details, that is dynamically created during the writing of the table. This Details button is added with the following code:

Button detailsButton = new Button();
detailsButton.Height = new Unit("18px");
detailsButton.Width = new Unit("65px");
detailsButton.Text = "Details";
detailsButton.ID = row.ItemArray[0].ToString();

detailsButton.PostBackUrl = "~\\DetailsPage.aspx?selectedSignalling=" +  detailsButton.ID;
//detailsButton.Click += detailsAgencyButton_Click;
//detailsButton.OnClientClick = "return true;";


The intention is to redirect the client towards the Postback URL when one button is pressed on a row. The Postback URL is dinamically created for each button, associating to each of them the ID of the item that the user would choose to display the details.

While this works fine on the my development environment, that is running IIS 7.5, this is not always working on the production environment, that runs IIS 6.0 and that cannot be updated. On IIS 6.0, some clients does not notice any problem, while others are not able to display the details page, but, when clicking on the Details button, the postback URL is not loaded and instead there is only the reload of the current page. I have tried to change many settings (set the detailsButton.Click, set the OnClientClick to "return true;"), but without luck. I have only noticed that adding the: detailsButton.OnClientClick = "return true;"; instruction, the redirect does not work in IIS 7.5 too. So it seems to me that when OnClientClick returns something (true/false), the PostBack is not activated, while some of the clients probably does not return any OnClientClick and the PostBack is activated. Can someone help me with this matter? Thanks in advance and sorry for my poor english, this is the first time for me here on StackOverflow and with programming challenges.

I have the following method in my Web Api controller:


// GET: api/Templates
public async Task<IActionResult> GetTemplate()
    ApplicationUser currentUser = await _userManager.GetUserAsync(HttpContext.User);
    IQueryable<Template> templates = from template in _context.Template
        where template.User.Id == currentUser.Id
        select template;

    return Ok(templates);

Which causes Chrome to throw an error ERR_INCOMPLETE_CHUNKED_ENCODING.

When I take out the WHERE clause, however, it works fine:

// GET: api/Templates
public async Task<IActionResult> GetTemplate()
    IQueryable<Template> templates = from template in _context.Template
        select template;

    return Ok(templates);

The ERR_INCOMPLETE_CHUNKED_ENCODING does not occur in Firefox or Edge, but the data fetch still fails silently.

What does it mean that HandleErrorAttribute filter handles MVC errors and Application_Error in Global.asax handles all ASP.NET errors. Can you give examples of what errors does Application_Error catch in addition to MVC errors?

I have a middleware on my asp.net core application and I am trying to acccess the user identity/user name through httpContext class but, the value is always empty.

   public async Task Invoke(HttpContext httpContext)

How to get the current user identity inside the middleware

I have an ASPX page that I've built that displays results from a sql pull in a gridview when you click the refresh button. Currently everything (including the button) are inside the updatepanel. I run UpdateProgress to show a loading wheel before the results populate. I use an AsyncPostBackTrigger so that only the updatepanel refreshes and not the entire page. All of this works great!

The problem is this... The button only works on the first click! Any subsequent clicks, the program is not aware of. I know this becasue I've added in the messagebox (windows.system.forms has been added to project) to show something on second click and that never pops up. Ideally i'll want to clear the datagrid and repopulate the gridview with new data but when I recognized the button stopped working this is how I began troubleshooting.

Below is the ASPX Page Code.

    <asp:ScriptManager EnablePartialRendering="true" ID="ScriptManager1" runat="server" AsyncPostBackTimeout="400" ></asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" ChildrenAsTriggers="true" runat="server" UpdateMode="Conditional">

            <asp:Button ID="btnRefreshAlerts" runat="server" OnClick="btnRefreshAlerts_Click" Text="Pull/Refresh" Width="84px" Visible="True" UseSubmitBehavior="False"/>

        <asp:GridView ID="GridView1" AllowSorting="false" BackColor="White" BorderColor="Black" Font-Names="Calibri" Font-Size="Small" ForeColor="Black" runat="server">
            <RowStyle BackColor="#F0F0F0" BorderColor="#666666" />

     <asp:AsyncPostBackTrigger ControlID="btnRefreshAlerts" EventName="Click" />

    <asp:UpdateProgress ID="updateProgress" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
        <div id="progressBackgroundFilter"><div style="text-align:center">
        <div id="processMessage"><div style="text-align:center">
            Loading...<br />
            <br />
            <img alt="Loading" src="images/ajax-loader.gif" />


Here is the CS Code Behind File

protected void btnRefreshAlerts_Click(object sender, EventArgs e)

if (counter == 0)

        Fill_DataGrid(sender, e);
    //I don't even want this to happen in the final product - i'll want to instead clear the gridview and repull/populate the gridview with new data
    MessageBox.Show("I recognize this is second press");


I run a query and increment the counter by one like this... (also the counter is initialized as 0 somewhere up the Code behind file and well before the Fill_DataGrid operation)

    protected void Fill_DataGrid(object sender, EventArgs e)

    //Load ALERTS into Datatable and then into data grid
    using (SqlConnection openCon = new SqlConnection("CONNECTIONSTRING"))
        using (SqlCommand PullData = new SqlCommand())

            PullData.Connection = openCon;
            PullData.CommandText = "CRAZYQUERY";
            PullData.CommandTimeout = 300000;


        GridView1.DataSource = AlertGrid;
        counter = counter + 1;



I'm creating WebPart for SP using c#, I create controls on the page at run-time depending on users query.

My problem as following:

User A: Access the page run query Z then buttonA gets created.

User B: Accessed the same page at the same time that userA finished his Zquery he will find that buttonA created and he will be in the same stage that UserA was.

The Q is how i can make client sessions for each code executed at server side ?

Plus... I'm using Session such Session["_PostStat"] = 0; this will run with each query executed to remember users stage.


I'm totally new & basic user in C#.

I need to be able to call @Html.Partial() without knowing at design time what the partial file will be. I'd like to do something like...

In the Controller:

string partial;
switch (some_val) {
    case 1:
        partial = "help.cshtml";

    case 2:
        partial = "legal.cshtml";

    // Other cases here...

        partial = "default.cshtml";

ViewBag.partial = partial;

And in the View:

@Render.Partial (@ViewBag.partial)


@Render.Partial ("@ViewBag.partial")

Note, there is no Model.

Is this possible?

Thanks, Jeff

I have a model like

public class A {
   // Properties - some of them are required some optional
   // Optional
   public class ICollection<B> Items { get; set; }
public class B {
    public string A {get;set;} // Required

To use the Html.EditoFor(o => o.Items[0]) I must add an empty object to Items and as such this object is sent to the server causing ModelState.IsValid to be false (if the user didn't choose to add any Bs.

How is the proper way of handling this? What would be an option is to create an [Optional] attribute for collections that could inspect the list and check if it contains just one object and if that object is the default object, then skip it.

The Items property is filled on client side by calling the controller that renders the partial view (Html.EditoFor(o => o.Items[0])) and then some more js-fiddle to ensure all indexs are correct.


This question already has an answer here:

I'm trying to create a custom validation rule which will check to see if Times overlap in any case, to do this I have the following:

public class TimesheetLogicAttribute : ValidationAttribute

    public TimesheetLogicAttribute()
        //this.jobRecords = jobRecords;

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        var records = value as List<TimesheetJobRec>;

        records = records.OrderBy(r => r.StartTime).ToList();
        DateTime? current = null;

        foreach(var record in records)
            if (record.StartTime > record.FinishTime)
                return new ValidationResult("Finish time is before start time on " + record?.JobNumber);

            if (current == null)
                current = record.FinishTime;

            if(record.StartTime < current)
                return new ValidationResult("Time overlapping");
            current = record.FinishTime;

        return ValidationResult.Success;

        //return base.IsValid(value, validationContext);


My corresponding model is:

public class TimesheetJobRec : ModelsBase
    // Job number stuff needs to go in here.
    public string JobNumber { get; set; }
    public Timesheet Timesheet { get; set; }

    public string WorkDescription { get; set; }

    public DateTime StartTime { get; set; }

    public DateTime FinishTime { get; set; }

    public double LunchTime { get; set; }

    [Range(0.25, 24)]
    public double Total { get; set; }


Then I decorate my view model like this:

  [Display(Name = "Job Records")]
  public IList<TimesheetJobRec> JobRecords { get; set; }

This all works fine and in my validation I receive my item list correctly, the problem occurs when returning a ValidationResult I get the following error on the ASP side of things:

Object reference not set to an instance of an object.

Line 43:                         <th>Total</th>
Line 44:                     </tr>
Line 45:                     @foreach (var item in Model.JobRecords)
Line 46:                     {
Line 47:                         Html.RenderPartial("_JobEditorRow", item);

On Line 45 the error is thrown, in that foreach in my View I am just rendering existing items. I'm not sure what the cause for this is and whether I'm doing validation correctly or not.

I'm trying to Redirect from view to action using Razor without clicking. Sometimes an error occurs when the page is loading.

I made a try and catch block to redirect.


    var x = Session["Username"];

        if (x.ToString().Equals(item.User.UserName))
                @Html.ActionLink("تعديل", "Edit", new { id = item.NotificationID }) |
                @Html.ActionLink("التفاصيل", "Details", new { id = item.NotificationID }) |
                @Html.ActionLink("حذف", "Delete", new { id = item.NotificationID })    
    catch (Exception e)
        //I want to redirect to an action, not view.


Home Controller:

[AuthorizeUserAccessLevel(UserRole = "Manager,Reviewer")]
public class HomeController : Controller

    TheUnitOfEnternalAuditEntities db = new TheUnitOfEnternalAuditEntities();

    public ActionResult Index()
        var username = User.Identity.Name;
        username = username.Replace("NCA\\", "");

        User user = db.Users.Where(u => u.UserName.Equals(username)).First();

        Session["UserName"] = username;
        Session["UserID"] = user.UserID;
        Session["UserFirstName"] = user.FirstName;
        Session["UserFullName"] = user.FullName;
        Session["UserRole"] = user.Role.RoleID;

        var Departments = db.Departments.ToList();

        ViewBag.Departments = Departments;

        return View(db.Departments.ToList());

Any Suggestions?

Hello I am creating web app using .NET MVC with jquery, bootstrap and I have bind the some data inside the table and want to read those data now.

How can I read those data using jquery or javascript to create xml format of data.

Example: enter image description here

I want to read all the information provided in table i.e. first column text, second column selected value from dropdownlist, third entered value in textbox.

In this google play developer console not able to link Google API

 "error": {
  "errors": [
    "domain": "androidpublisher",
    "reason": "projectNotLinked",
    "message": "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console."
  "code": 403,
  "message": "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console."

This question already has an answer here:

how to upload an image from your computer to the server in the CONTENT folder with by pressing button. I have next code on Page.

ViewBag.Title = "Test";
Layout = "~/Views/Shared/_Layout.cshtml";}

<div class="starter"> 
      <p>It is a test page !!!!!!;)</p>
     <input type="submit" value="Upload img" />

I am new to .NET Platform, I am from J2EE background.I don't have problem in reading the code. However i am not quite familiar with the Runtime environment

Task provided to me:

I need to migrate an ASP.NET C# website from IIS 6.0 to IIS 8.5.

My Actions so far:

  1. Published the website using Visual studio 2010
  2. The website uses Oracle database hence i have installed Oracle client and configured the database in tnsnames.ora
  3. Added the published website to the IIS 8.5 server using "add website" option and started the website

Environment details:

  1. TO-BE Runtime: IIS 8.5 , Microsoft Windows Server 2012R2
  2. AS-IS Runtime : IIS 6.0 , Oracle database is being used by the website.

Problem: The default webpage is getting loaded, however when i click a button, i noticed the following exception in windows events

    Exception information: 
    Exception type: NullReferenceException 
    Exception message: Object reference not set to an instance of an object. 

Request information: 
    Request URL: 
    Request path: /Profile.aspx 
    User host address: 
    Is authenticated: False 
    Authentication Type:  
    Thread account name: IIS APPPOOL\.NET v2.0 

Thread information: 
    Thread ID: 14 
    Thread account name: IIS APPPOOL\.NET v2.0 
    Is impersonating: False 
    Stack trace:    at Code_Profile.btnGetCustDet_Click(Object sender, EventArgs e)
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Exception related code

ASP.net page with Button click action

<asp:Button ID="btnGetCustDet" runat="server" OnClick="btnGetCustDet_Click" Text="Get Details" Width="111px" />

C# function handling that event.

protected void btnGetCustDet_Click(object sender, EventArgs e)
        txtBoxCustNameE.Text = "Button click entry";

Couldn't locate exactly where this exception is getting triggered. as per exception trace, at Code_Profile.btnGetCustDet_Click(Object sender, EventArgs e) But even the first line of btnGetCustDet_Click is not getting executed. So i am stuck here

Please advise , i suspect some migration issue. Please let me know if there is any standard procedure to perform and validate this migration

I have a classified website designed by using asp.net In there users can post ads and also they add 5 images to ad. I used file upload control and everything working fine.

When I save it I save them to two folders.

1) Full image

2) Thumbnail image

So when somebody viewing an ad he will see the big image and at below he will see other images which are related to the ad ( Thumbnails )

I did this to reduce the page loading time+bandwidth. So if user need to see the full image he has to click the thumbnail.

Here I attach a preview enter image description here

So this is the html code of thumbnail image

<img src='/Images/Thumbnail/{0}' data-url='/Images/Full/{0}' id='{0}' onclick='loadFullImage(this)'/>

This is the script that setting the full image path when somebody click on a thumbnail

    <script type="text/javascript">
    function loadFullImage(ctrl) {
        var url = ctrl.getAttribute("data-url");
        var imgFull = document.getElementById("imgFull");
        imgFull.src = url;


Hope now you understand what is happening. This is working fine.

Now the problem is ( actually I need a tweak) When someone click on the thumbnail it will take a while to load the image. Its not an error. Its the loading time. So i want to display an progress image until it fully loaded. How to do that? or is there a way to reduce that delay?

Please note that when somebody click on the thumbnail image there is no postback event occurring at server side. Only it will look for that full image folder.

So I want to keep a list in memory, with a get and post method.

All users must be able to post and read from the same list. I've looked into


for a controller, but it only keeps the same list in memory for a single user.

So how can I implement a List which is accessible by all users?

My project is WebAPI, so it must be easily accesible by Rest.

I need the small help. I have written the File watcher function in c#. The requirement is that It should be continous in Loop. I have stored the different Files location in database. That is read from database and details stored in List object _fileLocationList.

When I execute its after one Loop I am getting Out Of Memory Exception" and application crash.

I have also tried the WHILE loop instead of GOTO:

Code :

protected List<FileLocation> _fileLocationList = new List<FileLocation>();
   _fileLocationList == GetFileLocation();

 public void StartFileWatchers()
                Start :
                        logger.Log(LOG_TYPE.LOG_TYPE_FILE, "** Inside StartFileWatchers() Starting file watchers for each filelocation **");
                        foreach (FileLocation fileLocation in _fileLocationList)
                                Start(_cancelToken, DefaultFileDownloadInterval, fileLocation);
                            catch (Exception ex)
                                logger.Log(LOG_TYPE.LOG_TYPE_FILE, "Error inside Foreach Loop StartFileWatchers() " + ex);
                                logger.Log(LOG_TYPE.LOG_TYPE_FILE, "Clear Memory inside finally ");
                                IDisposable disposable = _fileLocationList as System.IDisposable;
                                if (disposable != null) disposable.Dispose();
                        logger.Log(LOG_TYPE.LOG_TYPE_FILE, "Loop end ");
                goto Start;
            catch (Exception ex)
                logger.Log(LOG_TYPE.LOG_TYPE_DATABASE, "Error inside StartFileWatchers " + ex, TYPE_MESSAGE.UNKNOWN_ERROR);

Error :

UNKNOWN_ERROR Message : Unable to update process entry so initiating shutdown : System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.Threading.Thread.StartInternal(IPrincipal principal, StackCrawlMark& stackMark)

I would like to Iterate the LIST in infinite order (Run from start after end by foreach() or other way.).

My IIS / Apppool are behaving very weird. They keep recycling for almost every minute or even less. I suppose there is a memory leak somewhere.

The private byte: 137.756,00 (137 MB) Virtual byte: 9.394.648,00 (9.39 GB????)

I only run about 2 websites. This is definitely not normal.

How can I fix this? Do I need to reinstall? I have tried to defrag my PC, but it did not help. I suppose that was because the memories are still being pointed by the application.

I tried to delete all my websites then deployed my application again, but it was not helping.

I remember that I force quit the "W something" process which was downloading some files from external source (trusted source). My web application was downloading through that "W something process" (I cant remember the name).

I force quit about 4-5 times, then this happens. What should I do to fix this?

I have read many reference for this question but not getting result. So, I thought let me try to explain my scienario here.

This is my 3 script which is in view.ascx control. I want to call it in .cs file function and in click event.


<script type="text/javascript">
function startLoading() {
    alert("load start");
    var el = jQuery(".scp-entry-header");

function stopLoading() {
    alert("load end");
    var el = jQuery(".scp-entry-header");

function getCalendarData() {


//ViewData button click
protected void btnGetData_Click(object sender, EventArgs e)
    //How to call startLoading function here?
    process from database;
    //How to call stopLoading function here?

//simple function call
protected void showCalendar()
    //How to call getCalendarData function here?

I have read about RegisterScript but not getting result. I don't understand where to RegisterScript and how to call it in function.

Can anybody please suggest me in detail how can I call javascript function here?

I have a gridview bind using IQueryable which I made it able to insert, update and delete. Both delete and insert is working fine but I can't update. I clicked edit and entered the values I want to update, once is done. I clicked update button. There is no response and change to the gridview but when I clicked cancel, the value got updated. Any idea how to solve this problem?

This is how it looked: Edit selected After valued entered, clicked update. No response. Have to click cancel to see the changes

Thank you!