The following method works:

[System.Web.Services.WebMethod]
public string GetData(string year)
{
    Int32 iYear = DateTime.Now.Year;
    if (DateTime.IsLeapYear(iYear))
    {
        return "true";
    } else
    {
        return "false";
    }
}

But if I pass a year say 2015 as a string, the following code doesn't work.

using System;

public partial class _Default : System.Web.UI.Page
{
public string output = "";
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Params["callback"] != null)
    {
        output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')";
    }
}

[System.Web.Services.WebMethod]
public string GetData(string year)
{
    int iYear = Convert.ToInt32(year);

    if (DateTime.IsLeapYear(iYear))
    {
        return "true";
    } else {
        return "false";
    }
}
}

I'm having a hard time figuring out my mistake. I'm passing year as a string to an jQuery Ajax call.

Any ideas why?

Joe

So im having trouble binding a dropdownlist from a FormViewEditItemTemplate

I created a asp:SqlDataSource, set the UpdateCommand, supposedly bind the id_enabled value, though it doesn't work

When i push the Edit button it crashes and gives the following error

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'id_enabled'

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/AdminPanel.Master" 
    AutoEventWireup="true" 
    CodeBehind="PassportDetail.aspx.cs" 
    Inherits="TipTourAdminPanel.PassportDetail" %>

<asp:Content 
    ID="Content1" 
    ContentPlaceHolderID="head" 
    runat="server">
</asp:Content>

<asp:Content 
    ID="Content2" 
    ContentPlaceHolderID="ContentPlaceHolder1" 
    runat="server">

    <asp:SqlDataSource 
        ID="SqlDataSource_rewardDetail" .  


        runat="server" 
        ConnectionString="<%$ ConnectionStrings:Tip-Tour %>"  

        SelectCommand= "SELECT 
                            tt_passport.id_passport,
                            tt_passport.id_tour, 
                            tt_passport.description AS passport_description,
                            tt_passport.id_passport_requirement,
                            tt_passport_requirement.description AS passport_requirements,
                            tt_tour.title AS tour_title,
                            tt_tour.body AS tour_description,
                            tt_passport.enabled             

                        FROM tt_passport

                            JOIN tt_passport_requirement
                                ON tt_passport_requirement.id_passport_requirement = tt_passport.id_passport_requirement

                            JOIN tt_tour
                                ON tt_tour.id_tour = tt_passport.id_tour

                        WHERE tt_passport.id_passport = @id_passport"

        UpdateCommand= "UPDATE tt_passport 
                        SET 
                            tt_passport.description = @passport_description,
                            tt_passport.id_passport_requirement = @id_passport_requirement,
                            tt_passport.enabled = @id_enabled

                        WHERE tt_passport.id_passport = @id_passport"


        DeleteCommand= "Delete FROM tt_passport 
                        WHERE tt_passport.id_passport = @id_passport">

        <SelectParameters>
            <asp:QueryStringParameter 
                DefaultValue="0" 
                Name="id_passport" 
                QueryStringField="id_passport" />
        </SelectParameters>

        <UpdateParameters>
            <asp:Parameter Name="passport_description" />
            <asp:Parameter Name="id_passport_requirement" />
            <asp:Parameter Name="id_passport"/>
            <asp:Parameter Name="id_enabled"/>
        </UpdateParameters>

    </asp:SqlDataSource>

    <asp:SqlDataSource 
        ID="sql_enabled_ddl" 
        runat="server" 
        ConnectionString="<%$ ConnectionStrings:Tip-Tour %>"  

        SelectCommand =";With passport_enabled AS
                        (
                            Select 1 as id_enabled, 'true' AS description                           
                            UNION                       
                            Select 0 as id_enabled, 'false' AS description
                        )
                        SELECT id_enabled, description FROM passport_enabled">

    </asp:SqlDataSource>

    <asp:SqlDataSource 
        ID="SqlDataSource_rewardRequirements" 
        runat="server" 
        ConnectionString="<%$ ConnectionStrings:Tip-Tour %>"  

        SelectCommand= "SELECT 
                            id_passport_requirement, 
                            description 
                        FROM tt_passport_requirement">

    </asp:SqlDataSource>


    <div class="textHeader">Passport:</div>

    <asp:FormView 
        ID="FormView1" 
        runat="server" 
        DataSourceID="SqlDataSource_rewardDetail" 
        DataKeyNames="id_passport">

        <EditItemTemplate>
            <table id="tableForm">
                <tr>
                    <th>id_passport:</th>
                    <td>
                        <asp:Label 
                            Text='<%# Eval("id_passport") %>' 
                            runat="server" 
                            ID="id_passportLabel1" />
                    </td>
                </tr>
                <tr>
                    <th>passport_description:</th>
                    <td>
                        <asp:TextBox 
                            Text='<%# Bind("passport_description") %>' 
                            runat="server" 
                            ID="passport_descriptionTextBox"
                            TextMode="MultiLine" 
                            Rows="10"/>
                    </td>
                </tr>

                <tr>
                    <th>passport_requirements:</th>
                    <td>                
                        <asp:DropDownList
                            ID="DropDownList1"
                            runat="server"
                            DataSourceID="SqlDataSource_rewardRequirements"
                            DataTextField="description"
                            DataValueField="id_passport_requirement" 
                            SelectedValue='<%# Bind("id_passport_requirement") %>' 
                            Width="87%">
                        </asp:DropDownList>             
                    </td>
                </tr>
                <tr>
                    <th>enabled:</th>
                    <td>                
                        <asp:DropDownList
                            ID="DropDownList2"
                            runat="server"
                            DataSourceID="sql_enabled_ddl"
                            DataTextField="description"
                            DataValueField="id_enabled"
                            SelectedValue='<%# Bind("enabled") %>' 
                            Width="87%">
                        </asp:DropDownList>             
                    </td>
                </tr>


            </table>

            <br />

            <asp:LinkButton 
                runat="server" 
                Text="Update" 
                CommandName="Update" 
                ID="UpdateButton" 
                CausesValidation="True" />

            &nbsp;

            <asp:LinkButton 
                runat="server" 
                Text="Cancel" 
                CommandName="Cancel" 
                ID="UpdateCancelButton" 
                CausesValidation="False" />
        </EditItemTemplate>



    </asp:FormView>


