I have following input element in razor view page

<input type="file" id="uploadFile" name="FileUpload" multiple="multiple" />

using following script I'm binding data to this ForData

$('#uploadFile').on('change', function()
{

  var fd = new FormData();
  var files = $('#uploadFile')[0].files;


  for (var i = 0; i < files.length; i++) 
  {
    if (files[i].size < 5242880) 
    {       
       fd.append("myFiles", files[i])
    }
  }  
});

I'm trying to get these files in C# method like following

[HttpPost]        
public ActionResult SomeAction(ModelClass model)
{
    var attchaedfiles = System.Web.HttpContext.Current.Request.Files["myFiles"];

                for (int i = 0; i < attchaedfiles.Count; i++)
                {
                    if (!string.IsNullOrEmpty(attchaedfiles[i].FileName))
                    {
                      ....
                    }
                }
}

but here I'm getting folllowing errors

Operator '<' cannot be applied to operands of type 'int' and 'method group'

Cannot apply indexing with [] to an expression of type 'System.Web.HttpPostedFile'

I am trying to connect my mobile app developed using Xamarin MvvmCross to the Azure Mobile App backend database.

I have successfully done this before, until I created a new project and the new Azure backend server requires ZUMO-API-VERSION 2.0.0 to GET the data. I followed the exact same procedures on retrieving the data, starting from creating the data model, interface for azure and the data, as well as Azure database class. I also registered them in the Setup.cs.

I have put some data in the database. However, when I try to get the data using var members = await memberDatabase.GetMembers(); the result is null. Any idea on what I am doing wrong?

Here I attach some relevant codes:

Project.Core/Models/Members.cs

public class Members
{
    public Members() { }
    public string ID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DOB { get; set; }
    public string MemberSince { get; set; }
    public double CurrentBalance { get; set; }
}

Project.Core/Interfaces/IDatabaseMembers.cs

public interface IDatabaseMembers
{
    Task<IEnumerable<Members>> GetMembers();
}

Project.Core/Interfaces/IAzureDatabase.cs

public interface IAzureDatabase
{
    MobileServiceClient GetMobileServiceClient();
}

Project.Core/Database/Members.cs

public class AzureDatabaseMembers : IDatabaseMembers
{
    private MobileServiceClient azureDatabase;
    private IMobileServiceSyncTable<Members> azureSyncTable;
    public AzureDatabaseMembers()
    {
        azureDatabase = Mvx.Resolve<IAzureDatabase>().GetMobileServiceClient();
        azureSyncTable = azureDatabase.GetSyncTable<Members>();
    }

    public async Task<IEnumerable<Members>> GetMembers()
    {
        await SyncAsync(true);
        var members = await azureSyncTable.ToListAsync();
        return members;
    }

    private async Task SyncAsync(bool pullData = false)
    {
        try
        {
            await azureDatabase.SyncContext.PushAsync();

            if (pullData)
            {
                await azureSyncTable.PullAsync("Members", azureSyncTable.CreateQuery()); // query ID is used for incremental sync
            }
        }

        catch (Exception e)
        {
            Debug.WriteLine(e);
        }
    }
}

Project.Droid/Database/AzureDatabase.cs

public class AzureDatabase : IAzureDatabase
{
    MobileServiceClient azureDatabase;

    public MobileServiceClient GetMobileServiceClient()
    {
        var platform = new Microsoft.WindowsAzure.MobileServices.CurrentPlatform();
        System.Diagnostics.Debug.WriteLine(platform);
        CurrentPlatform.Init();

        azureDatabase = new MobileServiceClient("http://myweb.azurewebsites.net/");
        InitializeLocal();
        return azureDatabase;
    }

    private void InitializeLocal()
    {
        var sqliteFilename = "Local.db3";
        string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
        var path = Path.Combine(documentsPath, sqliteFilename);
        if (!File.Exists(path))
        {
            File.Create(path).Dispose();
        }
        var store = new MobileServiceSQLiteStore(path);
        store.DefineTable<Project.Core.Models.Members>();
        azureDatabase.SyncContext.InitializeAsync(store);
    }
}

Project.Droid/Setup.cs

public class Setup : MvxAndroidSetup
{
    .
    .
    .
    protected override void InitializeFirstChance()
    {
        Mvx.LazyConstructAndRegisterSingleton<IAzureDatabase, AzureDatabase>();
        Mvx.LazyConstructAndRegisterSingleton<IDatabaseMembers, AzureDatabaseMembers>();
        base.InitializeFirstChance();
    }
}

I am making a n tier architecture program - which has BAL - Business access logic library, DAL - Data access logic - library, and settings - a library, and the main application - executable - asp.net web form. Now, I have written a unit test case to test the settings library - this library does nothing but reads the connection string from the main application web.config. When I invoke test case, the connection string isn't read. What am I doing wrong here.

