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

    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));
    // ==================== >>>


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)
            @Html.DisplayFor(modelItem => item.FirstName)
            @Html.DisplayFor(modelItem => item.Surname)
            @Html.DisplayFor(modelItem => item.Email)
            @Html.DisplayFor(modelItem => item.Password)
            @Html.DisplayFor(modelItem => item.PasswordSalt)
            @Html.DisplayFor(modelItem => item.Age)
            @Html.ActionLink("Edit", "Edit", new { email=item.Email })
            @Html.ActionLink("Delete", "Delete", new { email = item.Email })

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.

I am trying to implement Asp.net Identity 2.0 with DB first.

I have imported my model.edmx into the project. It contains all the tables I need with the correct information and structure.

In the database there is a table called 'FSKUsers' I have edited this to contain the needed fields of the AspNetUsers which is the default table for Identity 2.0

So in my Identity DB Context I have mapped my FskUser class (which is a high level user for Identity sake)

 public class IdentityDbContext : IdentityDbContext<FskUser, FskRole, int, FskUserLogin, FskUserRole, FskUserClaim>
    public IdentityDbContext()
        : base("FSK_FskNetworksEntities")

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)

        var userEntity = modelBuilder.Entity<FskUser>();

        userEntity.ToTable("FSKUsers", "dbo");
        userEntity.Property(p => p.Id).HasColumnName("FSKUserId");
        userEntity.Property(p => p.PasswordHash).HasColumnName("Password");

    public static IdentityDbContext Create()
        return new IdentityDbContext();

So basically I want to map the class FskUser to the Data Base table called FSKUser which is also contained in my .edmx model.

When I run the website I get the following error.

The entity type FskUser is not part of the model for the current context

My two POCO classes:

The one from my edmx model:

