I have registered my APP on Instagram and i Successfully retrieved recent media using: https://api.instagram.com/v1/users/self/media/recent/?access_token=ACCESS-TOKEN

Now I want to Subscribe user to instgram to get real time update , i tried this :

        $.ajax({                                                                   
            url: "https://api.instagram.com/v1/subscriptions/?client_id=MyClientID&client_secret=MyClientSecret&object=user&aspect=media&verify_token=MyToken&callback_url=MyService.ashx",
            type: 'POST',
            dataType: "jsonp",
            success: function (data) {
                console.log(data);
            },
            error: function (errorText) {
                console.log(errorText);
            }
        });

    });

the Post request above prints : {"meta": {"code": 200}, "data": []} which means it is a successful request

but i didn't receive any request from Instagram on my callback URL to send me the [ hub.challenge ]

Instagram subscription API :

Create a Subscription

To create a subscription, you make a POST request to the subscriptions endpoint.

enter image description here

Where I went Wrong ??

I have a web service written in Dotnet which returns a byte array that the web browser figures out is Excel and lets it be opened.
That is happy path.

But what if I get an error? then I'd like to return an error of some kind, let's say a human readable string.
I could return a different Excel document, one with error message, but would prefer to show it directly in the browser.

Is it even possible?
If so, how would this be implemented on the server and client?

I am using the default Web API of ASP.NET with Swagger to build and Restful API. What I am trying to do is to make it more accesible for older programs that only know Soap & Json.

I would like them to be able to send an email using a json, for example:

{"fulltemplate": "Default", "to":"info@google.com", "tags": { "Naam", "Googlemailer", "Url": "http://google.com" } }

