I would like to display records from an Umbraco forms on a page. So far, I managed to display:

  • total numbers of records
  • all records where "Display my name" value is TRUE

How do I limit it to display only 5 newest records (where "Display my name" value is TRUE)?

My codes below:

<ul id="formData">
    @{int i = 0;}	
    @foreach (dynamic record in Library.GetApprovedRecordsFromPage(@CurrentPage.Id).OrderBy("Created descending"))
    {		
        if (@record.GetField("Display my name").Values[0].ToString() == "True")
        {
            <li>								
                Name: @record.GetField("Name").Values[0]<br />
                Email: @record.GetField("Email").Values[0]<br />
                Display my name: @record.GetField("Display my name").Values[0]<br />	
                Created: @record.Created.ToString("dd MMMM yyy")<br />
            </li>
        }
        i++;	
    }					
</ul>
<h4>Total data: @i</h4>

I'd like to preface this saying I know very little JavaScript.

I have a Bootstrap datepicker using a date range, picked up from eternicode.

My goal is to select a day in startDate and then have the days available to endDate only be on or after startDate and within startDate's financial year.

Examples:

  • If I chose Oct 1st 2016, the endDate should cap out at Sep 30th 2017

  • If I chose Jan 12th 2017, the endDate should cap out at Sep 30th 2017

  • If I chose Sep 30th 2017, the endDate should also be Sep 30th 2017

  • Pretty much, if the startDate month is in [Oct, Nov, Dec] then endDate caps out at Sep 30th (startDate year + 1) else endDate caps out at Sep 30th (startDate year)

In my reportWebpage.cshtml file I have:

<div class="col-md-2">
    Date Range:
</div>
<div class="col-md-5" id="dateRangeContainer">
    <div class="input-daterange input-group" id="datepicker">
        @Html.TextBox("startDate", "", new { @class = "input-sm form-control", name= "startDate" })
        <span class="input-group-addon">to</span>
        @Html.TextBox("endDate", "", new { @class = "input-sm form-control", name = "endDate" })
    </div>
</div>

In my related.js I have a very basic datepicker setup:

$(function () {
    $('#dateRangeContainer .input-daterange').datepicker({
        autoclose: true,
        todayBtn: "linked",
        clearBtn: true
    });
});

I know there is a datesDisable property I can set, and while it's functionality is what I want it seems to be based off an array of dates which seems like the wrong idea here.


As a test, I replaced the datapicker js code above with what is shown below.

Like in this SO Answer I've tried adding an onSelect property to just the #startDate datepicker, but I'm not getting a response from the alert embedded, nor is Google Chrome's Dev Tools hitting the debug point placed on it:

$('#startDate').datepicker({
    onSelect: function() {
        var date = $(this).datepicker('getDate'),
            day = date.getDate(),
            month = date.getMonth() + 1, // Offset the zero index to match normal month indexes
            year = date.getFullYear();
        alert(day + '-' + month + '-' + year);
    }
});

I was hoping that by doing that I could at least start building some if else loops or something.

I'm struggling to figure out how to even start with this problem, so any help or suggestions will be very much appreciated!

I'm trying to set up a web application so that it handles permissions based on the device being used to open the application. For example, any users who logged on to Device A can access www.example.com/Site/1, and any users who logged on to Device B can access www.example.com/Site/2.

But, all users have to log on to the device, so it seems that the cookie needs to be created for each user who logged on a device.

Is it even possible to share a cookie between multiple users as long as they are logged on to the same device?? I've been searching but I just can't find any information on this.

This is a really simple problem I can't figure out. I am trying to get the value of a dropdownlist using Javascript. I have 4 digit job codes in my dropdownlist. On a button click I got to this function and am trying to get the value of what was selected when a button was pushed.

 function jobCodeToAdd() {

 var jobCode = document.getElementById("<%=jobCode.ClientID%>"));
 var selectedJobCode = jobCode.options[jobCode.selectedIndex].value;

What am I doing wrong? Thank you for your help.

I have ashx handler which throws this exception during compilation phase

C:\path\MyHandler.ashx(67): error BC32206: The project currently contains references to more than one version of Some.Assembly, a direct reference to version 17.1.0.23 and an indirect reference (through 'Other.Assembly') to version 17.1.3.9. Change the direct reference to use version 17.1.3.9 (or higher) of Some.Assembly. at System.Web.Compilation.BuildManager.PostProcessFoundBuildResult(BuildResult result, Boolean keyFromVPP, VirtualPath virtualPath)...