</asp:Content>

I am trying to consume web service using SOAP request in asp.net C# but it is failing with

The remote server returned an error: (500) Internal Server Error.

Below is my web service request code:

public static HttpWebRequest CreateWebRequest()
{
string action = "http://localhost:8081/Service.asmx?op=getData";
string url = "http://localhost:8081/Service.asmx";
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Headers.Add("SOAPAction", action);
    webRequest.ContentType = "application/soap+xml; charset=utf-8";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    webRequest.Timeout = 30000;

    return webRequest;
}
public static XmlDocument ServiceCall()
{
    HttpWebRequest request = CreateWebRequest();

    XmlDocument soapEnvelopeXml = CreateSoapEnvelope("MyUser", "MyUser", "MyUser");

    using (Stream stream = request.GetRequestStream())
    {
        soapEnvelopeXml.Save(stream);
    }

    IAsyncResult asyncResult = request.BeginGetResponse(null, null);

    asyncResult.AsyncWaitHandle.WaitOne(20 * 1000);

    string soapResult;
    using (WebResponse webResponse = request.EndGetResponse(asyncResult))
    using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
    {
        soapResult = rd.ReadToEnd();
    }


    XmlDocument resp = new XmlDocument();

    resp.LoadXml(soapResult);

    return resp;
}
private static XmlDocument CreateSoapEnvelope(string userName, string password, string DCSCommand)
{
    StringBuilder builder = new StringBuilder();
    builder.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    builder.Append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
    builder.Append("<soap12:Body>");
    builder.Append("<geteFliteData xmlns=\"http://test.org\">");
    builder.Append("<userName>" + userName + "</userName>");
    builder.Append("<password>" + password + "</password>");
    builder.Append("<DCSCommand>" + DCSCommand + "</DCSCommand>");
    builder.Append("</geteFliteData>");
    builder.Append("</soap12:Body>");
    builder.Append("</soap12:Envelope>");

    XmlDocument soapEnvelop = new XmlDocument();
    soapEnvelop.LoadXml(builder.ToString());
    return soapEnvelop;
}

Note: When I am consuming this web service using WSDL file it is working fine and returns expected XML

Several times a day I receive this error while running my MVC 4 Razor project. when i refresh the page it will be solved for only that time. What is the permanent solution of that.

Cannot create/shadow copy 'WebGrease' when that file already exists.

Trying to populate a DropDownList depending on logged in windows user's username. However, the list should have only one item if the condition fails.

Problem: The custom item is not added to the list when condition meets. Looked at lot of posts on SO but with no luck. Any direction would help.

