dimanche 28 juin 2015

How to make search engines crawl tens of thousands of pages in my website

I have a large amount of items that each item has a page like this site/item_show.aspx?id=The_ID_here there are tens of thousands of items and each day nearly two thousands are added. Furthermore each item has a description in its page so for each item, its page should be crawled by search engines.

My question is with this amount of data described: How can I generate sitemaps or anything like that to make all items visible by google and other search engines?

It is clear that I cannot show all items in the first pages but I can make pages that simply just contains the link of items and provide tens of them each page for just search engine. Would it work or is it anything better to do for making items be indexed by google?

FileUpload in form HTML

I have a Website and in one webpage there is a form, where one of the fields is to upload an image. I have created in my database a column picture of type LONGBINARY. I have read some webpages where they explain how to use <asp:FileUpload ID="FileUpload1" runat="server"/>. But the doubt is that I have an input tag <input id="Submit1" type="submit" value="Put In Store" /> for my form. All the webpages where they explain about FileUpload are using a ASP button, but for my form I need an submit input.

So:

  • What do I do if it says I need a ASP Button but I need a submit input?
  • Where need to be the code of the FileUpload when you click?

My last question about FileUpload(There are the links they gave me).

Can't get dropdown list in mvc5 for a specil title

I'm trying to get better with asp.net mvc5 how ever I've ran into a problem. I've made Gamemodel where you can create games. On my post/create I get a drop down list for the games I've added on my Game model.

I also have my 'Title / Next game' I want a drop-down list on that as-well. But right now it just takes a string, but I would like a drop-down list like for GameId how can I achieve this ?

This is my Post Model

public class Post
{
    [Key]
    public int PostId { get; set; }

    //URL
    [Display(Name = "URL")]
    [StringLength(80)]
    public string Url { get; set; }
    //User
    [Display(Name = "User")]
    public virtual ApplicationUser User { get; set; }

    //Game
    [Display(Name = "Game")]
    public int GameId { get; set; }
    [Display(Name = "Next Game")]
    public string Title { get; set; }
    public virtual Game Game { get; set; }

    //Time
    private DateTime? _date;
    public DateTime? Date
    {
        get
        {
            if (_date == null || _date.ToString() == "1/1/0001 12:00:00 AM")
            {
                return _date = DateTime.Now;
            }
            return _date;
        }
        set
        {
            _date = value;
        }
    }

And this is my Game Model

    public class Game
{
    [Key]
    public int GameId { get; set; }

    //Game
    [Display(Name = "Game")]
    public string Title { get; set; }

    //User
    [Display(Name = "User")]
    public virtual ApplicationUser User { get; set; }
}

Definition of configuration section

I am looking for a good definition of what's called configuration section in Asp.Net as I can't find anything about that anywhere. I am not against any links what can help me shed some light on it.

PopUp is not showing after Excel Download?

I'm writing data into an excel and after completion I'm downloading the excel sheet.

This is my code for downloading

byte[] fileBytes = System.IO.File.ReadAllBytes(excelPath);
        System.Web.HttpContext context = System.Web.HttpContext.Current;
        context.Response.Clear();
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
        context.Response.ContentType = "application/octet-stream ";
        context.Response.AppendHeader("content-disposition", "attachment; filename=" + "ExcelSheet.xls");
        context.Response.BinaryWrite(fileBytes);
        context.ApplicationInstance.CompleteRequest();

After completion of this I'm calling my JavaScript for Popup

    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
    lblLog.Text = "Successfully Downloaded";

But it is not showing the popup. If I remove the code for download it is working perfectly.What should I do to downlod and get poup.

Ninject doesn't make implementation of interface

I'm unable to make Ninject work in my ASP.NET MVC 5 project.
It doesn't want to make the concrete object connected to the interface and I'm out of ideas what could fix this.

My project has an interface IQuizRepository in Domain.Abstract which consists of only ICollection<Quiz> Quizes { get; }
The implementation is QuizRepository in Domain.Concrete and looks like this:

public class QuizRepository : IQuizRepository
{
    public ICollection<Quiz> Quizes { get; private set; }

    public QuizRepository()
    {
        List<Quiz> quizes = new List<Quiz>();
        // adding some Quiz objects to the list
        Quizes = quizes;
    }
}

The controller is Website.Controllers.HomeController.cs which simply tests if Ninject works and looks like this:

public ActionResult Index(IQuizRepository quiz)
{
    ViewBag.test = quiz.Quizes.First().Id;
    return View();
}

NinjectWebCommon which is in Website.App_Start is equal to the default generated one except the RegisterServices method:

public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<Domain.Abstract.IQuizRepository>().To<Domain.Concrete.QuizRepository>();
        }        
    }

It still fails to make the implementation of IQuizRepository.
I think I have all the NuGet packages installed that are required:

Ninject v3.2.0.0
Ninject.MVC5 v3.2.1.0
Ninject.Web.Common v3.2.0.0
Ninject.Web.Common.WebHost v3.2.0.0