web.config from the executable project -

 <connectionStrings>
    <!-- DataSource is SQLEXPRESS and Catalog is DBNAME-->
    <add name="SqlCon" connectionString="Data Source=SHREYAS-PC\SQLEXPRESS;Initial Catalog=SchoolManagementDb;Integrated Security=true"/>  
  </connectionStrings>


settings library -- 

namespace Settings
{
    public class Settings
    {
        public static string ConnectionString()
        {
            try
            {
                string Con = ConfigurationManager.ConnectionStrings["SqlCon"].ToString();
                return Con;

            }
            catch(Exception ex)
            {
                throw;
            }
        }
    }
}

The unit test case --

[TestClass]
    public class UnitTestSettings
    {
        [TestMethod]
        public void TestMethod1()
        {
            string con = Settings.Settings.ConnectionString();
            Console.WriteLine(con);
        }
    }

Unfortunately, when I am running the unit-test case, the connectionString return is NULL, whereas if I run the entire application I get the results I desire. Am I missing any concept here?

I've got a .NET MVC project. I've got two databases. One is called AfterContext which contains a few tables and the other is DefaultConnection which contains the AspNetUsers table etc.

I've added columns to the IdentityModels.cs file and then migrated them into AspNetUsers using: Enable-Migrations -ContextTypeName After.Models.ApplicationDbContext -MigrationsDirectory Migrations\ApplicationDbContext

But now I want to add a column to a table in AfterContext. I'm just a bit worried that the column will end up int the AspNetUsers table. How can i prevent this from happening. If I use Enable-Migrations -ContextTypeName After.DAL.AfterContext is that enough to do it?

Or is there an fail safe and easy way to switch between migrating different schemas?

Thanks.

in Umbraco I want to create a custom data type which represent a dynamic list of Entity which has a content in "RichTextBox" and a primary image.

I want use this dataType to create a page with a list of related topic witch are not a independent article and are only related to main Article.

how can I create this DataType? is there any solution with combination with Macroes and datatype in Umbraco?

I'm making a API Web service, How can I block the HTTP requests from browser?

Also, how can I block continues request from same IP ?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.Net.Mail;
using System.Net;

public partial class ForgetPassword : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnPassRes_Click(object sender, EventArgs e)
    {
        String CS = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd= new SqlCommand("select * from tbl_User Where Email='"+tbEmailId.Text+"'",con);
            con.Open();
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            if (dt.Rows.Count!=0)
            {
                String myGUID = Guid.NewGuid().ToString();
                int Uid =Convert.ToInt32(dt.Rows[0][0]);
                    SqlCommand cmd1 = new SqlCommand ("Insert into ForgetPasswordRequest values('"+myGUID+"','"+Uid+"',getdate())",con);
                    cmd1.ExecuteNonQuery();
                **//Send Email Coding Start From Here**  
                    String ToEmailAddress = dt.Rows[0][5].ToString();
                    String Username = dt.Rows[0][1].ToString();
                    String EmailBody = "Hii " + Username + ",<br/><br/> Click the link Below  to Reset Your Password <br/><br/> http://localhost:2958/RecoverPassword.aspx?Uid=" +myGUID;
                    MailMessage send = new MailMessage("youremail@gmail.com", ToEmailAddress);
                    send.Body = EmailBody;
                    send.IsBodyHtml = true;
                    send.Subject = "Reset Password";


                    SmtpClient SMTP = new SmtpClient("smtp.gmail.com", 587);
                    SMTP.Credentials = new NetworkCredential()
                    {
                        UserName = "yourusername@gmail.com",
                        Password = "yourGmailPassword"
                    };
                    SMTP.EnableSsl = true;
                    SMTP.Send(send);/////// error from there



                    lblforget.Text = "Please Check Your Email And Reset Your Password With Reset Link !!";
                    lblforget.ForeColor = Color.Green;
                    tbEmailId.Text = "";

            }
            else
            {
                lblforget.Text = "Please Enter A Valid Email Your is Not Register In our Database !!";
                lblforget.ForeColor = Color.Red;
            }
        }
    }
}

I created a web form for users to reset their password, with a reset password link, but it's not working. Please help - where is the error? What should I do?

This code is for sending a reset link to the user's e-mail and then user gets the link, but it's not working

I want to do a project which is for one of my friend. Projects like upload a excel show that in grid with search feature and some additional feature. I am confused little bit that how can i do that.

I can do that in ASP.NET c#, but which is better windows application or Web application?

If i do that in windows or web how i will give him the database and project? Please make some suggestion's.