Even though, I added this configuration in web.config

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

        <dependentAssembly>
            <assemblyIdentity name="Some.Assembly" />
            <bindingRedirect oldVersion="17.1.0.0-17.1.3.9" newVersion="17.1.0.23" />
        </dependentAssembly>

      . . . . 

When website starts and handler is compiled on the first use, it seem that it ignores my directive to use the specific version and suggests "Change the direct reference to use version 17.1.3.9". But now I am thinking that this is the key - compilation vs runtime. My directive is runtime. Is there a way to go around this, for example, using compilation tag?

i have created an android app to publish my products online, for that i have created a ASMX web service, and it's works fine. Now i want to create a website using php to display all my products listed in my database. My question is how can i access to this database using my web service and display all the data?

there is the methode getToolListing to get all the tools from database

        [WebMethod(MessageName = "GetToolListing", Description = "This method call ToolListing Procedure")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
    public void GetToolListing(string UserID, string Distance, string From, string to, string ToolTypeID, string ToolID, string q)
    {
        if (q.Equals("@")) q = "%"; // android cannot call link with %
        else
            q = "%" + q + "%";

        JavaScriptSerializer ser = new JavaScriptSerializer();

        ToolListing[] ToolData = null;
        int HasTool = 0;
        try
        {
            using (SqlConnection connection = new SqlConnection(DBConnection.ConnectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "ToolListing";
                cmd.Connection = connection;
                cmd.Parameters.AddWithValue("@UserID", UserID);
                cmd.Parameters.AddWithValue("@Distance", Distance);
                cmd.Parameters.AddWithValue("@From", From);
                cmd.Parameters.AddWithValue("@to", to);
                cmd.Parameters.AddWithValue("@ToolTypeID", ToolTypeID);
                cmd.Parameters.AddWithValue("@q", q);
                cmd.Parameters.AddWithValue("@ToolID", ToolID);
                connection.Open();

                SqlDataAdapter adpt = new SqlDataAdapter(cmd);
                DataTable dataTable = new DataTable();
                adpt.Fill(dataTable);

                ToolData = new ToolListing[dataTable.Rows.Count];
                int Count = 0;
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    ToolData[Count] = new ToolListing();
                    ToolData[Count].ToolID = Convert.ToString(dataTable.Rows[i]["ToolID"]);
                    ToolData[Count].ToolName = Convert.ToString(dataTable.Rows[i]["ToolName"]);
                    ToolData[Count].ToolDes = Convert.ToString(dataTable.Rows[i]["ToolDes"]);
                    ToolData[Count].ToolPrice = Convert.ToString(dataTable.Rows[i]["ToolPrice"]);
                    ToolData[Count].DateAdd = Convert.ToString(dataTable.Rows[i]["DateAdd"]);
                    ToolData[Count].PictureLink = Convert.ToString(dataTable.Rows[i]["PictureLink"]);
                    Count++;
                }
                if (dataTable.Rows.Count > 0)
                    HasTool = 1;
                dataTable.Clear();

                connection.Close();

            }


        }
        catch (Exception ex)
        {

        }
        var jsonData = new
        {
            ToolData = ToolData,
            HasTool = HasTool

        };

        HttpContext.Current.Response.Write(ser.Serialize(jsonData));
    }

I am using asp.net. I have a public form that users can create new accounts on, that sends out a verification text message to the user's phone when they hit submit. I don't want spam bots sending out these text messages that cost me money by posing as users.

It is my "guess" that a spam bot or script has to screen scrape the html from the page and find the javascript function that will send this info out via ajax to an asp.net page that sends text messages out. It can't just call and execute the javascript in place and on my server like my javascript does with real users and button clicks, so instead it will execute on whatever server or computer their script is running on and insert the values it got from screen scraping and make a get request or post to the correct url, and that computer or server ip address that the script is running on should show up as the http referrer.

Is that true?

If so, then can I check the http referrer variable when my asp.net page that will send the text message out gets invoked? I'm thinking that if spam bots work the way I think, and they are actually executing a script that mimics the javascript calls on the page but they are not due to user clicks, the script would have to be executing on another server or domain.

Is that true?

And can a script spoof the http referrer variable?

public ActionResult AddComplianceForm(string TemplateName)
{
}

In this ASP.net MVC5 application there is a folder Templates that contains a bunch of different classes that all have different TemplateName attributes. The first part of this method needs to find the class that has a TemplateName matching the string passed in. I then need to create an instance of whatever template matched. I am very new to working with attributes in C# so help would be very appreciated. I mostly need to know how to access that folder of classes in the program to look into it.

How can I somehow combine this:

@Html.TextBoxFor(model => model.Value)

with applying the invariant culture on a razor page

System.Globalization.CultureInfo.InvariantCulture

I want to avoid making changes in the web.config globalization setting and only apply this for a few input fields where needed. Thank you.

I know there are tons of posts similar to this, but I cannot seem to find the answer after much investigation. On post back CompanySetting.NewSetting.SettingType and CompanySetting.NewSetting.SettingValue are null, despite putting text into the TextBoxFor fields and clicking submit. Why is this?

Here is the view:

@model Project.Models.CompanySettingView
@using (Html.BeginForm())
                {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <form>
            <div class="form-group">
             <label>Setting Type</label>
             @Html.TextBoxFor(m => m.NewSetting.SettingType, new { @class = "form-control", @id = "SettingType" })

            <br />

             <label>Setting Value</label>
             @Html.TextBoxFor(m => m.NewSetting.SettingValue, new { @class = "form-control", @id = "SettingValue" })

            <br />
          </div>
            <div style="float: right;">
            <button type="button" style="width:100px;" onclick="ClearFields()" class="btn btn-default">Clear</button>
            <button type="submit" style="width:100px;" class="btn btn-primary">Submit</button>
           </div>
         </form>
                }

Receiving Controller:

 [HttpPost]
public ActionResult AddCompanySetting(CompanySettingView model)
{
...
}

CompanySettingView Class:

public class CompanySettingView
{
    public List<CompanySetting> Settings = new List<CompanySetting>();
    public CompanySetting NewSetting = new CompanySetting();
}

CompanySetting Class:

 public class CompanySetting
 {
     public int CompanySettingId { get; set; }
     public int CompanyId { get; set; }
     public string SettingType { get; set; }
     public string SettingValue { get; set; }
 }

Environment is ASP.NET Core.

Considering the following object:

public class DynField
{
        public long FieldID { get; set; }
        public string Fieldalue { get; set; }
}

And let's say I have a View with a form that should display a dynamic number of these field objects, i.e.

@model List<DynField>

Assuming all fields can be collecting using simple text Input, does any Razor syntax exist that allows me to collect both the FieldID and the FieldValue when the Form posts?

Something along these lines of...

 @for (int i = 0; i < Model.Count; i++)
 {
    var field = Model.[i]
    <tr>
       <td>@field.FieldName:</td>
       <td>
          <input type="text" name="@("Model["+ i + "].FieldID")" />
       </td>
    </tr>
 }

I'm hoping the fields can be collected using the default model binder.

public IActionResult DynFieldSearchResult(List<DynField> search)

Thanks in advance!

I am using Dto for data transfer view to domain and use automapper for mapping. My problem is, the property that not exist dto but i need to set before mapping to domain. I have tried to use Linq query to get external data from db on before and after mapping methods but linq query giving error.

Sample below

FooDto

public class FooDto 
{
public int MyProperty1 {get;set;}
}

FooDomain

public class Foo 
{
public int MyProperty1 {get;set;}
public int MyProperty2 {get;set;}
public int Foo2ID {get;set;}
public virtual Foo2 Foo2 {get;set;}
}

Foo2Domain

public class Foo2
{
public int ID {get;set;}
public int MyProperty1 {get;set;}
}

**AutoMapper*

Mapper.Initialize(x =>
{
x.CreateMap<FooDto, Foo>().BeforeMap(
(src, dest) =>dest.MyProperty2 = dest.Foo2.MyProperty1);
}

I want to set Foo2.MyProperty1 to Foo.MyProperty2 using mapping.

I have a page in which i am sending out an email blast. The page works and sends out an email. However, when i a try to add email addresses to include as replyto recipients i am getting this error:

'System.Net.Mail.MailMessage' does not contain a definition for 'ReplyToList' and no extension method 'ReplyToList' accepting a first argument of type 'System.Net.Mail.MailMessage' could be found (are you missing a using directive or an assembly reference?)   

i am using this code:

mailMessage.ReplyToList.Add("abc@abc.com");

this works for mailMessage.CC.Add("abc@abc.com");mailMessage.bcc.Add("abc@abc.com"); etc.

Thank you

I am using a CheckBoxList to display a group of Business Units. I want to restrict the selection to max 5 items and if the user selects the 6th Item then i should display an alert and Unselect the 6th Item selected.

The control is as below :

<asp:CheckBoxList ID="ckBLBusinessUnits" onclick="loader(this.id);" runat="server" AutoPostBack="True" Visible="false" OnSelectedIndexChanged="ckBLBusinessUnits_SelectedIndexChanged"></asp:CheckBoxList>

JS function i am using is:

function loader(controlID) {
    modal = document.getElementById('loadingImage');
    modal.style.display = "block";

    if (controlID == "ckBLBusinessUnits")
    {
        if (($('#ckBLBusinessUnits :checkbox:checked').length) > 5)
        {
            alert("Max 5 BU's can be selected");
//is it possible to uncheck here? I am unable to find any method to do so.
        }
    }
}

C# is below :

protected void ckBLBusinessUnits_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (selectedValues.Count <= 5)
            {
                //Do something and then disable the loader.
                loadingImage.Style.Add("display", "none");
            }
            else if (selectedValues.Count > 5)
            {
               //is it possible to uncheck here? I am unable to find any method to do so.
            }

        }

I am using the namespace test1 in the UserControl and is kept inside the UserControl folder and the class name is uc_ucname1 and I have a class file datafile.cs which inherits Page as well as Itemplate have same namespace i.e. test1 kept inside the App_code , both the folders reside in the Asp.net Web type project. When I try to access the UserControl file using uc_ucname1 in the datafile, it says type or name space 'uc_ucname1' could not be found.

I am working on a project where I need to pull GeoJSON from my .NET API via a jQuery ajax call. When I try to assign the data to a variable, and then load it into Google Maps like this:

 map.data.addGeoJson(data);

It throws an error saying:

js:70InvalidValueError: not a Feature or FeatureCollection

If I were to take that same response that the API gives, and paste it directly into the html file (so assign the same value to the JS variable data) it works fine and the map renders

My guess is maybe there is an encoding issue? I even output the response to a div, copied that div's values, pasted it in, and it worked. It seems to only be when I directly assign the value from the API that it throws an error.

Any ideas what I could do to format this or get it working correctly? Is the script "breaking" b/c of formatting or something when it's being directly written out in JavaScript?

Thanks so much!

I'm doing a project that requires reading an API into multiple platforms (there include: Windows Forms, ASP and Xamarin Forms PCL) I can do that separately, although I want to have something that I can do it all just once and just call method from each platform. But the thing is, I've been doing some tests and doing some research and looks like that is no class library that is compatible with all these three, at least.

So, I've been wondering, is there any alternative thatn just having to do it all separatly? I mean, between ASP and Windows Forms would work just fine, but Xamarin is a whole different story.

Anyway, I'd appreciate any help given.

I have a requirement of building a view which will look like outlook calendar in which each day will be having some workorders links specific to user valid for a day.Once the user clicks on any workorder it will land to another view with the workorder detail.

Could you suggest me the best approach to be taken here to incorporate this requirement? I am using asp.net MVC.

I want a custom button that magnifies the element, i.e., card, gauge, graph, etc, that the button is on.

I've only implemented the functionality for a blank pop-up to occur when I click on my custom button. How can I get the visual that is on the element to appear on the pop-up?

Thanks in advance!

function zoomWidget() {
    popup.Show();
}‚Äč

I'm using Asp.net Core with AutoFac and following the accepted answer here:

Validation: How to inject A Model State wrapper with Ninject?

This uses ninject. I don't understand how to do the equivalent of this ninject part in autoFac, specifically the kernel.Get:

Func<Type, IValidator> validatorFactory = type =>
{
    var valType = typeof(Validator<>).MakeGenericType(type);
    return (IValidator)kernel.Get(valType);
};

kernel.Bind<IValidationProvider>()
    .ToConstant(new ValidationProvider(validatorFactory));

Startup.cs

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    var containerBuilder = new ContainerBuilder();

    IValidator ValidatorFactory(Type type)
    {
        var valType = typeof(Validator<>).MakeGenericType(type);

        //This line is the problem
        // return (IValidator)container.Resolve(valType);
    }


    containerBuilder.Register(x => new ValidationProvider(ValidatorFactory)).As<IValidationProvider>().SingleInstance();

    containerBuilder.RegisterType<UploadValidator>().As<Validator<AudioModel>>();

    containerBuilder.Populate(services);

    var container = containerBuilder.Build();

    return container.Resolve<IServiceProvider>();
}

