I have a WCF streaming binary files. Below is a shortened version of the contract.
[MessageContract()]
public class DocumentTransfer
{
[MessageHeader(MustUnderstand = true)]
public string Title { get; set; }
[MessageHeader(MustUnderstand = true)]
public string FileName { get; set; }
[MessageBodyMember(Order = 1)]
public System.IO.Stream Data;
}
Everything works fine but there are scenarios when only some other values associated with the file need to be updated but not the file itself. In that case the client sets Data = null. The Data property then cannot be interpreted/serialized and throws this exception:
System.ServiceModel.Dispatcher.StreamFormatter.Serialize(XmlDictionaryWriter writer, Object[] parameters, Object returnValue)
System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)
System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Stream stream)
System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan timeout)
System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
...UploadDocument(DocumentTransfer request)
...UploadDocument(DocumentTransfer request) in ...
Any ideas guys?
You are getting the error in SerializeBodyContents when the body is null.
You can either create a different operation for when you do not have a file, or put a byte in the stream to avoid the exception. The first of these options is preferable, the last if you cannot change the contract.
Another option would be to return Stream.Null.
Related
I want to make new ride, for it I have this code:
using (var db = new CarManagerDbEntities())
{
Guid? carId = GetCarId(carLicenceId);
if (carId == null)
{
return null;
}
Guid rideId = Guid.NewGuid();
Ride newRide = new Ride() { DriverID = driverId, CarID = carId.Value, StartDrive= startTime, Id = rideId};
db.Ride.Add(newRide);
await db.SaveChangesAsync();
return carId;
}
but in the line:
await db.SaveChangesAsync();
I get this exception:
System.ServiceModel.FaultException`1 was unhandled
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at CarManager.TestingCLI.CarManagerServiceReference.ICarManagerApi.StartNewRide(Guid driverId, DateTime startTime, String carLicenceId)
at CarManager.TestingCLI.CarManagerServiceReference.CarManagerApiClient.StartNewRide(Guid driverId, DateTime startTime, String carLicenceId) in c:\Projetcs\CarManager.TestingCLI\Service References\CarManagerServiceReference\Reference.cs:line 990
at CarManager.TestingCLI.Program.Main(String[] args) in c:\Projetcs\CarManager.TestingCLI\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
The inner exception is null.
What I'm not doing right?
Occasionally (about once a month) an ASP.NET MVC 3 web application fails with this exception.
System.NullReferenceException: Object reference not set to an instance of an object.
Server stack trace:
at System.Collections.Specialized.NameObjectCollectionBase.BaseGetAllKeys()
at System.Collections.Specialized.NameValueCollection.get_AllKeys()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.<>c__DisplayClass4.<.ctor>b__0()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Lazy`1.get_Value()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value)
at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue)
at System.Web.Mvc.ViewContext.ScopeCache..ctor(IDictionary`2 scope)
at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes)
at ASP._Page_Views_mywebpage_Create_cshtml.Execute() in c:\App\Views\Mywebpage\Create.cshtml:line 11
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This exception occurs on a line with
#using (Html.BeginForm())
From the moment this exception occurs once, the application is unusable. Every view will start throwing this error. I've looked around in the source code but seem unable to find anything. There are people who experience the same behaviour but with a different error and or by different code.
When digging deeper in the source of WebConfigScopeDictionary you can see that the AppSettings are being read:
public WebConfigScopeDictionary() : this(WebConfigurationManager.AppSettings)
{
}
public WebConfigScopeDictionary(NameValueCollection appSettings)
{
this._items = new Lazy<Dictionary<object, object>>(() => appSettings.AllKeys.ToDictionary((string key) => key, (string key) => appSettings[key], ScopeStorageComparer.Instance));
}
The appsettings come from the ConfigurationManager:
public static NameValueCollection AppSettings
{
get
{
object section = ConfigurationManager.GetSection("appSettings");
if (section == null || !(section is NameValueCollection))
{
throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection)section;
}
}
If there would be a problem with the web.config this code should have thrown an exception. But it doesn't. Eventually count is called on the collection that is returned by the AppSettings property. Since it is probably null at this point it throws.
protected string[] BaseGetAllKeys()
{
int count = this._entriesArray.Count;
string[] array = new string[count];
for (int i = 0; i < count; i++)
{
array[i] = this.BaseGetKey(i);
}
return array;
}
If anyone has any ideas, feel free to share.
After enquiring with the ops team it would appear that the application pool was being recycled after the timed interval had expired. This happened during office hours while the application is under a significant load. We've now changed it to recycle at a specific time, which is still a workaround but should prevent the problem from occurring too frequently.
I'm new to Nancy and I'm trying to bind a decimal property using the Nancy.ModelBinding namespace like this:
var model = this.Bind<AddPaymentModel>();
My app is using a non-US culture (pt-BR) where decimals are represented differently (4.50 would be 4,50) and the code above throws an error, even thought the CurrentCulture is correctly set to pt-BR. I'm posting JSON and I think it might be related to the JSON deserializer...
Part of my stacktrace:
Nancy.RequestExecutionException: Oh noes! ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Exception: 450,00 is not a valid value for Decimal. ---> System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.DecimalConverter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
at Nancy.Json.JavaScriptSerializer.ConvertToType(Type type, Object obj)
at Nancy.Json.JavaScriptSerializer.ConvertToObject(IDictionary`2 dict, Type type)
at Nancy.Json.JavaScriptSerializer.ConvertToType(Type type, Object obj)
at Nancy.Json.JavaScriptSerializer.ConvertToType[T](Object obj)
at Nancy.Json.JavaScriptSerializer.Deserialize[T](String input)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Nancy.ModelBinding.DefaultBodyDeserializers.JsonBodyDeserializer.Deserialize(String contentType, Stream bodyStream, BindingContext context)
at Nancy.ModelBinding.DefaultBinder.DeserializeRequestBody(BindingContext context)
at Nancy.ModelBinding.DefaultBinder.Bind(NancyContext context, Type modelType, String[] blackList)
What am I missing?
you could try switcing to the Newtonsoft.JsonNet serializer for nancy instead.
http://nuget.org/packages/Nancy.Serialization.JsonNet
Here is a "catch all" example implementaion
using System;
using System.Collections.Generic;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Serialization.JsonNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Application
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override NancyInternalConfiguration InternalConfiguration
{
get
{
return NancyInternalConfiguration.WithOverrides(
c => c.Serializers.Insert(0, typeof(ModifiedJsonNetJsonSerializer)));
}
}
public class ModifiedJsonNetJsonSerializer : JsonNetSerializer
{
public ModifiedJsonNetJsonSerializer()
: base(new List<JsonConverter> { new FloatConverter() })
{ }
public class FloatConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var floatValue = (float)value;
writer.WriteValue(string.Format("{0:0.00}", floatValue));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jobject = JToken.Load(reader);
var str = jobject.Value<string>();
float number;
try
{
number = float.Parse(str);
}
catch (FormatException)
{
str = str.IndexOf(".", StringComparison.Ordinal) > -1 ? str.Replace('.', ',') : str.Replace(',', '.');
number = float.Parse(str);
}
return number;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(float) || objectType == typeof(Single);
}
}
}
}
}
I have an ViewModel like
namespace ViewModel
{
[Serializable]
public class TestViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Also, I have one action method:
public ActionResult Index()
{
TestViewModel model = new TestViewModel
{
Id = -1,
Name = "Some name",
Description = "Some description"
};
return View(model);
}
And my View something like this:
#using Microsoft.Web.Mvc
#model ViewModel.TestViewModel
#using (Html.BeginForm())
{
Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);
//....Editor fields
}
In line "Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);" debugger is stopped and returns exception "object reference not set to an instance of an object" (NullReferenceException). Although, the Model is not null and contains initial values.
I use ASP.Net MVC 3(Razor) and stack trace is below:
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData, MvcSerializer
serializer)
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData)
in Microsoft.Web.Mvc.SerializationExtensions.Serialize(HtmlHelper htmlHelper, String
name, Object data, SerializationMode mode)
in ASP._Page_Views_Wizard_Index_cshtml.Execute()
in c:\Projects\TestProject\Views\Wizard\Index.cshtml:line 15
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
in System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
in System.Web.WebPages.StartPage.RunPage()
in System.Web.WebPages.StartPage.ExecutePageHierarchy()
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,
TextWriter writer, WebPageRenderingBase startPage)
in System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer,
Object instance)
in System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter
writer)
in System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult)
in System.Web.Mvc.ControllerActionInvoker.
<>c__DisplayClass1c.InvokeActionResultWithFilters>b__19()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter,
ResultExecutingContext preContext, Func`1 continuation)
What's wrong in my code?
You need to use
#Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned)
if you want hidden field with model on form.
The problem was that I had assembly reference to Mvc2Futures ("Microsoft.Web.Mvc.dll"). But when I changed the reference to Mvc3Futures ("Microsoft.Web.Mvc.dll") all work fine.
Thanks a lot.
i'm creating a database with entity framework, in an mvc asp.net application, using code first.
I'm new to the argument so be patient... I've created the database for the first time and all seems to be right; but couse of i didn't create a DropCreateDatabaseIfModelChanges method to change the tables i decided to manually delete the database.
The problem is that the database is not recreating!
I've implemented the initializer and it is in a different class from the context...
public class WidgetDbInitializer : DropCreateDatabaseIfModelChanges<WidgetDbContext>
{
}
Setted it up in Global.asax.cs and forced to init that
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<Portale.Models.WidgetDbContext>(new Portale.Models.WidgetDbInitializer());
var _initer = new WidgetDbInitializer();
using (var db = new WidgetDbContext())
{
_initer.Seedit(db);
db.Database.Initialize(true);
}
}
I've just the default connection string couse now i don't care about it...
Please help me i've read tons of articles over the web and i can't get a solution...
The error i get:
System.ArgumentNullException non è stata gestita dal codice utente
Message=Il valore non può essere null.
Nome parametro: key
Source=mscorlib
ParamName=key
StackTrace:
in System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
in System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEntitySet entitySet, EdmEntityType entityType)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Configure()
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
in System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
in System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
in System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
in System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
in System.Data.Entity.Internal.InternalContext.Initialize()
in System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
in System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
in System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
in System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
in System.Linq.Queryable.Join[TOuter,TInner,TKey,TResult](IQueryable`1 outer, IEnumerable`1 inner, Expression`1 outerKeySelector, Expression`1 innerKeySelector, Expression`1 resultSelector)
in Portale.Controllers.WidgetContainerController.Index() in C:\Users\doompro\Documents\Visual Studio 2010\Projects\Portale\Portale\Controllers\WidgetContainerController.cs:riga 56
in lambda_method(Closure , ControllerBase , Object[] )
in System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
in System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
override Seed function in your WidgetDbInitializer class and try to add some data to your database .
protected override void Seed(WidgetDbContext context)
{
context.yourodel.add(new class() )
}
first check your overriden seed invoke correctly , then if your database dose not generated you will get an exception .
Solved the problem:
public class Widget
{
//This properties rapresent the primary key for entity framework
[Key]
public int WidgetID { get; set; }
//Foreing key to the column where this widget is stored
public virtual int ColumnID { get; set; }
//The title of the widget
public string Title { get; set; }
//Controller of the Widget, this property may be used on the RenderAction call
public string Controller { get; set; }
//ActionMethod of the Widget, this property may be used on the RenderAction call
public string ActionMethod { get; set; }
//The Type of the Model, used on deserialization
public Type ModelType { get; set; }
//The context of the widget
public string SerializedModel { get; set; }
}
The database just didn't accept the type "Type", all working fine as soon as I deleted that field... I just didn't look at it because it was working with the "Object" type, didn't expect it doesnt with Type..