public partial class FSKUser
    public FSKUser()
        this.AspNetUserClaims = new HashSet<AspNetUserClaim>();
        this.AspNetUserLogins = new HashSet<AspNetUserLogin>();
        this.FSKDevices = new HashSet<FSKDevice>();
        this.FSKEventLogs = new HashSet<FSKEventLog>();
        this.FSKReports = new HashSet<FSKReport>();
        this.FSKTransactions = new HashSet<FSKTransaction>();
        this.FSKTriggers = new HashSet<FSKTrigger>();
        this.UdlDownloads = new HashSet<UdlDownload>();
        this.AspNetRoles = new HashSet<AspNetRole>();
        this.FSKCompanies = new HashSet<FSKCompany>();

    public int FSKUserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public bool EmailConfirmed { get; set; }
    public string PhoneNumber { get; set; }
    public bool PhoneNumberConfirmed { get; set; }
    public string Password { get; set; }
    public string SecurityStamp { get; set; }
    public bool TwoFactorEnabled { get; set; }
    public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
    public bool LockoutEnabled { get; set; }
    public int AccessFailedCount { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public byte FSKAccessLevelId { get; set; }
    public string AddressStreet1 { get; set; }
    public string AddressStreet2 { get; set; }
    public string AddressStreet3 { get; set; }
    public string AddressPostCode { get; set; }
    public Nullable<int> CreatorId { get; set; }
    public Nullable<System.DateTime> CreateDate { get; set; }
    public string ConfirmationToken { get; set; }
    public Nullable<bool> IsConfirmed { get; set; }
    public Nullable<System.DateTime> LastPasswordFailureDate { get; set; }
    public Nullable<int> PasswordFailuresSinceLastSuccess { get; set; }
    public Nullable<System.DateTime> PasswordChangedDate { get; set; }
    public string PasswordVerificationToken { get; set; }
    public string PasswordVerificationTokenExpirationDate { get; set; }
    public bool IsDeleted { get; set; }
    public Nullable<int> CostCentreId { get; set; }
    public Nullable<int> AdminPasswordResetUserId { get; set; }
    public Nullable<System.DateTime> PreviousLogInDate { get; set; }
    public System.Guid msrepl_tran_version { get; set; }

    public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
    public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
    public virtual ICollection<FSKDevice> FSKDevices { get; set; }
    public virtual ICollection<FSKEventLog> FSKEventLogs { get; set; }
    public virtual ICollection<FSKReport> FSKReports { get; set; }
    public virtual ICollection<FSKTransaction> FSKTransactions { get; set; }
    public virtual ICollection<FSKTrigger> FSKTriggers { get; set; }
    public virtual ICollection<UdlDownload> UdlDownloads { get; set; }
    public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
    public virtual ICollection<FSKCompany> FSKCompanies { get; set; }

The one I use in my Identity

 public class FskUser : IdentityUser<int, FskUserLogin, FskUserRole, FskUserClaim>
    [Display(Name = "First Name")]
    [Required(ErrorMessage = "First Name is Required.")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Last Name is Required.")]
    public string LastName { get; set; }        

    [Display(Name = "Cell Number")]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
    [StringLength(10, ErrorMessage = "The {0} must be 10 numbers long.", MinimumLength = 10)]
    public override string PhoneNumber { get; set; }

    [Display(Name = "Access Level")]
    public byte? FSKAccessLevelId { get; set; }

    [Display(Name = "Street Address 1")]
    public string AddressStreet1 { get; set; }

    [Display(Name = "Street Address 2")]
    public string AddressStreet2 { get; set; }

    [Display(Name = "Street Address 3")]
    public string AddressStreet3 { get; set; }

    [Display(Name = "Postal Code")]
    public string AddressPostCode { get; set; }

    [Display(Name = "Previous Login")]
    public Nullable<DateTime> PreviousLogInDate { get; set; }

    [Display(Name = "Account Confirmed")]
    public Nullable<bool> IsConfirmed { get; set; }

    [Display(Name = "Last Password Failier")]
    public Nullable<DateTime> LastPasswordFailureDate { get; set; }

    [Display(Name = "Password Last Changed")]
    public Nullable<DateTime> PasswordChangedDate { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<FskUser, int> manager)
        //TODO: add option for web and api (to create different auth types

        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;

I want to display some images in the view. The images are in this address: Areas/DDM/Views/Help/Documents/DataCollection_UserGuide/image001.png I can drag and drop one image into the view code and I have this code: In the view, when the application is running, I can see only a little sign, that shows the place of image, but I can not see the image and also not the caption if I hade alt="bbb".

The interesting problem is that I have some other images somewhere else in this address: "Themes/Default/Styles/Default" and I can drag and drop these images on the view and I can see theme. for example:

I check many different ways to write address and different image formats. I don't know how can I display my images from the special areas?

I know there are number of similar qustions around here, but non of the solutions helped me with this. Here is my case:

I have a List in my model.

public List<SelectListItem> Layouts { get; set; }

After my "Load" method, the result is as follows:

enter image description here

Then in my view i use this overload:

 @Html.DropDownListFor(x => x.Layout, Model.Layouts, "Select a Layout", 
   new { @id = "ddLayouts", @onchange = "javascript:getExampleAddresses(this.value);" })

Stepping on that exact line with debbuger, i get the following result: enter image description here

So far everything looks good, but when i step on the next line, the selected value gets Selected = falseand my value does not gets selected. Does anybody have an idea why is this happening?

I have a textbox which i want to have a autocomplete function so i use the ajaxautocomplete extender on it. The problem is when the page loads and I tried to write anything on it, the page will suddenly hangs and become unresponsive. How can i fix this. Thanks

here is my code on clientside

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

  Item:<asp:TextBox ID="txtItemSearch" runat="server"></asp:TextBox>
             <cc1:AutoCompleteExtender ServiceMethod="SearchCustomers"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">

here is my code for the serverside

    public static List<string> SearchCustomers(string prefixText, int count)
        using (SqlConnection conn = new SqlConnection())
            conn.ConnectionString = ConfigurationManager
            using (SqlCommand cmd = new SqlCommand())
                cmd.CommandText = "select item_desc from Items where " +
                "item_desc like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefixText);
                cmd.Connection = conn;
                List<string> customers = new List<string>();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                    while (sdr.Read())
                return customers;

I want to disable the CheckBox when it is already selected.I used two gridview for two pages(admin page and faculty page).When I select a checkbox from one gridview(i.e admin page),it should disable that particular checkbox in other gridview(i.e faculty page). I stored that gridview(admin page) values as bool type(True and False) in database.When the checkbox is selected from admin page it will store value as "True" and vice versa.Then I used that values to retrieve from database, now I want use the query for checking the checkbox values and to disable the checkbox which is selected from gridview(admin page).This is the code I tried

     protected void createbtnclick_Click(object sender, EventArgs e)
        using (SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            SqlDataAdapter cmd1 = new SqlDataAdapter("select * from test where hour1='true' or hour2='true' or hour3='true' or hour4='true' or hour5='true' ", con1);
            DataTable dt = new DataTable("dt");
            Gv1.DataSource = dt;

here i doing API integration in my web application.

how we can load the team field dropdown by using sage CRM API mainly in Lead module?

(Asp.net C#)

Please see screen shot of sage CRM Page. enter image description here

I have a table 1:

enter image description here

and table 2 :

enter image description here

Each question can have multiple choices (ex: questionId 1 has two choices choiceId 1 and 2).

I have a form which will allow users to select multiple choices like this:

enter image description here

There is also a table for answers:

enter image description here

Now my question is: I want to form a SQL query based on the selection and show the count of selected answers.(ex: I want count of answers having gender as female and education as grade 1). How do I do that?

I tried something like this:

select * from answers where (questId =2 and choiceIndex='2.0000') and (questId =3 and choiceIndex='1.0000') and someId=72

This query does not give me the correct count as same choiceIndex can exists for a different choice.

How can I achieve this? Also user can selected many choices from the form so is there any way by which I can dynamically generate my SQL query?

Below is the code where I compute date by subtracting TimeSpan from Today's Date.

DateTime todayDate = DateTime.Today;
TimeSpan minTS = new TimeSpan(6570, 0, 0, 0, 0);
TimeSpan maxTS = new TimeSpan(7300, 0, 0, 0, 0);
DateTime minDate = todayDate.Subtract(minTS);
DateTime maxDate = todayDate.Subtract(maxTS);

My Query is as below:

sql = "select AId,AName,DOB,Religion from Applicant,Creator as C where (C.CId = Applicant.CId and Approved = 'Approved' and Gender !='" + gend + "' and AId !=" + id + ") and (Applicant.Status = '" + status.Items[status.SelectedIndex].ToString() + "' and Applicant.DOB BETWEEN '" + maxDate + "' and '" + minDate + "')";
                    cmd = new SqlCommand(sql, con);

SqlDataAdapter da = new SqlDataAdapter(cmd);      // use your existing SqlCommand here (don't use select *)
                    DataSet ds = new DataSet();                       // create a DataSet object to hold you table(s)... this can contain more than 1 table
                    da.Fill(ds, "Comment");      

This works fine for me. But when I change the values of TimeSpan to

TimeSpan(7300, 0, 0, 0, 0);
TimeSpan maxTS = new TimeSpan(9125, 0, 0, 0, 0);

I get the following error: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I am not getting where I am going wrong. Please help me out in fixing the problem.

Thanx in Advance

I have a hugh problem with the cach function of the internet explorer. I'm trying to develop a way for the internet explorer that it opens every hour a new PDF report but the internet explorer just caches the old version and if the user clicks open it will open the old version. That means that the user has to save first and than open the pdf but we all know that the average user will not understand it so my question is, is there a way to update the file every hours automaticaly?

Just so you know, everything is working fine right now with firefoy and chrome but at the system where this solution should work they are using an old version of ie (8 or 9)

I want to know how to use required attribute in asp.net.I'm newbie to asp.net.In html I used required attribute for mandatory fields.How to use it in asp .net.Now I used like this.Is it correct?

<p class="field-wrapper required-field"> <label>First Name</label><asp:TextBox ID="TextBox1" name="f_name" runat="server" required></asp:TextBox></p>

DataSet is said to be a collection of one or more DataTable objects. Is it possible to use an array of DataTable objects? If yes, then why use a DataSet? Are there any advantages? Please help!

I'm new to EC2 but I think it's very cool and suitable with my business:

I have a CMS system(Composite C1 asp.net) to display my website which contents don't change very much, all the things like applications(.aspx file, .swf, etc) and db files are store in one folder, near 1GB. Previously to load balance I just zip this folder and copy to other win2008 servers, run them up all and controlled by DNS rolls A record to each static IP.

But now I decided to change to EC2 with loadbalance:

  • 1) I firstly prepared all the things and created the image.
  • 2) Then I launched 2 instances with that image, which has totally same content but different ip address.
  • 3) I create a "Elastic Load Balance" and add both of instances into it. enter image description here

  • 4) I removed all DNS A record and created a new CNAME record points to loadbalance provided dns name. Then started to monitor on both vm: enter image description here