The stacktrace (sadly partly in Dutch since I can't get the error messages to show in English):

[MissingMethodException: Kan geen exemplaar van een interface maken.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +66
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +197

[MissingMethodException: Kan geen exemplaar van een interface maken. Object type 'Domain.Abstract.IQuizRepository'.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +233
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +532
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +331
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

unable to convert .htaccess to web.config

For this pc of code

<IfModule mod_rewrite.c>
RewriteEngine On
#RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

i am using

<rule name="rule 1A" stopProcessing="true">
<match url="."  />
<action type="Rewrite" url="/index.php"  />
</rule>

but not work... why ?

how to get data using OnRowCommand event in c# ASP.NET

I can not fetch data while using OnRowCommand event of GridView using c# ASP.NET.i am using linkButton inside gridview.I am explaining my code below.

faq.aspx.cs:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            //int faqID = int.Parse(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                case "DoEdit":
                    {
                        int index = Convert.ToInt32(e.CommandArgument);
                        GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
                        int RowIndex = row.RowIndex;
                        TextBox1.Text = GridView1.Rows[RowIndex].Cells[1].Text;
                        TextBox2.Text = GridView1.Rows[RowIndex].Cells[2].Text;
                        HiddenField1.Value = GridView1.Rows[RowIndex].Cells[0].Text;
                        Button1.Text = "Update";
                        break;
                    }
                case  "DoDelete":
                   {
                       faqBL objFaqBl = new faqBL();
                       int index = Convert.ToInt32(e.CommandArgument);
                       int faqID =Convert.ToInt16( GridView1.Rows[index].Cells[0].Text);
                       objFaqBl.deleteFaqData(faqID);
                       break;
                   }
            }
        }

I am passing OnRowCommand from GridView like below.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
                                            Width="100%" CssClass="table table-striped table-bordered margin-top-zero" 
                                            OnRowCommand="GridView1_RowCommand"  >
                                        <Columns>
                                           <asp:TemplateField HeaderText="Sl No">
                                           <ItemTemplate>
                                           <asp:Label ID="faqid" runat="server" Text='<%#Eval("FAQ_ID") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Question" >
                                           <ItemTemplate>
                                           <asp:Label ID="question" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Answer" >
                                           <ItemTemplate>
                                           <asp:Label ID="answer" runat="server" Text='<%#Eval("Answer") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Image" >
                                           <ItemTemplate>
                                           <asp:Image ID="Image1" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" ImageUrl='<%# "/Upload/" + Convert.ToString(Eval("Image")) %>'  /> 
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Action" >
                                           <ItemTemplate>
                                           <!--<a href="" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="Edit" id="editbtn" ><i class="fa fa-edit"></i></a>
            <a href=" " data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete"><i class="fa fa-times"></i></a> -->
                                            <asp:LinkButton ID="HyperLink1" runat="server" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="Edit" CommandName="DoEdit" CommandArgument='<%# Eval("FAQ_ID") %>' ><i class="fa fa-edit"></i></asp:LinkButton>
                                             <asp:LinkButton ID="HyperLink2" runat="server" data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete" CommandName="DoDelete" CommandArgument='<%# Eval("FAQ_ID") %>' ><i class="fa fa-times"></i></asp:LinkButton>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                        </Columns>
                                        </asp:GridView>

Please help me to resolve this issue.

UpdatePanel with Asyncpostback trys to load control outside updatepanel

I need to have UpdatePanel with asyncpostback, but in my case it seems that no partial postback happens, but fullpostback. I am new to web forms, please, check the code:

<%@ Register TagPrefix="Cust" TagName="CompanyInformationView" Src="~/CustomControls/CompanyInformationView.ascx" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:UpdatePanel runat="server" ID="UpdatePanel1" ChildrenAsTriggers="true" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Button ID="Button1" runat="server" OnClick= "Button1_Click" Text="test" />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>

    <Cust:CompanyInformationView ID="CompanyInformationView" runat="server" />   
</asp:Content>

So I have Test Button. OnClick it should do "nothing" for test. Also there is custom control on web form. Here is server side code for this form:

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // fill in custom control CompanyInfo c = GetInfo(); CompanyInformationView.Company = c; } }

protected void Button1_Click(object sender, EventArgs e)
{
    var i = 1;
}

CompanyInformationView is custom control with property "Company". There is no ViewState added for this property (so it cannot be loaded properly if postback is done). When I click on Test Button, the page fails, because "CompanyInformationView.Company" is not set (it is not set, because it cannot be loaded from ViewState, I guess).

Instead, I think that it should not work like this. AsynPostback should deal only with UpdatePanel.

Why it wants to reload custom control? Doesn't it mean that Full postback happen or maybe I do not understand Asyncpostback?

Customizing AspNet Identity Authentication DB objects

I am using Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext class for authentication of my users. This is a new concept to me and it confuses me a lot.

By default it creates 5 tables with default names: AspNetRoles, AspNetUserRoles, AspNetUserLogins, AspNetUsers which I think are a bit forcing on the user and does not suit my architecture. Also I want to add more columns to the above mentioned tables.

Is there a way to change the table names and add new columns to the existing tables?

using VS 2013, SQL Server 2014 Express.

Error in Updating a Record

Hello Everyone I'm new in here. I am currently making an asp.net project monitoring module. At this moment I am in the process of editing the project form and adding resources to the selected task in a project.

I'm having a problem in saving the record. Everytime I save the record it says "Column name or number of supplied values does not match table definition."

In my ProjectTasks Table I have RefNo(PK), TaskID(FK), Name and Description

Name - refers to the Task Name

Description - refers to the Task Description

What I want to happen is that my Resource Tables TaskID(FK) will be updated when I clicked the save button. As of now when I add a Resource from a task the TaskID = 0.


protected void btnSave_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "INSERT INTO ProjectTasks VALUES (@Name, @Description); " +
    "SELECT TOP 1 TaskID FROM ProjectTasks ORDER BY TaskID DESC;";
    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@Description", txtDescription.Text);
    int taskID = (int)cmd.ExecuteScalar();
    con.Close();

    con.Open();
    cmd.CommandText = @"UPDATE Resource_Materials SET TaskID=@TaskID WHERE TaskID=0; " +
                        "UPDATE Resource_Equipments SET TaskID=@TaskID WHERE TaskID=0; " +
                        "UPDATE Resource_Vehicles SET TaskID=@TaskID WHERE TaskID=0; " +
                        "UPDATE Resource_Contractors SET TaskID=@TaskID WHERE TaskID=0;";
    cmd.Parameters.AddWithValue("@TaskID", taskID);
    cmd.ExecuteNonQuery();
    con.Close();
    Helper.AddLog("1", "Add", "Assigned Resources to Task");
    Response.Redirect("~/Projects/Default.aspx");
}


Sorry about my grammar I'm just a student.

Selecting the right combination to fill DropDown list in asp

I'm working on an admission from . I was struck in simple problem. I've fourDropDown lists.three to Select the Major subjects and one to show the list whom Candidate can apply. I want to restrict the user to apply for the specific subject on the basis of selected subject. I only want to show the only the specific subject in fourth dropDown list. Suppose if user Select Physics , Computer and Statistics . He is should not able to apply for the Computer Sci ,Bio, Mathematics etc. How can I restrict the candidates to apply on the basis of selected subjects

async method for Cache CacheItemRemovedCallback

As a rule to make all functions async all way down to avoid mixing sync code with async ones (which can deadlock) I marked my Cache callback method async as it have async code inside. Is it ok to do so? Or I have to call sync methods only.

asp.net

public static async void Expired (String key, object value, CacheItemRemovedReason removedReason)
{
    if (removedReason != CacheItemRemovedReason.Removed)
    {
        Status retStatus=await processResultAsync(id)

    }
    return; 
}


public async  Task<ActionResult> check(xViewModel x)
{
  ....
 //I want to process thisid after 18-19 minutes even 
 // on cases when I will not be able to get redirectcallback
 HttpContext.Cache.Insert(x.id, payment_key, null, DateTime.Now.AddMinutes(19), Cache.NoSlidingExpiration,
                    CacheItemPriority.Default, new CacheItemRemovedCallback(Expired)); 
  ....
  return Redirect("external url that will call my RedirectCallback");
}



public async Task<ActionResult> RedirectCallback(String id)
{ 
    Status retStatus=await processResultAsync(id);
   ......
   HttpContext.Cache.Remove(id);
    .......
    return View(  retStatus);
}

Unable to dowload file using generic handler

I am using a generic handler to download csv/excel files. It was working fine until yesterday. Today suddenly it stopped working on deployment on IIS 7.5 (though he same code works well in visual studio debugging mode). Here is my code:

ASPX: This is a content page

<input type="button" class="btn-primary" id="btnDownload" title="Download" value="Download" onclick='return downloadReport(this);' data-toggle="modal" data-target="#myModal" navurl='<%: ResolveUrl("~/Handlers/DownloadData.ashx") %>' />

JS:

function downloadReport(btn) {
//I am using a kendoUI combo box and kendo js + also using bootstrap for design & modal popups & also i have applied bundling to kendo & bootstrap files. They seem to be working fine without any conflicts as all their api's are working.
var $mod = $("#masterModal");
    $mod.modal('show');
    //window.location = "Handlers/DownloadData.ashx?rtp=" + combobox.val();
    window.location.href = $(btn).attr("navurl") + "?rtp=" + combobox.val();
    setTimeout(function () {
        $mod.modal("hide");
    }, 2000);

    return false;
}

Master Page:

I am including the js file containing the above method just before end of body tag.

<script src='<%: ResolveUrl("~/Scripts/DataUploader.js") %>'></script>  
</body>
</html>

Handler: In handler Process Request Method

HttpResponse response = this._context.Response;
            HRReportData hrData = new HRReportData(ConfigMaster.DbProvider, ConfigMaster.ConnectionString, ConfigMaster.DBSchemaName);
            ReportDataManager rdm = null;
            ExcelPackage xlPackage = null;
            try
            {
                rdm = new ReportDataManager();
                DataSet ds = rdm.GetReportData(hrData, report_Type);
                if (ds != null && ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        xlPackage = new ExcelPackage();
                        ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add(report_Type.ToString());
                        worksheet.Cells["A1"].LoadFromDataTable(ds.Tables[0], true, TableStyles.Light1);
                        response.ClearHeaders();
                        response.ClearContent();
                        response.Clear();
                        response.ContentType = "application/octet-stream";
                        response.AppendHeader("content-disposition", "attachment;  filename=" + report_Type.ToString() + ".xlsx");
                        xlPackage.SaveAs(response.OutputStream);
                        response.Flush();
                        //response.Close();
                        //response.End();
                    }
                }
            }
            catch (Exception ex)
            {
                //LogError.MethodLevelError(Convert.ToString(Session["Username"]), ex);
                if (!(ex is System.Threading.ThreadAbortException))
                {
                    //Other error handling code here
                }
            }
            finally
            {
                if (xlPackage != null)
                {
                    xlPackage.Dispose();
                    xlPackage.Dispose();
                }
            }

Bundle config:

bundles.Add(new ScriptBundle("~/Kendo/kendo").Include(
                "~/Scripts/jquery-1.11.3.min.js",
                "~/Kendo/js/kendo.all.min.js"
               // "~/Scripts/DataUploader.js"
            ));
            bundles.Add(new ScriptBundle("~/bootstrap/bootstrap").Include(
                "~/bootstrap/js/holder.js",
                "~/bootstrap/js/ie10-viewport-bug-workaround.js",
                "~/bootstrap/js/ie-emulation-modes-warning.js",
                "~/bootstrap/js/bootstrap.min.js"
            ));

All above code works well in debugging mode and was working well in deployment mode as well. Don't know what has changed that it suddenly stopped working and I am unable to find out any reasons :(

Behaviour on deployment: Instead of staying on same page and downloading file it navigates to Handler and a blank screen is displayed. No file is downloaded.

Behaviour in debuuging mode OR when run using vs2012 express: It stays on same page and downloads the file as expected.

Somebody please help me on this.

Using LCSK (Live Chat Starter Kit) on ASP.NET WebForms Application

I use LCSK to implement Live Chat on my website, based on ASP.NET4.5 WebForms.

When I try to configure it using Install.html page, the Save Changes button does nothing.

The message "Configuring your installation You can configure some basics information here. After the first install you will be prompt to login to modify config values on this page. If you forget your admin password, simply remove the config file on your App_Data folder." is written on the page, but I don't have App_Data folder in my solution.

Any help would be appreciated.

Check which certificate is bound to an asp.net site from within site

I have an IIS hosted asp.net (mvc/api etc) app that runs under a limited context (e.g. App Pool Identity or similar). The loopback is not available. How can i check which certificate is bound to the site that hosts my app from within the app?

E.g. when admin specifies the ssl binding in IIS.

generate random string so no two threads collide

Here is the code for my random string generator

private static string GetUniqueKey()
{
    int maxSize  = 15 ;
    char[] chars = new char[62];
    string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    chars = a.ToCharArray();
    int size  = maxSize ;
    byte[] data = new byte[1];
    RNGCryptoServiceProvider  crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data) ;
    size =  maxSize ;
    data = new byte[size];
    crypto.GetNonZeroBytes(data);
    StringBuilder result = new StringBuilder(size) ;
    foreach(byte b in data )
    {
        result.Append(chars[b % (chars.Length - 1)]);
    }
    return result.ToString();

}

How do I write a unit test that would test for 100% guarantee that no 2 threads will generate the same random number

I don't want to lock thread because it creates performance night mare under extreme load tests.

This logic will be used in load balanced 8 app servers.

I can't use GUID because this random string should be humanly readable like a credit card number.

Do I have to constantly read database to ensure that this is a unique number before I store in DB?

how to implement message security in wcf [duplicate]

This question is an exact duplicate of:

I want to implement message signing using WCF. I know how to implement message signing in WSE, but i am facing issues while try to implement the same in WCF. I have already installed X509 certificate on my local machine, I have also successfully tested my application in SOAP UI tool. Below is the code i am using to achieve the same:

 public X509SecurityToken GetSecurityToken(string subjectName)
{
    X509SecurityToken objX509SecurityToken = null;
    X509Store objX509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    objX509Store.Open(OpenFlags.ReadOnly);
    try
    {
        X509Certificate2Collection objX509Certificate2Collection = objX509Store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, true);

        X509Certificate2 objX509Certificate2;
        if (objX509Certificate2Collection.Count == 1)
        {
            objX509Certificate2 = objX509Certificate2Collection[0];
            objX509SecurityToken = new X509SecurityToken(objX509Certificate2);
        }
        else
        {
            objX509SecurityToken = null;
        }
    }
    catch (Exception ex)
    {
        objX509SecurityToken = null;
    }
    finally
    {
        if (objX509Store != null)
            objX509Store.Close();
    }
    return objX509SecurityToken;
}
 // Get an X.509 certificate for signing the SOAP message.
        X509SecurityToken signatureToken = GetSecurityToken("subjectName");
        if (signatureToken == null)
        {
            throw new SecurityFault("Message Requirements could not be satisfied.");
        }

        // Add the X.509 certificate to the header.
        security.Tokens.Add(signatureToken);

        // Specify that the SOAP message is signed using this X.509
        // certifcate.
        MessageSignature sig = new MessageSignature(signatureToken);
        security.Elements.Add(sig);

Image size too big in Firefox works well in Chrome- Asp.net

I am creating an e-commerce website using asp.net and have a page which dynamically displays all the products.

The only 1 issue I have- In chrome the size of the image is correct as written in the CSS code but not sure why image width and height changes when I run the programme in FF- It becomes around 300 px each.

   .productImage 
{
    width:150px;
    height:150px;
    vertical-align:central;
    padding:10px;
    border:10px;
    border-radius:50px;
    -moz-border-radius:50px;
    -webkit-border-radius:50px;
    display:block;
    Text-indent: -9999px;


}

Can someone please help me?

How to get image from GridView using GridView_RowCommand event in c# ASP.NET

i am doing edit operation inside GridView using c# ASP.NET.i need when user will click on edit button all data will retrive from that row and display in text box but here i am unable to display the image.I am explaining my code below.

faq.aspx:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
                                            Width="100%" CssClass="table table-striped table-bordered margin-top-zero" OnRowCommand="GridView1_RowCommand" >
                                        <Columns>
                                           <asp:TemplateField HeaderText="Sl No">
                                           <ItemTemplate>
                                           <asp:Label ID="faqid" runat="server" Text='<%#Eval("FAQ_ID") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Question" >
                                           <ItemTemplate>
                                           <asp:Label ID="question" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Answer" >
                                           <ItemTemplate>
                                           <asp:Label ID="answer" runat="server" Text='<%#Eval("Answer") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Image" >
                                           <ItemTemplate>
                                           <asp:Image ID="Image1" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" ImageUrl='<%# "/Upload/" + Convert.ToString(Eval("Image")) %>'  /> 
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Action" >
                                           <ItemTemplate>
                                           <!--<a href="" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="Edit" id="editbtn" ><i class="fa fa-edit"></i></a>
            <a href=" " data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete"><i class="fa fa-times"></i></a> -->
                                            <asp:HyperLink ID="HyperLink1" runat="server" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="Edit" CommandName="DoEdit" CommandArgument='<%# Eval("FAQ_ID") %>' ><i class="fa fa-edit"></i></asp:HyperLink>
                                             <asp:HyperLink ID="HyperLink2" runat="server" data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete" CommandName="DoDelete" CommandArgument='<%# Eval("FAQ_ID") %>' ><i class="fa fa-times"></i></asp:HyperLink>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                        </Columns>
                                        </asp:GridView>

faq.aspx.cs:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int faqID = int.Parse(e.CommandArgument.ToString());
            switch (e.CommandName)
            {
                case "doEdit":
                    {
                        int index = Convert.ToInt32(e.CommandArgument);
                        TextBox1.Text = GridView1.Rows[index].Cells[1].Text;
                        TextBox2.Text = GridView1.Rows[index].Cells[2].Text;
                        HiddenField1.Value = GridView1.Rows[index].Cells[0].Text;
                        Image3.ImageUrl=
                        Button1.Text = "Update";
                    }
            }
        }

Here i need the image will retrive and set to image3 id.Please help me to solve this issue.

How to record datareader results at Session?

How to record datareader results at Session? I read database then value that I read want to assigne at Session Thank you in advance for your advise

dr = islem.KayitGetir_DataReader("SELECT * FROM products P INNER JOIN products_description PD ON P.products_id = PD.products_id WHERE P.products_id='" + Session[i].ToString() + "'");

if (dr.Read())
{
    cartProductImage.ImageUrl = dr["products_thumbnails_images"].ToString();
    lblCartProductName.Text   = dr["pro_description_name"].ToString();
    lblCartProductPrice.Text  = dr["products_price"].ToString();
    dr.Close();

    Session["ProImg"]      = cartProductImage;
    Session["ProImgName"]  = lblCartProductName;
    Session["ProImgPrice"] = lblCartProductPrice;
}

Wrap each 3 items with HTML Wrapper code in ForEach loop C#