Controller:

    public ActionResult Location()
    {
        UserPermissionDataContext dbContext = new UserPermissionDataContext();
        var viewModel = new UserDetail();
        var locationList = new SelectList(
                            (
                                from t in dbContext.UserDetails
                                where t.username.Equals(System.Environment.UserName)
                                select new SelectListItem{Text = t.location, Value = t.level}
                            ), "Value", "Text");

        if (locationList.Select(i => i.Value).Contains("Global"))
            ViewData["Locations"] = locationList;
        else
            ViewData["Locations"] = new SelectList(locationList, "Value", "No Access");
        return View(viewModel);
    }  

View:

<tr>
    <td>Global</td>
    <td>
        <div> 
            @Html.DropDownList("location", (SelectList)ViewData["Locations"])
        </div>
    </td>
</tr>

What would be the steps to generate a list in that case when condition failes with one item only which would have the item as "No Access".

I cannot get my form to update existing entries using my current viewmodel / model,

I can get it to create and post data initially.However when trying to update it throws the below error. Why am I missing

See below the error:

Value cannot be null.
Parameter name: source
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: source

Source Error: 


Line 217: }
Line 218: var selectedSkillsHs = new HashSet<string>(selectedSkills);
Line 219:            var jobSkills = new HashSet<int>
Line 220:            (viewModel.Skills.Select(s => s.Id));
Line 221:

My Controller: The error is occurring in private void UpdateSkillJobs

 // GET: CREATE PAGE 
    [Authorize]
    public ActionResult Create()
    {
        var viewModel = new JobFormViewModel();

        viewModel.Skills = new List<Skillsets>();
        viewModel.Locations = _context.Locations.ToList();
        PopulateAssignedSkillData(viewModel);
        ViewBag.Heading = "Create A Job";
        return View(viewModel);
    }
    // POST: CREATE PAGE CALLS UPDATE SKILL METHOD
    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(JobFormViewModel viewModel, string[] selectedSkills)
    {
        if (selectedSkills != null)
        {
            viewModel.Skills = new List<Skillsets>();
            foreach (var skill in selectedSkills)
            {
                var skillToAdd = _context.Skills.Find(int.Parse(skill));
                viewModel.Skills.Add(skillToAdd);
            }
        }
        if (ModelState.IsValid)
        {
            var job = new Job
            {
                ClientId = User.Identity.GetUserId(),
                DateTime = viewModel.GetDateTime(),
                LocationId = viewModel.Location,
                Description = viewModel.Description,
                JobTitle = viewModel.Title,
                RenumerationMin = viewModel.RenumerationMin,
                RenumerationMax = viewModel.RenumerationMax,
                Skillsets = viewModel.Skills
            };

            _context.JobLists.Add(job);
            _context.SaveChanges();
            return RedirectToAction("Mine", "JobList");
        }
        viewModel.Locations = _context.Locations.ToList();
        PopulateAssignedSkillData(viewModel);
        return View(viewModel);
    }

    //GET: EDIT FORM POPULATE SKILLS


    [Authorize]
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        var job = _context.JobLists.Include(i => i.Skillsets).Single(j => j.Id == id);
        var viewModel = new JobFormViewModel
        {                               
            Locations = _context.Locations.ToList(),
            Id = job.Id,
            Date = job.DateTime.ToString("d MMM yyyy"),
            Time = job.DateTime.ToString("HH:mm"),
            Location = job.LocationId,
            Heading = "Edit A JobFormViewModel Post",
            Title = job.JobTitle,
            Description = job.Description,
            RenumerationMin = job.RenumerationMin,
            RenumerationMax = job.RenumerationMax,
            Skills = job.Skillsets

        };
        PopulateAssignedSkillData(viewModel);
        return View(viewModel);
    }

    //POST: EDIT JOB BACK TO DATABASE

    [Authorize]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(JobFormViewModel viewModel, int? id, string [] selectedSkills)
    {
        if (!ModelState.IsValid)
        {
           viewModel.Skills = new List<Skillsets>();
            viewModel.Locations = _context.Locations.ToList();
            return View("Edit", viewModel);
        }

        var job = _context.JobLists
            .Include(j => j.Subscribers.Select(c => c.Candidate)).Include(i => i.Skillsets)
            .Single(j => j.Id == viewModel.Id);

        UpdateSkillJobs(viewModel, selectedSkills);

        job.Modify(
            viewModel.GetDateTime(),
            viewModel.Location,
            viewModel.Title,
            viewModel.Description,
            viewModel.RenumerationMin,
            viewModel.RenumerationMax,
            viewModel.Skills                                            
            );

        _context.SaveChanges();
        return RedirectToAction("Mine", "JobList");
    }
    // UPDATE  SKILLS In Each Job EDIT
    private void UpdateSkillJobs(JobFormViewModel viewModel, string[] selectedSkills)
    {
        if (selectedSkills == null)
        {
            viewModel.Skills = new List<Skillsets>();
            return;
        }
        var selectedSkillsHs = new HashSet<string>(selectedSkills);
        var jobSkills = new HashSet<int>
            (viewModel.Skills.Select(s => s.Id));

        foreach (var skill in _context.Skills)
        {
            if (selectedSkillsHs.Contains(skill.Id.ToString()))
            {
                if (!jobSkills.Contains(skill.Id))
                {
                    viewModel.Skills.Add(skill);
                }
            }
            else
            {
                if (jobSkills.Contains(skill.Id))
                {
                    viewModel.Skills.Remove(skill);
                }
            }
        }
    }