Validation classes:

internal sealed class ValidationProvider : IValidationProvider
{
    private readonly Func<Type, IValidator> _validatorFactory;

    public ValidationProvider(Func<Type, IValidator> validatorFactory)
    {
        _validatorFactory = validatorFactory;
    }

    public void Validate(object entity)
    {
        var results = _validatorFactory(entity.GetType()).Validate(entity).ToArray();

        if (results.Length > 0)
            throw new ValidationException(results);
    }

    public void ValidateAll(IEnumerable entities)
    {
        var results = (
            from entity in entities.Cast<object>()
            let validator = _validatorFactory(entity.GetType())
            from result in validator.Validate(entity)
            select result).ToArray();

        if (results.Length > 0)
            throw new ValidationException(results);
    }
}

public abstract class Validator<T> : IValidator
{
    IEnumerable<ValidationResult> IValidator.Validate(object entity)
    {
        if (entity == null)
            throw new ArgumentNullException(nameof(entity));

        return Validate((T)entity);
    }

    protected abstract IEnumerable<ValidationResult> Validate(T entity);
}

public class UploadValidator : Validator<AudioModel>
{
    protected override IEnumerable<ValidationResult> Validate(AudioModel model)
    {
        if (string.IsNullOrWhiteSpace(model.Name))
        {
            yield return new ValidationResult("Name", "Name is required");
        }
    }
}

