In our asp.net MVC application, we allow users to select preferred language and save them in database. Thus browser language settings are ignored.

If this setting needs to be read on every HTTP request, what is the best way to store it for a user session from performance/maintenance point of view? I mean whether it would be a good practice to store it in regular asp.net session or cookie. Is there any reason to avoid sessions? What are good options in this situation?

Thank you.

Murtaza

i'm having issues with one of the pages on my site where i'm using a cookie value to pull some data out of my DB. It's working fine for my strings, but having issues with my int's and dates.

I start by declaring blank variables:

int numAdults;

I then check to see if a cookie is set, and if it is, i perform a database query (numAdults is data type int in the DB):

if(Request.Cookies["BookingReq"] != null){
    var breq = db.QuerySingle("SELECT * FROM BookingRequests WHERE BookingGUID = @0", Request.Cookies["BookingReq"].Value);  
    numAdults = int.Parse(breq.NumAdults);        
}

The, in my form, i want to show as empty if the cookie isn't set, or show the "selected" option if it is:

<select class="form-control" id="numAdults" name="numAdults" @Validation.For("numAdults")>
    <option>Choose</option>
    <option value="0" selected="@(int.Parse(numAdults) == 0)">0</option>
    <option value="1" selected="@(int.Parse(numAdults) == 1)">1</option>
    <option value="2" selected="@(int.Parse(numAdults) == 2)">2</option>
    <option value="3" selected="@(int.Parse(numAdults) == 3)">3</option>
    <option value="4" selected="@(int.Parse(numAdults) == 4)">4</option>
</select>

This, however, leaves me with the following error when i run the page:

<option value="0" selected="@(numAdults == 0)">0</option>
Operator '==' cannot be applied to operands of type 'string' and 'int'

Thanks, Gavin

We are working on ASP.NET MVC 6 project and it's necessary to render Razor views from other than file system source (Azure Blob storage in particular but it's not important). Earlier (in MVC 5) it was possible to create and register custom VirtualPathProvider which can take view content from DB or resource DLLs (for example).

It seems that approach has been changed in MVC 6. Does anybody know where to look for?

I have this code in my project for checking the controller and the action in my .cshtml-file:

@if (ViewContext.RouteData.Values["controller"] == "Home" && ViewContext.RouteData.Values["action"] == "Index")
{
    //Some html
}

When I open the page at the root (http://localhost/), it shows the given html. But when I open it with the full link (http://localhost/Home/Index) it's not showing up.

When put the variables in the html of the webpage, they are exactly the same.

Why isn't this working then?

I have a nav within a unordered list, simplified html is like:

<ul>
    <li><a></a></li>
    <li><a></a></li>
    <li><a></a></li>
    <li><a></a></li>
    etc ...
</ul>

The nav for this module has a dynamic amount of links so how can I change the border of the first and last element with some fancy css selector? i'm terrible with css so apologies in advance :x

I need to add a custom radio button control that I created based on an if condition to my GridView. My radiobutton will be enabled or disabled based on this condition and will have the text changed as well.

I'm trying to figure out how to add a radiobutton object into my data row instead of a string dt.Columns.Add("FirstName").

<telerik:RadGrid runat="server" ID="grd1" OnNeedDataSource="grd1_NeedDataSource"> 
<MasterTableView AutoGenerateColumns="False">
<Columns>
     <telerik:GridTemplateColumn HeaderText="Radiobutton header" UniqueName="col1">
      <ItemTemplate>
       <asp:RadioButton ID="rbType" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "rbEnableorDisable")%>' />
       </ItemTemplate>
       </telerik:GridTemplateColumn>

       <telerik:GridTemplateColumn HeaderText="FirstName header" UniqueName="col2">
       <ItemTemplate>
       <asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "Name")%>' runat="server" />
       </ItemTemplate>
       </telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>

CodeBehind

Private dt As DataTable
Private dr As DataRow

dt= New DataTable
dt.Columns.Add("rbEnableorDisable")
dt.Columns.Add("FirstName")

Dim rb As RadioButton
rb = New RadioButton

