I'm new to ASP .NET, MVC and AngularJS so I'm trying to figure this all out still.

I have a Model called Words.cs which contains:

namespace liveSearch.Models
{
    public class Words
    {
        public int ID { get; set; }
        public string Word{ get; set; }
    }
}

The database is already populated with data and I want to use JavaScript/JQuery to get every Word from the database and then use AngularJS to display that on my index.cshtml page.

I currently have Razor in my index.cshtml which does:

@{
     foreach (var item in Model)
     {
         <li>
             @Html.DisplayFor(modelItem => item.Word)
         </li>
     }
 }

This works in getting and displaying all Words in the model but I want to get rid of the Razor and use JavaScript/Jquery to get the data and AngularJS to display it there.

Ideally, I want to get all Words from the DB (I don't care about the IDs) and add it to an array in the scope. Then I can use AngularJS to display each Word by using ng-repeat.

The problem is that I don't know how to get all the Words into an array in the scope from the DB/model.

I think I can use $.get() or $.ajax() but I don't really know how to use it with a DB/model.

Thank you

I'm new in MVC and need to figure out how to add textbox html helper controls a number of times based on user input on the same view.

I'm building a website for multiple organizations. For example, people could go to mydomain.com/org1/home/index or mydomain.com/org2/home/index.

What I am trying to do is have the following routing,

mydomain.com/{area}/{controller}/{action}/{id}

I can't figure out how to do this, and frankly not even sure how to even start setting up my routing. I want to be able to access {area} string in order to decide which images to display, what text etc.

I hope I'm making sense with what I'm trying to do.

I'm having a program where there will be notes in the textbox. I'd like the textbox to resize itself, so it fit the content.

enter image description here

 private void rg_pending_RowFormatting(object sender, RowFormattingEventArgs e)
        {
            which code i will place here
        }

This is probably a badly worded question and this is my first web api so I could be doing something completely wrong. I have my Controller and my Model, in my Controller I have 3 methods, string[] Apples string[]Get Judgment GetJudgmentByStateCaseId. I'm trying to call of of them using the following urls but all of the results come from Get() data.

  • /api/judgment
  • /api/apples
  • /api/GetJudgmentByStateCaseId

`JudgmentController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplicationsWData.Models;

namespace WebApplicationsWData.Controllers
{
    public class JudgmentController : ApiController
    {
        public string[] Apples()
        {
            return new string[]
            {
                "as","B"
            };
        }

        public string[] Get()
        {
            return new string[]
            {
                "as","C"
            };
        }


        public Judgment GetJudgmentByStateCaseId(string State, string CaseId)
        {

            Judgment judgement = new Judgment
            {
                CaseId = "1",
                State = "MeVMe"


            };
            if (judgement == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return judgement;

        }




    }

`Judgment.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

    namespace WebApplicationsWData.Models
    {
        public class Judgment
        {
            [Required]
            public string State { get; set; }

            [Required]
            public string CaseId { get; set; }

        }
    }

And here is my RouteConfig

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

I am planning to build a new social media website named Reciprocity built around a new social model with the hopes of ushering in the next gen experience in SM globally, in other words, it's meant to be disruptive and make FB obsolete in time if the network effect takes effect.

Having done some research into the web stack that would be most suitable for a such a large scale, very complex and extensive feature set I have arrived at following Web app framework -- ASP.NET MVC 5 , OS - win server 2012 R2 / 2016 , DB - MYSQL , CASSANDRA with MEMCACHED for caching (+ HAYSTACK DOWN THE LINE ) , client side coding : HTML5,CC3,javascript

The DB and caching part is exactly the same as FB uses today but the rest is a change to Microsoft tech .

My queries are .... 1) Will such a combination work well enough to support the complex and extensive feature set (involving extensive DB search based algorithms ) 2) I gathered that though MYSQL is supported, it is not as good as in PHP ..is that correct? if so what are key features missing? 3) Can NOSQL DB's like cassandra be used properly with ASP.NET MVC web apps? 4) is there support for MEMCAHCED AND HAYSTACK in ASP.NET MVC 5 framework? 5) Anything else I should know/ be concerned about if the rest checks out? ! Any and all answers(in full or part) would be highly appreciated! Thanks in advance for your valuable input!