My View Model

JobFormViewModel using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using WhiteSailsRecruitment.Models;

namespace WhiteSailsRecruitment.ViewModels
{
public class JobFormViewModel
{
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [Required]
    public int Location { get; set; }

    public IEnumerable<Location> Locations { get; set; }

    [Required]
    [FutureDate]
    public string Date { get; set; }

    [Required]
    [ValidTime]
    public string Time { get; set; }

    public virtual ICollection<Skillsets> Skills { get; set; }
    [AllowHtml]
    [Required]
    public string Description { get; set; }

    public string Heading { get; set; }

    public string RenumerationMin { get; set; }

    public string RenumerationMax { get; set; }


    public DateTime GetDateTime()
    {
        return DateTime.Parse(string.Format("{0} {1}", Date, Time));
    }
}
}

My Model that Binds to JobFormViewmodel and creates notifications when a change is made

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;

namespace WhiteSailsRecruitment.Models
{
    public class Job
                     {
    public int Id { get; set; }

    public bool IsExpired { get; set; }

    public ApplicationUser Client { get; private set; }

    [Required]
    public string ClientId { get; set; }
    public DateTime DateTime { get; set; }

    [Required]
    [StringLength(255)]
    public string JobTitle { get; set; }

    public Location Location { get; set; }
    [Required]
    public int LocationId { get; set; }
    [AllowHtml]
    [Required]
    public string Description { get; set; }

    public string RenumerationMin { get; set; }

    public string RenumerationMax { get; set; }

    public virtual ICollection<Skillsets> Skillsets { get; set; }     

    public ICollection<Interested> Subscribers { get; private set; }







    public Job()
    {
        Subscribers = new Collection<Interested>();
    }

    public void Expire()
    {
        IsExpired = true;

        var notification = Notification.JobExpired(this);


        foreach (var candidate in Subscribers.Select(i => i.Candidate))
        {
            candidate.Notify(notification);
        }
    }


    public void Modify(DateTime getDateTime, int location, string title, string description, string renumerationMin, string renumerationMax, ICollection<Skillsets> skills)
    {
        var notification = Notification.JobUpdated(this, DateTime, Location);
        LocationId = location;
        DateTime = getDateTime;
        JobTitle = title;
        Description = description;
        RenumerationMax = renumerationMax;
        RenumerationMin = renumerationMin;

        foreach (var subscriber in Subscribers.Select(c => c.Candidate))
            subscriber.Notify(notification);
    }
}
}

My View

@using WhiteSailsRecruitment.ViewModels.JobViewModels
@model WhiteSailsRecruitment.ViewModels.JobFormViewModel

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

<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
<p class="alert alert-info">
    All Fields are <strong>required</strong>
</p>
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.Id)
<div class="form-group">
    @Html.LabelFor(m => m.Title)
    @Html.TextBoxFor(m => m.Title, new { @class = "form-control", autofocus = "autofocus" })
    @Html.ValidationMessageFor(m => m.Title)

</div>
<div class="form-group">
    @Html.LabelFor(m => m.Location)
    @Html.DropDownListFor(m => m.Location, new SelectList(Model.Locations, "LocationId", "City"), "", new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.Location)

</div>
<div class="form-group">
    @Html.LabelFor(m => m.Date)
    @Html.TextBoxFor(m => m.Date, new { @class = "form-control", placeholder = "eg 1 Jan 2016" })
    @Html.ValidationMessageFor(m => m.Date)
</div>
<div class="form-group">
    @Html.LabelFor(m => m.Time)
    @Html.TextBoxFor(m => m.Time, new { @class = "form-control", placeholder = "eg 21:00" })
    @Html.ValidationMessageFor(m => m.Time)
</div>