I'm trying to bind each of 3 DropDownList Controls after selecting an item in the previous DropDownList..

DDLType.SelectedItem binds DDLMain DDLMain.SelectedItem binds DDLSub1 DDLSub1.SelectedItem bind DDLSub2

but after selecting an item from the first DropDownList, all the other DropDownList Controls disappear, although it works well without the UpdatePanel.

Edit: I tried it on another page, and it works fine without any CSS or other controls. What can be the problem then ?

ASPX

            </li>
            <li id="liMain" runat="server">
                <asp:DropDownList ID="DDLMain" runat="server" OnSelectedIndexChanged="DDLMain_OnSelectedIndexChanged" AutoPostBack="True">
                </asp:DropDownList>

            </li>
            <li id="liSub1" runat="server">
                <asp:DropDownList ID="DDLSub1" runat="server" OnSelectedIndexChanged="DDLSub1_OnSelectedIndexChanged" AutoPostBack="True">
                </asp:DropDownList>

            </li>
            <li id="liSub2" runat="server">
                <asp:DropDownList ID="DDLSub2" runat="server" OnSelectedIndexChanged="DDLSub2_OnSelectedIndexChanged" AutoPostBack="True">
                </asp:DropDownList>

            </li>
            </ul>
            <a href="#!" class="btn btn-primary" style="width: 90%">Search</a>
            </div>
            </div>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
        </ul>