I need to build an HTML code structure in C# code behind. The code inserted an HTML item that occupies 3 columns in a 12 columns Row (I'm using Zurb Foundation).

I iterate over over a collection of items in a foreach loop.

I want to add a <div class='row'>[item html code here]</div> code that will wrap the 3 column items.

Item code is something like this:

<div class='column large-4 medium-4- small-12' >some content</div>

What logic should I use (C#) in order to be able to inject the item HTML code inside the row code every three items?

My complications start when I need to separate the opening tags (<div class='row'>) with the closing tag (</div>) and put the items codes (the column divs) inside.

Assume large number of items that needs to iterate over.

The results html should look something like this if for example I have 7 items:

<div class='row'>
 <div class='column large-4'>item 1</div>
 <div class='column large-4'>item 2</div>
 <div class='column large-4'>item 3</div>
</div>
<div class='row'>
 <div class='column large-4'>item 4</div>
 <div class='column large-4'>item 5</div>
 <div class='column large-4'>item 6</div>
</div>
<div class='row'>
 <div class='column large-4'>item 7</div>
</div>

System.Security.Principal.GenericPrincipal ASP.NET MVC4

I tried make simple login via asp.net mvc4 but get stuck in this error when user name password correct no problem but when it is get wrong cannot get error massage here my code

Public Function Login(loguser As UserModule) As ActionResult
        If ModelState.IsValid Then
            If loguser.IsValid(loguser.UserName, loguser.Password) Then
                FormsAuthentication.SetAuthCookie(loguser.UserName, loguser.RememberMe)
                Session("uname") = loguser.UserName
                Session.Timeout = 10
                Return RedirectToAction("Index", "Home")
            Else
                ModelState.AddModelError("", "Login data is incorrect!")

            End If
        End If
        Return View(User)
    End Function

but in run time get this error

The model item passed into the dictionary is of type 'System.Security.Principal.GenericPrincipal', but this dictionary requires a model item of type 'LicOnlineMVCVB.UserModule'.

[InvalidOperationException: The model item passed into the dictionary is of type 'System.Security.Principal.GenericPrincipal', but this dictionary requires a model item of type 'LicOnlineMVCVB.UserModule'.]
   System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +589911
   System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +371
   System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +48
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +98
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +294
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +175
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651796
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

How i solve this error

IIS Url Rewrite with Special Characters in Route

I am using Asp.Net with Angular JS in my project. I want to create my route like below.

Required Url Format: http://localhost:9196/hotelname-cityname

eg: http://localhost:9196/magnolia-bengaluru

I want to redirect this route to my one of angular routes. Please help me on this.

Url Rewrite Code Web.Config

<rewrite>
 <rules>
  <rule name="RezEPropertyUrl" stopProcessing="true">
   <match url="^/*." />
   <action type="Redirect" url="/{R:2}-{R:1}" redirectType="Found"  />
  </rule>
 <rule name="RezEDefaultPage" stopProcessing="true">
  <match url="^Property/Cart" />
  <action type="Rewrite" url="/home.html" />
</rule>

Win32Exception (0x80004005): The network path was not found

while running my asp.net application package on test server I am getting "Win32Exception (0x80004005): The network path was not found" error and then saying: "[SqlException (0x80131904): 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]"

while publishing in publish web settings I checked "Use connection string at runtime " and " update database configure database updates" and in preview also my database is coming. But on deploying it on server I am getting error.

I already tried to change the connection string in web.config file but it didn't work.

please help.

Why TableAdapter doesn't recognize @parameter

I am using table adapter Query configuration wizard in Visual studio 2013 for getting data from my database. For some queries like this:

SELECT *
FROM ItemsTable
ORDER BY date_of_creation desc, time_of_creation desc
OFFSET (@PageNumber - 1) * @RowsPerPage ROWS
FETCH NEXT @RowsPerPage ROWS ONLY

it doesn't recognize the @pageNumber as a paremeter and it cannot generate function that has these arguments while it works fine for queries like:

Select Top (@count) * from items_table

Why does in first query tableadapter fail to generate function with mentioned arguments whereas it can generate function fine for second one for example: tableadapter.getDataByCount(?int count)

Am I forced to use stored procedure, if yes since I don't know anything about it how?

Returning TWO Lists using JSON and Serializer

I'm sending a List from my ASP.NET WebMethod to my Javascript using this:

List<Person> plist = new List<Person>();

string json = "";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(plist );

return json;

And I'm using this to retrieve these values from my JS:

function onSuccess(val) {
        var obj = JSON.parse(val)
        obj.forEach(function (entry) {
               console.log(entry);
       });
}

Everything works well. However now I want to return TWO lists such as:

List<Person> plist = new List<Person>();
List<Car> carlist = new List<Car>();

using the same mechanism I used before. How can I insert two lists to the Serializer and print them from my JS?

How to post data to WCF Service using jquery Ajax?

I am facing issue in consuming WCF service using JQUERY AJAX. I know this is cross domain issue and have read alot of solution about it. but none worked for me. Below is all the related code. Can anyone please help me out?

Thanks

 [OperationContract]
        [WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json)]
        [return: MessageParameter(Name = "result")]


        public ServiceSearchResponse GetSearchResults(ServiceSearchParams sParams)
        {
            /// search function
        }

JQUERY:

        $.ajax({
            type: 'POST',
            url: "http://ift.tt/1LFs4Pv",
            data: p,
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            crossDomain: true,
            success: function (data) {

                alert(data);
            },
            failure: function (response) {
                alert('failed');
            },
            error: function (response) {
                alert(JSON.stringify(response));
            }
        });

Webconfig:

  <system.webServer>        
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>

<system.serviceModel>
    <protocolMapping>
      <add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
    </protocolMapping>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultServiceBehavior">
          <!--Added DefaultServiceBehavior referenced at service tag above-->
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>       
        <behavior name="myserives.services.AppServicesAspNetAjaxBehavior">

          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>  
      <service name="mypackage.services.MyServices">
        <endpoint address="" behaviorConfiguration="myserives.services.AppServicesAspNetAjaxBehavior" binding="webHttpBinding"
           bindingConfiguration="LargeSizeMessages" contract="myContractName"  />
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="LargeSizeMessages" maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647" crossDomainScriptAccessEnabled="true">      
          <security mode="None" />
        </binding>
      </webHttpBinding>

    </bindings>

  </system.serviceModel>

Setting the SQL connection string for ASP.NET 5 web app in Azure

I have created a new ASP.NET 5 (MVC 6) web application in Visual Studio 2015. I've also set up an Azure web app to pull in the app from GitHub and run it. This works fine, but I'm having trouble connecting to the database on Azure.

Locally, this works, and it uses config.json and in code Data:DefaultConnection:ConnectionString for the connection string.

How can I leave the code as it is, and have it work in Azure too? I've tried setting the Application Settings in the portal, both the Connection Strings and the App Settings. And using both "SQLCONNSTR_DefaultConnection" and "Data:DefaultConnection:ConnectionString" as the key.