<div class="form-group">
    @Html.LabelFor(m => m.Description)
    @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = "3" })
    @Html.ValidationMessageFor(m => m.Description)
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <table>
            <tr>
            @{
                var cnt = 0;
                List<AssignedSkillData> skills = ViewBag.Skills;

                foreach (var skill in skills)
                {
                    if (cnt++%3 == 0)
                    {
                        @:</tr><tr>
                    }
                        @: <td>
                            <input type="checkbox"
                                   name="selectedSkills"
                                   value="@skill.SkillId"
                                   @(Html.Raw(skill.Assigned ? "checked=\"checked\"" : "")) />
                                @skill.SkillId @: @skill.SkillName
                                @: </td>
                }
                    @: </tr>
                }
            </table>
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.RenumerationMin)
        @Html.TextBoxFor(m => m.RenumerationMin, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.RenumerationMin)

    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.RenumerationMax)
        @Html.TextBoxFor(m => m.RenumerationMax, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.RenumerationMax)

    </div>
    <button type="submit" class="btn btn-primary btn-lg">Submit</button>
                    }

@section scripts {
@Scripts.Render("~/bundles/jqueryval")


<script>
    $(function() {
        $("#element")
            .popSelect({
                showTitle: false,
                placeholderText: 'Click to add Skills',
                position: 'bottom'
            });
    })
</script>
}

Finally my Application DB Context

using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace WhiteSailsRecruitment.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Job> JobLists { get; set; }
    public DbSet<Skillsets> Skills { get; set; }
    public DbSet<Location> Locations { get; set; }
    public DbSet<Interested> Interesteds { get; set; }
    public DbSet<Following> Followings { get; set; }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<BCategories> Categories {get; set; }
    public DbSet<Notification> Notifications { get; set; }
    public DbSet<UserNotification> UserNotifications { get; set; }      
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<BCategories>()
            .HasMany(c => c.Blogs).WithMany(i => i.Categories)
            .Map(t => t.MapLeftKey("CatId")
                .MapRightKey("BlogId")
                .ToTable("CategoryBlogs"));

        modelBuilder.Entity<Skillsets>()
           .HasMany(c => c.Jobs).WithMany(i => i.Skillsets)
           .Map(t => t.MapLeftKey("SkillId")
               .MapRightKey("JobId")
               .ToTable("SkillJobs"));

        modelBuilder.Entity<Interested>()
            .HasRequired(i => i.Job)
            .WithMany(j => j.Subscribers)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<ApplicationUser>()
            .HasMany(u => u.Followers)
            .WithRequired(f => f.Followee)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<ApplicationUser>()
            .HasMany(u => u.Followees)
            .WithRequired(f => f.Follower)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<UserNotification>()
            .HasRequired(n => n.User)
            .WithMany(u => u.UserNotifications)
            .WillCascadeOnDelete(false);          


        base.OnModelCreating(modelBuilder);
    }
}
}

Our event viewer shows two information-level messages that we want to omit from the event logs:

  1. When a user fails authentication (Event code: 4006 Event message: Membership credential verification failed.)
  2. When forms authentication has expired and the user navigates to the default page (Event code: 4005 Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired.)

Researching how to exclude these types of messages has led me to understand that if I include the following in my web.config file, these messages won't show up. When I test this, I see that is indeed the case.

<healthMonitoring>
    <rules>
        <clear />
        <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>
    </rules>
</healthMonitoring>

In other words, I omit this from the default web.config:

<add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>

My question is: what else could I potentially be excluding the event log by removing this node? And if there are other potential repercussions, is there another or a better way to exclude just those two types of error logs that I mentioned above?

Thanks in advance!

I have been running into this issue for quite some time. It occurs when I open up an asp.net page pointing to my localhost. I am running windows 2008 r2 with visual studio 2012 and iis 7.5.

The config source that it shows is this. :

 1451:                 <remove name="ASP.NET_4.0.30319.0" />
 1452:                 <filter name="ASP.Net_4.0_64bit" path="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="runtimeVersionv4.0,bitness64" />
 1453:                 <filter name="ASP.Net_4.0_32bit" path="C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_filter.dll" enableCache="true" preCondition="runtimeVersionv4.0,bitness32" />

It shows it is erroring on line 1452.

Initially, it was an issue in the applicationHost.config file in the inetsrv 32 and 64bit locations. I went in and removed the duplicate 4.0 entry and it worked for a good couple of months.

It then started throwing this error again. At that time I just did a full re-install of IIS and my application started working again.

Once again this error has started to occur, I once again performed a full reinstall of IIS but this time that does not help and my applications continue to error due to this duplicate collection error.

