I've the following code:
var bind = new PollingDuplexHttpBinding();
bind.MaxReceivedMessageSize = 2147483647;
EndpointAddress myEndpoint = new EndpointAddress(address);
try
{
var instContext = new InstanceContext(this);
var fact = new DuplexChannelFactory<IVisuWcfService>(instContext, bind);
var channel = fact.CreateChannel(myEndpoint);
this.visuServices.Add(visuService.Name, channel);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message+ex.StackTrace);
}
the try/catch is there to get the error in the designer.
So now the following:
I've a Instance of the class with this code in my datacontext. That means at designtime there will be created a instance of this object.
But then i get the following error: Unable to cast object of type 'proxy_xx' to type IVisuWcfService, where xx is a increasing number.
But when i've this code in runtime, everything is working well.
The error happens in the line: fact.CreateChannel(myEndpoint);
Related
I am collecting external data and then doing an ServiceBus.ResolveService<ISearchService>().UpdateIndex. This is working great but I wanted to SetBoost on the new Document. I have created an flag setboost with is using doc.SetBoost(1.5f); but I am getting a runtime error. Is this the correct way to set the boost score?
Severity Code Description Project File Line Suppression State Suppression State
Error CS1061 'Document' does not contain a definition for 'SetBoost' and no accessible extension method 'SetBoost' accepting a first argument of type 'Document' could be found (are you missing a using directive or an assembly reference?)\
public static void ExternalIndexerAdd(ExternalIndexModel externalIndexer,boolean setBoost)
{
try
{
var fields = new List<IField>();
var identityFld = new Field();
identityFld.Name = "IdentityField";
identityFld.Value = externalIndexer.IdentityField;
fields.Add(identityFld);
var titleField = new Field();
titleField.Name = "Title";
titleField.Value = externalIndexer.TitleField;
fields.Add(titleField);
var contentField = new Field();
contentField.Name = "Content";
contentField.Value = externalIndexer.ContentField;
fields.Add(contentField);
var linkField = new Field();
linkField.Name = "Link";
linkField.Value = externalIndexer.LinkField;
fields.Add(linkField);
var lastModifiedField = new Field();
lastModifiedField.Name = "LastModified";
lastModifiedField.Value = externalIndexer.LastModifiedField;
fields.Add(lastModifiedField);
var doc = new Document(fields, String.Format("{0}", "IdentityField"));
if (SetBoost == true){
doc.SetBoost(1.5f);
}
ServiceBus.ResolveService<ISearchService>().UpdateIndex("nccn-search-index", new List<IDocument>() { doc });
}
catch (Exception ex)
{
}
}
In order to accomplish this I believe you will need to customize the search scoring of Sitefinity's lucene search index. Here is the search API available: https://www.progress.com/documentation/sitefinity-cms/for-developers-customize-the-lucene-search-scoring
In the subscription (name: test-subscription) in the resource group (name: test-resource-group), I created Front Door Standard/Premium (Preview) (name: test-front-door-profile) with endpoint test-front-door-profile-endpoint.z01.azurefd.net and added new endpoint (endpoint name: test-endpoint.z01.azurefd.net).
For example: I created a request: https://test-endpoint.z01.azurefd.net/test/pictures/abcdefghi.jpeg. How can I purge test-endpoint.z01.azurefd.net/test/pictures/* using code?
I tried with this code, and different variants of contentPaths
using Microsoft.Azure.Management.FrontDoor;
using Microsoft.Azure.Management.FrontDoor.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
...
public async Task PurgeContentAsync()
{
var authContext = new AuthenticationContext(Authority);
var credential = new ClientCredential(ClientId, ClientSecret);
var authResult = await authContext.AcquireTokenAsync(_resource, credential);
var frontDoor = new FrontDoorManagementClient(new TokenCredentials(authResult.AccessToken)) { SubscriptionId = _subscriptionId };
var contentPaths = new List<string> { "/test-endpoint.z01.azurefd.net/test/pictures/*" };
var contentFilePaths = new PurgeParameters(contentPaths);
await frontDoor.Endpoints.BeginPurgeContentAsync("test-resource-group", "test-front-door-profile", contentFilePaths);
}
but I always get exception:
The exception Microsoft.Azure.Management.FrontDoor.Models.ErrorResponseException was unhandled on the service and could not be serialized for transferring to the client.
Detailed Remote Exception Information: Microsoft.Azure.Management.FrontDoor.Models.ErrorResponseException: Operation returned an invalid status code 'NotFound'
I tried with Microsoft.Azure.Management.Cdn library but I am getting back the same exception.
I have been pulling my hair out with this one.
I have a very simple test class that throws this error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
It doesn't seem to break much, as the put request is successful and the serialize is also successful.
EDIT
I have chased the serialize exception out if it was ever really there. I am starting to think it is a problem with typed HttpClient. It throws the exception that comes out on the console and in the response on Postman. However, it doesn't allow me to catch the exception in the code and the PUT call works. So the exception is happening after the PUT request and is handled before it returns control to my app.
I am going to try to use a standard HttpClientFactor instead of a typed client and see if that works. I know that the JSON exception is a red herring, but it is ugly and breaking the response.
Any suggestions would be welcome.
public virtual async Task<CouchResponse> Create(string id, string db, TObj info)
{
CouchResponse ret = new() { Reason = "Unknown and unExpected error", Ok = false };
HttpResponseMessage rc = null;
if (id is null)
{
return new CouchResponse() { Id = "missing", Ok = false, Rev = "missing" };
}
string url = $"{db}/1";
try
{
// login to Couchdb servwer
await CouchLogin();
try
{
//var jsonInfo = JsonUtils.Serialize<TestJson>(jTest);
var jsonInfo = JsonSerializer.Serialize<TObj>(info, options);
HttpContent content = new StringContent(jsonInfo, Encoding.UTF8,
"application/json");
rc = await client.PutAsync(url, content);
}
catch (Exception eNewton)
{
Console.WriteLine($"Json Exception: {eNewton.Message}");
}
if (rc is not null)
{
var str = await rc.Content.ReadAsStringAsync();
var ret = JsonSerializer.Deserialize<CouchResponse>(str,options);
rc.EnsureSuccessStatusCode();
}
return ret;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//return ret;
}
return ret;
}
Suggestions?
What a crazy bug. The diagnostic was very missing leading. Everything I was doing in the create method was correct.
What is missed was an await when I called the create method. This made it appear that the sendAsync was having the issue when it was really the controller trying to format the task return as a response. This caused the stack trace in the response message. Thanks for all the help.
Change this
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
To this
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
MaxDepth = null,
};
I would like to catch exceptions that might bubble up from a class library method to the action from which it was called and would like to display the error in the view without actually redirecting to a new view. I've overriden the OnException method in my controller and have created a partial view to display the error but when an error occurs the partial view is not being rendered where I want it to show but rather where I have a table and it will be replaced with the error message which is not what I wan, not to mention the table is in a different place in the view than where the error should display. I haven't done much exception handling with MVC so I don't know if my approach is completely wrong.
My code for the exception
protected override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var exp = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
//Assigns error message to property for message in view model
ReceivngFormViewModel viewModel = new ReceivngFormViewModel
{
ErrorMessage = exp.Exception.Message
};
filterContext.Result = new PartialViewResult()
{
//_Error is the partial view
ViewName = "_Error",
ViewData = new ViewDataDictionary(viewModel)
};
}
this code help you use ModelState.AddModelError
**Controller**
Model obj=new Model();
try{
}
cathch(exception ex){
ModelState.AddModelError("objectname", ex.tostring());
}
return obj;
**Viwe**
#Html.ValidationMessageFor(model => model.objectname)
I would like my Silverlight client to be able to display exceptions that have happened at the server during a WCF call.
Given my current code to create a WCF Channel (on the client):
// create the binding elements
BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement();
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement() { MaxBufferSize = int.MaxValue, MaxReceivedMessageSize = int.MaxValue };
// add the binding elements into a Custom Binding
CustomBinding customBinding = new CustomBinding(binaryMessageEncoding, httpTransport);
// create the Endpoint URL
EndpointAddress endpointAddress = new EndpointAddress(serviceUrl);
// create an interface for the WCF service
ChannelFactory<TWcfApiEndPoint> channelFactory=new ChannelFactory<TWcfApiEndPoint>(customBinding, endpointAddress);
channelFactory.Faulted += new EventHandler(channelFactory_Faulted);
TWcfApiEndPoint client = channelFactory.CreateChannel();
return client;
When an exception occurs, I just get a "NotFound" exception, which is obviously of no use. How can I get the exception information?
I use this code to use the client object returned above:
try
{
// customFieldsBroker is the client returned above
customFieldsBroker.BeginCreateCustomField(DataTypeID, newCustomField, (result) =>
{
var response = ((ICustomFieldsBroker)result.AsyncState).EndCreateCustomField(result);
}, customFieldsBroker);
}
catch (Exception ex)
{
// would like to handle exception here
}
Wrapping the Begin/End calls in a try { } catch { } block doesn't seem to even jump into the catch { } block.
If it matters, I'm using Silverlight 3 at the client.
Due to security limitations in the browser sandbox, silverlight can't see the body of server errors (status code 500). To get this working you need to make a change to the server side, to change the way it returns faults to the browser. There's an MSDN article that describes it in detail.
You need to do two things:
declare the Fault exception as part of the contract
throw the exception as a fault exception
[OperationContract]
[FaultContract(typeof(ArithmeticFault))]
public int Calculate(Operation op, int a, int b)
{
// ...
}
throw new FaultException();