The email should than automaticly be mapped to the right format (picked from database using the Fulltemplate variable. After that we will replace all strings in the emails that have [Key] with [value] so that we can dynamicly build emails.

I have been able to succesfully map fulltemplate and to into a variable, but the json object inside it named tags didn't work, I hoped it could automaticly map to a IDictionary<string,string> but that didn't work as intended.

I would I do such thing without having to serialize it myself in the code?

The class:

class RootObject
    {
        [JsonProperty("email")]
        public List<EmailModel> email { get; set; }
    }


    public class EmailModel
    {   
        public string fulltemplate { get; set; }    

        [JsonRequired]
        public string to { get; set; }

        public Dictionary<string, string> tags { get; set; }
    }

In old ASP.NET I could tell why my app stopped by looking at HostingEnvironment.ShutdownReason.

In ASP.NET Core, this doesn't exist. Where can I get this info?

I have done my project using ASP.Net MVC and SQL SERVER but the website which i gonna host, is not supporting SQL SERVER they asked me to change my database to MYSQL.

I used many ways, but got different run time errors.

QUESTION: HOW CAN I CHANGE MY DATABASE FROM SQL SERVER TO MYSQL?

Here is my model and context model:

namespace WebApplication11.Models
{
    [Table("Product")]
    public class ProductModel
    {
        [Key]
        [Required(ErrorMessage ="Please provide Product id",AllowEmptyStrings =false)]
        public int pid { get; set; }
        [Required(ErrorMessage = "Please provide Product Name", AllowEmptyStrings = false)]
        public string ProductName { get; set; }
        [Required(ErrorMessage = "Please Enter the Price", AllowEmptyStrings = false)]
        public decimal ProductPrice { get; set; }
        public string ProductDescription { get; set; }
        [Required(ErrorMessage = "Please Specify the Product Category", AllowEmptyStrings = false)]
        public string ProductCategory { get; set; }
        public string ProductAddress { get; set; }
        public string ProductImage1 { get; set; }
        public string ProductImage2 { get; set; }
        public string ProductImage3 { get; set; }
        [Required(ErrorMessage = "Please provide Customer ID", AllowEmptyStrings = false)]
        public int CustomerId { get; set; }
       // public DateTime ProductSubTime { get; set; }
    }

    [Table("Customer")]
    public class CustomerModel
    {
        [Key]
        public int cid { get; set; }
        [Required(ErrorMessage = "Please Enter Customer name", AllowEmptyStrings = false)]
        public string CustomerFullName { get; set; }
        [Required(ErrorMessage = "Please provide Contact Number", AllowEmptyStrings = false)]
        public int CustomerContact { get; set; }
        public string CustomerEmail { get; set; }
        [Required(ErrorMessage = "Please select Gender", AllowEmptyStrings = false)]
        public string CustomerGender { get; set; }
        public string CustomerAddress { get; set; }
    }


    [Table("adminlogin")]
    public class adminlogin
    {
        [Key]

        public string id { get; set; }
       public string name { get; set; }
        [Required(ErrorMessage = "Please Specify your name", AllowEmptyStrings = false)]
        public string username { get; set; }
        public string pass { get; set; }
        public string designation { get; set; }
    }

    [Table("contact")]
    public class contact
    {
        [Key]
        [Required(ErrorMessage = "Please Specify your name", AllowEmptyStrings = false)]
        public string Name { get; set; }
        [Required(ErrorMessage = "Please enter your contact", AllowEmptyStrings = false)]
        public string phone { get; set; }
        [Required(ErrorMessage = "Please Specify Email", AllowEmptyStrings = false)]
        public string email { get; set; }
        [Required(ErrorMessage = "Please Enter sugestion ", AllowEmptyStrings = false)]
        public string description { get; set; }
    }

    [Table("Category")]
    public class itemcategory
    {
        [Key]
        public string id { get; set; }
        public string Category { get; set; }

    }

    public class ContextModel :DbContext
    {
        public DbSet<ProductModel> Products { get; set; }
        public DbSet<CustomerModel> Customers { get; set; }
        public DbSet<itemcategory> itemCat { get; set; }
        public System.Data.Entity.DbSet<WebApplication11.Models.adminlogin> adminlogins { get; set; }

        public System.Data.Entity.DbSet<WebApplication11.Models.contact> contacts { get; set; }
    }

My connection string

<connectionStrings>
    <add name="ContextModel" 
         connectionString="Data Source=noori\sqlexpress;Initial Catalog=salesWebsiteDB;Integrated Security=True"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

And my homepage controller

public ActionResult Index()

{
    var bike = cm.Products.Where(p => p.ProductCategory == "Bike").ToList();
    var mobile = cm.Products.Where(p => p.ProductCategory == "Mobile").ToList();
    var others = cm.Products.Where(p => p.ProductCategory != "Cars" && p.ProductCategory!= "Mobile").ToList();

    ViewBag.bike = bike.ToList();
    ViewBag.mobile = mobile.ToList();
   ViewBag.others = others.ToList();


    return View(cm.Products.ToList());
}

What is the best way to Send back an image ID to a view Setting it to a HiddenFor, I want to save an image file before I save a center to which the image belongs 2.

Here is the controller code.

[HttpPost]
public ActionResult ImageUpload(IEnumerable<HttpPostedFileBase> files)
{
    Center ins = new Models.Maintenance.Center();
    ExamPortalCore.Models.Common.RenderImage Service = new 
    Models.Common.RenderImage();
    ins.CenterLogo = Service.UploadImageToDB(files);
    ImageRepository ImgRep = new ImageRepository();
    ins.Image = ImgRep.GetImageByID(ins.CenterLogo);
    CreateEditCenter(ins.CenterLogo);
    byte[] byteArray = { };
    byteArray = ins.Image.ImageBytes;
    if (byteArray != null)
    {
        return Json(new { base64imgage = Convert.ToBase64String(byteArray) }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return null;
    }
    return View();
}

The View Code:

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Center</title>
</head>

<body>

@using (Html.BeginForm("Create", "Center", FormMethod.Post))
{

    @Html.AntiForgeryToken()
    <h3>Upload School Image</h3>

    <img id="ItemPreview" src="" />

    <div class="demo-section k-content wide">
        <div class="wrapper">
            <div id="products"></div>
            <div class="dropZoneElement">
                <div class="textWrapper">
                    <p><span>+</span>Add Image</p>
                    <p class="dropImageHereText">Drop image here to upload</p>
                </div>
            </div>
        </div>
    </div>


    @(Html.Kendo().Upload()
    .Name("files")
    .Async(a => a
        .Save("ImageUpload", "Center", FormMethod.Post)
        .Remove("Remove", "Center")
        .AutoUpload(true)
    )
    .Events(e => e.Success("onSuccess"))
    .ShowFileList(false)
    .DropZone(".dropZoneElement")
    .Validation(validation =>
    {
        validation.AllowedExtensions(new string[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif" });
        validation.MinFileSize(500);
    })
    )

    <script>

        function onSuccess(e) {
            if (e.operation == "upload") {
                for (var i = 0; i < e.files.length; i++) {
                    var file = e.files[i].rawFile;

                    if (file) {
                        var reader = new FileReader();

                        reader.onloadend = function () {
                            $("<div class='product'><img src=" + this.result + " /></div>").appendTo($("#products"));
                        };

                        reader.readAsDataURL(file);
                    }
                }
            }
        }
    </script>



    <div class="col-lg-12">

        <div class="form-group">

            <h3>School Information</h3>
            <div class="col-md-10">
                @Html.LabelFor(model => model.CenterName, htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.Kendo().TextBoxFor(model => model.CenterName)
                @Html.ValidationMessageFor(model => model.CenterName, "", new { @class = "text-danger" })
            </div>
            <div class="col-md-10">
                @Html.LabelFor(model => model.CenterURL, htmlAttributes: new { @class = "control-label col-md-2" })
                @Html.Kendo().TextBoxFor(model => model.CenterURL)
                @Html.ValidationMessageFor(model => model.CenterURL, "", new { @class = "text-danger" })
            </div>

        </div>
    </div>
    <hr />



    @Html.HiddenFor(model => model.CenterLogo,new { @Value= ViewBag.CenterLogo})
    <p>
        <input type="submit" value="Save" />
    </p>

}

I save the image before i save the center and i need to save the id of the image back to a model.

I have a page on a ASP.NET site which uses Bootstrap (v3.3.6). I am using Razor syntax to place a dropdown select input on the page, the issue I'm having is that the width of the boxes appears to be set by the length of the options within. I'd like instead to have all these dropdowns the same width. I understand I may be able to specify a specific or min/max width in CSS to resolve this but was wondering if there is any combination of the Bootstrap classes that could achieve this in a more dynamic manner?

<div class="container-fluid">
        <div class="form-group">
            <div class="col-lg-6 col-md-6 col-sm-12">
                @Html.LabelFor(model => model.AssigneeTeam, htmlAttributes: new { @class = "control-label col-md-5 col-sm-12 text-left" })
                <div class="col-md-6 col-md-offset-1 col-sm-12">
                    @Html.DropDownListFor(model => model.AssigneeTeam,
     EnumHelper.GetSelectList(typeof(WebApplication1.Models.RequestBase.AssigneeTeams)),
 new { htmlAttributes = new { @class = "form-control input-sm" } })
                    @Html.ValidationMessageFor(model => model.AssigneeTeam, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="col-lg-6 col-md-6 col-sm-12">
                @Html.LabelFor(model => model.Priority, htmlAttributes: new { @class = "control-label col-md-5 col-sm-12 text-left" })
                <div class="col-md-6 col-md-offset-1 col-sm-12">
                    @Html.DropDownListFor(model => model.Level,
     EnumHelper.GetSelectList(typeof(WebApplication1.Models.RequestBase.PriorityLevels)),
 new { htmlAttributes = new { @class = "form-control input-sm" } })
                    @Html.ValidationMessageFor(model => model.Priority, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="col-lg-6 col-md-6 col-sm-12">
                @Html.LabelFor(model => model.AffectedComponent, htmlAttributes: new { @class = "control-label col-md-5 col-sm-12 text-left" })
                <div class="col-md-6 col-md-offset-1 col-sm-12">
                    @Html.DropDownListFor(model => model.AffectedComponent,         EnumHelper.GetSelectList(typeof(WebApplication1.Models.RequestBase.EstateComponents)), new { htmlAttributes = new { @class = "form-control input-sm" } })
                    @Html.ValidationMessageFor(model => model.AffectedComponent, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="col-lg-6 col-md-6 col-sm-12">
                @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-5 col-sm-12 text-left" })
                <div class="col-md-6 col-md-offset-1 col-sm-12">
                    @Html.DropDownListFor(model => model.Type,
     EnumHelper.GetSelectList(typeof(WebApplication1.Models.RequestBase.ChangeType)),new { htmlAttributes = new { @class = "form-control input-sm" } })
                    @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
    </div>
</div>

This is a screenshot of the result, as you can see the dropdowns vary in width

for (int i = 0; i < xxx.Models.cbsearchmodel.searchvars.loopnum; i++)
{
    @using (Html.BeginForm("cbtView", "cb"))
    {
        <fieldset>
            <div class="container center-block" style="background-color: #000000;margin-top: 15px;color: #ffffff;box-shadow: 2px 2px 1px #ffd800;   border: 1px solid #ffd800;">
                <h3></h3>
                <p></p>
                <p></p>
                <p></p>
                <input type="submit" />
            </div>
         </fieldset>
    }
}

When button on this page is clicked the integer loopnum gets value and loops through the code, however when I do it again it does not clear the current values and simply adds more code. I can not find anything close to solution of this problem, is there any way at all I can fix this?

In MVC Core View, I am trying to display the Date Modified instead of Date Created if it is not empty.

So, I wrote like the following

@Html.DisplayFor(modelItem => (item.DateModified.HasValue ? item.DateModified : item.DateCreated))

But got an error saying that

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions

So, instead of that I changed it to the following and it works.

@(item.DateModified.HasValue ? item.DateModified.Value.ToString("dd/MM/yyyy") : item.DateCreated.ToString("dd/MM/yyyy"))

However, the problem is that I have to re-specify the format of the date which I already did in Model Declaration. If not, it's showing data in dd/MM/yyyy HH:mm:ss format because I am not using DisplayFor anymore.

Another possibility is that I could use the ViewModel and add a new property to handle this kind of special text.

May I know if there is a better way to handle this kind of scenario?

I am getting IndexOutOfRangeException on IIS event log, exception is not not occurring on every request, I am getting exception in 2-3 days. I have verified my code it not seems to be application level exception.

Here are my complete event log

Event code: 3005 
Event message: An unhandled exception has occurred. 
Event time: 1/11/2017 9:58:56 AM 
Event time (UTC): 1/11/2017 3:58:56 PM 
Event ID: b3dff3b2248047b386816a4efa5b697b 
Event sequence: 604 
Event occurrence: 2 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/2/ROOT-1-131286032828250910 
    Trust level: Full 
    Application Virtual Path: / 
    Application Path: C:\inetpub\wwwroot\VWF\ 
    Machine name: IIS-VWF 

Process information: 
    Process ID: 1004 
    Process name: w3wp.exe 
    Account name: PATRIOTWEB\vwfSvc 

Exception information: 
    Exception type: IndexOutOfRangeException 
    Exception message: Index was outside the bounds of the array.
   at System.Collections.Generic.Dictionary`2.Resize(Int32 newSize, Boolean forceNewHashCodes)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at IronRuby.Runtime.RubyUtils.RecursionTracker.TryPushInfinite(Object obj)
   at IronRuby.Runtime.RubyUtils.RecursionTracker.TrackObject(Object obj)
   at IronRuby.Builtins.RubyArray.GetHashCode(UnaryOpStorage hashStorage, ConversionStorage`1 fixnumCast, IList self)
   at IronRuby.Builtins.IListOps.GetHashCode(UnaryOpStorage hashStorage, ConversionStorage`1 fixnumCast, IList self)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at IronRuby.Runtime.EqualityComparer.System.Collections.Generic.IEqualityComparer<System.Object>.GetHashCode(Object obj)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)`enter code here`
   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
   at IronRuby.Runtime.RubyUtils.SetHashElement(RubyContext context, IDictionary`2 obj, Object key, Object value)
   at IronRuby.Builtins.HashOps.CreateSubclass(ConversionStorage`1 toAry, RubyClass self, IList list)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
   at IronRuby.Runtime.Calls.RubyObjectMethodDispatcherWithScope`1.Invoke[TScope](CallSite callSite, TScope scope, Object self, T0 arg0)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
   at IronRuby.Runtime.Calls.RubyObjectMethodDispatcherWithScopeAndBlock`1.Invoke[TScope,TProc](CallSite callSite, TScope scope, Object self, TProc proc, T0 arg0)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`5.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronRuby.Runtime.RubyScriptCode.Run(Scope scope, Boolean bindGlobals)
   at IronRuby.Runtime.RubyScriptCode.Run(Scope scope)
   at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at SassAndCoffee.SassFileCompiler.Init(HttpApplication context)
   at SassAndCoffee.CompilableFileModule.Init(HttpApplication context)
   at System.Web.HttpApplication.InitModulesCommon()
   at System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
   at System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context)
   at System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context)
   at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)



Request information: 
    Request URL: http://XX.YYYY.ZZZZ.com/Content/kendo/kendo.default.min.css 
    Request path: /Content/kendo/kendo.default.min.css 
    User host address: 50.84.121.250 
    User:  
    Is authenticated: False 
    Authentication Type:  
    Thread account name: PATRIOTWEB\vwfSvc 

Thread information: 
    Thread ID: 64 
    Thread account name: PATRIOTWEB\vwfSvc 
    Is impersonating: False 
    Stack trace:    at System.Collections.Generic.Dictionary`2.Resize(Int32 newSize, Boolean forceNewHashCodes)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at IronRuby.Runtime.RubyUtils.RecursionTracker.TryPushInfinite(Object obj)
   at IronRuby.Runtime.RubyUtils.RecursionTracker.TrackObject(Object obj)
   at IronRuby.Builtins.RubyArray.GetHashCode(UnaryOpStorage hashStorage, ConversionStorage`1 fixnumCast, IList self)
   at IronRuby.Builtins.IListOps.GetHashCode(UnaryOpStorage hashStorage, ConversionStorage`1 fixnumCast, IList self)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at IronRuby.Runtime.EqualityComparer.System.Collections.Generic.IEqualityComparer<System.Object>.GetHashCode(Object obj)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.set_Item(TKey key, TValue value)
   at IronRuby.Runtime.RubyUtils.SetHashElement(RubyContext context, IDictionary`2 obj, Object key, Object value)
   at IronRuby.Builtins.HashOps.CreateSubclass(ConversionStorage`1 toAry, RubyClass self, IList list)
   at Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
   at IronRuby.Runtime.Calls.RubyObjectMethodDispatcherWithScope`1.Invoke[TScope](CallSite callSite, TScope scope, Object self, T0 arg0)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
   at IronRuby.Runtime.Calls.RubyObjectMethodDispatcherWithScopeAndBlock`1.Invoke[TScope,TProc](CallSite callSite, TScope scope, Object self, TProc proc, T0 arg0)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
   at Microsoft.Scripting.Interpreter.DynamicInstruction`5.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 arg1)
   at IronRuby.Runtime.RubyScriptCode.Run(Scope scope, Boolean bindGlobals)
   at IronRuby.Runtime.RubyScriptCode.Run(Scope scope)
   at Microsoft.Scripting.SourceUnit.Execute(Scope scope, ErrorSink errorSink)
   at Microsoft.Scripting.Hosting.ScriptSource.Execute(ScriptScope scope)
   at SassAndCoffee.SassFileCompiler.Init(HttpApplication context)
   at SassAndCoffee.CompilableFileModule.Init(HttpApplication context)
   at System.Web.HttpApplication.InitModulesCommon()
   at System.Web.HttpApplication.InitInternal(HttpContext context, HttpApplicationState state, MethodInfo[] handlers)
   at System.Web.HttpApplicationFactory.GetNormalApplicationInstance(HttpContext context)
   at System.Web.HttpApplicationFactory.GetApplicationInstance(HttpContext context)
   at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)


Custom event details:  

I've read a bunch of questions about the subject but haven't managed to find a solution to this specific problem.

Controller

public ActionResult Index() {
    string categorie = "--Tout--";
    string souscategorie = "--Tout--";

    if (Session["Categorie"] != null) {
        categorie = Session["Categorie"].ToString();
    }

    if (Session["SousCategorie"] != null) {
        souscategorie = Session["SousCategorie"].ToString();
    }

    SelectList cats = new SelectList(GetCategories(), categorie);
    SelectList sCats = new SelectList(GetSousCategories(), souscategorie);

    ViewBag.Categories = cats;
    ViewBag.SousCategories = sCats;

    using(DAL.WebShopEntities entities = new WebShopEntities()) {
        return View(entities.Article.ToList());
    }
}

View

@Html.Label("Cat├ęgories")
@Html.DropDownList("Categories", (SelectList)ViewBag.Categories, new { @class = "form-control dropdownlist" })

<br />

@Html.Label("Sous-Cat├ęgories")
@Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategories, new { @class = "form-control dropdownlist" })

When debugging the view I can see clearly that the option stocked in the session is sent to the View. But it displays the index 0 when checking in the browser. This has me bugging because the SelectList behaves normally, I think the problem lays with the DropDown but what could be the problem?

In old ASP.NET, in the Global.asax.cs class, I would log when the app starts, stops and throws unhandled exceptions:

  • Application_Start()
  • Application_End()
  • Application_Error()

How do I do the same in ASP.NET Core? It has a Startup class, but it is for configuration.

Where do I hook into the app's start/stop/error events?

I have a textbox(along with many other textboxes) in my cshtml view, where the user can enter some random texts(which can me multiline in nature) and save it in database. Once the data is saved successfully, the user can view the saved data using a "View Stats" button. On click of this button, all the saved data will be loaded in read-only mode in respective labels. The problem here is, the multiline texts that the user entered, is displayed in single line in the label. But when the user tries to edit the record(where the data is disaplyed in a textbox) the data is shown as multiline. How can I achieve the same functionality in view mode where I wish to display the multiline texts in label.

Below is my textbox:

@using (Html.BeginInnerPanel(true, new { style = "width:100%;", id =      "pnlRemarks" }, "", false))
{
  using (Html.BeginInnerPanelBody())
  {
     using (Html.BeginFieldWrap("Remarks", "", new { style = "width:100%"   }))
    {
         @Html.TextArea("txtRemarks", "", new { style = "width:99%;height:80px; text-transform: uppercase;" });
     }
  }
}

Below is my Label:

@using (Html.BeginInnerPanel(true, new { style = "width:100%; display:none;", id = "pnlRemarksV" }, "", false))
 {
    using (Html.BeginInnerPanelBody())
    {
       using (Html.BeginFieldWrap("Remarks", "", new { style = "width:100%"    }))
    {
       <label id="lblViewRemarks" style = "font-weight:bold"></label>
    }
  }
}

I hide and show the panels based on edit or view mode. Could you please help me display text in label as multiline.

I have a project where I want to generate a PDF from gridview but after generating Pdf I want to refresh my gridview and add new data.

private void Generate_PDF()
            {

                     StringWriter sw = new StringWriter();
                     HtmlTextWriter hw = new HtmlTextWriter(sw);
                      StringBuilder sb = new StringBuilder();
                        StringBuilder sb1 = new StringBuilder();

                        //Generate Invoice (Bill) Header.
                        sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
                        sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Bill Report</b></td></tr>");
                        sb.Append("<tr><td colspan = '2'></td></tr>");
                        sb.Append("<tr><td><b>Bill No: </b>");
                        sb.Append(HiddenField1.Value);
                        sb.Append("</td><td align = 'right'><b>Date: </b>");
                        sb.Append(DateTime.Now);
                        sb.Append(" </td></tr>");


                        sb.Append("</table>");
                        sb.Append("<br />");
                        GridOfTestRequest.RenderControl(hw);

                        StringReader sr = new StringReader(sw.ToString());
                        StringReader sr1 = new StringReader(sb.ToString());
                        sb1.Append("<table border = '1'>");
                        sb1.Append("<tr><td align = 'right' colspan = '");
                        sb1.Append(GridOfTestRequest.HeaderRow.Cells.Count - 1);
                        sb1.Append("'>Total</td>");
                        sb1.Append("<td>");
                        sb1.Append(testList.Sum(x=>x.testFee));
                        sb1.Append("</td>");
                        sb1.Append("</tr></table>");


                        StringReader sr2 = new StringReader(sb1.ToString());
                        testList.Clear();
                        GridOfTestRequest.DataSource = null;
                        GridOfTestRequest.DataBind();
                        Document pdfDoc = new Document(PageSize.A5, 10f, 10f, 10f, 0f);
                        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

                        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                        pdfDoc.Open();
                        htmlparser.Parse(sr1);
                        htmlparser.Parse(sr);
                        htmlparser.Parse(sr2);

                        pdfDoc.Close();

                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-disposition", "attachment;filename=Invoic.pdf");
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);

                        Response.Write(pdfDoc);

                        Response.Flush();
                        Response.ClearContent();
                        Response.Clear();
                        Response.Cookies.Clear();

                        Response.End();



            }

After execution of this method in a button click, I want to clear the Gridview. How can I do it? I tried to clear it with gridview.datasource=null but it doesn't work.

I have this problem, where the project works fine on local, it just doesn't wortk on production

on local, everything works on IIS Express

on production, IIS 7.5, windows 2008 r2:

Exception type: ConfigurationErrorsException 
    Exception message: Could not load file or assembly 'Telerik.OpenAccess, Version=2014.3.1209.1, Culture=neutral, PublicKeyToken=7ce17eeaf1d59342' or one of its dependencies. The system cannot find the file specified. (\\xxx\xxx\xxx\web.config line 106)
  1. checked the file versions physically in the locaiton, they are present and correct
  2. deleted the complete folder from production, then deployed
  3. checked and ticked 32-bit applicaiton compatibility on IIS

also note that we had a previous version of the project deployed on production ( with same referenced files and versions) - only the target .net version has been changed and it stopped working (it's still targetting the same assembly, and works on local)

the files are there and all references in the referenced projects are correct for this file

what else can I look into ?

This is my EmployeeController, I don't understand why I can access url as Employee/Index/1

namespace MVCDemo.Controllers
{
    public class EmployeeController : Controller
    {

        public ActionResult index(int departmentId)
        {
            EmployeeContext employeeContext = new EmployeeContext();
            List<Employee> employee = employeeContext.Employees.Where(emp => emp.DepartmentId == departmentId).ToList();

            return View(employee);
        }

        public ActionResult Details(int id)
        {
            EmployeeContext employeeContext = new EmployeeContext();
            Employee employee = employeeContext.Employees.Single(emp => emp.EmployeeId == id);

            return View(employee);
        }

    }
}

/Employee/Index //of course doesn't work, fair enough,

/Employee/Index/1 //why it doesn't work? isn't it the same as details action method?

/Employee/Details/1 //worked

/Employee/Index?departmentId=1 //worked but why /Index/1 doesn't work

Below is my jquery code to implement search filter for gridview along with paging,i am able to implement searching but the problem is in paging if i click edit button i am getting back to first page of my gridview instead of staying in that particular page.How to get stayed in that particular page on clicking edit button in gridview

 <script>
            $(function () {
                // Setup - add a text input to each footer cell
                $('#<%=GridView1.ClientID %> th').each(function () {
                    var title = $(this).text();
                    if (title == "Audio Name" || title == "Physician  Name" || title == "Speciality") {
                        $(this).html(title + '<br/><input type="text" style="width:120px" placeholder="Search ' + title + '" />');
                    }
                    else {
                        if (title != " ") {
                            //$(this).html(title + '<br/><input type="text" style="background-color:#646464;border:none" disabled="disabled"   />');
                        }
                    }
                });

                // DataTable
                //var table = $('#<%=GridView1.ClientID %>').DataTable({
                var table = $('#<%=GridView1.ClientID %>').prepend($('<thead></thead>').append($('#<%=GridView1.ClientID %>').find('tr:first'))).DataTable({
                    "paging": true,
                    "ordering": false,
                    "info": false,
                    "pageLength": 10,
                    "bLengthChange": false
                });

                table.columns().every(function () {
                    var that = this;

                    $('input', this.header()).on('keyup change', function () {
                        if (that.search() !== this.value) {
                            that
                                .search(this.value)
                                .draw();
                        }
                    });
                });
            });

    </script>

I have to create this table in gridview

Output Format

In the output file, the header is completely different than the column present in database. The first column which having condition likes Abnormal, Sub-Normal etc are constant so i have to do it statically. The values present in the output image, which showing integers values are the values coming from the database.

I have one button and on the button click the table will be displayed.

Here is my button code:

protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        List<String> s1 = new List<String>();
        s1.Add("Abnormal");
        s1.Add("Sub-Normal");
        s1.Add("Normal");
        s1.Add("Critical");
        s1.Add("Super-Critical");
        s1.Add("Total");

        dt.Columns.Add("Loss Range");


        foreach (String s in s1)
        {
            DataRow row = dt.NewRow();
            row["Loss Range"] = s.ToString();
            dt.Rows.Add(row);
        }

        dt.Columns.Add("No of clusters");

        BoundField SOUTH = new BoundField();
        SOUTH.HeaderText = "SOUTH";
        GridView1.Columns.Add(SOUTH);

        BoundField SOUTHCENTRAL = new BoundField();
        SOUTHCENTRAL.HeaderText = "SOUTH CENTRAL";
        GridView1.Columns.Add(SOUTHCENTRAL);

        BoundField CENTRAL = new BoundField();
        CENTRAL.HeaderText = "CENTRAL";
        GridView1.Columns.Add(CENTRAL);

        BoundField NORTH = new BoundField();
        NORTH.HeaderText = "NORTH";
        GridView1.Columns.Add(NORTH);

        BoundField EAST = new BoundField();
        EAST.HeaderText = "EAST";
        GridView1.Columns.Add(EAST);

        BoundField TOTAL = new BoundField();
        TOTAL.HeaderText = "TOTAL";
        GridView1.Columns.Add(TOTAL);

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Attributes.Add("rowspan", "2");

            GridViewRow HeaderRow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
            TableCell HeaderCell2 = new TableCell();
            HeaderCell2.Text = "Category";
            HeaderCell2.ColumnSpan = 7;
            HeaderRow.Cells.Add(HeaderCell2);

            GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

            GridViewRow HeaderRow1 = new GridViewRow(1, 1, DataControlRowType.Header, DataControlRowState.Insert);
            TableCell HeaderCell1 = new TableCell();
            HeaderCell1.Text = "No of clusters";
            HeaderCell1.ColumnSpan = 6;
            HeaderRow1.Cells.Add(HeaderCell1);

            GridView1.Controls[0].Controls.AddAt(1, HeaderRow1);
        }
    }

And the HTML code is

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCreated="GridView1_RowCreated">
        <Columns>
            <asp:BoundField DataField="Loss Range" HeaderText="Loss Range" />
        </Columns>
    </asp:GridView>

I don't have knowledge about gridview use.

Thanks in advanced.

How can I set three buttons to position themselves in one column after the window size is changed to a certain size, or better yet once the buttons start to overlap?

i'm have a web service with asp.net i'm need to send data to this service by ajax used this code

$.ajax({
    type : "POST", 
    contenttype: 'application/json; charset=utf-8',
    dataType: "json",
    url :  "myurl", 
    data: { 
        mydata
    },
  error: function (data) {
         console.log(data.responseText);
    },


     success: function () {
     }
    })

then i'm have this respons in my console

<?xml version="1.0" encoding="utf-8"?>
<JsonResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
  <Data xsi:type="xsd:string">{"reuslt":"-2"}</Data>
  <JsonRequestBehavior>AllowGet</JsonRequestBehavior>
  <MaxJsonLength xsi:nil="true" />
  <RecursionLimit xsi:nil="true" />
</JsonResult>

how can read this respons i'm need to the parameter result how can read this ?

can any one help me

thank you