For each item in itemlist //some data iteration declared elsewhere
 dr = dt.NewRow()
   If (Condition)
      rb.Text = "Should be Disabled"
      rb.Enabled = False
   Else
      rb.Text = "Should be Enabled"
      rb.Enabled = True
   End if

   dr.Item("FirstName") = item.FirstName
   dr.Item("rbEnableOrDisable") = rb//?Code for inserting a radio button object
   dt.Rows.Add(dr)
Next

    With grd1
        .DataSource = dt
        .DataBind()
    End With

So far with this code I am only able to display the radiobutton text if i have dr.Item("rbEnableOrDisable") = rb.Text.

I need to display the whole radiobutton object(show the text and if it's enabled or disabled among others)

I tried

LocationData.Columns.Add(New DataColumn("rbType", GetType(RadioButton)))

but it seems I need to append to the ItemTemplate

Also tried adding the whole column dynamic with:

grd1.Controls.Add(rb)

Upon clicking btnSearch, it disables it with telerik's SingleClick=true property. If validation fails it doesn't postback and I try to set the button back to being enabled but it doesn't get set. It still is disabled with the text saying "Searching...".

What I am trying to do is if it fails the validation, I want the button to be enabled again. Right now if i click on it and validation fails, it gets stuck being disabled.

javascript

function Validate(button, args) {
     if (error) {
                    button.set_autoPostBack(true);
                }
                else { //validation fails
                    button.set_autoPostBack(false);
                    button.set_enabled(true); // i have currently
                }
    }

aspx

 <telerik:RadButton ID="btnSearch"  Text="Search" SingleClick="true" OnClick="btnSearch_Click" OnClientClicking="Validate" SingleClickText="Searching..." ></telerik:RadButton>

I have two Telerik radListBoxes (source and destination). Both are databound with their DataKeyField and DataTextField values set. When I transfer an item from the source to the destination box using the built in buttons, I can see the value is transferred over, but the datakey is null.

I'm new to these controls, and everything is working well, except for this.

I've been following the steps given in this website: http://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal. I am already on the "Modifying Login Functionality". There seems to be a problem in the SignInManager.When I hover the pointer, it appears "The type or namespace name 'SignInManager' could not be found (are you missing a using directive or an assembly reference?)". Can you help found out why?

using System;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using WebApplication1.Models;

namespace WebApplication1.Account
{
    public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register";
            // Enable this once you have account confirmation enabled for password reset functionality
            //ForgotPasswordHyperLink.NavigateUrl = "Forgot";
            OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
            var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
            }
        }

        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

                // This doen't count login failures towards account lockout
                // To enable password failures to trigger lockout, change to shouldLockout: true
                var result = **signinManager**.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: true);

                switch (result)
                {
                    case SignInStatus.Success:
                        WingtipToys.Logic.ShoppingCartActions usersShoppingCart = new WingtipToys.Logic.ShoppingCartActions();
                        String cartId = usersShoppingCart.GetCartId();
                        usersShoppingCart.MigrateCart(cartId, Email.Text);

                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                        break;
                    case SignInStatus.LockedOut:
                        Response.Redirect("/Account/Lockout");
                        break;
                    case SignInStatus.RequiresVerification:
                        Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                        Request.QueryString["ReturnUrl"],
                                                        RememberMe.Checked),
                                          true);
                        break;
                    case SignInStatus.Failure:
                    default:
                        FailureText.Text = "Invalid login attempt";
                        ErrorMessage.Visible = true;
                        break;
                }
            }
        }
    }
}   

When I check the IdentityConfig.cs, it also shows an error. Not only one but three. The following lines are:

SignInManager base(userManager, authenticationManager) UserManager

The code is below. The lines above are located at the bottom:

using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using WebApplication1.Models;

namespace WebApplication1
{
    public class EmailService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
        }
    }

    public class SmsService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            return Task.FromResult(0);
        }
    }

    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    public class ApplicationSignInManager : **SignInManager<ApplicationUser, string>**

    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
            **base(userManager, authenticationManager)** { }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)**UserManager**);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }
}

While executing the following code in ASP.NET with VB, I am getting the error "No data exists for the row/column."