I'm developing ASP.NET Web API application which uses OAuth (owin) protocol to authenticate my clients. Some time after the initial version of the API I've added additional Forms authentication (cookie based) and mixed in ASP.NET MVC app on top of it. Now, during startup I

// forms
app.UseCookieAuthentication(... options ...);
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

// oauth
app.UseOAuthAuthorizationServer

It works perfect and my MVC users can call my API without need to be authenticated which is cool. The only drawback and it causes lots of issues now is that when my API clients are trying to access the API with an expired token instead of 403 error I'm getting 200 and html response of my login page.

Request:
GET https://server.com/api/v1/controller/action1
Authoration: bearer <expired token here>

Response:
200 <html>

What I need is that any API request with expired token should lead to 403 http response and no login page.

Is it possible to achieve in my mixed environment or should I split my solution?

Antaris RazorEngine v3.9.3 is used in ASP.NET MVC4 controller to create form element. In result html input elements are rendered outside form element. For example

@using (Html.BeginForm("Test", "Upload"))
{
<input type="file" />
<input type="submit"/>
}

produces

<form action="/Upload/Test" method="post"></form>
<input type="file" />
<input type="submit"/>

while correct result should be

<form action="/Upload/Test" method="post">
<input type="file" />
<input type="submit"/>
</form>

RenderScript returns only input elements. <form action="/Upload/Test" method="post"> is written to output directly. It looks like BeginForm() writes directly to view and Razorengine does not capture its output.

How to fix this ?

View:

        @Model.RenderScript()

Model:

public IHtmlString RenderScript() {
    var config = new TemplateServiceConfiguration();
    config.BaseTemplateType = typeof(HtmlTemplateBase<>);
    config.Namespaces = new HashSet<string>(new string[] {
                    "System",
                    "System.Collections",
                    "System.Collections.Generic",
                    "System.Globalization",
                    "System.Linq",
                    "System.Web",
                    "System.Web.Mvc",
                    "System.Web.Mvc.Html"
                });
    razor = RazorEngineService.Create(config);
    var colModel=@"
    @using (Html.BeginForm(""Test"", ""Upload""))
    {
    <input type='file' />
    <input type='submit'/>
    }
    ";
    string res = razor.RunCompile(colmodel, colmodel, typeof(object), new object());
    return MvcHtmlString.Create(res);
}

Template base class:

using RazorEngine.Templating;
using RazorEngine.Text;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;

public class HtmlTemplateBase<T> : TemplateBase<T>, IViewDataContainer
{
    // http://stackoverflow.com/questions/8561164/razorengine-issues-with-html
    HtmlHelper<T> helper = null;
    ViewDataDictionary viewdata = null;

    public HtmlHelper<T> Html
    {
        get
        { 

            // https://github.com/Antaris/RazorEngine/issues/150
             if (helper == null)
            {
                var p = WebPageContext.Current;
                var wvp = p.Page as WebViewPage;
                var context = wvp != null ? wvp.ViewContext : null;

                context.Writer = this.CurrentWriter;

                helper = new HtmlHelper<T>(context, this);
            }

            return helper;
        }
    }


