private void FileSystemWatcher_Renamed(object sender, RenamedEventArgs e) { if (ActivityEvent != null) { NodeType nodeType; if (!e.FullPath.StartsWith(((LocalNodeAddress)this.RootAddress).AbsoluteNativePath)) { return; } nodeType = (sender == this.fileSystemWatcherFile) ? NodeType.File : NodeType.Directory; OnActivityEvent(new FileSystemRenamedActivityEventArgs(FileSystemActivity.Renamed, nodeType, Path.GetFileName(e.OldName), StringUriUtils.NormalizePath( e.OldFullPath.Substring( this.fileSystemWatcherFile.Path.Length - 1)), Path.GetFileName(e.Name), StringUriUtils.NormalizePath( e.FullPath.Substring( ((LocalNodeAddress)this.RootAddress).AbsoluteNativePath. Length - 1)))); } }
public override INode Find(INodeResolver resolver, string uri, NodeType nodeType, FileSystemOptions options) { var address = LayeredNodeAddress.Parse(uri); if (address.Port >= 0 || address.UserName != "" || address.Password != "" || address.ServerName != "") { throw new MalformedUriException(uri, "Network & Authentication information not permitted"); } if (nodeType.Is(typeof(IFile))) { var uri2 = address.InnerUri; if (StringUriUtils.ContainsQuery(uri2)) { uri2 += "&shadow=true"; } else { uri2 += "?shadow=true"; } return(resolver.Resolve(uri2, nodeType)); } return(resolver.Resolve(address.InnerUri)); }
public virtual INodeAddress ResolveAddress(string name, AddressScope scope) { int x; var query = ""; if (name.Length == 0 || (name.Length > 0 && name[0] != FileSystemManager.RootChar)) { // Path is relative. if (this.IsRoot) { name = FileSystemManager.RootChar + name; } else { name = this.absolutePath + FileSystemManager.SeperatorChar + name; } } if ((x = name.IndexOf('?')) >= 0) { query = name.Substring(x + 1); name = name.Substring(0, x); } name = StringUriUtils.NormalizePath(name); if (!CheckPathScope(this.AbsolutePath, name, scope)) { throw new AddressScopeValidationException(name, scope); } return(CreateAddress(name, query)); }
public static NetworkNodeAddress CreateAsRoot(string scheme, NetworkNodeAddress modelAddress, bool exposeAsNonComplexAddress) { var upperLayerUri = StringUriUtils.Combine(modelAddress.InnerUri, modelAddress.AbsolutePath); var address = new NetworkNodeAddress(scheme, modelAddress.UserName, modelAddress.Password, modelAddress.ServerName, modelAddress.Port, upperLayerUri, "", "/", "", exposeAsNonComplexAddress); return(address); }
public virtual INode Filter(ref INodeResolver resolver, ref INodeAddress address, ref NodeType nodeType, out bool canCache) { string value; canCache = false; if (this.QueryKey == null) { value = "true"; } else { try { if (address.QueryValues[QueryKey] == null) { return(null); } value = (string)address.QueryValues[this.QueryKey]; } catch (KeyNotFoundException) { value = null; } } if (nodeType.Equals(NodeType.File) && value != null && value.ToLower() == "true") { canCache = true; var innerNodeType = nodeType.InnerType; if (innerNodeType == null) { innerNodeType = NodeType.File; } var query = StringUriUtils.BuildQuery ( address.QueryValues, QueryFilter ); var uri = address.AbsolutePath + "?" + query; return(new ShadowFile((IFile)resolver.Resolve(uri, innerNodeType), address)); } return(null); }
public override INode Filter(ref INodeResolver resolver, ref INodeAddress address, ref NodeType nodeType, out bool canCache) { string value; canCache = false; if (this.QueryKey == null) { return(null); } else { try { if (address.QueryValues[this.QueryKey] == null) { return(null); } value = (string)address.QueryValues[this.QueryKey]; } catch (KeyNotFoundException) { return(null); } } if (nodeType.Equals(NodeType.File)) { canCache = true; var query = StringUriUtils.BuildQuery ( address.QueryValues, pair => pair.Key.Equals(this.QueryKey, StringComparison.CurrentCultureIgnoreCase) ); var uri = address.AbsolutePath + "?" + query; var file = resolver.ResolveFile(uri); var service = (ITempIdentityFileService)file.GetService(new TempIdentityFileServiceType(value)); canCache = true; return(service.GetTempFile()); } return(null); }
private static IFile GetZipFile(IFile zipFile) { if (zipFile.Address.QueryValues["shadow"] as string == "true") { return(zipFile); } if (ConfigurationSection.Instance.AutoShadowThreshold == -1 || zipFile.Length <= ConfigurationSection.Instance.AutoShadowThreshold) { zipFile = zipFile.ResolveFile(StringUriUtils.AppendQueryPart(zipFile.Address.NameAndQuery, "shadow", "true")); } return(zipFile); }
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e) { if (ActivityEvent != null) { NodeType nodeType; if (!e.FullPath.StartsWith(((LocalNodeAddress)this.RootAddress).AbsoluteNativePath)) { return; } /* * There is a race here between when the watcher sees the event and when it is processed * which may mean that a changed event meant for a dir goes to a file (or vice versa). * There's nothing we can do about it but since the Changed event is pretty opaque * (users will have to figure what has changed anyway) it doesn't matter too much. */ nodeType = GetNodeType(e.FullPath.Substring(((LocalNodeAddress)this.RootAddress).AbsoluteNativePath.Length - 1)); if (nodeType == NodeType.None) { OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Changed, NodeType.File, e.Name, StringUriUtils.NormalizePath( e.FullPath.Substring( ((LocalNodeAddress)this.RootAddress).AbsoluteNativePath.Length - 1)))); OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Changed, NodeType.Directory, e.Name, StringUriUtils.NormalizePath( e.FullPath.Substring( ((LocalNodeAddress)this.RootAddress).AbsoluteNativePath.Length - 1)))); return; } else { OnActivityEvent(new FileSystemActivityEventArgs(FileSystemActivity.Changed, nodeType, e.Name, StringUriUtils.NormalizePath( e.FullPath.Substring( ((LocalNodeAddress)this.RootAddress).AbsoluteNativePath.Length - 1)))); } } }
protected override INode DoRenameTo(string name, bool overwrite) { string destPath; name = StringUriUtils.RemoveQuery(name); destPath = Path.Combine(this.directoryInfo.Parent.FullName, name); if (this.FileSystem.PathsEqual(destPath, this.directoryInfo.Parent.FullName, destPath.Length)) { return(this); } for (var i = 0; i < 5; i++) { try { if (overwrite) { Directory.Delete(destPath); } // // Don't use FileInfo.MoveTo as it changes the existing FileInfo // use the new path. // Directory.Move(this.directoryInfo.FullName, destPath); this.directoryInfo.Refresh(); break; } catch (IOException) { if (i == 4) { throw; } Thread.Sleep(500); } } return(this); }
protected override INode DoRenameTo(string name, bool overwrite) { name = StringUriUtils.RemoveQuery(name); var destPath = Path.Combine(this.fileInfo.DirectoryName, name); for (var i = 0; i < 5; i++) { try { if (overwrite) { File.Delete(destPath); } // // Don't use FileInfo.MoveTo as it changes the existing FileInfo // use the new path. // File.Move(this.fileInfo.FullName, destPath); this.fileInfo.Refresh(); break; } catch (IOException) { if (i == 4) { throw; } Thread.Sleep(500); } } return(this); }
public override ServiceModel Reflect() { var descriptions = configuration.Services.GetApiExplorer().ApiDescriptions.AsEnumerable() .Where(c => !c.ActionDescriptor.GetCustomAttributes <FickleExcludeAttribute>().Any()) .ToList(); if (this.options.ControllersTypesToIgnore != null) { descriptions = descriptions.Where(x => !this.options.ControllersTypesToIgnore.Contains(x.ActionDescriptor.ControllerDescriptor.ControllerType)).ToList(); } bool secureByDefault = false; var enums = new List <ServiceEnum>(); var classes = new List <ServiceClass>(); var gateways = new List <ServiceGateway>(); var referencedTypes = GetReferencedTypes(descriptions).ToList(); var controllers = descriptions.Select(c => c.ActionDescriptor.ControllerDescriptor).ToHashSet(); var serviceModelInfo = new ServiceModelInfo(); foreach (var enumType in referencedTypes.Where(c => c.BaseType == typeof(Enum))) { var serviceEnum = new ServiceEnum { Name = GetTypeName(enumType), Values = Enum.GetNames(enumType).Select(c => new ServiceEnumValue { Name = c, Value = Convert.ToInt64(Enum.Parse(enumType, c)) }).ToList() }; enums.Add(serviceEnum); } foreach (var type in referencedTypes .Where(TypeSystem.IsNotPrimitiveType) .Where(c => c.BaseType != typeof(Enum)) .Where(c => !c.IsInterface) .Where(c => !typeof(IList <>).IsAssignableFromIgnoreGenericParameters(c))) { var baseTypeName = GetTypeName(type.BaseType); var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Where(c => !c.GetCustomAttributes <FickleExcludeAttribute>().Any()) .Select(c => new ServiceProperty { Name = c.Name, TypeName = GetTypeName(c.PropertyType) }).ToList(); var serviceClass = new ServiceClass { Name = GetTypeName(type), BaseTypeName = baseTypeName, Properties = properties }; classes.Add(serviceClass); } var allowedMethods = new HashSet <string>(new[] { "GET", "POST" }, StringComparer.InvariantCultureIgnoreCase); foreach (var controller in controllers) { var methods = new List <ServiceMethod>(); secureByDefault = this.referencingAssembly.GetCustomAttributes <FickleSecureAttribute>()?.FirstOrDefault()?.Secure ?? false; var controllerSecureByDefault = controller.GetCustomAttributes <FickleSecureAttribute>(true)?.FirstOrDefault()?.Secure ?? secureByDefault; var serviceNameSuffix = "Service"; var attribute = this.referencingAssembly.GetCustomAttribute <FickleSdkInfoAttribute>(); if (attribute != null) { serviceNameSuffix = attribute.ServiceNameSuffix ?? serviceNameSuffix; serviceModelInfo.Name = attribute.Name ?? serviceModelInfo.Name; serviceModelInfo.Summary = attribute.Summary ?? serviceModelInfo.Summary; serviceModelInfo.Author = attribute.Author ?? serviceModelInfo.Author; serviceModelInfo.Version = attribute.Version ?? serviceModelInfo.Version; } foreach (var api in descriptions .Where(c => c.ActionDescriptor.ControllerDescriptor == controller && allowedMethods.Contains(c.HttpMethod.Method))) { var formatters = api.ActionDescriptor.ControllerDescriptor.Configuration.Formatters; var returnType = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; if (!formatters.Any(c => c is JsonMediaTypeFormatter)) { returnType = typeof(string); } var parameters = api.ParameterDescriptions.Select(d => new ServiceParameter { Name = d.ParameterDescriptor.ParameterName, TypeName = GetTypeName(d.ParameterDescriptor.ParameterType) }).ToList(); ServiceParameter contentServiceParameter = null; var contentParameter = api.ParameterDescriptions.SingleOrDefault(c => c.Source == ApiParameterSource.FromBody); var uniqueNameMaker = new UniqueNameMaker(c => api.ParameterDescriptions.Any(d => d.Name.EqualsIgnoreCase(c))); if (contentParameter == null && api.HttpMethod.Method.EqualsIgnoreCaseInvariant("POST") && api.ActionDescriptor.GetCustomAttributes <NoBodyAttribute>().Count == 0) { contentServiceParameter = new ServiceParameter { Name = uniqueNameMaker.Make("content"), TypeName = GetTypeName(typeof(byte[])) }; parameters.Add(contentServiceParameter); } else if (contentParameter != null) { contentServiceParameter = new ServiceParameter { Name = contentParameter.Name, TypeName = GetTypeName(contentParameter.ParameterDescriptor.ParameterType) }; } var serviceMethod = new ServiceMethod { Authenticated = api.ActionDescriptor.GetCustomAttributes <AuthorizeAttribute>(true).Count > 0, Secure = api.ActionDescriptor.GetCustomAttributes <FickleSecureAttribute>(true)?.FirstOrDefault()?.Secure ?? controllerSecureByDefault, Name = api.ActionDescriptor.ActionName, Path = StringUriUtils.Combine(this.configuration.VirtualPathRoot, api.RelativePath), Returns = GetTypeName(returnType), ReturnFormat = "json", Method = api.HttpMethod.Method.ToLower(), Parameters = parameters }; if (contentServiceParameter != null) { serviceMethod.Content = contentServiceParameter.Name; serviceMethod.ContentServiceParameter = contentServiceParameter; } methods.Add(serviceMethod); } var serviceGateway = new ServiceGateway { BaseTypeName = null, Name = controller.ControllerName + serviceNameSuffix, Hostname = hostname, Methods = methods }; gateways.Add(serviceGateway); } return(new ServiceModel(serviceModelInfo, enums, classes, gateways)); }
public static LocalNodeAddress Parse(string uri) { Group group; Match match = null; string root, scheme, query; // Often Parse will be called with the exact same URI reference that was last passed // to CanParse. If this is the case then use the results cached by the last call to // CanParse from this thread. if ((object)uri == (object)lastCanParseUri) { match = lastCanParseMatch; } while (true) { if (match == null) { match = localFileNameRegEx.Match(uri); } if (!match.Success) { throw new MalformedUriException(uri); } bool schemeExplicitlyProvided; group = match.Groups["scheme"]; if (group.Value == "") { scheme = "file"; schemeExplicitlyProvided = false; } else { scheme = group.Value; schemeExplicitlyProvided = true; } group = match.Groups["uncserver"]; if (group.Success) { string path; Pair <string, string> result; path = match.Groups["path1"].Value; result = path.SplitAroundCharFromLeft(1, PredicateUtils.ObjectEqualsAny('\\', '/')); root = "//" + group.Value + result.Left.Replace('\\', '/'); path = "/" + result.Right; if (path == "") { path = "/"; } query = match.Groups["query"].Value; return(new LocalNodeAddress(scheme, root, true, StringUriUtils.NormalizePath(path), query)); } else { string path; group = match.Groups["root"]; if (group.Captures.Count > 0) { // // Windows path specification // root = group.Value; path = match.Groups["path2"].Value; if (path.Length == 0) { path = FileSystemManager.SeperatorString; } query = match.Groups["query"].Value; path = StringUriUtils.NormalizePath(path); if (schemeExplicitlyProvided) { // // Explicitly provided scheme means // special characters are hexcoded // path = TextConversion.FromEscapedHexString(path); query = TextConversion.FromEscapedHexString(query); } return(new LocalNodeAddress(scheme, root, true, path, query)); } else if (match.Groups["path3"].Value != "") { // // Unix path specification // path = match.Groups["path3"].Value; query = match.Groups["query"].Value; path = StringUriUtils.NormalizePath(path); if (schemeExplicitlyProvided) { // // Explicitly provided scheme means // special characters are hexcoded // path = TextConversion.FromEscapedHexString(path); query = TextConversion.FromEscapedHexString(query); } return(new LocalNodeAddress(scheme, "", true, path, query)); } else { // // Relative path specification // path = match.Groups["path4"].Value; query = match.Groups["query"].Value; path = StringUriUtils.Combine(Environment.CurrentDirectory, path); path = StringUriUtils.NormalizePath(path); if (!string.IsNullOrEmpty(query)) { query = "?" + query; } else { query = ""; } if (schemeExplicitlyProvided) { uri = scheme + "://" + path + "query"; } else { uri = path + query; } match = null; } } } }
public BasicNodeAddress(string rootUri, string path) : this(StringUriUtils.GetScheme(rootUri), rootUri, path, false) { }
protected Expression CreateGatewayCallMethod(MethodDefinitionExpression method, out ParameterExpression optionsParameter) { var methodName = method.Name.ToCamelCase(); methodCount++; var self = Expression.Variable(currentType, "self"); var hostname = Expression.Variable(typeof(string), "hostname"); var port = Expression.Variable(typeof(string), "port"); var protocol = Expression.Variable(typeof(string), "protocol"); var optionsParam = FickleExpression.Parameter("NSDictionary", "options"); var localOptions = FickleExpression.Variable("NSMutableDictionary", "localOptions"); var requestObject = FickleExpression.Variable("NSObject", "requestObject"); var requestObjectValue = (Expression)Expression.Constant(null, typeof(object)); var url = Expression.Variable(typeof(string), "url"); var responseType = ObjectiveBinderHelpers.GetWrappedResponseType(this.CodeGenerationContext, method.ReturnType); var variables = new [] { url, localOptions, protocol, hostname, requestObject, port }; var declaredHostname = currentTypeDefinitionExpression.Attributes["Hostname"]; var declaredPath = method.Attributes["Path"]; var path = StringUriUtils.Combine("%@://%@%@", declaredPath); var httpMethod = method.Attributes["Method"]; var declaredProtocol = Convert.ToBoolean(method.Attributes["Secure"]) ? "https" : "http"; var retryBlockVariable = Expression.Variable(new FickleDelegateType(typeof(void), new FickleParameterInfo(FickleType.Define("id"), "block")), "retryBlock"); var retryBlockParameter = Expression.Variable(FickleType.Define("id"), "block"); var parametersByName = method.Parameters.ToDictionary(c => ((ParameterExpression)c).Name, c => (ParameterExpression)c, StringComparer.InvariantCultureIgnoreCase); var formatInfo = ObjectiveStringFormatInfo.GetObjectiveStringFormatInfo(path, c => parametersByName[c]); var args = formatInfo.ValueExpressions; var parameters = formatInfo.ParameterExpressions; var parameterInfos = new List <FickleParameterInfo> { new ObjectiveParameterInfo(typeof(string), "s"), new ObjectiveParameterInfo(typeof(string), "protocol", true), new ObjectiveParameterInfo(typeof(string), "hostname", true), new ObjectiveParameterInfo(typeof(string), "port", true), }; parameterInfos.AddRange(parameters.Select(c => new ObjectiveParameterInfo(c.Type, c.Name, true))); var methodInfo = new FickleMethodInfo(typeof(string), typeof(string), "stringWithFormat", parameterInfos.ToArray(), true); args.InsertRange(0, new Expression[] { Expression.Constant(formatInfo.Format), protocol, hostname, port }); var newParameters = new List <Expression>(method.Parameters) { optionsParam }; var callback = Expression.Parameter(new FickleDelegateType(typeof(void), new FickleParameterInfo(responseType, "response")), "callback"); newParameters.Add(callback); Expression blockArg = Expression.Parameter(FickleType.Define("id"), "arg1"); var returnType = method.ReturnType; if (ObjectiveBinderHelpers.NeedsValueResponseWrapper(method.ReturnType)) { returnType = FickleType.Define(ObjectiveBinderHelpers.GetValueResponseWrapperTypeName(method.ReturnType)); } var responseFilter = FickleExpression.Property(self, "FKGatewayResponseFilter", "responseFilter"); var conversion = Expression.Convert(blockArg, returnType); var innerRetryBlockBody = FickleExpression.Block ( FickleExpression.Call(Expression.Convert(retryBlockParameter, retryBlockVariable.Type), typeof(void), "Invoke", new { block = retryBlockParameter }).ToStatement() ); var innerRetryBlock = (Expression)FickleExpression.SimpleLambda ( typeof(void), innerRetryBlockBody, new Expression[0] ); var body = FickleExpression.GroupedWide ( Expression.IfThen(Expression.NotEqual(responseFilter, Expression.Constant(null, responseFilter.Type)), Expression.Assign(blockArg, FickleExpression.Call(responseFilter, typeof(object), "gateway", new { value = self, receivedResponse = blockArg, fromRequestURL = url, withRequestObject = requestObject, retryBlock = innerRetryBlock, andOptions = localOptions })).ToStatementBlock()), Expression.IfThen ( Expression.AndAlso(Expression.NotEqual(blockArg, Expression.Constant(null, blockArg.Type)), Expression.NotEqual(callback, Expression.Constant(null, callback.Type))), FickleExpression.Call(callback, "Invoke", conversion).ToStatementBlock() ) ); var conversionBlock = FickleExpression.SimpleLambda(null, body, new Expression[0], blockArg); var error = FickleExpression.Variable("NSError", "error"); Expression parseResultBlock; var nsdataParam = Expression.Parameter(FickleType.Define("NSData"), "data"); var clientParam = Expression.Parameter(FickleType.Define("PKWebServiceClient"), "client"); var jsonObjectWithDataParameters = new[] { new FickleParameterInfo(FickleType.Define("NSDictionary"), "obj"), new FickleParameterInfo(typeof(int), "options"), new FickleParameterInfo(FickleType.Define("NSError", true), "error", true) }; var objectWithDataMethodInfo = new FickleMethodInfo(FickleType.Define("NSJSONSerialization"), FickleType.Define("NSData"), "JSONObjectWithData", jsonObjectWithDataParameters, true); var deserializedValue = Expression.Parameter(FickleType.Define("id"), "deserializedValue"); var parseErrorResult = FickleExpression.Call(self, "webServiceClient", new { clientParam, createErrorResponseWithErrorCode = "JsonDeserializationError", andMessage = FickleExpression.Call(error, "localizedDescription", null) }); if (method.ReturnType == typeof(void)) { var responseObject = FickleExpression.Variable(responseType, "responseObject"); parseResultBlock = FickleExpression.SimpleLambda ( FickleType.Define("id"), FickleExpression.GroupedWide ( Expression.Assign(responseObject, FickleExpression.New(responseType, "init", null)).ToStatement(), Expression.Assign(deserializedValue, Expression.Call(objectWithDataMethodInfo, nsdataParam, FickleExpression.Variable(typeof(int), "NSJSONReadingAllowFragments"), error)).ToStatement(), Expression.IfThen(Expression.Equal(deserializedValue, Expression.Constant(null)), FickleExpression.Return(parseErrorResult).ToStatementBlock()), FickleExpression.Return(responseObject).ToStatement() ), new Expression[] { deserializedValue, responseObject, error }, clientParam, nsdataParam ); } else if (TypeSystem.IsPrimitiveType(method.ReturnType) || method.ReturnType is FickleListType) { var responseObject = FickleExpression.Variable(responseType, "responseObject"); var needToBoxValue = ObjectiveBinderHelpers.ValueResponseValueNeedsBoxing(method.ReturnType); parseResultBlock = FickleExpression.SimpleLambda ( FickleType.Define("id"), FickleExpression.GroupedWide ( Expression.Assign(responseObject, FickleExpression.New(responseType, "init", null)).ToStatement(), Expression.Assign(deserializedValue, Expression.Call(objectWithDataMethodInfo, nsdataParam, FickleExpression.Variable(typeof(int), "NSJSONReadingAllowFragments"), error)).ToStatement(), Expression.IfThen(Expression.Equal(deserializedValue, Expression.Constant(null)), FickleExpression.Return(parseErrorResult).ToStatementBlock()), PropertiesFromDictionaryExpressonBinder.GetDeserializeExpressionProcessValueDeserializer(method.ReturnType, deserializedValue, c => FickleExpression.Call(responseObject, typeof(void), "setValue", needToBoxValue ? Expression.Convert(c, typeof(object)) : c).ToStatement()), FickleExpression.Return(responseObject).ToStatement() ), new Expression[] { deserializedValue, responseObject, error }, clientParam, nsdataParam ); } else { parseResultBlock = FickleExpression.SimpleLambda ( FickleType.Define("id"), FickleExpression.GroupedWide ( Expression.Assign(deserializedValue, Expression.Call(objectWithDataMethodInfo, nsdataParam, FickleExpression.Variable(typeof(int), "NSJSONReadingAllowFragments"), error)).ToStatement(), PropertiesFromDictionaryExpressonBinder.GetDeserializeExpressionProcessValueDeserializer(method.ReturnType, deserializedValue, c => FickleExpression.Return(c).ToStatement()), FickleExpression.Return(parseErrorResult).ToStatement() ), new Expression[] { deserializedValue, error }, clientParam, nsdataParam ); } var uniqueNameMaker = new UniqueNameMaker(c => newParameters.Cast <ParameterExpression>().Any(d => d.Name.EqualsIgnoreCaseInvariant(c))); var key = FickleExpression.Variable(typeof(string), uniqueNameMaker.Make("key")); var integrateOptions = FickleExpression.ForEach ( key, optionsParam, FickleExpression.Call(localOptions, typeof(void), "setObject", new { value = FickleExpression.Call(optionsParam, typeof(object), "objectForKey", key), forKey = key }).ToStatementBlock() ); parseResultBlock = FickleExpression.Call(parseResultBlock, parseResultBlock.Type, "copy", null); var client = Expression.Variable(FickleType.Define(this.CodeGenerationContext.Options.ServiceClientTypeName ?? "PKWebServiceClient"), "client"); Expression clientCallExpression; if (httpMethod.Equals("get", StringComparison.InvariantCultureIgnoreCase)) { clientCallExpression = FickleExpression.Call(client, "getWithCallback", conversionBlock); } else { var contentParameterName = method.Attributes["Content"]; var contentFormat = method.Attributes["ContentFormat"]; if (string.IsNullOrEmpty(contentParameterName)) { clientCallExpression = FickleExpression.Call(client, "postWithRequestObject", new { requestObject, andCallback = conversionBlock }); } else { var content = parametersByName[contentParameterName]; requestObjectValue = content.Type == typeof(byte[]) ? (Expression)content : FickleExpression.Call(self, typeof(object), this.GetNormalizeRequestMethodName(content.Type, contentFormat), new { serializeRequest = Expression.Convert(content, typeof(object)), paramName = Expression.Constant(contentParameterName) }); clientCallExpression = FickleExpression.Call(client, "postWithRequestObject", new { requestObject, andCallback = conversionBlock }); } } var retryBlock = (Expression)FickleExpression.SimpleLambda ( typeof(void), FickleExpression.StatementisedGroupedExpression ( Expression.Assign(client, FickleExpression.Call(Expression.Variable(currentType, "self"), "PKWebServiceClient", "createClientWithURL", new { url, options = localOptions })), Expression.Assign(FickleExpression.Property(client, currentType, "delegate"), self), clientCallExpression ), new Expression[] { client }, retryBlockParameter ); retryBlock = FickleExpression.Call(retryBlock, retryBlock.Type, "copy", null); var block = FickleExpression.Block ( variables.Concat(retryBlockVariable).ToArray(), Expression.Assign(requestObject, requestObjectValue), Expression.Assign(callback, FickleExpression.Call(callback, callback.Type, "copy", null)), Expression.Assign(localOptions, FickleExpression.Call(FickleExpression.Property(self, FickleType.Define("NSDictionary"), "options"), "NSMutableDictionary", "mutableCopyWithZone", new { zone = Expression.Constant(null, FickleType.Define("NSZone")) })), Expression.IfThen(Expression.NotEqual(requestObject, Expression.Constant(null)), FickleExpression.Call(localOptions, typeof(void), "setObject", new { value = requestObject, forKey = "$RequestObject" }).ToStatementBlock()), FickleExpression.Call(localOptions, typeof(void), "setObject", new { value = FickleExpression.StaticCall(responseType, "class", null), forKey = "$ResponseClass" }).ToStatement(), Expression.Assign(hostname, FickleExpression.Call(localOptions, typeof(string), "objectForKey", Expression.Constant("hostname"))), Expression.IfThen(Expression.Equal(hostname, Expression.Constant(null)), Expression.Assign(hostname, Expression.Constant(declaredHostname)).ToStatementBlock()), Expression.Assign(protocol, FickleExpression.Call(localOptions, typeof(string), "objectForKey", Expression.Constant("protocol"))), Expression.IfThen(Expression.Equal(protocol, Expression.Constant(null)), Expression.Assign(protocol, Expression.Constant(declaredProtocol)).ToStatementBlock()), Expression.Assign(port, FickleExpression.Call(FickleExpression.Call(localOptions, FickleType.Define("NSNumber"), "objectForKey", Expression.Constant("port")), typeof(string), "stringValue", null)), Expression.IfThenElse(Expression.Equal(port, Expression.Constant(null)), Expression.Assign(port, Expression.Constant("")).ToStatementBlock(), Expression.Assign(port, FickleExpression.Call(Expression.Constant(":"), typeof(string), "stringByAppendingString", port)).ToStatementBlock()), FickleExpression.Grouped ( FickleExpression.Call(localOptions, "setObject", new { obj = parseResultBlock, forKey = "$ParseResultBlock" }).ToStatement(), method.ReturnType.GetUnwrappedNullableType() == typeof(bool) ? FickleExpression.Call(localOptions, "setObject", new { obj = Expression.Convert(Expression.Constant(1), typeof(object)) }).ToStatement() : null ), Expression.Assign(url, Expression.Call(null, methodInfo, args)), FickleExpression.Call(localOptions, typeof(void), "setObject", new { value = url, forKey = "$RequestURL" }).ToStatement(), integrateOptions, Expression.Assign(retryBlockVariable, retryBlock), FickleExpression.Call(retryBlockVariable, typeof(void), "Invoke", retryBlockVariable).ToStatement() ); optionsParameter = optionsParam; return(new MethodDefinitionExpression(methodName, newParameters.ToReadOnlyCollection(), typeof(void), block, false, null)); }
private static string GetFileName(TypeDescriptorProvider typeDescriptorProvider, string cacheDirectory, string serializedConfiguration, out string fullhash) { var sha1 = SHA1.Create(); var modelAssembly = typeDescriptorProvider.DataAccessModelType.Assembly; var uniquelyReferencedAssemblies = new HashSet <Assembly> { typeof(DataAccessModel).Assembly, modelAssembly }; foreach (var type in typeDescriptorProvider.GetTypeDescriptors()) { var current = type.Type; while (current != null) { uniquelyReferencedAssemblies.Add(current.Assembly); current = current.BaseType; } } var bytes = Encoding.UTF8.GetBytes(serializedConfiguration); sha1.TransformBlock(bytes, 0, bytes.Length, null, 0); foreach (var assembly in uniquelyReferencedAssemblies.OrderBy(c => c.FullName)) { bytes = Encoding.UTF8.GetBytes(assembly.FullName); sha1.TransformBlock(bytes, 0, bytes.Length, null, 0); bytes = Encoding.UTF8.GetBytes(assembly.GetName().Version.ToString()); sha1.TransformBlock(bytes, 0, bytes.Length, null, 0); var path = StringUriUtils.GetScheme(assembly.CodeBase) == "file" ? new Uri(assembly.CodeBase).LocalPath : assembly.Location; if (path != null) { if (assembly.GetName().GetPublicKeyToken().Length == 0) { var fileInfo = new FileInfo(path); bytes = BitConverter.GetBytes(fileInfo.Length); sha1.TransformBlock(bytes, 0, bytes.Length, null, 0); bytes = BitConverter.GetBytes(fileInfo.LastWriteTimeUtc.Ticks); sha1.TransformBlock(bytes, 0, bytes.Length, null, 0); } } } sha1.TransformFinalBlock(bytes, 0, 0); var fileName = modelAssembly.Location == null?modelAssembly.GetName().Name : Path.GetFileNameWithoutExtension(modelAssembly.Location); cacheDirectory = cacheDirectory?.Trim(); var codebaseUri = new Uri(modelAssembly.CodeBase); var modelName = typeDescriptorProvider.DataAccessModelType.Name; if (modelAssembly.GetExportedTypes().Any(c => c.Name == modelName && c != typeDescriptorProvider.DataAccessModelType)) { modelName = typeDescriptorProvider.DataAccessModelType.FullName.Replace(".", "_"); } fullhash = TextConversion.ToHexString(sha1.Hash); fileName = $"{fileName}.{modelName}.Generated.dll"; cacheDirectory = !string.IsNullOrEmpty(cacheDirectory) ? cacheDirectory : !codebaseUri.IsFile ? Environment.CurrentDirectory : Path.GetDirectoryName(codebaseUri.LocalPath); return(Path.Combine(cacheDirectory, fileName)); }