Dim hdnuserid = e.CommandArgument
    If e.CommandName = "additem" Then

        ' First, see if the product is already in the vendor_catalog table

        Dim dr, dr2, username
        dr = connection.returnsqlresult("SELECT * FROM vendor_users where vendor_id = '" & Request("vendor_id") & "' AND userid = '" & hdnuserid & "'")
        If dr.hasrows() Then
            dr.read()
            Response.Write("<script type=""text/javascript"">alert(""User already assigned to this vendor."");</script>")

        Else
            dr2 = connection.returnsqlresult("SELECT * FROM users WHERE userid = '" & hdnuserid & "'")
            Response.Write(hdnuserid)
            If dr2.hasrows() Then
                dr2.read()
                username = dr("username")
                connection.executesql("INSERT INTO vendor_users(userid, vendor_id, username) VALUES('" & hdnuserid & "','" & Request("vendor_id") & "','" & username & "')")
                'ScriptManager.RegisterStartupScript(Me, GetType(Page), "itemsadded", "window.opener.__doPostBack('__Page', 'populate_usergrid');window.close();", True)
            Else
                Response.Write("<script type=""text/javascript"">alert(""User does not exist."");</script>")

            End If
            dr2.close()
        End If
        dr.close()
    Else

    End If

I have checked that the columns exist in my tables, and also checked the select * from users statement in SQL directly with a hard coded value and I see the result I expect. I'm not sure why I am getting this error. The error is being thrown on the username = dr("username") line.

Any assistance in this would be very helpful.

JV

I started seeing errors in a .Net MVC web app hosted on Appharbor whilst a background thread was running - after careful analysis - I can't work out the cause.

Firstly, the exception I noticed is a ThreadAbortException.

However, this is really just signifying that the thread is being killed. Before the thread is killed, you can see a new worker is created by IIS and Application_Start is called on the same machine. Once the new application is up and running, IIS kills the old app and new requests are handled as expected.

At the same time, IIS logs a message of:

ShutDown Message: IIS configuration change
HostingEnvironment initiated shutdown
HostingEnvironment caused shutdown
ShutDown Stack:    at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal()
   at System.Web.Hosting.HostingEnvironment.InitiateShutdownWithoutDemand()
   at System.Web.Hosting.PipelineRuntime.StopProcessing()

In .Net Health Monitor Logging you get a:

Message: Application is shutting down. Reason: Configuration changed.
Event Detail Code: 50004

A quick google reveals the source code I suspect is the reason for the error:

if (!HostingEnvironment.StopListeningWasCalled && !HostingEnvironment.ShutdownInitiated) {
    // If GL_STOP_LISTENING wasn't triggered, the reset is likely due to a configuration change.
    HttpRuntime.SetShutdownReason(ApplicationShutdownReason.ConfigurationChange, "IIS configuration change");
}

source: https://github.com/Microsoft/referencesource/blob/master/System.Web/Hosting/IPipelineRuntime.cs

My first thought was to check timestamps for file changes, both in the bin folder and the main application directory - however, this error is thrown without any file changes. Given it only happens on Appharbor, I can't attach to the process and debug that way. I've also monitored memory usage, and don't see any issues there.

The source code states:

If GL_STOP_LISTENING wasn't triggered, the reset is likely due to a configuration change.

Hence, what else could be causing the error and application recycle, if the web.config / other config files aren't changing?

I am using an asp TextBox control with its TextChanged event and my goal is to capture text as a user enters it. If there are one or more characters entered, I would like a button control to be enabled without the user having to leave the TextBox control.

My source code for the TextBox on the aspx page is

<asp:TextBox ID="NewSpendingCategoryTextBox" MaxLength="12" runat="server" 
     AutoPostBack="True" 
     OnTextChanged="NewSpendingCategoryTextBox_TextChanged" 
     ViewStateMode="Enabled" >
</asp:TextBox>

and my source code on the code behind page is

Protected Sub NewSpendingCategoryTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles NewSpendingCategoryTextBox.TextChanged
    Dim strSpendingCategoryTextBox As String = Nothing
    strSpendingCategoryTextBox = NewSpendingCategoryTextBox.Text
    If strSpendingCategoryTextBox.Length <= 0 Then
        Me.NewSpendingCategoryInsertButton.Enabled = False
    Else 'strSpendingCategoryTextBox.Length > 0
        Me.NewSpendingCategoryInsertButton.Enabled = True
    End If 'strSpendingCategoryTextBox.Length <= 0