My questions are:

  1. The site seems work well now, but do I really using the load balance now? Operations are correct or suitable with my business(file db, the whole simple site can be copied within one zip file)?
  2. Started perfmon.exe, seems different with A record DNS rolling, each request routes to both servers rather than only one of them, is that normal for amazon load balance?

Hope I describe my situation and question clearly and also hope for your advice, thank you in advance.

I have written a code in C# and I want certain functions to be called at every 15 minutes from morning 6 AM to evening 11:59 PM everyday to perform a certain task.

My code looks something like below:

using System.Timers;

public partial class _nirav : System.Web.UI.Page

    private static System.Timers.Timer aTimer;

    protected void Page_Load(object sender, EventArgs e)
         aTimer = new System.Timers.Timer(15*60*1000);
         aTimer.Elapsed += OnTimedEvent;
         aTimer.Enabled = true;

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)

I am new to Stack Overflow and I know very little about System.Timers.Timer.

I have used IIS before, but I've never used a database and I've never done a web app. I did the same steps for putting a site onto IIS and everything works EXCEPT for when I go to a page that has a DB connection on it. I've tried a lot and this is all I get.

A network-related or instance-specific error occurred while establishing a >connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.

Windows Application Event Log:

Cannot get a local application data path. Most probably a user profile is not loaded. If LocalDB is executed under IIS, make sure that profile loading is enabled for the current user.