    public ViewDataDictionary ViewData
    {
        get
        {
            if (viewdata == null)
            {
                viewdata = new ViewDataDictionary();
                viewdata.TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = string.Empty };

                if (this.Model != null)
                {
                    viewdata.Model = Model;
                }
            }
            return viewdata;
        }
        set
        {
            viewdata = value;
        }
    }

    public override void WriteTo(TextWriter writer, object value)
    {
        if (writer == null)
            throw new ArgumentNullException("writer");

        if (value == null) return;
        //try to cast to RazorEngine IEncodedString
        var encodedString = value as IEncodedString;
        if (encodedString != null)
        {
            writer.Write(encodedString);
        }
        else
        {
            var htmlString = value as IHtmlString;
            if (htmlString != null) writer.Write(htmlString.ToHtmlString());
            else
            {
                encodedString = TemplateService.EncodedStringFactory.CreateEncodedString(value);
                writer.Write(encodedString);
            }

        }
    }
}

Posted also in https://github.com/Antaris/RazorEngine/issues/443

How to read any strings in a aspx page.

example: http://foo.com/bike stand

I want to read/get the strings in a specified aspx page. expected page string is bike stand
expected page is getstring.aspx

Here i like to read the string and redirect to specified page.
Note: I like to do this in just ASP.Net (Not with MVC)

I am trying to implement FormsAuthentication for my website. Users may only access Welcome.aspx via successful login.

If the login details are authenticated, the user logs in successfully, & Welcome.aspx is displayed. But, I don't want to create a cookie upon login.

So when you try to access Welcome.aspx in a new browser instance, you should be required to log in again.

 protected void btnLogin_Click(object sender, EventArgs e)
{
    if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text))
    {
        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
        //When we specify false above, cookies shouldn't be saved.
        //But, this is not working, it's still allowing me to access the 
        //Welcome page, even though I should be asked to log back in 
        //when I open a new instance of the browser
    }
    else
    {
        lblMessage.Text = "Invalid username and/or password";
    }
}

Even though I specify 'false', I am still having the problem above. Any thoughts?

I'm generating an online quiz system, I am using MSSQL, Question Table [QuestionID,Statement,RightAnswer,WrongAnswer1,WrongAnswer2,WrongAnswer3]

When reading them to the application how to randomly read them so Right answer is not stuck at same radio button in every question

Note: Using Data list control.

Please help for any other ideas. Thanks in advance.

I'm working with google charts here and trying to get my data into it, the first code here is one that works and the second part of the code is the one that does not work, it just simply does not appear on the screen, the only difference about the two is the foreach loop inside them, if I remove it and enter hard coded data the chart will appear in the second code case, I don't know why it does not work? is there something wrong with my foreach?

This is the query for the foreach in the following code:

var getWorkout = "SELECT * FROM Test WHERE date = @0 ORDER BY ID";
db.Execute(getWorkout, inputDate);

.

var i = 1;
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<script>