End Sub

Is there a simple way to achieve this goal?

I am trying to catch exception while updating a gridview. code is

public static int UpdateProduct(
                             int productID,
                             string productName,
                             int supplierID,
                             int categoryID,
                             string quantityPerUnit,
                             decimal unitPrice,
                             int unitsInStock,
                             int unitsOnOrder,
                             int reorderLevel,
                             bool discontinued)
    {
        int rowsAffected = 0;

        using (SqlConnection connection = ConnectionManager.GetNorthwindConnection())
        {
              SqlCommand command = new SqlCommand("ttUpdateProduct", connection);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
                command.Parameters.Add("@ProductName", SqlDbType.NVarChar, 40).Value = productName;
                command.Parameters.Add("@SupplierID", SqlDbType.Int).Value = supplierID;
                command.Parameters.Add("@CategoryID", SqlDbType.Int).Value = categoryID;
                command.Parameters.Add("@QuantityPerUnit", SqlDbType.NVarChar, 20).Value = quantityPerUnit;
                command.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = unitPrice;
                command.Parameters.Add("@UnitsInStock", SqlDbType.SmallInt).Value = unitsInStock;
                command.Parameters.Add("@UnitsOnOrder", SqlDbType.SmallInt).Value = unitsOnOrder;
                command.Parameters.Add("@ReorderLevel", SqlDbType.SmallInt).Value = reorderLevel;
                command.Parameters.Add("@Discontinued", SqlDbType.Bit).Value = discontinued;

                rowsAffected = command.ExecuteNonQuery();



        }
        return rowsAffected;
    using (SqlConnection connection = ConnectionManager.GetNorthwindConnection())
        {
              SqlCommand command = new SqlCommand("ttUpdateProduct", connection);
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add("@ProductID", SqlDbType.Int).Value = productID;
                command.Parameters.Add("@ProductName", SqlDbType.NVarChar, 40).Value = productName;
                command.Parameters.Add("@SupplierID", SqlDbType.Int).Value = supplierID;
                command.Parameters.Add("@CategoryID", SqlDbType.Int).Value = categoryID;
                command.Parameters.Add("@QuantityPerUnit", SqlDbType.NVarChar, 20).Value = quantityPerUnit;
                command.Parameters.Add("@UnitPrice", SqlDbType.Money).Value = unitPrice;
                command.Parameters.Add("@UnitsInStock", SqlDbType.SmallInt).Value = unitsInStock;
                command.Parameters.Add("@UnitsOnOrder", SqlDbType.SmallInt).Value = unitsOnOrder;
                command.Parameters.Add("@ReorderLevel", SqlDbType.SmallInt).Value = reorderLevel;
                command.Parameters.Add("@Discontinued", SqlDbType.Bit).Value = discontinued;

                rowsAffected = command.ExecuteNonQuery();



        }
        return rowsAffected;

and code for exception handling is

protected void ProductGridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
    if (e.Exception != null)
    {
        Master.ErrorMessage = "Cannot Update Record";
        e.ExceptionHandled = true;
    }
    else
    {
        Master.ResultMessage = "Record Updated Succesfully";
    }

but still i am getting error :The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Products_Suppliers". The conflict occurred in database "NORTHWIND", table "dbo.Suppliers", column 'SupplierID'. The statement has been terminated. it had worked once ,but not working everytime. And i am also getting Asp.net Validation of viewstate MAC failed error.

I need to add a OnChange event to a HttpHelper DropDownList for retrieve some values and put in the background-color of a divs

view:

<div class="col-md-8">
    <div class="col-xs-6 col-sm-3" id="stylesheet">Hojas de estilos</div>
    <div class="col-xs-6 col-sm-3">
        @Html.DropDownList("cssFiles", (IEnumerable<SelectListItem>)ViewBag.cssFiles, "Crear Nuevo", new { @class = "form-control", @id = "selCssFile", onchange = "cssFileChange()" })
        <span>
            <input type="text" class="form-control" id="txtFileName" name="TxtFileName" style="display:none;" placeholder="Nombre del archivo">
        </span>
    </div>
</div>
<div class="col-md-8">
    Color base, links, botones, borde encabezado y pie
</div>
<div class="col-md-4">
    <div id="colorSelector" class="colorSelector"><div style="background-color: #0000ff"></div></div>
</div>

I am trying to retrieve multiple values of and store in a list. In my Code string value is equal to this data.

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns:x="http://schemas.microsoft.com/office/2008/07/excelservices/rest" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservice" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
  <title type="text">Part_Number</title>
  <id>http://test.net/excel/_vti_bin/ExcelRest.aspx/docs/abc.xlsm/Model/Ranges('Part_Number')</id>
  <updated>2015-04-07T16:23:43Z</updated>
  <author>
    <name />
  </author>
  <link rel="self" href="http://test.net/excel/_vti_bin/ExcelRest.aspx/docs/abc.xlsm/Model/Ranges('Part_Number')?$format=atom" title="Part_Number" />
  <category term="ExcelServices.Range" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <x:range name="Part_Number">
      <x:row>
        <x:c>
          <x:fv>Part Number</x:fv>
        </x:c>
      </x:row>
      <x:row>
        <x:c>
          <x:fv>LBL-61641-000</x:fv>
        </x:c>
      </x:row>
      <x:row>
        <x:c>
          <x:fv>HDW-61277-001</x:fv>
        </x:c>
      </x:row>
    </x:range>
  </content>
</entry>

C# Code

List<string> lirangeName = new List<string>();
string value = GetRangeValue1("abc.xlsm", lirangeName[0]);  //Value contains the above xml value
XmlDocument doc = new XmlDocument();
doc.LoadXml(value);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("x", "http://schemas.microsoft.com/office/2008/07/excelservices/rest");
string answer = doc.SelectSingleNode("//x:fv", nsmgr).InnerXml;

Here, string answer = Part Number. So, I get 1 value but I want a list of values.

Answer I want :
Part Number
LBL-61641-000
HDW-61277-001

Answer I get:.
Part Number

I have a question, we have an ASP.NET web app that can service multiple clients.

The only difference is that the app needs to convert some JSON string into a .NET object of type <T> in order to pass that object to a WCF service.

For that purpose I am using Newtonsoft.Json.Converter:

T input = JsonConvert.DeserializeObject<T>(jsonInput);

The problem is that that type <T> is unknown at design time. But after the deserialization I need to have a generic strongly-typed object so that I can pass it to WCF service. The reason for that is WCF service is different for each client, and the parameter input may have a different structure for each client.

var client = new CalcEngine.CalculatorClient();
var input = new CalcEngine.CalcInputTypes();
var result = client.Calculate(input);

Here input is of type CalcEngine.CalcInputTypes. For clientA and clientB CalcEngine.CalcInputTypes may have different structure.

What is the best way to accomplish that?

Thanks.

I am trying one of regular expression for condition like:

atleast 1 number, atleast 1 character, should be 3 to 16 digit long. No character and number should repeat more than 2 time.

I tried one regular expression here what i tried.

(^(?=.*\d)(?=.*[a-zA-Z]).{3,16}$)\1{2,}

but it did not do the trick.

example for valid and invalid post:

  • advan@123 -valid

  • advan@4 -valid

  • advvvan@123 -invalid

  • advan@11123 -invalid

  • advan123 -valid
  • 1231123123ab -valid
  • advadvvadv12 -valid

First off, here is my SelectedIndexChanged event for my table:

protected void MaintenanceTable_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow r = MaintenanceTable.Rows[MaintenanceTable.SelectedIndex];
        int mid = Convert.ToInt32(r.Cells[2].Text);
        string query = "SELECT * FROM Laptops WHERE Maintenance_ID = "+mid;
        string query1 = "SELECT * FROM Workstations WHERE Maintenance_ID = "+mid;
        lpDataSource.SelectCommand = query;
        lpDataSource.DataBind();
        wsDataSource.SelectCommand = query1;
        wsDataSource.DataBind();
        if (lpTable.Rows.Count > 0)
        {
            lpTableLabel.Visible = true;
            Panel1.Visible = true;
        }
        else
        {
            lpTableLabel.Visible = false;
            Panel1.Visible = false;
        }

        if (GridView1.Rows.Count > 0)
        {
            wsTableLabel.Visible = true;
            Panel2.Visible = true;
        }
        else
        {
            wsTableLabel.Visible = false;
            Panel2.Visible = false;
        }

    }