This was built in Visual Studio and I have a SQL Express DB. I posted my connection strings, any help is greatly appreciated.

I have added this to my applicationHost.config:

<add name="DefaultAppPool">
    <processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />

And now I get:

An attempt to attach an auto-named database for file |MY DB1 FILE| failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DB1.mdf;Initial Catalog=aspnet-ICCAA_VIZIER-20150223043129;Integrated Security=True" providerName="System.Data.SqlClient"/>
<add name="ConnectionString" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DB2.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient"/>

I have a display template in MVC that is for a collection of items, so the first line of my cshtml file is as follows:

@model IList<Some.Namespace.ViewModels.MyListItem>

If I add some new HTML to the file and then do CTRL + K + D to auto format, it now changes my model to all lower case like this:

@model IList<some.namespace.viewmodels.mylistitem>

This is a massive pain to keep changing after auto formatting, because it obviously breaks my html helpers until I correct the casing. I found this question and it said it was due to MVC3.

I'm running VS2013 Update 4 with MVC5 and I still have this problem. I can't find anything in the Text Editor options to change this behaviour.

I'm also using ReSharper 8.2 and Web Essentials 2013 for Update 4.

Is this a known issue or do I have a setting that is breaking things somewhere?

After googling i changed the target frame work to application pool frame work Eventhough geeting error

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive.

Any solution for this?

I got this problem (Incorrect syntax near '2015'.) .. This problem because date time

Sql_Command.Parameters.AddWithValue("@CourseName", CourseName.Text);
Sql_Command.Parameters.AddWithValue("@StartDate", DateTime.Parse(Request.Form[StartDate.UniqueID]);
Sql_Command.Parameters.AddWithValue("@EndDate", DateTime.Parse(Request.Form[EndDate.UniqueID]));
Sql_Command.Parameters.AddWithValue("@StartTime", DateTime.Parse(Request.Form[StartTime.UniqueID]));
Sql_Command.Parameters.AddWithValue("@EndTime", DateTime.Parse(Request.Form[EndTime.UniqueID]));

I use this script

<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=StartDate.ClientID %>").dynDateTime({
            showsTime: false,
            ifFormat: "%Y-%m-%d",
            daFormat: "%l;%M %p, %e %m,  %Y",
            align: "BR",
            electric: false,
            singleClick: false,
            displayArea: ".siblings('.dtcDisplayArea')",
            button: ".next()"

The type in SQL is datetime.

I am very new to javascript and .net fremework. Please help me with this issue. Here is the small snippet of my code, and I am displaying a table onclick, but I want it to display on page load.

I have tired window.onload, Placed the code in tag, placed it in $(documen).ready() but none of them are working, can someone please let me know what are to be modified in order to display the table on page load instead of onclick?

Here is my code snippet:

<tr id='group11' class="group1" rel="<%# Eval("RowCount") %>">
    <td colspan="6" class="description first">
        <a href="javascript:void(0);" onclick="toggleCategory('#group11',<%# Eval("RowCount") %>);" class="control collapse">[-]</a> 
        <a href="javascript:CallDialog('<%# Eval("SummaryMessage") %>');" style= "background-color:yellow">RI [<font size="2"> <i> <%# Eval("LastRI")%> </i> </font>]

Thank you

I am having a problem with the AutoPostBack event. My dropdown"s AutoPostBack does not work. It worked fine until I introduced bootstrap into the mix.


<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="namesSQL" 
    DataTextField="Name" DataValueField="EmplID" AutoPostBack="true" 

SQL Data Source

<asp:SqlDataSource ID="namesSQL" runat="server" 
    ConnectionString="<%$ ConnectionStrings:MAFapp %>" 
    SelectCommand="SELECT EmplID, EmpName, LastName, 
    { fn CONCAT(EmpName, LastName) } AS Name 
    FROM Employees 
    ORDER BY { fn CONCAT(EmpName, LastName) }">

The data source works fine, I listed it since I know someone will ask for it...