(Setting the App Settings doesn't seem to work by the way. I think the value I provide is too long).

So how can I provide the connection string for my Azure database to my Azure web app (ASP.NET 5), without checking it in in source control?

Drag and Drop between 2 listboxs & Database Update

I want to implement a facility for a web app users for drag an item from a listbox and drop it to the other listbox. After every Drag & Drop needs to update a sql table. I googled about D&D and find some solutions, but I do not know which one is the best? and also I do not know the right way. Which on I have to use? jquery, Ajax, or some other plugins? I'd appreciate If someone give me a pathway to accomplish this task.

Message signing in wcf using x509 certificate

I am facing an issue while trying to consume a WCF web service which requires mutual authentication and message signing using X509 certificate. I have already implemented mutual authentication using X509 certificate, but I am facing an issue while trying to implement message signing. I have successfully installed certificates on my machine. The error message I am getting is:

Signature verification failed

Please note I have successfully tested this application using SoapUI. But I am facing this issue while trying to implement the same in C#.

Angular JS Route Query String with Special Characters

I am using Asp.Net with Angular JS in my project. I want to create my route like below.

Required Url Format: http://localhost:9196/hotelname-cityname

eg: http://localhost:9196/magnolia-bengaluru

I want to access these hotel name and city name in my angular app.

I came to know that, I need to rewrite the iis rule and as well as angular app route changes. Please help me how to do this?

Regards, Arjun

Request.IsAuthenticated doest change the view in FormsAuthentication in ASP.NET MVC

I am developing simple asp.Net MVC application which needs FormsAuthentication,

Model

public class Member
{
    [Required]
    [Display(Name = "Username")]
    public string Username { set; get; }

    [Required]
    [Display(Name = "Password")]
    public string Password { set; get; }

    [Display(Name = "Remember Me?")]
    public bool RemeberMe { set; get; }

    public bool IsValid(string username,string password)
    {
        return (new TestdbEntities()).Members.Any(m => m.Username == username && m.Password == password);
    }
}

Controller

    [HttpGet]
    public ActionResult Login()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login(Models.Member member)
    {
        if (ModelState.IsValid)
        {
            if (member.IsValid(member.Username, member.Password))
            {
                FormsAuthentication.SetAuthCookie(member.Username,member.RemeberMe);
                return RedirectToAction("Index","Home");
            }
            else
            {
                ModelState.AddModelError("","Invalid Username/Passowrd!");
            }
        }
        return View(member);
    }

View

The problem occure in view, which i expect the login changed to Logout when the user successfully authenticated, but even when i trace, the login is successful but Request.IsAuthenticated is false.

<body>
    <ul class="nav nav-pills">
        <li>
            @Html.ActionLink("Home", "Index", "Home")
        </li>
        <li>
            @if (Request.IsAuthenticated)
            {
                <label>Welcome </label>  @Html.Encode(User.Identity.Name)
                @Html.ActionLink("Signout", "Logout", "Membership")
                @Html.Label(User.Identity.Name.ToString())
            }
            else
            {
                @Html.ActionLink("Login", "Login", "Membership")
            }
        </li>
    </ul>
    <div>
        @RenderBody()
    </div>
</body> 

Sharing Session between CookieContainer and IHttpHandler

I have a Web API project and in the same domain I have another HTML based application. My Web API project uses sessions and that part works fine. From my HTML project, I make requests from an IHttpHandler using:

            var handler             = new HttpClientHandler();
            handler.CookieContainer = CookieContainer;

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress  = new Uri(ServerAddress);                   
                var message         = client.GetAsync(url);
                return message.Result.Content.ReadAsStringAsync().Result;
            }

When I use the same CookieContainer it works fine as the session is between the HttpClient and Web API project throught the CookieContainer. My requirement is that I want to access the same session in the IHttpHandler.

What I noticed is that HttpContext.Current.Session in the IHttpHandler is null and if I use the IRequiresSessionState or IReadOnlySessionState, the session is not null but the values in the session are not passed on.

I feel that the session in the CookieContainer is different when compared to the session in the Handler. Is there a way to access the session in the Handler (the one in CookieContainer). Do I need to make a Web Request in a different way?

I also tried the CookieLessSession entry in Web.config and that did not work out well for me. Any thoughts?

ASP.NET Query database column with array of accepted keys

I've reached a problem with query the database correctly. I can't find it answered anywhere else.

My datamaodel contains three tables one with the Image data and another with tags. The third table joins the two tables creting a many to many relationship:

[Image] - 1 --- * ->[ImageTagJoin] <- * --- 1 - [Tag]

From a user input of a set of tags I want to get every image contaning all of the tags. The following code works for one tag

 viewModel.Tags = db.Tags.Where(
                            s =>
                                s.Name == searchString)
                         .Include(i => i.Images.Select( ii => ii.Image));
 viewModel.Images = t.Images.Select(x => x.Image);

The only solution I have is if, input is tag1, tag2, tag3, the controller iterated over each tag.

  1. Get set of images with the tag tag1
  2. From that set of images of tag1 get the subset of images with tag2
  3. From that set get the subset of images with tag3

Now I have a set of images with the tags tag1, tag2 and tag3. Though that this solution works but not as elegant because it requires to search the database once for every tag and every image row gets looked up for every tag in the input.

Conclusion: How can I query a many-to-many relationship between images and tags, where I select all images that have the subset of n tags given from the user.

Thanks.

Asp.net - binding beetween GridView and DetailsView doesn't work

I created a GridView and a DetailsView of Contacs. I want that if user select a contact in GridView, it will show full details in GridView.

this is the aspx source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Contacs.aspx.cs" Inherits="Atid4.Contacs" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                    DataKeyNames="ID" 
                    DataSourceID="SqlDataSourceMain" 
                    ShowSelectButton="true" 
                    EnableViewState="true"
                    EnablePersistedSelection="true" 
                    OnSelectedIndexChanged="GridViewMain_SelectedIndexChanged">
                    <Columns>
                        <asp:CommandField ShowSelectButton="True" />
                        <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
                        <asp:BoundField DataField="first_name" HeaderText="first_name" SortExpression="first_name" />
                        <asp:BoundField DataField="last_name" HeaderText="last_name" SortExpression="last_name" />
                    </Columns>
                </asp:GridView>

                <asp:DetailsView ID="DetailsView1" runat="server" DataSourceID="SqlDataSourceMain" Height="50px" Width="125px">
                </asp:DetailsView>
                <asp:SqlDataSource ID="SqlDataSourceMain" runat="server" ConnectionString="<%$ ConnectionStrings:AtidConnectionString %>" SelectCommand="SELECT * FROM [Contacs]"></asp:SqlDataSource>

            </ContentTemplate>
        </asp:UpdatePanel>

    </div>
    </form>
</body>
</html>

I added a function GridViewMain_SelectedIndexChanged that is called when user selects a row in Gridview. the function is called when user selects one of the contacts, but the contact doesn't change in the GridView. it continues to show the first Contact.

this is the code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Atid4
{
    public partial class Contacs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DetailsView1.DataBind();
            }
        }

        protected void GridViewMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsView1.SetPageIndex(GridView1.SelectedIndex);
        }
    }
}

thanks.

how to record the input time on a textbox control in asp.net

i have been working on some assignment and was facing a problem...

how to record the input time on a text-box control in asp.net that is the timer starts at the time when i start to input in the text-box and stops when i move to the next text-box or move to any other control.. ??

<table style="width: 685px">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <tr>
            <td colspan="3">
                <asp:Image ID="Image1" runat="server" Height="174px" ImageUrl="~/Registration/images/registerwithus.jpg"
                    Width="605px" />
            </td>
        </tr>
        <tr>
            <td>
                User&nbsp; Name
            </td>
            <td colspan="2">
                <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                    ErrorMessage="Please Enter the correct Name" ForeColor="Red"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="style5">
                Choose Password
            </td>
            <td colspan="2">
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
                    ErrorMessage="Choose Password" ForeColor="Red"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td class="style5">
                Confirm Password
            </td>
            <td class="style6" colspan="2">
                <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox3"
                    Display="Dynamic" ErrorMessage="Choose Password" ForeColor="Red"></asp:RequiredFieldValidator>
                <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox2"
                    ControlToValidate="TextBox3" Display="Dynamic" ErrorMessage="Both the Password fields do not match"
                    ForeColor="#CC0000" SetFocusOnError="True"></asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td class="style5">
                Email Id
            </td>
            <td class="style6" colspan="2">
                <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox4"
                    Display="Dynamic" ErrorMessage="Enter your EmailId" ForeColor="Red"></asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox4"
                    Display="Dynamic" ErrorMessage="Invalid Email Id" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                Mob No
            </td>
            <td colspan="2">
                <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Invalid Mobile No."
                    ControlToValidate="TextBox5" ForeColor="Red" ValidationExpression="^[7-9][0-9]{9}$"></asp:RegularExpressionValidator>
            </td>
        </tr>

best t-sql for providing nth page in showing data?

I want to item 1 to 50 in my first page by SELECT TOP(50) * From Items_table and it works fine but how can I get second 50 items for next page? How should be the query be?