It's quite simple, when a user selects a row, it should bring up related rows from either of the two tables, either in Panel1 or Panel2. My problem is that when I select a row where only one table have content for, it works fine, reveals the table and its associated Maintenance_ID, I go to select another row where both tables have the associated Maintenance_ID and it only reveals the content for the table that was already previously revealed.

When I put a breakpoint I notice that the Rows.Count for the other table equates to 0, but when I run the program over and select a row where both tables have content, it reveals both tables as it should. And when I go to select another row with content from only one table it still reveals both tables, only it displays the table that doesn't have a related Maintenance_ID as empty.

So obviously I'm doing something wrong syntactically but I'm not sure what, open to suggestions.

This question already has an answer here:

I have a small website project in Visual Studio 2013. It's an ASP.NET MVC4 website which utilises the Razor syntax.

For this website, I want to implement a 'hit counter' if you will. It should record the amount of visits the website has and be displayed on a cshtml webpage.

What will I need (code wise) in order to achieve this? I already have a database so is it a question of simply creating another table and use that to store the number of visits?

I have no real idea on where to begin in terms of implementing this so any help would be appreciated. Thanks!

If there's any additional information that you require in order to formulate a solution then I am more than happy to provide that in a future edit.

EDIT: I've tried this following tutorial however I am looking for a solution that does not zero out the counter every time the solution gets restarted. http://www.c-sharpcorner.com/Blogs/46603/how-to-count-total-number-of-hit-in-Asp-Net-mvc.aspx