Behind Code

protected void Page_PreRender(object sender, EventArgs e)
{
    List<string> typeList = new List<string>();
    for (int i = 0; i < 4; i++)
    {
        typeList.Add("Type" + i);
    }
    DDLType.DataSource = typeList;
    DDLType.DataBind();
}

protected void DDLType_OnSelectedIndexChanged(object sender, EventArgs e)
{

    List<string> subList1 = new List<string>();
    for (int i = 0; i < 4; i++)
    {
        subList1.Add("Main" + i);
    }
    DDLMain.DataSource = subList1;
    DDLMain.DataBind();
    DDLType.Visible = true;
    DDLMain.Visible = true;
    DDLSub1.Visible = false;
    DDLSub2.Visible = false;
    DDLType.EnableViewState = true;
    DDLMain.EnableViewState = true;
}

protected void DDLMain_OnSelectedIndexChanged(object sender, EventArgs e)
{
    List<string> subList1 = new List<string>();
    for (int i = 0; i < 4; i++)
    {
        subList1.Add("Sub1 " + i);
    }
    DDLSub1.DataSource = subList1;
    DDLSub1.DataBind();
    DDLType.Visible = true;
    DDLMain.Visible = true;
    DDLSub1.Visible = true;
    DDLSub2.Visible = false;
    DDLType.EnableViewState = true;
    DDLMain.EnableViewState = true;
    DDLSub1.EnableViewState = true;
}

protected void DDLSub1_OnSelectedIndexChanged(object sender, EventArgs e)
{
    List<string> subList1 = new List<string>();
    for (int i = 0; i < 4; i++)
    {
        subList1.Add("Sub2 " + i);
    }
    DDLSub2.DataSource = subList1;
    DDLSub2.DataBind();
    DDLType.Visible = true;
    DDLMain.Visible = true;
    DDLSub1.Visible = true;
    DDLSub2.Visible = true;
    DDLType.EnableViewState = true;
    DDLMain.EnableViewState = true;
    DDLSub1.EnableViewState = true;
    DDLSub2.EnableViewState = true;
}

protected void DDLSub2_OnSelectedIndexChanged(object sender, EventArgs e)
{
    DDLType.Visible = true;
    DDLMain.Visible = true;
    DDLSub1.Visible = true;
    DDLSub2.Visible = true;
}