I have a gridview with columns ' provider , client ,amount, startdate'.There are two dropdownlists for start date and end date .I want to change the color of a row for a particular date. Suppose if the startdate displayed in the grid is 21/2/17 then it should be green ,or if it is 3/2/17 it should be red etc...I am using asp.net c# and I have to apply the same to different pages .Someone please help me with the css and javascript to apply the changes.

I want to make customer queuing system (FIFO) by ASP.Net But I'm thinking on how to include the virtual sound on the queue by ASP.Net (the sound will be like : "the queue no one, go to Locket 2) ? or do you have idea, which programming language more compatible on customer FIFO system ?

I've made a modal dialog used load() method but now I don't know how to close it.

The button and div:

<a href="#" id="btnAdd">Add</a>

<div id="AddModal" style="display:none"></div>

Script to call the modal:

$("#btnAdd").click(function () {
    $("#AddModal").load("/Customer/Modal/AddCustomerModal.aspx").show();
});

AddCustomerModal loaded inside the AddModal:

<body>
    <div id="AddModalContent">
        <h3>MODAL</h3>

        XYZ<br />
        <input type="button" class="btnCloseModal" value="Close" />
    </div>
</body>

Script to close

$(".btnCloseModal").click(function () {
        $("#AddModal").hide();
});

ashx handler to download some files when user clicks a button. My .aspx looks like this right now

<asp:Button OnClick:"Download" runat="server" />

And within the Download event I have to do some processing before the download starts. So I'm looking for a way to invoke the handler from my C# code and pass in some parameters that are required for the download process.

Thanks in advance.

I have a form that I cannot get to bind values to my model. The model is empty on the post action.

I've stripped everything down to the simplest of examples and still can't get it to bind.

The model

public class simplemodel
{
    public string SomeVal;
}

The view

@model MyApp.Models.simplemodel

@using(Html.BeginForm("Index", "Test", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.SomeVal);
    <input type="submit" value="submit" id="btnSubmit" />
}

The controller action

[HttpPost]
public ActionResult Index(simplemodel model)
{
    string ReceivedVal = model.SomeVal;

    //do whatever...
}

This is as straight forward as it gets, but my model doesn't bind.

ReceivedVal is always empty. I have plenty of other places where I'm binding to models with no issue. I'm baffled. What could I possibly be missing?

I do receive "SomeVal" if I change the controller action to receive a FormCollection. So I know it's getting posted properly, it just won't bind to the model.

Today I recognised a strange behaviour. Normally I put all my javascript stuff like that in my views:

@section Scripts
{
    @Scripts.Render("~/Scripts/AutoComplete/AutoCompleteCustomer.js")
}

Now, I created a jS-File that includes this function:

    function AutoCompleteCustomerID() {
    $(".customerid").autocomplete({
        source: "/AutoComplete/AutoCompleteCustomerID",
        minLength: 1,
        change: function (event, ui) {
            if (!ui.item) {
                $('.customerid').val('');
            }
        }
    });
}

Now, I want to call that function in my JavaScript-Code in the view after Section Scripts:

AutoCompleteCustomerID();

In the console I get following Error-Message: "Uncaught ReferenceError: AutoCompleteCustomerID is not defined"

But when I put like this in my view, it works, no Error-Message in the console:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "New Order";
    <script src="~/Scripts/AutoComplete/AutoCompleteCustomer.js" type="text/javascript"></script>

}

Do you have any idea, why I get this ErrorMessage when I render it like I did in Section Scripts?

I'm pretty new to using C# and IIS and have been having a hard time getting my .net updated to 4.5. My application as of right now is just a single handler page with no solution hosted on a url controlled by Iis. The current version my IIS is running for that application pool is v4.0. I want to enable v4.5 but don't know where to start. I've been searching google for the past few hours now but none of it makes any sense to me.

I've tried a few things and I'm not quite sure if my problem is code or frameworks competing. For disclosure, I'm in an aspx site, linked css, Kentico 10, using jquery, jquery ui, and bootstrap.

What I'm doing: replacing img src via jquery. This works.

The goal: Not all images have the same dimensions. I want the dimensions of the image to "animate" between the old size and the size of the new image source. What it's doing, as you would expect, is just flashing to the new size. Surrounding layout objects just teleport to the new location.

The problem: The transition I have applied to the image tag does not seem to do squat.

The code... note that the image tag with CSS class productImage is inside a repeater:

CSS:

.mainImage {
    max-width: 551px;
    cursor: pointer;
    -webkit-transition: all .6s ease-in-out !important;
    -moz-transition: all .6s ease-in-out !important;
    -o-transition: all .6s ease-in-out !important;
    -ms-transition: all .6s ease-in-out !important;
    transition: all .6s ease-in-out !important;
}

HTML:

This is the main image, the target that will change img src.