I have an asp.net site that uses razor syntax with @helpers and functions.

I have this code in my cshtml page:

@helper HtmlCaptcha(string msg) {
    // a lot of code for my control
    <div>...@msg...</div>
}

@{
    var captchaControl = new RecaptchaControl(){
                                ID = "recaptcha", 
                                PublicKey="mypkey", ... };

    // === here to optimize <<<
    var myHtmlCode = new StringBuilder(HtmlCaptcha(msg).ToString());
    var htmlWriter = new HtmlTextWriter(new StringWriter(myHtmlCode));
    // ==================== >>>

    captchaControl.RenderControl(htmlWriter);
}

Is there a better way to use the output of a "helper" to render a control like this?

I want to make a hit counter for an MVC4 Project I'm working on that utilises the Razor syntax.

I've tried this following tutorial however I am looking for a solution that does not zero out the counter every time the solution gets restarted. http://www.c-sharpcorner.com/Blogs/46603/how-to-count-total-number-of-hit-in-Asp-Net-mvc.aspx

How do I save the value of hits into a database file and then retrieve it every time the solution loads?

I've implemented the above tutorial fully however I am looking for a solution that allows me to increase the counter every time the solution gets opened. (For example, it starts with 1 and the next time you open the solution, it would say 2 and so on)

I understand that you are meant to add a new table in the database etc however I'm stuck in terms of what to actually write. I've only ever used databases based on user input (ie from 'html forms', text boxes etc). I don't know how to make the whole process automated (in terms of saving/ editing/ loading the number). It's always been from user input and creating new views every time.

EDIT: I have a file in my App_Data folder of the solution named MyMainDB.mdf. Correct me if I'm wrong but I believe this refers to the database. When double clicked, it sends me to the Server Explorer and shows a file named MyMainDBEntities. Within this database, I have an existing table for a separate, irrelevant function, where I know I have to make a table. Once this table is made, what information does it require? Just an integer value named counter?

Here's an example of where I've used databases before:

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Surname)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Password)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PasswordSalt)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { email=item.Email })
            @Html.ActionLink("Delete", "Delete", new { email = item.Email })
        </td>
    </tr>

As you can see, none of that is done automatically as the ActionLink at the bottom with the name Edit requires user input to click the button and then user input to assign a new value to the field.