I believe this all stems from an ISAPI issue I had long long ago prior to all of this which is detailed here. :

http://weblog.west-wind.com/posts/2011/Apr/04/Error-on-64-Bit-Install-of-IIS-LoadLibraryEx-failed-on-aspnetfilterdll

Really, I wondering if anyone else has seen this. Where I am really confused is if I look at the temp applicationHost.config file in the inetpub/temp/appPools location (this is the file that the application running is referencing and erroring on). The problem I have with this is that the current temp applicationHost.config that is being used by the application differs from the one found in the inteserv locations in that it has the ASP.NET_4.0.30319.0 line which is causing the error. The confusion is that this line causing the error has to be coming from some where but I cannot find it in the inetsrv locations or in the app pool locations, hence my confusion.

I'm working on a WebForms app, and I'm not getting a validation for a field. I tried using only ValidateEmptyText="true" but w/o ControlToValidate: it doesn't work. However I do have other controls that work properly with ControlToValidate and ValidateEmptyText properties added. This CustomValidator doesn't work:

ASPX code

<td id="TableCellLocation" runat="server">
<asp:CustomValidator 
    ID="CustomValidatorLocation" 
    ValidationGroup="Bulk" 
    OnServerValidate="LocationValidate" 
    ValidateEmptyText="true" 
    Display="None"  
    ControlToValidate="AutoCompleteBoxLocation" 
    ErrorMessage="Required" 
    runat="server"></asp:CustomValidator>
<uc:AutoCompleteBox 
    runat="server" 
    ID="AutoCompleteBoxLocation" 
    CssClass="RoundedTextBox" 
    Width="100%" 
    MethodName="GetAllLocations" 
    EmptyMessage="Search..." />
</td>

CS code

protected void LocationValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = !String.IsNullOrEmpty(args.Value);
        string errorMessage = "Required";

        ChangeErrorMessage(AutoCompleteBoxLocation.RadTextBox, args.IsValid, errorMessage.ToString());
    }

Now, on the same page I have several other ASPX markups exactly like this one, but with different IDs, that work; the Validate code block from the CS page fires. For this little bugger it ain't.

Any help is appreciated.

I have a asp.net page with the code as shown below.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

  <!DOCTYPE html>

  <html xmlns="http://www.w3.org/1999/xhtml">

  <head runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
    <style>
      body {
        margin: 0px;
      }
      header,
      footer {
        background-color: black;
        color: white;
        padding: 20px;
        text-align: center;
      }
      header {
        position: fixed;
        top: 0;
        width: 100%;
      }
      header li {
        display: inline-block;
        border: 1px solid rgb(0, 153, 255);
        background-color: dodgerblue;
      }
      header li:hover {
        background-color: white;
      }
      header a {
        text-decoration: none;
        color: white;
        padding: 15px;
      }
      header a:hover {
        color: dodgerblue;
      }
    </style>
  </head>

  <body>

    <form id="form1" runat="server">
      <div>
        <header runat="server">
          <h1>Welcome to SAIC</h1>
          <asp:Menu ID="MainMenu" runat="server" Orientation="Horizontal">
            <Items>
              <asp:MenuItem Value="Home" NavigateUrl="~/Home.aspx"></asp:MenuItem>
              <asp:MenuItem Value="Login" NavigateUrl="~/Login.aspx"></asp:MenuItem>
              <asp:MenuItem Value="Add Products" NavigateUrl="~/Add Products.aspx"></asp:MenuItem>
              <asp:MenuItem Value="View Product Details" NavigateUrl="~/View Product Details.aspx"></asp:MenuItem>
            </Items>
          </asp:Menu>
        </header>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
      </div>
      <footer>
        <p>Copyrights @ 2016</p>
      </footer>
    </form>
  </body>

  </html>

I've applied padding for anchor tag. But only padding-top and padding-bottom are being set. The padding of left and right are not appearing.

I've tried to set padding: 15px 15px 15px 15px; but that also doesn't work.

Here is the generated source. /* <![CDATA[ */ is being generated automatically. https://jsfiddle.net/q2Lcrgux/

I have a solution with two projects: one command-line application and one web application. I want to call a funcion from the console application from the web application. I have tried adding a reference and adding a reference to the .exe file of the console application but it is still not working. Any ideas on how to reference the console application?

it might sound stupid but let me explain, i have this ScriptManager.RegisterStartupScript and it does call a JS method which shows a pop up, I want to change the font-family of the text inside that pop up, how may i do it?

here is my code:

ScriptManager.RegisterStartupScript(Page, typeof(Page),
"custom_alert", "swal({title: 'Alart',text: 'Please take a long look at the text, and try again',type: 'error',confirmButtonText: 'Okay'})",
true);

I have a requirement for a project at work to print to a thermal printer (specifically a Citizen CT-S651) that is attached to the computer via USB from ASP.NET C# Webforms. So far, I have tried a few things and did a lot of research. The main three things I have tried was using QZ Tray (formerly known as JZebra, found here https://qz.io/), however the non-free version costs too much right now, and the free version is too annoying in its popups to be of much use right now. I also tried to generate a PDF using MigraDoc (http://www.pdfsharp.net/), but when I try to print to the printer, it uses far too much paper before it even prints "Hello World" code for that shown below:

    private void print()
    {
        Document document = CreateDocument();
        document.UseCmykColor = true;
        const bool unicode = false;

        const PdfFontEmbedding embedding = PdfFontEmbedding.Always;

        PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(unicode, embedding);

        pdfRenderer.Document = document;

        pdfRenderer.RenderDocument();

        //pdfRenderer.Save("C:/Users/jamesl/Documents/Visual Studio 2013/Projects/TestCheckScanner/TestCheckScanner/TestDocument.pdf");


        MemoryStream stream = new MemoryStream();
        pdfRenderer.PdfDocument.Save(stream, false);

        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-length", stream.Length.ToString());
        Response.BinaryWrite(stream.ToArray());
        Response.Flush();
        stream.Close();
        Response.End();

    }

    private Document CreateDocument()
    {
        Document document = new Document();

        MigraDoc.DocumentObjectModel.Unit width, height;

        width = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(80);
        height = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(50);


        Section section = document.AddSection();
        section.PageSetup.PageHeight = height;
        section.PageSetup.PageWidth = width;
        section.PageSetup.PageHeight = height;
        section.PageSetup.PageWidth = width;
        section.PageSetup.LeftMargin = 0;
        section.PageSetup.RightMargin = 0;
        section.PageSetup.TopMargin = 0;


        Paragraph paragraph = section.AddParagraph();

        paragraph.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black; //Same as System.Drawing.Color

        paragraph.AddFormattedText("Hello, World!");

        return document;
    }

Since that hasn't worked very well, I have gotten it to print a little bit using PrintDocument, however, the main problems I have with this way are twofold: 1. Formatting it print a proper receipt is going to be very tedious although if it is ends up being the best way with my current constraints I am all for it. 2. This method only works if I print from Visual Studio, when I try it on the test web app I have set up on a server, I get an error of "Settings to access printer 'CITIZEN CT-S651' are not valid." Here is my code for that:

    private void print()
    {

        try
        {
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            pd.PrinterSettings.PrinterName = "CITIZEN CT-S651";
            pd.Print();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            Response.End();
        }
    }

    void pd_PrintPage(object sender, PrintPageEventArgs e)
    {
        e.Graphics.DrawString("Test Print", new System.Drawing.Font("Arial", 12), new SolidBrush(Color.Black), 60, 0);
        e.Graphics.DrawString("Test Again", new System.Drawing.Font("Arial", 12), new SolidBrush(Color.Black), 60, 20);
    }

Any help you can give on this matter would be awesome!

I'm developing an ASP.Net web application, using MVC 5. This application authenticates via LDAP and will assign an Identity Role of "Admin" to a designated user.

The Admin user will be able to go to an administration page to add users with a role of either "Admin" or "Employee".

I am using the UserManager class from ASP.Net Identity

My question: How can my Controller and Model solution be improved? The View is not complete so that can be overlooked, but I would appreciate some help with best practice or best technique when dealing with controllers and models.

Would there be a better way to implement this? It works fine but this is my first web application, less than a year of experience and I would like to start off with good programming habits.

Thanks!

My controller code:

public ActionResult Manage()
    {
        var users = UserManager.Users.ToList();
        var list = new List<ManageViewModel>();

        foreach (var user in users)
        {
            var isAdmin = UserManager.IsInRole(user.Id, "Admin");
            var isEmployee = UserManager.IsInRole(user.Id, "Employee");
            list.Add(new ManageViewModel { Id = user.UserName, isAdmin = isAdmin, isEmployee = isEmployee });
        }

        var viewModel = new ManageViewModel
        {
            Users = list,
        };

        return View(viewModel);

My viewModel class:

    public class ManageViewModel
{
    public string Id { get; set; }
    public bool isAdmin { get; set; }
    public bool isEmployee { get; set; }
    public List<ManageViewModel> Users { get; set; }
}

And here's my simple View to display application user information (still need to implement the logic to set user roles).

@model App.ViewModels.ManageViewModel
@{
    ViewBag.Title = "Manage Application Users";
}

<h2>Manage Application Users</h2>

@foreach (var user in Model.Users)
{
    <li>
        @user.Id
        @user.isAdmin
        @user.isEmployee
    </li>
}

My idea is to create a sessionID from the login page, and save it into DB, then after login, jump to myInfo.aspx. At myInfo.aspx i will check systemID( as sid) and sessionID to see if them match to login page

But i found the sessionID i create from login page, by string newSessionID = manager.CreateSessionID(Context) is different than the one i get from myInfo.aspx by string sessionID = manager.GetSessionID(Context);

login page:

// check user name and password, then get system ID(sid) from this user

    Session.Clear();
    Session.Abandon();
    Response.Cookies.Clear();
    Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

    SessionIDManager manager = new SessionIDManager();
    string newSessionID = manager.CreateSessionID(Context);
    bool redirected = false;
    bool isAdded = false;
    manager.SaveSessionID(Context, newSessionID, out redirected, out isAdded);
// write sessionID to DB
    logins.updateSession(sid, newSessionID,"landlord");
    Response.Redirect("~/MyInfo.aspx?sid="+sid);

page 2: MyInfo.aspx

    protected void Page_Load(object sender, EventArgs e)
    {

        SessionIDManager manager = new SessionIDManager();
        string sessionID = manager.GetSessionID(Context);

        if (logins.checkSession(sid, sessionID, "landlord")==false)
        {
            Response.Redirect("Default.aspx");
        }
}

Thanks

I am using visual studio using asp.net and c#

I currently have an imagebutton and when you click on the image it tells you the coordinates and adds them into a table. I now need to make it so when you click the image it also leaves a marker there such as an X. Im new to visual studio and the language so I am wondering what the easiest and best way to accoplish this.

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    Label1.Text = "The shot is recorded at the coordinates: (" +
                   e.X.ToString() + ", " + e.Y.ToString() + ")";
    SqlDataSource1.InsertParameters["xCoordinate"].DefaultValue = e.X.ToString();
    SqlDataSource1.InsertParameters["yCoordinate"].DefaultValue = e.Y.ToString();
    SqlDataSource1.Insert();
}

this is what I have for my event handler so far, im assuming i need to use some drawing function to leave the marker on the image but im not familar with the code to do so. I havnt been able to find any questions on here for what Im trying to do, so any help would be greatly appreciated.

I would like to use the following library in order to implement versioning for my Web API application (using .NET Core 1.0). However as this library is currently pre-release I haven't been able to find any documentation for it.

https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Versioning/1.0.0-beta1

Are there any examples on how this library? Or source code? Does it support specifying the version in the URL query string? E.g. http://www.example.com/api/products?version=1

I've also considered the following library however it doesn't appear to support .NET Core:

https://github.com/Sebazzz/SDammann.WebApi.Versioning

We have issue about upload file to google drive, it is a service, when user put something in our "WatchFolder", our service will automatic upload file to google drive, we hope user login google account in ASP web page, get token, and then service use that token upload file, but the service is C#, do anyone have way to do that kind of things?

I keep getting this error when building:

Unrecognized configuration section system.identityModel

I have added the following to my config:

<system.identityModel>
    <identityConfiguration>
      <audienceUris>
        <add value="TEST"/>
      </audienceUris>
      <issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <trustedIssuers>
          <add thumbprint="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234" name="YourSTSName"/>
        </trustedIssuers>
      </issuerNameRegistry>
      <certificateValidation certificateValidationMode="None"/>
    </identityConfiguration>
  </system.identityModel>

I am using .Net 4.6

Here is a typical problem. Imagine that you have a table of data, where you can add, update and delete rows dynamically (in ajax).
Your data table is complex, with many fields, dropdowns, textboxes, etc.

How would you create the rows in javascript ? I currently have a lot of JS/Jquery creating and populating nodes, but I find it quite ugly, and not very reusable.

I would love to have my row's HTML in a user control that I could call in ajax (through a service for instance), so that I can create a row both in JS and in .net, but I'm not sure how to proceed.

I would like to include a JavaScript file with razor like this

<script src="@ScriptPath"></script>

Except that I need to change some pathnames dynamically according to @ScriptPath inside the JavaScript before I do. Something like replace all will do.

Can it be achieved and how can it be achieved with razor or/and through controllers?