<div class="col-md-6">
    <asp:Image ImageUrl="http://placehold.it/551x373" runat="server" ID="imgProduct" AlternateText="Product Image" ToolTip="Product Image" CssClass="mainImage" />
</div>

...

This is the image thumbnail that you click on that fires the javsacript src replacement and is inside of a repeater. Note that the data-target attribute is set server-side and only contains the url of the src url that we want the main image to be changed to.

<div class="col-sm-1">
    <asp:Image ImageUrl="http://placehold.it/64x64" runat="server" ID="img1" AlternateText="Product Image" ToolTip="Product Image" CssClass="productImage" onclick="ShowImage(this);" />
</div>

JavaScript:

function ShowImage(ctl) { //this is already a jquery item...
    var targetImage = $("#<%= imgProduct.ClientID %>");    
    targetImage.attr("src", $(ctl).attr("data-target"));
}

$(document).ready(function () {
    ShowImage($("[id$='img1']:first"));
});

This question is an exact duplicate of:

I am trying to figure out how to apply "Shipping charges are $3.99 for the first item and $.99 for each additional item" in my Cart View.

Right now I have

@{
       double itemTotal = 0;
       double subTotal = 0;
       int totalQty = 0;
       double discount = 0.8;
       double shippingBase = 3.99;
       double shippingItem = 0.99;
       double totalShipping = 0;
}

@foreach (var item in Model)
    {

            double price = (double)item.price / 100 * discount;
            itemTotal = @item.qty * price;
            subTotal += itemTotal;
            totalQty += @item.qty;

I am not sure how to approach this. Would I use a foreach loop to count the total quantitys and if the quantity is greater that one it would add 3.99+99???

I"m currently running .net version 4.5 and am trying to use it's "new" zip functions. I'm including System.IO.Compression and am trying to run the following code:

using System.IO.Compression;
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);

The issue I'm getting is that The name 'ZipFile does not exist in the current context. I don't know why it wouldn't exist if I'm already using what requires it.

I have Checkbox on asp.net that I would like when user click on the checkbox then hit delete key, delete it selected checkbox, the problem I have when I hit the key it does not delete a correct index selected, what is wrong on my code? asp.net code:

<Columns>
<asp:TemplateField HeaderText="DELETE">
<ItemTemplate>
<asp:CheckBox ID="chkDeleteKey" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" DeleteImageUrl="~/Images/48/delete-row.png" SelectImageUrl="~/Images/48/select-row.png" ShowDeleteButton="true" ShowSelectButton="true">
<ItemStyle Font-Size="8pt" Width="10%" />
</asp:CommandField>
<asp:BoundField DataField="ClientCode" HeaderText="Client Code">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle Font-Size="8pt" HorizontalAlign="Left" Width="10%" />
</asp:BoundField>

C# code:

protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in gvLegalRecords.Rows)
{
CheckBox chkDelete = (CheckBox)gvRow.FindControl("chkDeleteKey");
if (chkDelete.Checked)
{
String ClientCode = (String)gvLegalRecords.DataKeys[gvRow.RowIndex].Values["ClientCode"];
Int32 DebtorNumber = (Int32)gvLegalRecords.DataKeys[gvRow.RowIndex].Values["DebtorNumber"];
LegalEvents.Remove(ClientCode, DebtorNumber);
}
}
LoadLegalRecords();
}

I am using Razor MVC 5. I have code that works in a controller. It uses AE.Net.Mail and I have run Install-Package AE.Net.Mail with nuget console, although I suspect that's not terribly relevant to my issue.

Project/Controllers/TestController.cs

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WebFloV2.Data;
using System;
using AE.Net.Mail;

namespace Something.Controllers
{
    public class TestController : DataController
    {        
        public ActionResult DoStuff()
        {
            ImapClient ic = new ImapClient("imap.gmail.com", "example@gmail.com", "password", AuthMethods.Login, 993, true);
            ic.SelectMailbox("INBOX");
        }
    }
}

This works, but I wanted to move this logic into a new folder called Libraries. I have added <Compile Include="Libraries\Test.cs" /> to .csproj. Here is the new path and code.

Project/Libraries/Test.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AE.Net.Mail;

namespace WebFloV2.Libraries
{
    public class ShippingExceptions
    {
            ImapClient ic = new ImapClient("imap.gmail.com", "example@gmail.com", "password", AuthMethods.Login, 993, true);
            ic.SelectMailbox("INBOX");
    }
}

In this new file location, I hit an issue. On ic.SelectMailbox("INBOX"); I get

The name 'ic' does not exist in the current context.

This is strange to me, because it worked as Controller logic and there's no issues with the previous line ImapClient ic = ... where I define it. If I must, I could use the controller, but I'd like to know if what I'm attempting is possible.

How can I use ic in Project/Libraries/Test.cs?