This question already has an answer here:

Here my code to send an email on my website (using 1and1 host). This code work in local but return false when it's online :

   public static bool Send_requete(string nom, string mail, string sujet, string msg)
            MailMessage Msg = new MailMessage();
            Msg.From = new MailAddress("");
            Msg.Subject = "CONTACT : De " + nom + " " + sujet;
            Msg.Body = "De : " + mail + Environment.NewLine + " Message : " + msg;
            SmtpClient smtp = new SmtpClient("", 587);
            smtp.Credentials = new NetworkCredential("", "mypass");
            smtp.EnableSsl = true;
            return true;
            return false;

Someone have an idea considering that i cant really know where it crash from the server side, Regards.

I'm using the following snippet for a Bootstrap drop-down menu in my web application (ASP.NET MVC5). Users are supposed to select one from the drop down and that option stays highlighted in the button. You can see the jQuery code below.

My question is the following:

How can I access the text from the button so I can process the requests accordingly in my controller? I'm new to ASP.NET MVC.. any help will be appreciated. Thanks.

$(".dropdown-menu li a").click(function() {
  $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
<!-- Includes -->
<script src=""></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<!-- Markup -->
<div class="col-md-2" style="text-align: center;">
  <h4>Priority </h4>
  <div class="dropdown">
    <button class="btn btn-default dropdown-toggle def-button" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
      <span class="caret"></span>
    <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">

I have created a simple product viewing website in and SQL Server. With every product I upload 1 to 3 PDF. It work perfect in my localhost server. but when I publish it and try to add some product it gives an error. And massage is (Run-time Error Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine. )

Can anyone give me a solution.

I am building a Webservice via VS2012 and need to fetch some data from the Web.Config file based on the dynamic data I would get from an Stored Procedure.

Code block in Web.Config

         <add name="0" source="170" />
         <add name="1" source="171" />
         <add name="2" source="172" />
         <add name="3" source="173" />
         <add name="12" source="174" />

Source code in DomainConfiguration.cs as below

public class DomainElement : ConfigurationElement
        [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
        public string Name
            get { return (string)this["name"]; }
            set { this["name"] = value; }

        [ConfigurationProperty("source", IsRequired = true, DefaultValue = "170")]
        public string Source
            get { return (string)this["source"]; }
            set { this["source"] = value; }

    public class DomainCollection : ConfigurationElementCollection
        protected override ConfigurationElement CreateNewElement()
            return new DomainElement();

        protected override object GetElementKey(ConfigurationElement element)
            return ((DomainElement)element).Name;

    public class DomainSection : ConfigurationSection
        [ConfigurationProperty("domainIDs", IsDefaultCollection = true)]
        public DomainCollection DomainID
            get { return (DomainCollection)this["domainIDs"]; }
            set { this["domainIDs"] = value; }

Sourcecode in the main cs file from where I wish to retrieve the data from the Web.Config

vDomainID = new B2B().Domain(SourceID, Subject);

DomainCollection collection;

collection = ConfigurationManager.GetSection("domainSource") as DomainCollection;
vDomainSource = collection[vDomainID];

This is where I am stuck vDomainID would be a value 0/1/2/3/12, based on this value I need to fetch its respective Source from the Web.Config. Any help on this aspect would be really appreciated.

I have an MVC View where I need to display DATA in a certain format. It needs to be Top Down, split into 2 different columns. As shown in the image attached it is alphabetic going down, then when half way through it needs to start on the next column, row 1.

enter image description here

This will be in a partial view and be used with several different result sets. Definitely cannot hard code.

I've thought of splitting the array in half, then just looping through each array item by item but wondering if there is a better way.

Thanks in advance!!

For extra security I am generating a FormsAuthentication cookie in my WCF service and returning it to my web application, however I want to then utilize that cookie when making requests to particular services on WCF. How can I configure this to be passed with every request? I have setup the machine and decryption key but every time I inspect the cookies when it hits the WCF service there are no cookies to be found.

We have a legacy web application in ASP.Net and C#, for which we are getting around 400 plus cross site scripting flaw raised by Veracode scan. I have created a sample web application and simulated the issue, and found that whenever we are using any string input directly its raising the flaw. Doing HttpUtility.HtmlEncode(TextBox1.Text);"satisfies the veracode, however applying this change in all 400 places is not feasible as then there would be huge amount of work and testing efforts. I am looking for someway to implement some plug in in httphandler so that all the inputs get encoded at one place and we don't have to change it everywhere. Can someone please steer me if this is possible if yes even if you can guide me on just on approach would be good enough to have a direction at least. Many thanks in advance.

StringOps strop = new StringOps();
        string txt1, txt2;
        txt1 = HttpUtility.HtmlEncode(TextBox1.Text);
        txt2 = HttpUtility.HtmlEncode(TextBox2.Text);
        Response.Write(strop.Add(txt1, txt2));

If I remove the HttpUtility.HTMLEncode lines Veracode complains about it. Since there are so many places where in we are doing this string operations so implementing this everywhere is not feasible. Would this be possible to have this encoding implemented on a single place and all the response and request should go through that pipeline e.g. HTTPHandler and HTTPModule.

I need a help with a simple Avatar system.

I have three tables - "LoginDetails" (consists of LoginDetails_ID, Username, Password), then "PersonalInfo" (consists of PersonalInfo_ID, FirstName, LastName, Age, Country, Phone, E-mail) and "PersonalAvatar" (Consists of PersonalAvatar_ID, Head, Body, Legs).

The logic behind is the following:

1.User inserts his Username and Password into a login form, these are checked with details in "LoginDetails" table and if there is a match, it will create a new session called same as his username and he will be redirected to the "Profile Page", which in simple grid view displays only his information from "PersonalInfo" table

// until this point I am fine

2. Out of this grid view, webpage should also contain 12 different pictures (100px x 100px) - 4 pictures of different heads, 4 pictures of different bodies and 4 pictures of different legs which all will represent some kind of "menu to choose from". Once user clicks on the first picture of head, value in Head column of "PersonalAvatar" table connected with his account will be "1", if he clicks on the next one, the value will be changed into "2", if third, then "3" and so on (same for body and legs).

3. All of these pictures in their bigger resolution should be displayed below in one big div, one below each other:

  • Picture_Head_1.jpg
  • Picture_Head_2.jpg
  • Picture_Head_3.jpg
  • Picture_Head_4.jpg
  • Picture_Body_1.jpg
  • Picture_Body_2.jpg
  • Picture_Body_3.jpg
  • Picture_Body_4.jpg
  • Picture_Legs_1.jpg
  • Picture_Legs_2.jpg
  • Picture_Legs_3.jpg
  • Picture_Legs_4.jpg

4. And finally, by default, these all should be hidden and then, once the webpage loads, it should check the values for this specific user in the PersonalAvatar and do something like:

  • if value of Head == 1, display Picture_Head_1.jpg
  • if value of Head == 2, display Picture_Head_2.jpg

etc. ...

Can anyone please help me with the code which will on Page_Load check these values and show only the correct pictures?

Thanks for help,


I keep getting a 404 and searching all over SO and cannot target the issue here. The form is the result of a render action and appears on the home page (home controller). However, I want it to post a different controller action and it keeps giving me a 404. I have included all the correct script for unobtrusive javascript as well as the necessary web.config settings and I'm unable to come across a similar problem from my research.

This is the partial with the form that is being rendered:

@model AFS.Models.SearchLocationModel
<div class="site-search-module">
<div class="site-search-module-inside">
    @using (Ajax.BeginForm("SearchCare", "LevelOfCare", null, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchDiv" }, new { @class = "search-form", enctype = "multipart/form-data" }))
        <div class="row">
            <div class="col-md-12">
                <h5>Select a category</h5>
                @Html.DropDownListFor(x => x.Level, Model.LevelSelectList, new { @class = "form-control input-lg selectpicker" })
            <div class="col-md-12">
                <h5>Enter location</h5>
                <input type="text" id="Location" name="Location" class="form-control input-lg selectpicker" placeholder="City, State OR Zip Code" required />
            <div class="col-md-12"> <button type="submit" class="btn btn-primary btn-block btn-lg search"><i class="fa fa-search"></i> Search</button> </div>

The controller action is:

    public ActionResult SearchCare(SearchLocationModel model)
        if (ModelState.IsValid)

            SearchLocationModel geocodeModel = Geocode(new SearchLocationModel() { Level = model.Level, Location = model.Location });
            if (geocodeModel.Status == "OK")
                Session["level"] = model.Level;
                return RedirectToRoute("LevelCity", new { level = model.Level, state = geocodeModel.State, city = geocodeModel.City, latitude = geocodeModel.Latitude, longitude = geocodeModel.Longitude });
                ModelState.AddModelError(string.Empty, "Please enter City, State OR Zip Code.");
                return RedirectToAction("SearchWidget", "Home");
            return RedirectToAction("SearchError");

Got couple of tabs and partial views rendering under those.

What I'd like to do is instead of just rendering the partial view but to call an action that is gonna return the view.

Something like:

 <li  class="active">
        <a data-modal-transform="lg" data-toggle="tab" href="#webcms-shop-home">@Lang("Home")</a>

   <div class="tab-pane fade in active" id="webcms-shop-home" style="position: relative;">

        @*@Html.Partial("~/Views/WebCMS/Shop/_ShopCms.cshtml", Model)*@ //Instead of this !

        @Url.Action("Shop", "WebCms", new { id = Model.ShopId }) //This is rendering as /WebCms/Shop/12 atm.

I'm noob with jquery, razor, Bootstrap, etc. I'm trying to learn by myself.

I am using mvc, I have a list and I want to add some new elements.

How can I do that??

Here my code:

@{var otherTechsList = Model.Technologies.Where(r =>
    r.CategoryId == null).ToList();}
@for (int x = 0; x < otherTechsList.Count; x++) {
    var technTrId = "techTr" + otherTechsList[x].TechnologyId.ToString();
    <div id="@technTrId" class="panel-body">
       */ My Elements here /*

Thank you.

This is my code for query.

String query = 'abc';

CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey });
   Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query);
   listRequest.Cx = searchEngineId;
   search_results = listRequest.Execute();

How can I add options like filtering here? I searched whole internet and github but I couldn't find any sample code or proper documentation.

Here what i tried

  DataTable dt = new DataTable();
  dt.DefaultView.Sort = "ratio DESC";
  dt.Columns.Add(new DataColumn("Rank", typeof(int)));
  int count = 1;

  foreach (DataRowView dr in dt.DefaultView)
      dr["Rank"] = count++;

While i looping it should check some condition, Can any one help me pls? Thanks in advance

I want to draw image, based on user input (width, height, etc...)

I have my form in .aspx page, but i'm drawing image using ashx handler.

I've got a code that draws image, but only from pre-assigned values.

Now what i want to do is get values from my .aspx form


<asp:TextBox ID="input_width" Width="125" Text="600" runat="server" ClientIDMode="Static"></asp:TextBox><br/>
<asp:TextBox ID="input_height" Width="125" Text="400" runat="server"></asp:TextBox>


int width = 600;
int height = 400;

Bitmap bmp = new Bitmap(width, height);

Graphics g = Graphics.FromImage((Image)bmp);
g.FillRectangle(Brushes.Red, 0f, 0f, bmp.Width, bmp.Height);

MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);

byte[] bajt = ms.ToArray();

context.Response.ContentType = "image/png";

Already tried this

string _width = context.Request.QueryString.Get("input_width.Text");

        int __width = Convert.ToInt32(_width);

But the value seems to be null

Some1 please help me?

Thank you!


<a href="ImageGen.ashx">Press here</a><br />
        <img src="ImageGen.ashx" width="600" height="400"/>

I am trying to make a modal popup in (just css and js) but when click the button. the background shows up and closes really fast. and the modal doesnt show. this is the code.

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>Modal Header</h2>
    <div class="modal-body">
      <p>Some text in the Modal Body</p>
      <p>Some other text...</p>
    <div class="modal-footer">
      <h3>Modal Footer</h3>



    /* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */

/* Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}

/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;

.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;

.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;

.modal-body {padding: 2px 16px;}

.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;


<script type="text/javascript">
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function () { = "block";

// When the user clicks on <span> (x), close the modal
span.onclick = function () { = "none";

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
    if ( == modal) { = "none";

but it doesnt work. I followed this tuttorial here: W3Schools EDIT: I removed the snipped because the code was just too big and just repeated it self. but also published the page and you can test it here.

the modal closes it self after 1 second

I have just started using Azure and i created a mobile app , setup a database and chose a .net backend .

I got a preconfigured backend folder which i downloaded and then published to my azure server.

However i have no idea how to verify in the azure portal if its working.

I can see my databases but not the actual tables and content .

I'm using .net backend so easytables are not supported .

Does Azure has something like phpmyadmin that lets me check the content of the database while i'm programming ?


I'm getting this error but I don't really no why. I'm new to ASP.NET a tutorial

Here is my web.config file

    <?xml version="1.0" encoding="utf-8"?>
      For more information on how to configure your ASP.NET application, please visit
            <!-- For more information on Entity Framework configuration, visit -->
        <add name="VidNetContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-VidNet-20161118032259.mdf;Initial Catalog=aspnet-VidNet-20161118032259;Integrated Security=True" providerName="System.Data.SqlClient" />

        <add key="webpages:Version" value="" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        <authentication mode="None" />
        <compilation debug="true" targetFramework="4.5.2" />
        <httpRuntime targetFramework="4.5.2" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
          <remove name="FormsAuthentication" />
          <remove name="ApplicationInsightsWebTracking" />
          <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
        <validation validateIntegratedModeConfiguration="false" />
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"F>
            <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="" newVersion="" />
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />

Here is my VidNetContext File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace VidNet.Models
    public class VidNetContext : DbContext
        public VidNetContext() : base("VidNetContext")


            public DbSet<Video> Video { get; set; }

            public DbSet<Director> Director { get; set; }

            public DbSet<Producer> Producer { get; set; }

            public DbSet<Genre> Genre { get; set; }

I want to make an application using c# to get the notification if any changes made in the excel sheet. Suppose Someone has added some data or modified some data then at that time i should get the window notification that some changes has been made.

New to MVC and just struggling with retrieving my form data from a List<>. In my controller, I am able to get my Name value (recipe name) correctly but cannot get the Ingredient Name value, always coming back as NULL?

Below are some code snippets from my project.


public class Recipe

    public string Name { get; set; }
    public List<Ingredient> Ingredients { get; set; }

    public Recipe()
        Ingredients = new List<Ingredient>()
            new Ingredient()


public class Ingredient
    public string Name { get; set; }


@using (Html.BeginForm("CreateEdit", "Recipe"))
        <div class="form-group">
            @Html.LabelFor(x => x.Name, "Name")
            @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
            @Html.ValidationMessageFor(x => x.Name)

        <div class="form-group">
            @Html.LabelFor(x => x.Ingredients.FirstOrDefault().Name, "Name")
            @Html.TextBoxFor(x => x.Ingredients.FirstOrDefault().Name, new { @class = "form-control" })
        <div class="form-group">
            <input class="btn btn-primary" type="submit" text="submit" />


public ActionResult CreateEdit(Recipe recipe)
   var recipeName = recipe.Name // <--- Works
   var ingredientName = recipe.Ingredients.FirstOrDefault().Name; //<--- NULL value

   return View(recipe);

I wrote the control myself (not by scaffolding) this way:

@Html.EditorFor(m => Model.Title, new { @class = "form-control" })

the control didn't render the the class form-control but when I changed it to:

@Html.EditorFor(m => Model.Title, new { htmlAttributes = new { @class = "form-control" } }) rendered the required class. the LabelFor control uses the first parameter signature and works fine.

There is similar question but no helpful answer:

Difference between htmlAttributes: new { @class = "class1" }, new {htmlAttributes = new {@class = "class2"}} and new {@class = "class3"}

There is a difference in the parameteres definitions in both controls: the LabelFor parameter is

object htmlAttributes

whereas the EditorFor parameter is

object additionalViewData

I can't understand the difference, why not just using htmlAttributes object with EditorFor

I have MVC Project that contain many views, I want the client to edit the content as he/she like and save it.

How I can make CMS (content management system )of the views?

I have read about RedEditor in telerik but it work only with html files , the MVC is cshtml files that contain razor?