Please note that I can't use sql LIMIT because I am using SQL SERVER. I have also problem with queries like:

    select * from (select ROW_NUMBER() over (ORDER BY date_of_creation desc, time_of_creation desc) AS Row2,* from Items_table ) ir
where ir.Row2 between @start and @end

the problem is in this condition table adapter doesn't support OVER. Is there any other t-sql code that table adapter support?

if-elseif-else statements in iron-python for .Net

I am trying to integrate the iron-python as rule engine in my .Net project. I want to know is it possible to execute the expressions like this:

if(c.agents > 100) then 10 elseif (c.agents < 50) then 2 else 0)

I tried the following code but result is always null.

               // string expression = if(c.agents > 100) then 10  elseif (c.agents < 50) then 2 else 0)
                dynamic config = new ExpandoObject();
                var configDictionary = config as IDictionary<string, Object>;
                configDictionary.Add("agents", 100);
                var engine = Python.CreateEngine();

                var statements = new StringBuilder();
                statements.AppendLine("if c.agents > 100: 10");
                statements.AppendLine("elif c.agents < 50: 5");
                statements.AppendLine("else: 0");

                engine.CreateScriptSourceFromString(statements.ToString(), SourceCodeKind.Statements);

                var scope = engine.CreateScope();
                scope.SetVariable("c", config);

                var result = engine.Execute(statements.ToString(), scope);

Can someone guide me how to write such conditional statements in iron-python way.

samedi 27 juin 2015

Can I use the Membership provider in ASP.NET WebForms with my own User database? If so, how?

I am looking for ways to implement login functionality in my ASP.NET WebForms application.
I know that I can use the default Membership provider which creates its own tables. I want to know if I can use my own schema for the database. I don't want to install the Membership tables in my database or otherwise.
I have an existing database with an existing structure that I cannot modify.

Or do I have to go the hard way and write my own membership provider like this suggests. If yes, then please be kind enough to point me to some tutorials about how to write a basic membership provider.

Event not firing up (onlick)

Try changing almost everything(i.e runat="server", single-double colons) Here is the try:

<head runat="server">

<script type="text/javascript" >

    function Decide() {

        document.getElementById('l').innerText = "after";

    }

</script>
</head>

<body>
    <form id="form1" runat="server">
        <button    onclick="Decide()">Click!</button>
        <asp:Label ID="l" runat="server">before</asp:Label>

    </form>
</body>

What am i doing wrong?

asp.net web pages in supported in asp.net 5

I have a question about asp.net 5. Is asp.net web pages are supported in asp.net 5 or deleted ? ( Like asp.net webform)

How to change Column Charts colurs in Chart Properties

How can i change the Color of chart columns in Asp.Net Charts.i know how to do it in Code Behind. i tried like

Series series1 = new Series("Spline");

        series1.ChartType = SeriesChartType.StackedColumn;

        series1.Points.AddXY("A", "100");
        series1.Points.AddXY("B", "200");
        series1.Points.AddXY("C", "300");
        series1.Points[0].Color = System.Drawing.Color.Red;
        series1.Points[1].Color = System.Drawing.Color.Green;
        series1.Points[2].Color = System.Drawing.Color.Blue;

        Chart1.Series.Add(series1);

but i want to know how to do it in Charts Properties(Chart Control Properties)

How to implement Login functionality using ASP.NET WebForms and existing SQL Server database?

I have a SQL Server database that I made using Visual Studio's LocalDB. It has 5 tables, one for the Employee information and credentials, one for the location codes of the offices of the company and others for the meetings he attended and the tasks assigned to him.

I am mainly looking to implement Login functionality on my WebApp. How do I access the SQL database and implement Login? I have currently connected the database and used ADO.NET Entity Model to access the database. I am looking to avoid stored procedures. It would be best if the someone explained how to do this with ADO.NET Entity Model and the Login control.

Edit image and delete row from GridView using c# ASP.NET

I have a problem.I need to edit and delete row of GridView using C# ASP.NET.I tried once and able to fill the data in textbox after click on edit button but i have also one image to edit and i need when user will click on edit image the image will also display in proper place to edit.In case of delete part i have image in anchor tag and i need which event i should pass from GridView and define in code behind page so that i can do the operation.I am explaining my code below.

faq.aspx:

<div class="col-md-6">
                                                <label for="question" accesskey="T"><span class="required">*</span> Question</label>
                                                <asp:TextBox ID="TextBox1" runat="server"  size="30" value="" name="question" ></asp:TextBox>
                                                <div id="noty" style="display:none;" runat="server"></div>
                                                <label for="answer" accesskey="A"><span class="required">*</span> Answer</label>
                                                <asp:TextBox ID="TextBox2" runat="server"  size="30" value="" name="answer" ></asp:TextBox>
                                                <div id="Div1" style="display:none;" runat="server"></div>
                                            </div>
                                            <div class="col-md-6 bannerimagefile">
                                                <label for="insertimage" accesskey="B"><span class="required">*</span> Insert Image</label>
                                                <asp:FileUpload runat="server" class="filestyle" data-size="lg" name="insertimage" id="FileUpload1" onchange="previewFile()" />
                                                <label for="bannerimage" accesskey="V"><span class="required">*</span> View Image</label>
                                                <div style="padding-bottom:10px;">
                                                    <asp:Image ID="Image3" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;"   />
                                                </div>
                                                <div class="clear"></div>
                                                <asp:Button ID="Button1" runat="server" Text="Submit" class="submit" 
                                                    onclick="Button1_Click" />
                                                </div>
                                        </div>
                                </div>

                            </div>
                            <!--end_1st_faq_add_div-->
                            <!--2nd_list_banner_view_div-->
                            <div class="widget-area">
                                <h2 class="widget-title"><strong>FAQ List</strong></h2><asp:HiddenField ID="HiddenField1"  runat="server" />
                                <div class="streaming-table margin-top-zero padding-top-zero">
                                    <div class="table-responsive">
                                        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
                                            Width="100%" CssClass="table table-striped table-bordered margin-top-zero" 
                                            onselectedindexchanged="GridView1_SelectedIndexChanged">
                                        <Columns>
                                           <asp:TemplateField HeaderText="Sl No">
                                           <ItemTemplate>
                                           <asp:Label ID="faqid" runat="server" Text='<%#Eval("FAQ_ID") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Question" >
                                           <ItemTemplate>
                                           <asp:Label ID="question" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Answer" >
                                           <ItemTemplate>
                                           <asp:Label ID="answer" runat="server" Text='<%#Eval("Answer") %>'></asp:Label>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Image" >
                                           <ItemTemplate>
                                           <asp:Image ID="Image1" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" ImageUrl='<%# "/Upload/" + Convert.ToString(Eval("Image")) %>'  /> 
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                           <asp:TemplateField HeaderText="Action" >
                                           <ItemTemplate>
                                           <a href="" data-toggle="tooltip" title="" class="btn btn-xs btn-success" data-original-title="Edit" id="editbtn" ><i class="fa fa-edit"></i></a>
            <a href=" " data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete"><i class="fa fa-times"></i>
                                           </ItemTemplate>
                                           </asp:TemplateField>
                                        </Columns>
                                        </asp:GridView>
                                    </div>

faq.aspx.cs:

protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
        {
            int index = Convert.ToInt32(e.NewSelectedIndex);
            TextBox1.Text = GridView1.Rows[index].Cells[1].Text;
            TextBox2.Text = GridView1.Rows[index].Cells[2].Text;
            HiddenField1.Value = GridView1.Rows[index].Cells[0].Text;
            Button1.Text = "Update";
        }

As I am new to ASP.NET please help me to resolve this issue.

Asp.net MVC Loading Parent View from the actionlink of PartialView using Ajax not working

I have a situation where I need to call ParentView from its partial view. Like I have list of ToDos in Partial view where Ajax actionlink is used to edit the data in parent by passing its id. The same is working without using Ajax as it is manipulating url by putting querystring. But we would like to have internal call with Ajax which is not firing.

The code we are using is like that:

<li>@Ajax.ActionLink(@item.ToDoTitle, "Index", new { tdid = @item.ToDoId }, new AjaxOptions { UpdateTargetId = "saved", InsertionMode = InsertionMode.Replace, HttpMethod="POST" })</li>

and controller is like that:

public ActionResult Index(int tdid =0)
    {
        if (tdid !=0)
        {
            ToDo t = new ToDo();
            t.ToDoTitle = "Ramlal";
            t.ToDoDesc = "Shyamlal";
            t.ToDoId = tdid;
            return Json(t);
        }
        else
        {
            return View();
        }
    }

Updating table in ms sql server for asp.net mvc project but class definations disapeared

I updated the tables in MS SQL Server by changing a lot of the data types stored. To update this change in my ASP.NET MVC project, I refreshed the database connection, updated the model from database in my .edmx diagram and tranformed all T4 templates.

However, now all my class definitions for each table have disappeared. Is there a way to regenerate these .cs documents?

Any help would be appreciated.

I'm trying to deploy to Microsoft Azure this ASP.NET MVC project, the template of which I got from Xamarin. I've spent, literally, 20 hours trying to figure out why deployments keep failing. I've tried both

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

and

<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets"     Condition="'$(VSToolsPath)' != ''" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets" Condition="true" />

for the Imports, as per suggestions on the web. I've also added

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

and I've toggled between Classic and Integrated for Azure's Managed Pipeline Version setting. I've toggled between .NET versions 3.5 and 4.5 for Azure's .NET Framework Version setting (Xamarin doesn't tell me which version I'm using).

You can actually look here and see all my commits where I've messed with configuration settings to try and get this damn thing to work. It's like Microsoft is trying to force me to publish through Visual Studio rather than GitDeploy (what I'm trying to do).

The error I'm getting right now is

error MSB4057: The target "pipelinePreDeployCopyAllFilesToOneFolder" does not exist in the project.

Anyways, I'm out of ideas, unless you guys have any.

Ajaxfied RadGrid RadCombo FilterTemplate

I want to know how to implement custom filter in RadGrid.

I have a Ajaxfied RadGrid and datasource is binded in NeedDatasource event. The RadGrid has five columns.. In that, I want to change the filter of one of the column to selectable filter..

So, I added a FilterTemplate and added the RadComboBox inside to it..

Initially, I hardcoded all the RadComboBox item in the design time itself.. Binded a javascript to clientside_selectedchanged event.. This approach worked fine..

When I binded RadComboBox with collection (List) in the code behind.. The filtering didn't work.. I binded the RadComboBox in GridItemDataBound or GridItemCreated event.. But no luck..

Any help.. will be very much useful to me.. I spent nearly two days but I didn't any direction...

Custom Filter Code The following is sample code which I copied from my project and pasted here.. I have changed the field names alone..

Filter Template:

<telerik:GridBoundColumn DataField="DepartmentDescription" Groupable="true" HeaderText="Program" UniqueName="DepartmentDescription">
    <FilterTemplate>
        <telerik:RadComboBox ID="RadComboBoxDepartmentDescription" runat="server"
            AppendDataBoundItems="true"
            DataTextField="DepartDesc"
            DataValueField=" DepartDesc "
            OnClientSelectedIndexChanged=" RadComboBoxDepartmentDescriptionIndexChanged"
            OnDataBound="RadComboBoxAllFilters_OnDataBound"
            SelectedValue='<%# TryCast(Container,GridItem).OwnerTableView.GetColumn("DepartmentDescription ").CurrentFilterValue %>'
            Width="100px">
            <Items>
                <telerik:RadComboBoxItem Text="All" Value="" />
            </Items>
        </telerik:RadComboBox>
        <telerik:RadScriptBlock ID="RadScriptBlockProgram" runat="server">
            <script type="text/javascript">

                function RadComboBoxDepartmentDescriptionIndexChanged(sender, args) {
                    var tableView = $find("<%# TryCast(Container,GridItem).OwnerTableView.ClientID %>");
                    tableView.filter("DepartmentDescription", args.get_item().get_value(), "EqualTo");
                }
            </script> 
        </telerik:RadScriptBlock>
    </FilterTemplate>
    <ItemStyle Wrap="False" />
    <HeaderStyle Wrap="false" />
</telerik:GridBoundColumn>

RadGrid DataBinding Code

protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
(sender as RadGrid).DataSource = employeeList//This is a list of employee of values.. which comes from service layer.. of type .. List<Employee>
}

RadGrid UI Code

<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1"></telerik:AjaxUpdatedControl>
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <div>
        <telerik:RadGrid runat="server" ID="RadGrid1" AllowPaging="True" AllowSorting="true"
            OnNeedDataSource="RadGrid1_NeedDataSource"
..other code I removed it.. like the grid events and bound columns definitions
        </telerik:RadGrid>

RadComboBox Filter DataBinding Code in the Code Behind:

Protected Sub RadGrid1_ItemDataBound(sender As Object, e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemDataBound

If TypeOf e.Item Is Telerik.Web.UI.GridFilteringItem Then

    'Populate Filters by binding the combo to datasource
    Dim filteringItem As Telerik.Web.UI.GridFilteringItem = CType(e.Item, Telerik.Web.UI.GridFilteringItem)
    Dim myRadComboBox As Telerik.Web.UI.RadComboBox = DirectCast(filteringItem.FindControl("RadComboBoxDepartmentDescription"), Telerik.Web.UI.RadComboBox)

    myRadComboBox.DataSource = departmentList; //This is a collection which comes from service layer… and the type is List<Department>
    myRadComboBox.DataTextField = " DepartmentDescription"
    myRadComboBox.DataValueField = " DepartmentDescription"
    myRadComboBox.DataBind()

End If

Even I pasted the same code in ItemCreated Event as well but no luck…

IIS Redirects me to another URL

I have a website on my local computer. It is a CMS(DNN) Website which is for long time on my computer. it is on 127.0.0.1:80 but I set an address for it in the host file. It was working well till today that when I tried to visit it, I was redirected to another address which I had set on the host file too. I deleted that address from the host file and restarted my computer but I still redirected to that address.

mercredi 6 mai 2015

Remote validation is not working

When I entered value for email in textbox it didn't fire VerifyUserEmail method. Below is my code. Where is my mistake?

View

<div class="form-group">
    @Html.LabelFor(model => model.User_Email, new { @class = "control-label col-lg-2" })
        <div class="col-lg-4">
            @Html.EditorFor(model => model.User_Email)
            @Html.ValidationMessageFor(model => model.User_Email)
        </div>
</div>

Model

[DisplayName("Email")]       
[Remote("VerifyUserEmail", "User", ErrorMessage = "Email already exists!")]
public string User_Email { get; set; }

Controller

    public JsonResult VerifyUserEmail(string User_Email)
    {
        try
        {
            using (RKDYMEntities objConnection = new RKDYMEntities())
            {
                ObjectParameter objIErrorCode = new ObjectParameter("ErrorCode", typeof(Int32));
                ObjectParameter objBFlag = new ObjectParameter("bFlg", typeof(bool));
                objConnection.Check_User_Exists(User_Email, objBFlag, objIErrorCode);

                if (Convert.ToBoolean(objBFlag.Value) != true)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }
        }
        catch (Exception Ex)
        {
            return Json(false, JsonRequestBehavior.AllowGet);
        }
    }

I have also added <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> in web.config.

Below is generated html code:

 <div class="form-group">
    <label class="control-label col-lg-2" for="User_Email">Email</label>
        <div class="col-lg-4">
            <input class="text-box single-line" data-val="true" data-val-length="The field Email must be a string with a maximum length of 200." data-val-length-max="200" data-val-remote="Email already exists!" data-val-remote-additionalfields="*.User_Email" data-val-remote-url="/User/VerifyUserEmail" id="User_Email" name="User_Email" type="text" value="" />
            <span class="field-validation-valid" data-valmsg-for="User_Email" data-valmsg-replace="true"></span>
       </div>
 </div>

Send double value to MVC controller as a string

I've got an action in my controller

    [HttpGet]
    [Route("classificators/{type}/{criteria}/{predicate?}")]
    public ActionResult Classificators(string type, string criteria, string predicate)
    {
        try
        {
            //Lot's of cool code here!          

            return Json(new { Data = "Cool data!" }, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json(new
            {
                state = "error",
                message = ExceptionReport(ex)
            }, JsonRequestBehavior.AllowGet);
        }
    }

And sending request to it like so..

/classificators/MAIN/CODE/50.1

Where: type - MAIN criteria - CODE predicate - 50.1

But action treats parametr 50.1 like double value so I've got an error. How to specify action to treat this value like a string

Image displaying error from database

After the recent changes in my application still i get this issue while displaying the image using the relative path in the database. Error: 404 NOT FOUND http://localhost:1256/Empdet/%22/Photos/jobs.jpg%22

Screenshot

Controller.js:

 $scope.UploadFile = function () {
    console.log('UploadFile');
    console.log($scope.Empdet.PhotoFile);
    var file = $scope.Empdet.PhotoFile;
    console.log('file is ' + JSON.stringify(file));
    var uploadUrl = "../Photos";
    console.log('before file upload');
    EmployeeFactory.UploadFile(file, uploadUrl).success(function (response)  {
        $scope.Empdet.PhotoText = response;
        console.log('$scope.Empdet.PhotoText');
        console.log(response);
    }).error(function () {
        console.log('error');
    });
    console.log('after file upload');
};

service.js:

service.UploadFile = function (file, uploadUrl) {
    var fd = new FormData();
    fd.append('file', file);
    return $http.post('/Empdet/UploadFile', fd, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
    });
}

EmpdetController.cs:

[HttpPost]
    public ActionResult UploadFile()
    {
        var file = Request.Files[0];
        var path = Path.Combine(Server.MapPath("~/Photos/"), file.FileName);
        file.SaveAs(path);

        // prepare a relative path to be stored in the database and used to display later on.
        var filename = Url.Content("~/Photos/" + file.FileName);
        // save to db
        return Json(filename.ToString(), JsonRequestBehavior.AllowGet);

    }

How to disable radio button overwrite?

I have second thing on my page: In array (Completed is bool):

@Html.EditorFor(m => Model.Options[i].Completed)

As html this looks like

<td>
    Yes 
    <div id="Options_0__Completed-styler" class="jq-radio" unselectable="on" style="-webkit-user-select: none; display: inline-block; position: relative;">
        <input id="Options_0__Completed" name="Options[0].Completed" type="radio" value="True" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
        <div class="jq-radio__div"></div>
    </div>
    No
    <div id="Options_0__Completed-styler" class="jq-radio checked" unselectable="on" style="-webkit-user-select: none; display: inline-block; position: relative;">
        <input checked="checked" id="Options_0__Completed" name="Options[0].Completed" type="radio" value="False" style="position: absolute; z-index: -1; opacity: 0; margin: 0px; padding: 0px;">
        <div class="jq-radio__div"></div>
    </div>
</td>

My issue is that potentialy, because of jq-radio (comes from jquery.formstyler.js) I can't do any change for radio buttons.

For example:

    for (var i = 0; i < value; i++) {
        var test = $('input[name="Options[' + i + '].Completed"]').filter('[value=False]');
        test.attr('disabled', true);
    }

If I look on html, then I will see that input with value False is disabled, BUT visually, nothing changes for be.

How can I fix this kind of issue?

Inherited RoutePrefixAttribute in ASP.NET MVC

Currently, my ASP.NET MVC website uses RouteConfig.RegisterRoutes to map routes. I would like to convert this to the new Attribute routing system, but I am missing one small thing there.

The website is multi-language, so every URL needs to be prefixed with a two-letter ISO language code. In the current implementation, the website uses a custom RouteHandler to handle the culture part of all routes. After registering all routes, a loop adds the custom handler and culture constraints to every route.

See below the current implementation:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.RouteExistingFiles = true; 

        // various calls to routes.MapRoute()

        foreach (Route r in routes)
        {
            if (!(r.RouteHandler is SingleCultureMvcRouteHandler))
            {
                r.RouteHandler = new MultiCultureMvcRouteHandler();
                r.Url = "{culture}/" + r.Url;

                // Add the default language
                if (r.Defaults == null)
                    r.Defaults = new RouteValueDictionary();
                r.Defaults.Add("culture", Culture.nl.ToString());

                // Add language constraints
                if (r.Constraints == null)
                    r.Constraints = new RouteValueDictionary();
                r.Constraints.Add("culture", new CultureConstraint(Culture.nl.ToString(), Culture.de.ToString(), Culture.en.ToString(), Culture.fr.ToString()));
            }
        }
    }
}

Culture enum:

public enum Culture
{
    nl = 1,
    en = 2,
    de = 3,
    fr = 4
}

Custom routehandler:

public class SingleCultureMvcRouteHandler : MvcRouteHandler { }

public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var culture = requestContext.RouteData.Values["culture"].ToString();
        var ci = new CultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = ci;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL");

        return base.GetHttpHandler(requestContext);
    }
}

Culture constraints

public class CultureConstraint : IRouteConstraint
{
    private string[] _values;
    public CultureConstraint(params string[] values)
    {
        this._values = values;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string value = values[parameterName].ToString();
        return _values.Contains(value);
    }
}

In order to convert this to the new AttributeRouting, I just thought I'd add a RoutePrefix attribute to my base controller, which would handle the culture part. BUT it seems inheritance of route attributes is not supported...

The release notes of ASP.NET MVC 5.2 state that inherited route attributes are supported in that version by implementing a custom RouteAttribute and DirectRouteProvider. This is however for the RouteAttribute, not for the RoutePrefixAttribute.

What I have tried:

I've tried to create my own InheritedRoutePrefixAttribute by inheriting from the RoutePrefixAttribute, but then in order to actually support the inherited route, I still need to create a InheritedDirectRouteProvider and override the GetControllerRouteFactories() method, which returns a collection of IDirectRouteFactory.
So in order to do that, my InheritedRoutePrefixAttribute needs to implement the IDirectRouteFactory interface, but what to do in the CreateRoute() method?

My code so far:

[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class InheritedRoutePrefixAttribute : RoutePrefixAttribute, IDirectRouteFactory
{
    public RouteEntry CreateRoute(DirectRouteFactoryContext context)
    {
        // ...
    }
}

Custom route provider

// Custom direct route provider which supports attribute route inheritance.
public class InheritedDirectRouteProvider : DefaultDirectRouteProvider
{
    protected override IReadOnlyList<IDirectRouteFactory> GetControllerRouteFactories(ControllerDescriptor controllerDescriptor)
    {
        return controllerDescriptor.GetCustomAttributes(typeof(InheritedRoutePrefixAttribute), inherit: true).Cast<IDirectRouteFactory>().ToArray();
    }
}

ASP.NET MVC customError page doesn't get displayed for some of the 400 errors

I'm having quite an interesting issue with the custom error pages management for a new ASP.NET MVC application.

This issue is like this:
- if I'm calling an URL (doesn't matter which) with a "bad" argument at the end of URL, like ..../c<, the application is displaying the correct server error page as instructed in the web.config;
- if I'm changing the URL to a more nasty one, like .../<c (to look more like an HTML tag, there is no more server error page displayed in the browser and instead of that, I'm getting a plain YSOD with a message like An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

According to ELMAH, both requests ended with a 400 status code and the message being:
- for the first one: System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (<). at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)
- for the second one: System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (<). at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

So, both errors are the same, the status code is the same, but for one of the errors, the custom error page is not getting displayed. I've also went to global.asax in debug mode and checked the Server.GetLastError() in protected void Application_Error(object sender, EventArgs e) and again, both errors were the same, nothing is different.

In web.config, this is how my <customErrors> tag looks like:

<customErrors mode="On" defaultRedirect="/ServerError.aspx" redirectMode="ResponseRewrite"> <error statusCode="500" redirect="/ServerError.aspx" /> <error statusCode="404" redirect="/PageNotFound.aspx" /> </customErrors>

Can please someone tell me why the behavior is different in these two cases?

Thank you very much for your time.