google.charts.load('current', {
    'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);


function drawVisualization() {

var data = google.visualization.arrayToDataTable([
['Day', 'Kilogram', 'Average', 'Peak'],

@foreach (var c in db.Query(getWorkout, inputDate))
{
    <text>['@i', @c.kg, @c.rep, @c.sett],</text>
    i++;
}

]);

var options = {
    title: 'Volume statistics',
    vAxes: {

        0: { logScale: false, viewWindow: {min: 0}},
        1: { logScale: false, maxValue: 2 }
    },
    hAxis: { title: 'Day' },
    seriesType: 'bars',
    curveType: 'function',
    series: {
        0: { targetAxisIndex: 0, color: '#20f400'},
        1: { targetAxisIndex: 1 },
        1: { targetAxisIndex: 1, type: "line"},
        2: { targetAxisIndex: 1, type: "line"}
    }
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 100%; height: 500px;"></div>

This is the query for the foreach in the following code:

var querythis = "SELECT SUM(kg * rep * sett) as weight, SUM(kg / max * rep * sett) as avg, SUM(rep * sett) as reps, " +
                " t.date, pk.peak FROM Test t INNER JOIN (SELECT MAX(kg / max) as peak, date FROM Test WHERE date BETWEEN @0 AND " +
                " @1 AND exercise < 4 group by date) as pk on t.date = pk.date WHERE t.date BETWEEN @0 AND @1 AND exercise < 4 GROUP " +
                "BY t.date, pk.peak";
        db.Execute(querythis, inputDate, endDate);

.

<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<script>
google.charts.load('current', {
    'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);

function drawVisualization() {

var data = google.visualization.arrayToDataTable([
['Day', 'Kilogram', 'Average', 'Peak'],


@foreach (var c in db.Query(querythis, inputDate, endDate))
{
    <text>['@c.date', @c.weight, @c.avg, @c.peak],</text>
}

]);

var options = {
    title: 'Volume statistics',
    vAxes: {
        0: { logScale: false, viewWindow: {min: 0}},
        1: { logScale: false, maxValue: 2 }
    },
    hAxis: { title: 'Day' },
    seriesType: 'bars',
    curveType: 'function',
    series: {
        0: { targetAxisIndex: 0, color: '#20f400'},
        1: { targetAxisIndex: 1 },
        1: { targetAxisIndex: 1, type: "line"},
        2: { targetAxisIndex: 1, type: "line"}
    }
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 100%; height: 500px;"></div>

I am trying to start/stop service form asp.net(webform). But when i start my code, i get exception "Either a required impersonation level was not provided, or the provided impersonation level is invalid". But when i trying to start this one service from Management console it start "OK" without any error. This service is run from "Adm" local user. OS is Windows 10. Thnx.

Impersonate context = new Impersonate(".", "Adm", "5555");


            if (context.impersonateValidUser())
            {


                ServiceController service = new ServiceController("Test");
                service.Start();
}

I have got a response back from an API which contains a list of hotels, which i want to store in an array and then display this list in a table, something like this.

        //Get a response
            IRestResponse<RootObject> searchResponse = client.Execute<RootObject>(searchRequest);

            var hotelList = searchResponse.Data.HotelListResponse.HotelList.HotelSummary.ToArray();

            foreach (var hotelSummary in hotelList.ToArray())
            {
                TextBoxResults.Text = hotelSummary.hotelId.ToString();
                TextBoxResults.Text = hotelSummary.shortDescription.ToString();
                TextBoxResults.Text = hotelSummary.address1.ToString();
                TextBoxResults.Text = hotelSummary.address2.ToString();
                TextBoxResults.Text = hotelSummary.city.ToString();
            }

At the moment, what this is doing is only returning one of the ten results from the list of results and not all 10.

What I'm trying to do is put the list into an array and then display the results in a table in my ASP.net page, the list will not contain more than ten results.

I downloaded the ASP.NET MVC with AngularJS and Entity Framework, module zero sample. I added an entity called DivePlan, with only one string property name for now.

enter image description here

namespace PlanMyDive.DivePlan
{
    public class DivePlan : Entity
    {
        public virtual string Name { get; set; }


        public DivePlan() { }
        public DivePlan(string name)
        {
            this.Name = name;
        }

    }
}

Then I created a service in the application layer:

enter image description here

namespace PlanMyDive.DivePlan.Dto
{
    [AutoMapTo(typeof(DivePlan))]
    public class CreateDivePlanInput
    {
        [Required]
        public string Name { get; set; }

    }
}

namespace PlanMyDive.DivePlan
{
    public class DivePlanAppService : IDivePlanAppService
    {
        private readonly IRepository<DivePlan> _divePlanRepository;

        public DivePlanAppService(IRepository<DivePlan> personRepository)
        {
            _divePlanRepository = personRepository;
        }

        public void CreateDivePlan(CreateDivePlanInput input)
        {
            var diveplan = input.MapTo<DivePlan>();
            _divePlanRepository.Insert(diveplan);
        }
    }
}

namespace PlanMyDive.DivePlan
{
    public interface IDivePlanAppService : IApplicationService
    {
        void CreateDivePlan(CreateDivePlanInput input);
    }
}

Finally, I added a page Plans in the Angular routes and implemented as follows:

enter image description here

(function () {
    angular.module('app').controller('app.views.plans.plan', [
        '$scope', '$modal', 'abp.services.app.divePlan',
        function ($scope, $modal, divePlanService) {
            var vm = this;

            vm.divePlan = {
                name: 'MyDivePlan'
            };


            vm.createNewDivePlan = function () {
                abp.ui.setBusy();
                divePlanService.createDivePlan(vm.divePlan);
                abp.ui.clearBusy();
            };
        }
    ]);
})();

@using PlanMyDive.DivePlan
<div ng-controller="app.views.plans.plan as vm">
    <h1>Welcome to your DivePlan</h1>
    <div class="row">
        <div class="col-md-12">
            <form name="planCreateForm" role="form" novalidate class="form-validation">
                <button type="button" class="btn btn-default" ng-click="vm.createNewDivePlan()">Create Plan</button>
            </form>
        </div>
    </div>
    <div class="row">
        <table class="table">
            <thead>
                <tr>
                    <th>DivePlan Name</th>
                    <th>Autre</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="plan in vm.plans">
                    <td>{{plan.name}}</td>
                    <td>{{plan.name}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

I have a breakpoint in my JS code at the line divePlanService.createDivePlan(vm.divePlan); and a breakpoint in my DivePlanAppService when the function public void CreateDivePlan(CreateDivePlanInput input) is called. The issue I get is that the JS code executes but the DivePlanAppService function CreateDivePlan never executes, or at leave it never breaks at my breakpoint. The user interface shows the following: enter image description here

I tried to simplify the code as much as I could. That's why the Service method doesn't do much so far. I noticed the constructor of DivePlanAppService is never called whereas the constructor of UserAppService is called whenever I navigate to the /#/users page.

What did I miss? Am I not providing the CreateDivePlanInput in the proper format? I tried to copy how TenantAppService works. Thanks in advance.

I'm stuck doing a listing page on a new site.

I have 2 tables in my database, Location and Location_Images, with a common field location_id in each.

I'm wanting to create a list of locations where each location's name is displayed alongside its related images.

Here's my code:

var db = Database.Open("StarterSite");
var selectCommand = "SELECT * FROM Location";
var searchTerm = "";
var selectedPlace = db.Query(selectCommand, searchTerm);

var selectImagesCommand = "SELECT loc_image_url FROM Location_Images JOIN Location ON Location_Images.location_id=Location.location_id";
var selectImagesTerm = "";
var selectedPlacePics = db.Query(selectImagesCommand, selectImagesTerm);


@foreach(var row in selectedPlace)
{
    @row.location_name;

    foreach(var pic in selectedPlacePics)
    {
        <img src="img/locations/@pic.loc_image_url" alt=".">;
    };

 }

At this stage ALL images are showing for EVERY location.

Any help would be greatly appreciated.

  • IIS 7, Windows Server 2008 SP2

I am getting the following stack overflow exception which is killing the application pool and making for some unhappy users.

enter image description here

We have 4 ASP.NET applications all running in the same application pool. I don't know which ASP app is killing the process. So having read:

I have made sure that the following settings have been made for the application pool in terms of reporting things in the event log:

enter image description here

However the information in the event log is rather sparse.

  1. Is there anything else I can do (registry settings etc.) that would give me more information about what caused the termination? Even an application name would help.

I have done custom authentication system by following this example and it works. my code is like below. I am wondering how I should control if the user is authenticated in other Actions, lets say if users goes to /Profile/Index?

I have tried HttpContext.User and User.Identity but didnt work.

[HttpPost]
public ActionResult Login(string username, string password)
{
    if (new UserManager().IsValid(username, password))
    {
        var ident = new ClaimsIdentity(
          new[] {
      new Claim(ClaimTypes.NameIdentifier, username),
      new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
      new Claim(ClaimTypes.Name,username)
          },
          DefaultAuthenticationTypes.ApplicationCookie);

        HttpContext.GetOwinContext().Authentication.SignIn(
           new AuthenticationProperties { IsPersistent = false }, ident);
        return RedirectToAction("MyAction"); // auth succeed 
    }
    ModelState.AddModelError("", "invalid username or password");
    return View();
}

this is my Global.asax

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

getting and error when trying to load a partial view that should display a list on the create view of the mvc app. the list is based on a value will come from a list of values drop control.

Well on create view there is no selection so the list is empty and will need to refreshed after the user selects a value while in the mvc create view.

So Followed this answer: The Answer is the one with the Green Check Marking. and got errors:

Updating PartialView mvc 4 But I have some questions about what is being said.

The Guys says: "There are some ways to do it. For example you may use jQuery:"

and he shows the Java Query..

But he also shows another method and says: "If you use logic in your action UpdatePoints() to update points"

[HttpPost]
public ActionResult UpdatePoints()
{    
   ViewBag.points =  _Repository.Points;
   return PartialView("UpdatePoints");
 }

I get the following error

The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateList(Int32)' in 'System.Controllers.RController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I have no clue what this error means

So in create view:

            <div class="form-horizontal" style="display:none" id="PVList">

                @{ Html.RenderAction("UpdateList");}

            </div>
        </div>

In controller under the create action as its own function

    [HttpGet]
    public ActionResult UpdateList(int ID)
    {

        if (ID != 0)
        {
            ViewBag.List = Get_List(ID);
            return PartialView("PV_List");

        }
        else
        {
            ViewBag.List = "";
            return PartialView("");
        }


    }

And the function that makes the list for the view bag function:

private List<SQL_VIEW_LIST> Get_List(int ID)
        {

            return db.SQL_VIEW_LIST.Where(i => i.ID == ID).ToList();
        }

The Java Scripts for the for the list of values drop down list of values: That also controls turning on the visibility of the list when it has data

    //Fire The List to make visible after list values select 
    $(document).ready(function () {
        $('#RES_VEH_ID').change(function ()
        {

            $("#PV_List").show(); // Shows Edit Message
            $.post('@Url.Action("PostActionTo_Partial","Create")').always(function()
                   { ('.target').load('/Create'); })

        });
    })

Also does anyone know what this string mean: ? "PostActionTo_Partial"

Thanks so very much for your time and help

I am using asp.net core, razor engine, and entity framework. I am getting this error when I try to run my code in VS code using dotnet watch run. Here is the full error.

Project c-login (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
A JSON parsing exception occurred in [/Users/aaronmk2/Desktop/CodingDojo/c#/asp.net/entity/c-
login/bin/Debug/netcoreapp1.0/c-login.deps.json]: * Line 1, Column 2 Syntax error: Malformed
token
Error initializing the dependency resolver: An error occurred while parsing /Users/aaronmk2/D
esktop/CodingDojo/c#/asp.net/entity/c-login/bin/Debug/netcoreapp1.0/c-login.deps.json
[DotNetWatcher] fail: dotnet exit code: 139
[DotNetWatcher] info: Waiting for a file to change before restarting dotnet...

Has anyone seen this error before? What is the workaround?

I'm trying to connect to Web service hosted over Https. I have this method:

ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) 
{                    
     if (sslPolicyErrors != SslPolicyErrors.None)
     {
          return false;
     }                   
     return true;
}; 

The service is being called fine since the SSLPolicyErrors value is 'None' and hence the method returns true. But when I comment out this code, the call is throwing the error:

Message:System.ServiceModel.Security.SecurityNegotiationException: Could not establish secure channel for SSL/TLS with authority '******************'. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

I'm not sure what code I can write to detect this. I really need to catch all possible errors with the security certificate. Also, when I open the URL directly in IE and try to see details about the certificate, I cannot see any problems with the certificate and it looks valid.

Thanks for help.