Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes and improvements #44

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Breeze.Sharp/AutoGeneratedKeyType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Breeze.Sharp {
/// <summary>
/// AutoGeneratedKeyType is an enum containing all of the valid states for an automatically generated key.
/// </summary>
public enum AutoGeneratedKeyType {
None = 0,
Identity = 1,
KeyGenerator = 2
}
}
3 changes: 3 additions & 0 deletions Breeze.Sharp/Breeze.Sharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@
<PackageReference Include="Microsoft.Data.Services.Client">
<Version>5.8.4</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>12.0.3</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
Expand Down
48 changes: 26 additions & 22 deletions Breeze.Sharp/CsdlMetadataProcessor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Breeze.Sharp.Core;
using Breeze.Sharp.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
Expand All @@ -11,11 +11,11 @@ namespace Breeze.Sharp {
internal class CsdlMetadataProcessor {

public CsdlMetadataProcessor() {

}

public MetadataStore MetadataStore { get; private set; }

public void ProcessMetadata(MetadataStore metadataStore, JObject json) {
MetadataStore = metadataStore;
_schema = json["schema"];
Expand All @@ -38,7 +38,7 @@ public void ProcessMetadata(MetadataStore metadataStore, JObject json) {
}
et.UpdateNavigationProperties();
});


var complexTypes = ToEnumerable(_schema["complexType"]).Cast<JObject>()
.Select(ParseCsdlComplexType).Where(ct => ct != null).ToList();
Expand All @@ -47,23 +47,23 @@ public void ProcessMetadata(MetadataStore metadataStore, JObject json) {
if (entityContainer != null) {
var entitySets = ToEnumerable(entityContainer["entitySet"]).Cast<JObject>().ToList();
entitySets.ForEach(es => {
var clientEtName = GetClientTypeNameFromClrTypeName((String) es["entityType"]);
var clientEtName = GetClientTypeNameFromClrTypeName((String)es["entityType"]);
var entityType = MetadataStore.GetEntityType(clientEtName, true);
if (entityType != null) {
var resourceName = (String) es["name"];
var resourceName = (String)es["name"];
MetadataStore.SetResourceName(resourceName, entityType, true);
}
});
}

}



private NamingConvention NamingConvention {
get { return MetadataStore.NamingConvention; }
}

private EntityType ParseCsdlEntityType(JObject csdlEntityType) {
var abstractVal = (String)csdlEntityType["abstract"];
var baseTypeVal = (String)csdlEntityType["baseType"];
Expand All @@ -75,9 +75,9 @@ private EntityType ParseCsdlEntityType(JObject csdlEntityType) {
MetadataStore.OnMetadataMismatch(etName, null, MetadataMismatchTypes.MissingCLREntityType);
return null;
}

entityType.IsAbstract = isAbstract;

var baseKeyNamesOnServer = new List<string>();
if (baseTypeVal != null) {
var baseEtName = GetClientTypeNameFromClrTypeName(baseTypeVal);
Expand All @@ -96,7 +96,7 @@ private EntityType ParseCsdlEntityType(JObject csdlEntityType) {
var keyNamesOnServer = keyVal == null
? new List<String>()
: ToEnumerable(keyVal["propertyRef"]).Select(x => (String)x["name"]).ToList();

keyNamesOnServer.AddRange(baseKeyNamesOnServer);

ToEnumerable(csdlEntityType["property"]).ForEach(csdlDataProp => {
Expand Down Expand Up @@ -135,6 +135,10 @@ private DataProperty ParseCsdlDataProperty(StructuralType parentType, JObject cs
private DataProperty ParseCsdlSimpleProperty(StructuralType parentType, JObject csdlProperty, List<String> keyNamesOnServer) {

var typeVal = (String)csdlProperty["type"];

if (typeVal == "Edm.Time")
typeVal = "Edm.TimeSpan";

var nameVal = (String)csdlProperty["name"];
var nullableVal = (String)csdlProperty["nullable"];
var maxLengthVal = (String)csdlProperty["maxLength"];
Expand All @@ -146,7 +150,7 @@ private DataProperty ParseCsdlSimpleProperty(StructuralType parentType, JObject
}

var dpName = NamingConvention.ServerPropertyNameToClient(nameVal, parentType);
var dp = parentType.GetDataProperty( dpName);
var dp = parentType.GetDataProperty(dpName);
if (dp == null) {
MetadataStore.OnMetadataMismatch(parentType.Name, dpName, MetadataMismatchTypes.MissingCLRDataProperty);
return null;
Expand Down Expand Up @@ -178,7 +182,7 @@ private DataProperty ParseCsdlSimpleProperty(StructuralType parentType, JObject
var maxLength = (maxLengthVal == null || maxLengthVal == "Max") ? (Int64?)null : Int64.Parse(maxLengthVal);
var concurrencyMode = concurrencyModeVal == "fixed" ? ConcurrencyMode.Fixed : ConcurrencyMode.None;



CheckProperty(dp, dp.DataType, dataType, "DataType");
CheckProperty(dp, dp.IsScalar, true, "IsScalar");
Expand All @@ -187,7 +191,7 @@ private DataProperty ParseCsdlSimpleProperty(StructuralType parentType, JObject
dp.IsNullable = isNullable;
dp.MaxLength = maxLength;
dp.DefaultValue = defaultValue;
// fixedLength: fixedLength,
// fixedLength: fixedLength,
dp.ConcurrencyMode = concurrencyMode;
dp.IsAutoIncrementing = isAutoIncrementing;

Expand All @@ -210,7 +214,7 @@ private DataProperty ParseCsdlComplexProperty(StructuralType parentType, JObject
MetadataStore.OnMetadataMismatch(parentType.Name, name, MetadataMismatchTypes.MissingCLRDataProperty);
return null;
}

if (!dp.IsComplexProperty) {
var detail = "Defined as a ComplexProperty on the server but not on the client";
MetadataStore.OnMetadataMismatch(parentType.Name, name, MetadataMismatchTypes.InconsistentCLRPropertyDefinition, detail);
Expand Down Expand Up @@ -241,7 +245,7 @@ private NavigationProperty ParseCsdlNavigationProperty(EntityType parentType, JO
// throw new Error("Foreign Key Associations must be turned on for this model");
// }
}

var name = NamingConvention.ServerPropertyNameToClient(nameOnServer, parentType);
var np = parentType.GetNavigationProperty(name);
if (np == null) {
Expand All @@ -252,8 +256,8 @@ private NavigationProperty ParseCsdlNavigationProperty(EntityType parentType, JO
CheckProperty(np, np.EntityType.Name, dataEtName, "EntityTypeName");
CheckProperty(np, np.IsScalar, isScalar, "IsScalar");

np.AssociationName = (String) association["name"];
np.AssociationName = (String)association["name"];

var principal = constraintVal["principal"];
var dependent = constraintVal["dependent"];

Expand Down Expand Up @@ -361,7 +365,7 @@ private void AddValidators(DataProperty dp) {
dp._validators.Add(new RequiredValidator());
}
if (dp.DataType == DataType.String && dp.MaxLength.HasValue) {
var vr = new MaxLengthValidator((Int32) dp.MaxLength.Value);
var vr = new MaxLengthValidator((Int32)dp.MaxLength.Value);
dp._validators.Add(vr);
}
}
Expand Down Expand Up @@ -410,9 +414,9 @@ private IEnumerable<T> ToEnumerable<T>(T d) {

private JToken _schema;
private String _namespace;

private Dictionary<String, String> _cSpaceOSpaceMap;


}
}
20 changes: 11 additions & 9 deletions Breeze.Sharp/DataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Breeze.Sharp {
/// </remarks>
public class DataService : IJsonSerializable {


/// <summary>
/// Constructs a new DataService with the option to use an already configured HttpClient. If one is not provided
/// then the DataService will create one internally. In either case it will be available via the HttpClient property.
Expand Down Expand Up @@ -94,12 +94,10 @@ private void InitializeHttpClient(HttpClient httpClient) {
httpClient = DefaultHttpMessageHandler == null ? new HttpClient() : new HttpClient(DefaultHttpMessageHandler);
}
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri(ServiceName);
Copy link
Author

@GioviQ GioviQ Sep 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.



// Add an Accept header for JSON format.
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

}

private IDataServiceAdapter GetAdapter(string adapterName) {
Expand Down Expand Up @@ -134,7 +132,7 @@ public async Task<String> GetAsync(String resourcePath) {

public async Task<String> GetAsync(String resourcePath, CancellationToken cancellationToken) {
try {
var response = await _httpClient.GetAsync(resourcePath, cancellationToken);
var response = await _httpClient.GetAsync($"{ServiceName}{resourcePath}", cancellationToken);

cancellationToken.ThrowIfCancellationRequested();

Expand All @@ -158,10 +156,9 @@ public async Task<String> PostAsync(String resourcePath, String json) {
// new KeyValuePair<string, string>("", "login")
// });

var response = await _httpClient.PostAsync(resourcePath, content);
var response = await _httpClient.PostAsync($"{ServiceName}{resourcePath}", content);
return await ReadResult(response);
}
catch (Exception e) {
} catch (Exception e) {
Debug.WriteLine(e);
throw;
}
Expand All @@ -171,6 +168,11 @@ private static async Task<string> ReadResult(HttpResponseMessage response) {

var result = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) {
try {
var json = JNode.DeserializeFrom(result);
response.ReasonPhrase = json.Get<string>("Message");
} catch (Exception) { }

throw new DataServiceRequestException(response, result);
}
return result;
Expand Down Expand Up @@ -210,7 +212,7 @@ public DataServiceRequestException(HttpResponseMessage httpResponse, String resp

public String ResponseContent { get; private set; }
public HttpResponseMessage HttpResponse { get; private set; }

}

}
10 changes: 6 additions & 4 deletions Breeze.Sharp/DataType.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
Expand Down Expand Up @@ -91,8 +91,8 @@ public virtual Object Parse(Object val) {
DataTypeInfo = DataTypeInfo.IsDate
};

public static DataType Time = new DataType(typeof(TimeSpan)) {
Name = "Time",
public static DataType TimeSpan = new DataType(typeof(TimeSpan)) {
Name = "TimeSpan",
DefaultValue = new TimeSpan(0),
FmtOData = FmtTime,
};
Expand Down Expand Up @@ -229,6 +229,8 @@ protected static String FmtUndefined(Object val) {
return val.ToString();
}


public override string ToString() {
return $"{nameof(DataType)}: {Name}";
}
}
}
21 changes: 21 additions & 0 deletions Breeze.Sharp/DomainException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;

namespace Breeze.Sharp {
public class DomainException : Exception {
public string Description { get; }

public DomainException(string message) : base(message) {

}

public DomainException(string description, string message) : base(message) {
Description = description;

}

public DomainException(string description, string message, Exception innerException) : base(message, innerException) {
Description = description;

}
}
}
20 changes: 15 additions & 5 deletions Breeze.Sharp/EntityAspect.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Breeze.Sharp.Core;
using Breeze.Sharp.Core;
using System;
using System.Collections;
using System.Collections.Generic;
Expand Down Expand Up @@ -624,7 +624,7 @@ private void SetDpValueKey(DataProperty property, object newValue, object oldVal

if (this.IsAttached) {
this.EntityType.InverseForeignKeyProperties.ForEach(invFkProp => {
if (invFkProp.RelatedNavigationProperty.Inverse == null) {
if (invFkProp.RelatedNavigationProperty != null && invFkProp.RelatedNavigationProperty.Inverse == null) {
// this next step may be slow - it iterates over all of the entities in a group;
// hopefully it doesn't happen often.
EntityManager.UpdateFkVal(invFkProp, oldValue, newValue);
Expand Down Expand Up @@ -931,13 +931,14 @@ private bool FixupFksOnUnattached(NavigationProperty np) {
var npEntity = GetValue<IEntity>(np);
// property is already linked up
if (npEntity != null) {
if (npEntity.EntityAspect.IsDetached) {
if (npEntity.EntityAspect.IsDetached && np.ForeignKeyProperties.Any()) {
// need to insure that fk props match
var fkProps = np.ForeignKeyProperties;
npEntity.EntityAspect.EntityType = np.EntityType;
// Set this Entity's fk to match np EntityKey
// Order.CustomerID = aCustomer.CustomerID
npEntity.EntityAspect.EntityKey.Values.ForEach((v, i) => SetDpValue(fkProps[i], v));
//commented because set keys to default values
Copy link
Author

@GioviQ GioviQ Sep 10, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In https://github.com/enkodellc/blazorboilerplate/blob/development/src/Shared/BlazorBoilerplate.Shared/Dto/Db/UserProfile.cs

ApplicationUser has wrong key as empty Guid

Probably you have a better solution. You can use that repo as test.

//npEntity.EntityAspect.EntityKey.Values.ForEach((v, i) => SetDpValue(fkProps[i], v));
}
return false;
}
Expand Down Expand Up @@ -1001,7 +1002,16 @@ internal void UpdateRelated(DataProperty property, object newValue, object oldVa
// ==> (see set navProp above)

if (newValue != null) {
var key = new EntityKey(relatedNavProp.EntityType, newValue);
var newValues = new List<object>();

foreach (var fKey in relatedNavProp.ForeignKeyProperties) {
if (fKey == property)
newValues.Add(newValue);
else
newValues.Add(GetValue(fKey));
}

var key = new EntityKey(relatedNavProp.EntityType, newValues.ToArray());
var relatedEntity = EntityManager.GetEntityByKey(key);

if (relatedEntity != null) {
Expand Down
Loading