/// <summary> /// Constructs an HTTP PUT request with name-value pairs to be sent in the request BODY. /// </summary> /// <param name="path">Partial URL</param> /// <param name="parameters">Name-value pairs to be sent in request BODY</param> public HttpPut(string path, ParameterMap parameters) : base(path, parameters) { HttpMethod = "PUT"; Path = path; ContentType = UrlEncoded; if (parameters != null) Content = parameters.UrlEncodeBytes(); }
/// <summary> /// Constructs an HTTP PUT request with arbitrary content. If parameters is non-null, the name-value pairs will be /// appended to the QUERY STRING while /// the content is sent in the request BODY. This is not a common use case and is therefore not represented in the /// put() methods in /// AbstractRestClient or AsyncRestClient, but is nevertheless possible using this constructor /// </summary> /// <param name="path">Partial URL</param> /// <param name="parameters">Name-value pairs to be sent in request BODY</param> /// <param name="contentType">Content Type</param> /// <param name="data">Content to post</param> public HttpPut(string path, ParameterMap parameters, string contentType, byte[] data) : base(path, parameters) { HttpMethod = "PUT"; Path = path; ContentType = contentType; Content = data; }
/// <summary>Create a set of parameters covering all known effects, with default values across the board.</summary> public static ParameterMap CreateParameterMap() { ParameterMap set = new ParameterMap(); foreach (ParameterDescription desc in s_parameters) { set.Add(new ConstantParameter(desc)); } return set; }
/// <summary> /// Constructor /// </summary> /// <param name="path">Resource Path</param> /// <param name="parameters">Request parameter</param> protected HttpRequest(string path, ParameterMap parameters) { if (!path.IsEmpty()) Path = path; if (parameters != null) { string queryString = parameters.UrlEncode(); Path += "?" + queryString; } }
internal EffectSettings(string[] labels, ParameterMap[] parameterMaps) { UpLabel = labels[0]; RightLabel = labels[1]; DownLabel = labels[2]; LeftLabel = labels[3]; Up = parameterMaps[0]; Right = parameterMaps[1]; Down = parameterMaps[2]; Left = parameterMaps[3]; }
public void AddSignature(ParameterMap parameterMap) { var signatureBaseElements = parameterMap .Select(parameter => parameter.Key + parameter.Value) .ToArray(); var simplickrConfig = _simplickrConfigurationProvider.GetConfig(); var secret = simplickrConfig.Secret; var signatureBase = secret + string.Join("", signatureBaseElements); var signature = MD5Hash(signatureBase); parameterMap.Set("api_sig", EncodingUtility.UrlEncode(signature)); }
internal PlayerModel( int playerIndex, int asioChannel, HolofunkModel holofunkModel) { m_playerIndex = playerIndex; m_asioChannel = asioChannel; m_parent = holofunkModel; // TODO: EVIL INIT ORDER DEPENDENCY: hand models contain state machines, which update scene graphs on initialization! m_playerSceneGraph = new PlayerSceneGraph(holofunkModel.SceneGraph, playerIndex, asioChannel); m_leftHandModel = new PlayerHandModel(this, false); m_rightHandModel = new PlayerHandModel(this, true); // the microphone has only per-loop parameters m_microphoneParameters = AllEffects.CreateParameterMap(); }
/// <summary> /// This method is used to delete Contact Roles and print the response. /// </summary> /// <param name="contactRoleIds">The List of ContactRole IDs to be deleted.</param> public static void DeleteContactRoles(List <long> contactRoleIds) { //example //List<long> contactRoleIds = new List<long>() { 34770615208001, 34770615208002, 34770615177003, 34770616104001 }; //Get instance of ContactRolesOperations Class ContactRolesOperations contactRolesOperations = new ContactRolesOperations(); //Get instance of ParameterMap Class ParameterMap paramInstance = new ParameterMap(); foreach (long id in contactRoleIds) { paramInstance.Add(DeleteContactRolesParam.IDS, id); } //Call DeleteContactRoles method that takes paramInstance as parameter APIResponse <ActionHandler> response = contactRolesOperations.DeleteContactRoles(paramInstance); if (response != null) { //Get the status code from response Console.WriteLine("Status Code: " + response.StatusCode); //Check if expected response is received if (response.IsExpected) { //Get object from response ActionHandler actionHandler = response.Object; if (actionHandler is ActionWrapper) { //Get the received ActionWrapper instance ActionWrapper actionWrapper = (ActionWrapper)actionHandler; //Get the list of obtained ContactRole instances List <ActionResponse> actionResponses = actionWrapper.ContactRoles; foreach (ActionResponse actionResponse in actionResponses) { //Check if the request is successful if (actionResponse is SuccessResponse) { //Get the received SuccessResponse instance SuccessResponse successResponse = (SuccessResponse)actionResponse; //Get the Status Console.WriteLine("Status: " + successResponse.Status.Value); //Get the Code Console.WriteLine("Code: " + successResponse.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in successResponse.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + successResponse.Message.Value); } //Check if the request returned an exception else if (actionResponse is APIException) { //Get the received APIException instance APIException exception = (APIException)actionResponse; //Get the Status Console.WriteLine("Status: " + exception.Status.Value); //Get the Code Console.WriteLine("Code: " + exception.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in exception.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + exception.Message.Value); } } } //Check if the request returned an exception else if (actionHandler is APIException) { //Get the received APIException instance APIException exception = (APIException)actionHandler; //Get the Status Console.WriteLine("Status: " + exception.Status.Value); //Get the Code Console.WriteLine("Code: " + exception.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in exception.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + exception.Message.Value); } } else { //If response is not as expected //Get model object from response Model responseObject = response.Model; //Get the response object's class Type type = responseObject.GetType(); //Get all declared fields of the response class Console.WriteLine("Type is: {0}", type.Name); PropertyInfo[] props = type.GetProperties(); Console.WriteLine("Properties (N = {0}):", props.Length); foreach (var prop in props) { if (prop.GetIndexParameters().Length == 0) { Console.WriteLine("{0} ({1}) in {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject)); } else { Console.WriteLine("{0} ({1}) in <Indexed>", prop.Name, prop.PropertyType.Name); } } } } }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap"/>. /// </summary> /// <param name="parameterMap">The parameter map.</param> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.Names.Clear(); parameterMap.Data.Names.AddRange(Names); parameterMap.Data.IsNameSet = true; }
/// <summary> /// Constructs an HTTP HEAD request /// </summary> /// <param name="path">Partial URL</param> /// <param name="parameters">Name-value pairs to be appended to the URL</param> public HttpHead(string path, ParameterMap parameters) : base(path, parameters) { HttpMethod = "HEAD"; ContentType = UrlEncoded; }
internal void ShareLoopParameters(ParameterMap parameters) { foreach (Loopie loopie in TouchedLoopies) { loopie.Track.Parameters.ShareAll(parameters); // TODO: figure out how to handle these moments outside of time... Time(0) is terrible loopie.Track.UpdateEffects(HolofunkModel.Clock.Time(0)); } }
/// <summary> /// Defines methods to enable pluggable configuration of parameter mapping. /// </summary> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.Ignore = true; }
public CounterMap(ParameterMap other) { foreach (Parameter p in other) { m_counters.Add(p.Description, 0); } }
/// <summary> /// Add a contact group using a key-value pairs data structure /// </summary> /// <param name="data">The contact group data <see cref="ParameterMap" /></param> /// <returns>A <see cref="ContactGroup" /> object.</returns> /// <exception cref="Exception">Exception with the appropriate message</exception> public ContactGroup AddContactGroup(ParameterMap data) { const string resource = "/contacts/groups/"; if (data == null) throw new HttpRequestException(new Exception("Parameter 'data' cannot be null")); HttpResponse response = RestClient.Post(resource, data); if (response == null) throw new Exception("Request Failed. Unable to get server response"); if (response.Status == Convert.ToInt32(HttpStatusCode.Created)) return new ContactGroup(JsonConvert.DeserializeObject<ApiDictionary>(response.GetBodyAsString())); string errorMessage = String.Format("Status Code={0}, Message={1}", response.Status, response.GetBodyAsString()); throw new Exception("Request Failed : " + errorMessage); }
/// <summary> /// Execute a HEAD request and return the response. The supplied parameters are URL encoded and sent as the query /// string. /// </summary> /// <param name="path">Url resource</param> /// <param name="parameters">HTTP Payload</param> /// <returns>Response object</returns> public HttpResponse Head(string path, ParameterMap parameters) { return Execute(new HttpHead(path, parameters)); }
/// <summary> /// Execute a POST request with parameter map and return the response. /// </summary> /// <param name="path">Url resource</param> /// <param name="parameters">HTTP Payload</param> /// <returns>Response object</returns> public HttpResponse Post(string path, ParameterMap parameters) { return Execute(new HttpPost(path, parameters)); }
/// <summary> /// Execute a DELETE request and return the response. The supplied parameters are URL encoded and sent as the query /// string. /// </summary> /// <param name="path">Url resource</param> /// <param name="parameters">HTTP Payload</param> /// <returns>Response object</returns> public HttpResponse Delete(string path, ParameterMap parameters) { return Execute(new HttpDelete(path, parameters)); }
/// <summary> /// This method uploads files onto the remote server using the POST method /// </summary> /// <param name="path">Resource Path</param> /// <param name="uploadFiles">Files to upload</param> /// <param name="parameters">Additional form data</param> /// <returns>HttpResponse Object</returns> /// <exception cref="HttpRequestException"></exception> /// <exception cref="Exception"></exception> public HttpResponse PostFiles(string path, UploadFile[] uploadFiles, ParameterMap parameters) { HttpResponse response = null; try { Connected = false; // Let us open the connection, prepare it for writing and reading data. HttpWebRequest urlConnection = OpenConnection(path); urlConnection.Accept = Accept; urlConnection.KeepAlive = true; urlConnection.ReadWriteTimeout = ReadWriteTimeout*1000; urlConnection.Timeout = ConnectionTimeout*1000; urlConnection.Method = "POST"; urlConnection.Headers.Add("Accept-Charset", "UTF-8"); AppendRequestHeaders(urlConnection); Connected = true; // Build form data to send to the server. // Let us set the form data NameValueCollection form = parameters.ToNameValueCollection(); // upload the files HttpWebResponse resp = HttpUploadHelper.Upload(urlConnection, uploadFiles, form); using (resp) { if (resp != null) { using (Stream inputStream = resp.GetResponseStream()) { if (inputStream != null) { var buffer = new byte[resp.ContentLength]; int bytesRead = 0; int totalBytesRead = bytesRead; while (totalBytesRead < buffer.Length) { bytesRead = inputStream.Read(buffer, bytesRead, buffer.Length - bytesRead); totalBytesRead += bytesRead; } response = new HttpResponse(urlConnection.Address.AbsoluteUri, urlConnection.Headers, Convert.ToInt32(resp.StatusCode), buffer); } } } } return response; } catch (Exception e) { if (e.GetType() == typeof (WebException)) { var ex = e as WebException; try { response = ReadStreamError(ex); } catch (Exception ee) { // Must catch IOException, but swallow to show first cause only RequestLogger.Log(ee.StackTrace); } finally { if (response == null || response.Status <= 0) throw new HttpRequestException(e, response); } } else { // Different Exception // Must catch IOException, but swallow to show first cause only RequestLogger.Log(e.ToString()); } } finally { // Here we log the Http Response if (RequestLogger.IsLoggingEnabled()) RequestLogger.LogResponse(response); } return response; }
/// <summary> /// Constructs an HTTP DELETE request /// </summary> /// <param name="path">Partial URL</param> /// <param name="parameters">Name-value pairs to be appended to the URL</param> public HttpDelete(string path, ParameterMap parameters) : base(path, parameters) { HttpMethod = "DELETE"; ContentType = UrlEncoded; }
public void BuildParameterMap(Mod mod) { Dictionary <string, object> parameterDictionary = new Dictionary <string, object>(); if (IsVanillaJob(this, mod.Game)) { if (Header == JobHeader.BASEGAME && mod.Game == MEGame.ME3 && mod.LegacyModCoal) { // moddesc 2 supported this flag. In MM3 it auto converted the // meaning of this into basegame coalesced job. We // should convert it here since there are no raw values // cached into raw parameterDictionary[@"moddir"] = @"."; parameterDictionary[@"newfiles"] = @"Coalesced.bin"; parameterDictionary[@"replacefiles"] = @"BIOGame\CookedPCConsole\Coalesced.bin"; // Technically this doesn't support more on this version of moddesc. // But since we can't save older moddesc formats we will allow // additional parameters and not show the modcoal flag in the UI. } else { parameterDictionary[@"moddir"] = JobDirectory; parameterDictionary[@"newfiles"] = NewFilesRaw; parameterDictionary[@"replacefiles"] = ReplaceFilesRaw; } if (mod.Game == MEGame.ME3 || Header == JobHeader.BASEGAME) { // Add files parameterDictionary[@"addfiles"] = AddFilesRaw; parameterDictionary[@"addfilestargets"] = AddFilesTargetsRaw; parameterDictionary[@"addfilesreadonlytargets"] = ReadOnlyIndicators; } parameterDictionary[@"gamedirectorystructure"] = GameDirectoryStructureRaw ? @"True" : null; parameterDictionary[@"jobdescription"] = RequirementText; } else if (Header == JobHeader.CUSTOMDLC) { // These are serialized in special way by the editor // Do not put them into the parameter map //parameterDictionary[@"sourcedirs"] = CustomDLCFolderMapping.Keys; //parameterDictionary[@"destdirs"] = CustomDLCFolderMapping.Values; parameterDictionary[@"outdatedcustomdlc"] = mod.OutdatedCustomDLC; parameterDictionary[@"incompatiblecustomdlc"] = mod.IncompatibleDLC; // NOT MAPPED: HUMAN READABLE NAMES // CONFIGURED DIRECTLY BY EDITOR UI } else if (Header == JobHeader.LOCALIZATION) { parameterDictionary[@"files"] = FilesToInstall.Values; parameterDictionary[@"dlcname"] = mod.RequiredDLC.FirstOrDefault(); } else if (Header == JobHeader.BALANCE_CHANGES) { parameterDictionary[@"moddir"] = JobDirectory; parameterDictionary[@"newfiles"] = FilesToInstall.Values; } else if (Header == JobHeader.ME1_CONFIG) { parameterDictionary[@"moddir"] = JobDirectory; // files raw is handled by ui } ParameterMap.ReplaceAll(MDParameter.MapIntoParameterMap(parameterDictionary, Header.ToString())); }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap" />. /// </summary> /// <param name="parameterMap">The parameter map.</param> /// <exception cref="NotImplementedException"></exception> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.TypeConverterOptions.NullValues.Clear(); parameterMap.Data.TypeConverterOptions.NullValues.AddRange(NullValues); }
public void Modify(ParameterMap parameterMap) { throw new NotImplementedException(); }
static public bool ExportParameters(string objectName, string objectId, ParameterMap parameterMap, out string propertyFileName) { propertyFileName = string.Empty; if (parameterMap == null || parameterMap.Size == 0) { return(false); } if (curentPropertyJsObject.Count == MaxPropertiesPerSingleFile) { currentFileId = StringConverter.NewGuid(); curentPropertyJsObject = new JObject(); PropertyObjectDic.Add(currentFileId, curentPropertyJsObject); } Dictionary <string, List <string> > propertyCategoryDic = new Dictionary <string, List <string> >(); var itor = parameterMap.ForwardIterator(); while (itor.MoveNext()) { Parameter param = itor.Current as Parameter; Definition def = param.Definition; if (def == null) { continue; } string categoryName = LabelUtils.GetLabelFor(def.ParameterGroup); string paramName = def.Name; if (string.IsNullOrEmpty(paramName)) { continue; } string paramValue = ""; if (!string.IsNullOrEmpty(param.AsString())) { paramValue = param.AsString(); } else if (!string.IsNullOrEmpty(param.AsValueString())) { paramValue = param.AsValueString(); } if (propertyCategoryDic.ContainsKey(categoryName)) { propertyCategoryDic[categoryName].Add(paramName); propertyCategoryDic[categoryName].Add(paramValue); } else { propertyCategoryDic.Add(categoryName, new List <string> { paramName, paramValue }); } } JObject objectPropertyJObj = new JObject(); objectPropertyJObj.Add("name", objectName); JArray propertyCategoriesJArr = new JArray(); foreach (var propertyCategory in propertyCategoryDic) { JObject propertyCategoryJObj = new JObject(); JArray propertyJArr = new JArray(propertyCategory.Value); propertyCategoryJObj.Add(propertyCategory.Key, propertyJArr); propertyCategoriesJArr.Add(propertyCategoryJObj); } objectPropertyJObj.Add("PropertyCategories", propertyCategoriesJArr); curentPropertyJsObject.Add(objectId, objectPropertyJObj); propertyFileName = currentFileId + ".js.gz"; return(true); }
/// <summary> /// Constructs an HTTP GET request /// </summary> /// <param name="path">Partial URL</param> /// <param name="parameters">Name-value pairs to be appended to the URL</param> public HttpGet(string path, ParameterMap parameters) : base(path, parameters) { HttpMethod = "GET"; ContentType = UrlEncoded; }
private static int?CheckForBadNonTrailingNamedArgument(AnalyzedArguments arguments, ParameterMap argsToParameters, ImmutableArray <ParameterSymbol> parameters) { // Is there any named argument used out-of-position and followed by unnamed arguments? // If the map is trivial then clearly not. if (argsToParameters.IsTrivial) { return(null); } // Find the first named argument which is used out-of-position int foundPosition = -1; int length = arguments.Arguments.Count; for (int i = 0; i < length; i++) { int parameter = argsToParameters[i]; if (parameter != -1 && parameter != i && arguments.Name(i) != null) { foundPosition = i; break; } } if (foundPosition != -1) { // Verify that all the following arguments are named for (int i = foundPosition + 1; i < length; i++) { if (arguments.Name(i) == null) { return(foundPosition); } } } return(null); }
/// <summary> /// Updates an Account Contact /// </summary> /// <param name="accountContactId">Account Contact Id</param> /// <param name="data">Account Contact Data to update</param> /// <returns>true when successful</returns> /// <exception cref="Exception">Exception with the appropriate message</exception> public bool UpdateAccountContact(uint accountContactId, ParameterMap data) { string resource = "/account/contacts/"; if (data == null) throw new Exception("Parameter 'data' cannot be null"); resource += accountContactId; HttpResponse response = RestClient.Put(resource, data); if (response == null) throw new Exception("Request Failed. Unable to get server response"); if (response.Status == Convert.ToInt32(HttpStatusCode.OK)) return true; string errorMessage = String.Format("Status Code={0}, Message={1}", response.Status, response.GetBodyAsString()); throw new Exception("Request Failed : " + errorMessage); }
private static ArgumentAnalysisResult AnalyzeArguments( Symbol symbol, AnalyzedArguments arguments, bool isMethodGroupConversion, bool expanded) { Debug.Assert((object)symbol != null); Debug.Assert(arguments != null); ImmutableArray <ParameterSymbol> parameters = symbol.GetParameters(); bool isVararg = symbol.GetIsVararg(); // The easy out is that we have no named arguments and are in normal form. if (!expanded && arguments.Names.Count == 0) { return(AnalyzeArgumentsForNormalFormNoNamedArguments(parameters, arguments, isMethodGroupConversion, isVararg)); } // We simulate an additional non-optional parameter for a vararg method. int argumentCount = arguments.Arguments.Count; int[] parametersPositions = null; int? unmatchedArgumentIndex = null; bool? unmatchedArgumentIsNamed = null; // Try to map every argument position to a formal parameter position: bool seenNamedParams = false; bool seenOutOfPositionNamedArgument = false; bool isValidParams = IsValidParams(symbol); for (int argumentPosition = 0; argumentPosition < argumentCount; ++argumentPosition) { // We use -1 as a sentinel to mean that no parameter was found that corresponded to this argument. bool isNamedArgument; int parameterPosition = CorrespondsToAnyParameter(parameters, expanded, arguments, argumentPosition, isValidParams, isVararg, out isNamedArgument, ref seenNamedParams, ref seenOutOfPositionNamedArgument) ?? -1; if (parameterPosition == -1 && unmatchedArgumentIndex == null) { unmatchedArgumentIndex = argumentPosition; unmatchedArgumentIsNamed = isNamedArgument; } if (parameterPosition != argumentPosition && parametersPositions == null) { parametersPositions = new int[argumentCount]; for (int i = 0; i < argumentPosition; ++i) { parametersPositions[i] = i; } } if (parametersPositions != null) { parametersPositions[argumentPosition] = parameterPosition; } } ParameterMap argsToParameters = new ParameterMap(parametersPositions, argumentCount); // We have analyzed every argument and tried to make it correspond to a particular parameter. // There are now four questions we must answer: // // (1) Is there any named argument used out-of-position and followed by unnamed arguments? // (2) Is there any argument without a corresponding parameter? // (3) Was there any named argument that specified a parameter that was already // supplied with a positional parameter? // (4) Is there any non-optional parameter without a corresponding argument? // // If the answer to any of these questions is "yes" then the method is not applicable. // It is possible that the answer to any number of these questions is "yes", and so // we must decide which error condition to prioritize when reporting the error, // should we need to report why a given method is not applicable. We prioritize // them in the given order. // (1) Is there any named argument used out-of-position and followed by unnamed arguments? int?badNonTrailingNamedArgument = CheckForBadNonTrailingNamedArgument(arguments, argsToParameters, parameters); if (badNonTrailingNamedArgument != null) { return(ArgumentAnalysisResult.BadNonTrailingNamedArgument(badNonTrailingNamedArgument.Value)); } // (2) Is there any argument without a corresponding parameter? if (unmatchedArgumentIndex != null) { if (unmatchedArgumentIsNamed.Value) { return(ArgumentAnalysisResult.NoCorrespondingNamedParameter(unmatchedArgumentIndex.Value)); } else { return(ArgumentAnalysisResult.NoCorrespondingParameter(unmatchedArgumentIndex.Value)); } } // (3) was there any named argument that specified a parameter that was already // supplied with a positional parameter? int?nameUsedForPositional = NameUsedForPositional(arguments, argsToParameters); if (nameUsedForPositional != null) { return(ArgumentAnalysisResult.NameUsedForPositional(nameUsedForPositional.Value)); } // (4) Is there any non-optional parameter without a corresponding argument? int?requiredParameterMissing = CheckForMissingRequiredParameter(argsToParameters, parameters, isMethodGroupConversion, expanded); if (requiredParameterMissing != null) { return(ArgumentAnalysisResult.RequiredParameterMissing(requiredParameterMissing.Value)); } // __arglist cannot be used with named arguments (as it doesn't have a name) if (arguments.Names.Any() && arguments.Names.Last() != null && isVararg) { return(ArgumentAnalysisResult.RequiredParameterMissing(parameters.Length)); } // We're good; this one might be applicable in the given form. return(expanded ? ArgumentAnalysisResult.ExpandedForm(argsToParameters.ToImmutableArray()) : ArgumentAnalysisResult.NormalForm(argsToParameters.ToImmutableArray())); }
private static int? CheckForMissingRequiredParameter( ParameterMap argsToParameters, ImmutableArray<ParameterSymbol> parameters, bool isMethodGroupConversion, bool expanded) { Debug.Assert(!(expanded && isMethodGroupConversion)); // If we're in the expanded form then the final parameter is always optional, // so we'll just skip it entirely. int count = expanded ? parameters.Length - 1 : parameters.Length; // We'll take an early out here. If the map from arguments to parameters is trivial // and there are as many arguments as parameters in that map, then clearly no // required parameter is missing. if (argsToParameters.IsTrivial && count <= argsToParameters.Length) { return null; } // This is an O(n squared) algorithm, but (1) we avoid allocating any more heap memory, and // (2) n is likely to be small, both because the number of parameters in a method is typically // small, and because methods with many parameters make most of them optional. We could make // this linear easily enough if we needed to but we'd have to allocate more heap memory and // we'd rather not pressure the garbage collector. for (int p = 0; p < count; ++p) { if (CanBeOptional(parameters[p], isMethodGroupConversion)) { continue; } bool found = false; for (int arg = 0; arg < argsToParameters.Length; ++arg) { found = (argsToParameters[arg] == p); if (found) { break; } } if (!found) { return p; } } return null; }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap"/>. /// </summary> /// <param name="parameterMap">The parameter map.</param> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.Name = Names[0]; parameterMap.Data.IsNameSet = true; }
/// <summary> /// Deserializes the specified configuration in a Statement object. /// </summary> /// <param name="modelStore"></param> /// <param name="config">The config.</param> /// <param name="configurationSetting">Default settings.</param> /// <returns></returns> protected void BaseDeserialize(IModelStore modelStore, IConfiguration config, ConfigurationSetting configurationSetting) { nameSpace = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_NAMESPACE); id = configurationSetting.UseStatementNamespaces ? ApplyNamespace(nameSpace, config.Id) : config.Id; cacheModelName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_CACHEMODEL); extendsName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_EXTENDS); listClassName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_LISTCLASS); parameterClassName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_PARAMETERCLASS); parameterMapName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_PARAMETERMAP); resultClassName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_RESULTCLASS); resultMapName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_RESULTMAP); remapResults = ConfigurationUtils.GetBooleanAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_REMAPRESULTS, false); sqlSourceClassName = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_SQLSOURCE); preserveWhitespace = ConfigurationUtils.GetBooleanAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_PRESERVEWHITSPACE, configurationSetting.PreserveWhitespace); // Gets the results Map //resultMaps的属性值会有多个返回值的情况 并且以","分割 if (resultMapName.Length > 0) { string[] ids = resultMapName.Split(','); for (int i = 0; i < ids.Length; i++) { string name = ApplyNamespace(nameSpace, ids[i].Trim()); resultsMap.Add(modelStore.GetResultMap(name)); } } // Gets the results class //resultClass的属性值也会有多个返回值的情况 并且以","分割 if (resultClassName.Length > 0) { string[] classNames = resultClassName.Split(','); for (int i = 0; i < classNames.Length; i++) { resultClass = modelStore.DataExchangeFactory.TypeHandlerFactory.GetType(classNames[i].Trim()); IFactory resultClassFactory = null; if (Type.GetTypeCode(resultClass) == TypeCode.Object && (resultClass.IsValueType == false) && resultClass != typeof(DataRow)) { //用于创建类对象的函数 resultClassFactory = modelStore.DataExchangeFactory.ObjectFactory.CreateFactory(resultClass, Type.EmptyTypes); } IDataExchange dataExchange = modelStore.DataExchangeFactory.GetDataExchangeForClass(resultClass); bool isSimpleType = modelStore.DataExchangeFactory.TypeHandlerFactory.IsSimpleType(resultClass); IResultMap autoMap = new AutoResultMap(resultClass, resultClassFactory, dataExchange, isSimpleType); resultsMap.Add(autoMap); } } // Gets the ParameterMap //去DefaultModelBuilder中的parameterMaps字典中获取对应的参数类 if (parameterMapName.Length > 0) { parameterMap = modelStore.GetParameterMap(parameterMapName); } // Gets the ParameterClass //去TypeHandlerFactory中的typeAlias字典中获取其对应的类别名类 if (parameterClassName.Length > 0) { parameterClass = modelStore.DataExchangeFactory.TypeHandlerFactory.GetType(parameterClassName); } // Gets the listClass if (listClassName.Length > 0) { //去TypeHandlerFactory中的typeAlias字典中获取其对应的类别名类 listClass = modelStore.DataExchangeFactory.TypeHandlerFactory.GetType(listClassName); //创建对应的对象创建工厂类 listClassFactory = modelStore.DataExchangeFactory.ObjectFactory.CreateFactory(listClass, Type.EmptyTypes); } // Gets the CacheModel if (cacheModelName.Length > 0) { //DefaultModelBuilder中的cacheModels字典中获取对应的缓存类 cacheModel = modelStore.GetCacheModel(cacheModelName); } // Gets the SqlSource if (sqlSourceClassName.Length > 0) { //获取SqlSource属性值对应的类 Type sqlSourceType = modelStore.DataExchangeFactory.TypeHandlerFactory.GetType(sqlSourceClassName); //获取创建得到类的工厂 IFactory factory = modelStore.DataExchangeFactory.ObjectFactory.CreateFactory(sqlSourceType, Type.EmptyTypes); //调用构造函数 初始化该类 sqlSource = (ISqlSource)factory.CreateInstance(null); } }
public static void GetEmailTemplates(string moduleAPIName) { //Get instance of EmailTemplatesOperations Class EmailTemplatesOperations emailTemplatesOperations = new EmailTemplatesOperations(); ParameterMap parameter = new ParameterMap(); parameter.Add(GetEmailTemplatesParam.MODULE, moduleAPIName); //Call GetEmailTemplates method APIResponse <ResponseHandler> response = emailTemplatesOperations.GetEmailTemplates(parameter); if (response != null) { //Get the status code from response Console.WriteLine("Status Code: " + response.StatusCode); if (new List <int>() { 204, 304 }.Contains(response.StatusCode)) { Console.WriteLine(response.StatusCode == 204 ? "No Content" : "Not Modified"); return; } //Check if expected response is received if (response.IsExpected) { //Get object from response ResponseHandler responseHandler = response.Object; if (responseHandler is ResponseWrapper) { //Get the received ResponseWrapper instance ResponseWrapper responseWrapper = (ResponseWrapper)responseHandler; //Get the list of obtained EmailTemplate instances List <API.EmailTemplates.EmailTemplate> emailTemplates = responseWrapper.EmailTemplates; foreach (API.EmailTemplates.EmailTemplate emailTemplate in emailTemplates) { //Get the CreatedTime of each EmailTemplate Console.WriteLine("EmailTemplate CreatedTime: " + emailTemplate.CreatedTime); List <Attachment> attachments = emailTemplate.Attachments; if (attachments != null) { foreach (Attachment attachment in attachments) { //Get the Size of each Attachment Console.WriteLine("Attachment Size: " + attachment.Size); //Get the FileId of each Attachment Console.WriteLine("Attachment FileId: " + attachment.FileId); //Get the FileName of each Attachment Console.WriteLine("Attachment FileName: " + attachment.FileName); //Get the Id of each Attachment Console.WriteLine("Attachment ID: " + attachment.Id); } } //Get the Subject of each EmailTemplate Console.WriteLine("EmailTemplate Subject: " + emailTemplate.Subject); API.Modules.Module module = emailTemplate.Module; if (module != null) { //Get the Module Name of the EmailTemplate Console.WriteLine("EmailTemplate Module Name : " + module.APIName); //Get the Module Id of the EmailTemplate Console.WriteLine("EmailTemplate Module Id : " + module.Id); } //Get the Type of each EmailTemplate Console.WriteLine("EmailTemplate Type: " + emailTemplate.Type); //Get the CreatedBy User instance of each EmailTemplate User createdBy = emailTemplate.CreatedBy; //Check if createdBy is not null if (createdBy != null) { //Get the Id of the CreatedBy User Console.WriteLine("EmailTemplate Created By User-ID: " + createdBy.Id); //Get the Name of the CreatedBy User Console.WriteLine("EmailTemplate Created By User-Name: " + createdBy.Name); Console.WriteLine("EmailTemplate Created By User-Email : " + createdBy.Email); } //Get the ModifiedTime of each EmailTemplate Console.WriteLine("EmailTemplate ModifiedTime: " + emailTemplate.ModifiedTime); //Get the Folder instance of each EmailTemplate API.EmailTemplates.EmailTemplate folder = emailTemplate.Folder; //Check if folder is not null if (folder != null) { //Get the Id of the Folder Console.WriteLine("EmailTemplate Folder Id: " + folder.Id); //Get the Name of the Folder Console.WriteLine("EmailTemplate Folder Name: " + folder.Name); } //Get the LastUsageTime of each EmailTemplate Console.WriteLine("EmailTemplate LastUsageTime: " + emailTemplate.LastUsageTime); //Get the Associated of each EmailTemplate Console.WriteLine("EmailTemplate Associated: " + emailTemplate.Associated); //Get the name of each EmailTemplate Console.WriteLine("EmailTemplate Name: " + emailTemplate.Name); //Get the ConsentLinked of each EmailTemplate Console.WriteLine("EmailTemplate ConsentLinked: " + emailTemplate.ConsentLinked); //Get the modifiedBy User instance of each EmailTemplate User modifiedBy = emailTemplate.ModifiedBy; //Check if modifiedBy is not null if (modifiedBy != null) { //Get the ID of the ModifiedBy User Console.WriteLine("EmailTemplate Modified By User-ID: " + modifiedBy.Id); //Get the Name of the CreatedBy User Console.WriteLine("EmailTemplate Modified By User-Name: " + modifiedBy.Name); Console.WriteLine("EmailTemplate Modified By User-Email : " + modifiedBy.Email); } //Get the ID of each EmailTemplate Console.WriteLine("EmailTemplate ID: " + emailTemplate.Id); //Get the EditorMode each EmailTemplate Console.WriteLine("EmailTemplate EditorMode: " + emailTemplate.EditorMode); Console.WriteLine("EmailTemplate Content: " + emailTemplate.Content); // Get the Description of each EmailTemplate Console.WriteLine("EmailTemplate Description: " + emailTemplate.Description); // Get the EditorMode of each EmailTemplate Console.WriteLine("EmailTemplate EditorMode: " + emailTemplate.EditorMode); //Get the Favorite of each EmailTemplate Console.WriteLine("EmailTemplate Favorite: " + emailTemplate.Favorite); // Get the Favourite of each EmailTemplate Console.WriteLine("EmailTemplate Subject: " + emailTemplate.Subject); } API.Record.Info info = responseWrapper.Info; Console.WriteLine("EmailTemplate Info PerPage : " + info.PerPage); Console.WriteLine("EmailTemplate Info Count : " + info.Count); Console.WriteLine("EmailTemplate Info Page : " + info.Page); Console.WriteLine("EmailTemplate Info MoreRecords : " + info.MoreRecords); } //Check if the request returned an exception else if (responseHandler is APIException) { //Get the received APIException instance APIException exception = (APIException)responseHandler; //Get the Status Console.WriteLine("Status: " + exception.Status.Value); //Get the Code Console.WriteLine("Code: " + exception.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in exception.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + exception.Message.Value); } } else { //If response is not as expected //Get model object from response Model responseObject = response.Model; //Get the response object's class Type type = responseObject.GetType(); //Get all declared fields of the response class Console.WriteLine("Type is: {0}", type.Name); PropertyInfo[] props = type.GetProperties(); Console.WriteLine("Properties (N = {0}):", props.Length); foreach (var prop in props) { if (prop.GetIndexParameters().Length == 0) { Console.WriteLine("{0} ({1}) in {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject)); } else { Console.WriteLine("{0} ({1}) in <Indexed>", prop.Name, prop.PropertyType.Name); } } } } }
public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null) { RefitSettings = refitSettings ?? new RefitSettings(); Type = targetInterface; Name = methodInfo.Name; MethodInfo = methodInfo; var hma = methodInfo.GetCustomAttributes(true) .OfType <HttpMethodAttribute>() .First(); HttpMethod = hma.Method; RelativePath = hma.Path; IsMultipart = methodInfo.GetCustomAttributes(true) .OfType <MultipartAttribute>() .Any(); VerifyUrlPathIsSane(RelativePath); DetermineReturnTypeInfo(methodInfo); // Exclude cancellation token parameters from this list var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList(); ParameterInfoMap = parameterList .Select((parameter, index) => new { index, parameter }) .ToDictionary(x => x.index, x => x.parameter); ParameterMap = BuildParameterMap(RelativePath, parameterList); BodyParameterInfo = FindBodyParameter(parameterList, IsMultipart, hma.Method); Headers = ParseHeaders(methodInfo); HeaderParameterMap = BuildHeaderParameterMap(parameterList); // get names for multipart attachments AttachmentNameMap = new Dictionary <int, Tuple <string, string> >(); if (IsMultipart) { for (var i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i)) { continue; } var attachmentName = GetAttachmentNameForParameter(parameterList[i]); if (attachmentName == null) { continue; } AttachmentNameMap[i] = Tuple.Create(attachmentName, GetUrlNameForParameter(parameterList[i]).ToLowerInvariant()); } } QueryParameterMap = new Dictionary <int, string>(); for (var i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item3 == i)) { continue; } if (parameterList[i].GetCustomAttribute <QueryAttribute>() != null) { var typeInfo = parameterList[i].ParameterType.GetTypeInfo(); var isValueType = typeInfo.IsValueType && !typeInfo.IsPrimitive && !typeInfo.IsEnum; if (typeInfo.IsArray || parameterList[i].ParameterType.GetInterfaces().Contains(typeof(IEnumerable)) || isValueType) { QueryParameterMap.Add(QueryParameterMap.Count, GetUrlNameForParameter(parameterList[i])); } else { foreach (var member in parameterList[i].ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { QueryParameterMap.Add(QueryParameterMap.Count, GetUrlNameForMember(member)); } } continue; } QueryParameterMap.Add(QueryParameterMap.Count, GetUrlNameForParameter(parameterList[i])); } var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList(); if (ctParams.Count > 1) { throw new ArgumentException($"Argument list to method \"{methodInfo.Name}\" can only contain a single CancellationToken"); } CancellationToken = ctParams.FirstOrDefault(); IsApiResponse = SerializedReturnType.GetTypeInfo().IsGenericType&& SerializedReturnType.GetGenericTypeDefinition() == typeof(ApiResponse <>); }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap"/>. /// </summary> /// <param name="parameterMap">The parameter map.</param> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.Index = Index; parameterMap.Data.IsIndexSet = true; }
/// <summary> /// Process the Sql cpmmand text statement (Build ISql) /// </summary> /// <param name="statementConfiguration">The statement configuration.</param> /// <param name="statement">The statement.</param> private void ProcessSqlStatement(IConfiguration statementConfiguration, IStatement statement) { if (dynamicSqlEngine != null) { statement.SqlSource = dynamicSqlEngine; } if (statement.SqlSource != null) { #region sqlSource - external processor string commandText = string.Empty; if (statementConfiguration.Children.Count > 0) { IConfiguration child = statementConfiguration.Children[0]; if (child.Type == ConfigConstants.ELEMENT_TEXT || child.Type == ConfigConstants.ELEMENT_CDATA) { // pass the unformated sql to the external processor commandText = child.Value; } } ExternalSql externalSql = new ExternalSql(modelStore, statement, commandText); statement.Sql = externalSql; #endregion } else { #region default - internal processor bool isDynamic = false; DynamicSql dynamic = new DynamicSql( modelStore.SessionFactory.DataSource.DbProvider.UsePositionalParameters, modelStore.DBHelperParameterCache, modelStore.DataExchangeFactory, statement); StringBuilder sqlBuffer = new StringBuilder(); isDynamic = ParseDynamicTags(statementConfiguration, dynamic, sqlBuffer, isDynamic, false, statement); if (isDynamic) { statement.Sql = dynamic; } else { string sqlText = sqlBuffer.ToString(); string newSqlCommandText = string.Empty; ParameterMap map = inlineParemeterMapBuilder.BuildInlineParemeterMap(statement, sqlText, out newSqlCommandText); if (map != null) { statement.ParameterMap = map; } if (SimpleDynamicSql.IsSimpleDynamicSql(newSqlCommandText)) { statement.Sql = new SimpleDynamicSql( modelStore.DataExchangeFactory, modelStore.DBHelperParameterCache, newSqlCommandText, statement); } else { if (statement is Procedure) { statement.Sql = new ProcedureSql( modelStore.DataExchangeFactory, modelStore.DBHelperParameterCache, newSqlCommandText, statement); // Could not call BuildPreparedStatement for procedure because when NUnit Test // the database is not here (but in theory procedure must be prepared like statement) // It's even better as we can then switch DataSource. } else if (statement is Statement) { statement.Sql = new StaticSql( modelStore.DataExchangeFactory, modelStore.DBHelperParameterCache, statement); // this does not open a connection to the database ISession session = modelStore.SessionFactory.OpenSession(); ((StaticSql)statement.Sql).BuildPreparedStatement(session, newSqlCommandText); session.Close(); } } } #endregion } Contract.Ensure.That(statement.Sql, Is.Not.Null).When("process Sql statement."); }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap"/>. /// </summary> /// <param name="parameterMap">The parameter map.</param> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.TypeConverterOptions.BooleanFalseValues.Clear(); parameterMap.Data.TypeConverterOptions.BooleanFalseValues.AddRange(FalseValues); }
/// <summary>The method to get all contact roles of deal</summary> /// <param name="dealId">long?</param> /// <param name="paramInstance">Instance of ParameterMap</param> /// <returns>Instance of APIResponse<RecordResponseHandler></returns> public APIResponse <RecordResponseHandler> GetAllContactRolesOfDeal(long?dealId, ParameterMap paramInstance) { CommonAPIHandler handlerInstance = new CommonAPIHandler(); string apiPath = ""; apiPath = string.Concat(apiPath, "/crm/v2.1/Deals/"); apiPath = string.Concat(apiPath, dealId.ToString()); apiPath = string.Concat(apiPath, "/Contact_Roles"); handlerInstance.APIPath = apiPath; handlerInstance.HttpMethod = Constants.REQUEST_METHOD_GET; handlerInstance.CategoryMethod = Constants.REQUEST_CATEGORY_READ; handlerInstance.Param = paramInstance; handlerInstance.ModuleAPIName = "Contacts"; Utility.GetFields("Contacts", handlerInstance); return(handlerInstance.APICall <RecordResponseHandler>(typeof(RecordResponseHandler), "application/json")); }
public virtual string GenerateMappingAssigment( ParameterMap <TParameterFrom, TParameterTo> map, string variableSourceName, string destinationVariableName) { return(destinationVariableName + "." + GenerateMappingAssigment(map, variableSourceName)); }
public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null) { RefitSettings = refitSettings ?? new RefitSettings(); Type = targetInterface; Name = methodInfo.Name; MethodInfo = methodInfo; var hma = methodInfo.GetCustomAttributes(true) .OfType <HttpMethodAttribute>() .First(); HttpMethod = hma.Method; RelativePath = hma.Path; IsMultipart = methodInfo.GetCustomAttributes(true) .OfType <MultipartAttribute>() .Any(); VerifyUrlPathIsSane(RelativePath); DetermineReturnTypeInfo(methodInfo); // Exclude cancellation token parameters from this list var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList(); ParameterInfoMap = parameterList .Select((parameter, index) => new { index, parameter }) .ToDictionary(x => x.index, x => x.parameter); ParameterMap = BuildParameterMap(RelativePath, parameterList); BodyParameterInfo = FindBodyParameter(parameterList, IsMultipart, hma.Method); Headers = ParseHeaders(methodInfo); HeaderParameterMap = BuildHeaderParameterMap(parameterList); // get names for multipart attachments AttachmentNameMap = new Dictionary <int, Tuple <string, string> >(); if (IsMultipart) { for (var i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i)) { continue; } var attachmentName = GetAttachmentNameForParameter(parameterList[i]); if (attachmentName == null) { continue; } AttachmentNameMap[i] = Tuple.Create(attachmentName, GetUrlNameForParameter(parameterList[i]).ToLowerInvariant()); } } QueryParameterMap = new Dictionary <int, string>(); for (var i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item3 == i)) { continue; } QueryParameterMap[i] = GetUrlNameForParameter(parameterList[i]); } var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList(); if (ctParams.Count > 1) { throw new ArgumentException("Argument list can only contain a single CancellationToken"); } CancellationToken = ctParams.FirstOrDefault(); }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap" />. /// </summary> /// <param name="parameterMap">The parameter map.</param> /// <exception cref="NotImplementedException"></exception> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.IsOptional = true; }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap" />. /// </summary> /// <param name="parameterMap">The parameter map.</param> /// <exception cref="NotImplementedException"></exception> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.TypeConverterOptions.NumberStyles = NumberStyles; }
public void Modify(ParameterMap parameterMap) { _signatureGenerator.AddSignature(parameterMap); }
public void InitializeParametersFromMicrophone() { m_parameters = m_parent.PlayerModel.MicrophoneParameters.Copy(forceMutable: true); m_baseParameters = m_parameters.Copy(); }
/// <summary> /// The method is used to collect template information, specifying the New Window Parameters /// </summary> private void CollectTemplateInfo() { List <Wall> walls = Utility.GetElements <Wall>(m_application, m_document); m_wallThickness = walls[0].Width; ParameterMap paraMap = walls[0].ParametersMap; Parameter wallheightPara = walls[0].get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);//paraMap.get_Item("Unconnected Height"); if (wallheightPara != null) { m_wallHeight = wallheightPara.AsDouble(); } LocationCurve location = walls[0].Location as LocationCurve; m_wallWidth = location.Curve.Length; m_windowInset = m_wallThickness / 10; FamilyType type = m_familyManager.CurrentType; FamilyParameter heightPara = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT); FamilyParameter widthPara = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH); FamilyParameter sillHeightPara = m_familyManager.get_Parameter("Default Sill Height"); if (type.HasValue(heightPara)) { switch (heightPara.StorageType) { case StorageType.Double: m_height = type.AsDouble(heightPara).Value; break; case StorageType.Integer: m_height = type.AsInteger(heightPara).Value; break; } } if (type.HasValue(widthPara)) { switch (widthPara.StorageType) { case StorageType.Double: m_width = type.AsDouble(widthPara).Value; break; case StorageType.Integer: m_width = type.AsDouble(widthPara).Value; break; } } if (type.HasValue(sillHeightPara)) { switch (sillHeightPara.StorageType) { case StorageType.Double: m_sillHeight = type.AsDouble(sillHeightPara).Value; break; case StorageType.Integer: m_sillHeight = type.AsDouble(sillHeightPara).Value; break; } } //set the height,width and sillheight parameter of the opening m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT), m_height); m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH), m_width); m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"), m_sillHeight); //get materials FilteredElementCollector elementCollector = new FilteredElementCollector(m_document); elementCollector.WherePasses(new ElementClassFilter(typeof(Material))); IList <Element> materials = elementCollector.ToElements(); foreach (Element materialElement in materials) { Material material = materialElement as Material; m_para.GlassMaterials.Add(material.Name); m_para.FrameMaterials.Add(material.Name); } //get categories Categories categories = m_document.Settings.Categories; Category category = categories.get_Item(BuiltInCategory.OST_Windows); CategoryNameMap cnm = category.SubCategories; m_frameCat = categories.get_Item(BuiltInCategory.OST_WindowsFrameMullionProjection); m_glassCat = categories.get_Item(BuiltInCategory.OST_WindowsGlassProjection); //get referenceplanes List <ReferencePlane> planes = Utility.GetElements <ReferencePlane>(m_application, m_document); foreach (ReferencePlane p in planes) { if (p.Name.Equals("Sash")) { m_sashPlane = p; } if (p.Name.Equals("Exterior")) { m_exteriorPlane = p; } if (p.Name.Equals("Center (Front/Back)")) { m_centerPlane = p; } if (p.Name.Equals("Top") || p.Name.Equals("Head")) { m_topPlane = p; } if (p.Name.Equals("Sill") || p.Name.Equals("Bottom")) { m_sillPlane = p; } if (p.Name.Equals("Left")) { m_leftPlane = p; } if (p.Name.Equals("Right")) { m_rightPlane = p; } } }
/// <summary> /// Updates the metadata of a given library and returns the updated library. /// </summary> /// <param name="libraryId">The content library Id</param> /// <param name="parameterMap"> /// The Content Library data. A key-value pair data structure <see cref="ParameterMap" /> /// </param> /// <returns> /// <see cref="ContentLibrary" /> /// </returns> /// <exception cref="Exception">Exception with the appropriate message.</exception> public ContentLibrary UpdateContentLibrary(string libraryId, ParameterMap parameterMap) { if (!libraryId.IsGuid()) throw new Exception("libraryId must not be null and be a valid UUID"); if (parameterMap == null) throw new Exception("Parameter 'parameterMap' cannot be null"); return UpdateContentLibrary(new Guid(libraryId), parameterMap); }
public void InitializeParametersFromLoops() { m_parameters = AllEffects.CreateParameterMap(); m_parent.UpdateParameterMapFromTouchedLoopieValues(m_parameters); m_baseParameters = m_parameters.Copy(); }
/// <summary> /// Applies configuration to the given <see cref="ParameterMap" />. /// </summary> /// <param name="parameterMap">The parameter map.</param> public void ApplyTo(ParameterMap parameterMap) { parameterMap.Data.TypeConverter = TypeConverter; }
void DragParameter(Moment now, ParameterMap other, Parameter p, float value) { // We have a tiny gutter around 0, since some effects have a sharp step from 0 to anything else and // this sounds more jarring if it happens with no tolerance. if (value < 0.1f) { value = 0; } // We deliberately use SSA-like structure here to be able to see all the intermediate values in the debugger. // First, get the endpoint value of p float pValue = p[now.Time]; // Next, get the base value of p, in normalized terms ParameterDescription pDesc = p.Description; float pBaseValueNormalized = pDesc.Min == pDesc.Max ? pDesc.Base : (pDesc.Base - pDesc.Min) / (pDesc.Max - pDesc.Min); // Now we want to move from pBaseValueNormalized towards pValue, by an amount proportional to dragValue float newDestValue = pBaseValueNormalized + ((pValue - pBaseValueNormalized) * value); Parameter dest = m_parameters[p.Description]; if (m_baseParameters.Contains(p.Description)) { float baseValue = m_baseParameters[p.Description][now.Time]; float averagedDestValue = newDestValue; if (other != null && other.Contains(p.Description)) { averagedDestValue = (averagedDestValue + other[p.Description][now.Time]) / 2; } float adjustedDestValue = averagedDestValue; if (!p.Description.Absolute) { // only grow upwards from the base value, proportionately to how big the base value already is adjustedDestValue = baseValue + (averagedDestValue * (1 - baseValue)); } Spam.Model.WriteLine("parameter " + p.Description.Name + ": pValue " + pValue + ", pBVN " + pBaseValueNormalized + ", baseValue " + baseValue + ", adjustedDestValue " + adjustedDestValue); // clamp to [0, 1] because we may overshoot a bit with this algorithm dest[now.Time] = Math.Max(0, Math.Min(1f, adjustedDestValue)); } }
/// <summary>The method to get record</summary> /// <param name="id">long?</param> /// <param name="moduleAPIName">string</param> /// <param name="paramInstance">Instance of ParameterMap</param> /// <param name="headerInstance">Instance of HeaderMap</param> /// <returns>Instance of APIResponse<ResponseHandler></returns> public APIResponse <ResponseHandler> GetRecord(long?id, string moduleAPIName, ParameterMap paramInstance, HeaderMap headerInstance) { CommonAPIHandler handlerInstance = new CommonAPIHandler(); string apiPath = ""; apiPath = string.Concat(apiPath, "/crm/v2/"); apiPath = string.Concat(apiPath, moduleAPIName.ToString()); apiPath = string.Concat(apiPath, "/"); apiPath = string.Concat(apiPath, id.ToString()); handlerInstance.APIPath = apiPath; handlerInstance.HttpMethod = Constants.REQUEST_METHOD_GET; handlerInstance.CategoryMethod = Constants.REQUEST_CATEGORY_READ; handlerInstance.Param = paramInstance; handlerInstance.Header = headerInstance; Utility.GetFields(moduleAPIName); handlerInstance.ModuleAPIName = moduleAPIName; return(handlerInstance.APICall <ResponseHandler>(typeof(ResponseHandler), "application/json")); }
public void Apply(ParameterMap parameters, Moment now) { foreach (HolofunkEffect effect in m_effects) { effect.Apply(parameters, now); } }
/// <summary>The method to get deleted records</summary> /// <param name="moduleAPIName">string</param> /// <param name="paramInstance">Instance of ParameterMap</param> /// <param name="headerInstance">Instance of HeaderMap</param> /// <returns>Instance of APIResponse<DeletedRecordsHandler></returns> public APIResponse <DeletedRecordsHandler> GetDeletedRecords(string moduleAPIName, ParameterMap paramInstance, HeaderMap headerInstance) { CommonAPIHandler handlerInstance = new CommonAPIHandler(); string apiPath = ""; apiPath = string.Concat(apiPath, "/crm/v2/"); apiPath = string.Concat(apiPath, moduleAPIName.ToString()); apiPath = string.Concat(apiPath, "/deleted"); handlerInstance.APIPath = apiPath; handlerInstance.HttpMethod = Constants.REQUEST_METHOD_GET; handlerInstance.CategoryMethod = Constants.REQUEST_CATEGORY_READ; handlerInstance.Param = paramInstance; handlerInstance.Header = headerInstance; return(handlerInstance.APICall <DeletedRecordsHandler>(typeof(DeletedRecordsHandler), "application/json")); }
/// <summary>Initialize the destination map with the average of the parameter values of all touched /// loopies (and the microphone if applicable); then have all touched loopies (and the microphone if /// applicable) share those newly initialized parameters.</summary> internal void UpdateParameterMapFromTouchedLoopieValues(ParameterMap dest) { // initialize the parameters from the average of the values in the loopies & mike int count = TouchedLoopies.Count + 1; IEnumerable<ParameterMap> touchedParameterMaps = TouchedLoopies.Select(loopie => loopie.Track.Parameters); /* MIKEFFECTS: if (MicrophoneSelected) { touchedParameterMaps = touchedParameterMaps.Concat(new ParameterMap[] { MicrophoneParameters }); } */ dest.SetFromAverage(HolofunkModel.Clock.Time(0), touchedParameterMaps); }
/// <summary>The method to get mass update status</summary> /// <param name="moduleAPIName">string</param> /// <param name="paramInstance">Instance of ParameterMap</param> /// <returns>Instance of APIResponse<MassUpdateResponseHandler></returns> public APIResponse <MassUpdateResponseHandler> GetMassUpdateStatus(string moduleAPIName, ParameterMap paramInstance) { CommonAPIHandler handlerInstance = new CommonAPIHandler(); string apiPath = ""; apiPath = string.Concat(apiPath, "/crm/v2/"); apiPath = string.Concat(apiPath, moduleAPIName.ToString()); apiPath = string.Concat(apiPath, "/actions/mass_update"); handlerInstance.APIPath = apiPath; handlerInstance.HttpMethod = Constants.REQUEST_METHOD_GET; handlerInstance.CategoryMethod = Constants.REQUEST_CATEGORY_READ; handlerInstance.Param = paramInstance; return(handlerInstance.APICall <MassUpdateResponseHandler>(typeof(MassUpdateResponseHandler), "application/json")); }
/// <summary> /// Updates Account Settings or Preferences and returns the updated preference object. /// </summary> /// <param name="settingId">The Account Setting ID</param> /// <param name="data">The setting data to update <see cref="ParameterMap" /></param> /// <returns>Settings object <see cref="Settings" /></returns> /// <exception cref="Exception">Exception with the appropriate message</exception> public Settings UpdateAccountSettings(uint settingId, ParameterMap data) { string resource = "/account/settings/"; if (data == null) throw new Exception("Parameter 'data' cannot be null"); resource += settingId; HttpResponse response = RestClient.Put(resource, data); if (response == null) throw new Exception("Request Failed. Unable to get server response"); if (response.Status == Convert.ToInt32(HttpStatusCode.OK)) return new Settings(JsonConvert.DeserializeObject<ApiDictionary>(response.GetBodyAsString())); string errorMessage = String.Format("Status Code={0}, Message={1}", response.Status, response.GetBodyAsString()); throw new Exception("Request Failed : " + errorMessage); }
/// <summary>The method to delete record</summary> /// <param name="id">long?</param> /// <param name="moduleAPIName">string</param> /// <param name="paramInstance">Instance of ParameterMap</param> /// <param name="headerInstance">Instance of HeaderMap</param> /// <returns>Instance of APIResponse<ActionHandler></returns> public APIResponse <ActionHandler> DeleteRecord(long?id, string moduleAPIName, ParameterMap paramInstance, HeaderMap headerInstance) { CommonAPIHandler handlerInstance = new CommonAPIHandler(); string apiPath = ""; apiPath = string.Concat(apiPath, "/crm/v2/"); apiPath = string.Concat(apiPath, moduleAPIName.ToString()); apiPath = string.Concat(apiPath, "/"); apiPath = string.Concat(apiPath, id.ToString()); handlerInstance.APIPath = apiPath; handlerInstance.HttpMethod = Constants.REQUEST_METHOD_DELETE; handlerInstance.CategoryMethod = Constants.REQUEST_METHOD_DELETE; handlerInstance.Param = paramInstance; handlerInstance.Header = headerInstance; return(handlerInstance.APICall <ActionHandler>(typeof(ActionHandler), "application/json")); }
private static int? NameUsedForPositional(AnalyzedArguments arguments, ParameterMap argsToParameters) { // Was there a named argument used for a previously-supplied positional argument? // If the map is trivial then clearly not. if (argsToParameters.IsTrivial) { return null; } // PERFORMANCE: This is an O(n-squared) algorithm, but n will typically be small. We could rewrite this // PERFORMANCE: as a linear algorithm if we wanted to allocate more memory. for (int argumentPosition = 0; argumentPosition < argsToParameters.Length; ++argumentPosition) { if (arguments.Name(argumentPosition) != null) { for (int i = 0; i < argumentPosition; ++i) { if (arguments.Name(i) == null) { if (argsToParameters[argumentPosition] == argsToParameters[i]) { // Error; we've got a named argument that corresponds to // a previously-given positional argument. return argumentPosition; } } } } } return null; }
public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null) { RefitSettings = refitSettings ?? new RefitSettings(); Type = targetInterface; Name = methodInfo.Name; MethodInfo = methodInfo; var hma = methodInfo.GetCustomAttributes(true) .OfType <HttpMethodAttribute>() .First(); HttpMethod = hma.Method; RelativePath = hma.Path; IsMultipart = methodInfo.GetCustomAttributes(true) .OfType <MultipartAttribute>() .Any(); verifyUrlPathIsSane(RelativePath); determineReturnTypeInfo(methodInfo); var parameterList = methodInfo.GetParameters().ToList(); ParameterInfoMap = parameterList .Select((parameter, index) => new { index, parameter }) .ToDictionary(x => x.index, x => x.parameter); ParameterMap = buildParameterMap(RelativePath, parameterList); BodyParameterInfo = findBodyParameter(parameterList, IsMultipart); Headers = parseHeaders(methodInfo); HeaderParameterMap = buildHeaderParameterMap(parameterList); // get names for multipart attachments AttachmentNameMap = new Dictionary <int, string>(); if (IsMultipart) { for (int i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i)) { continue; } var attachmentName = getAttachmentNameForParameter(parameterList[i]); if (attachmentName == null) { continue; } AttachmentNameMap[i] = attachmentName; } } QueryParameterMap = new Dictionary <int, string>(); for (int i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item2 == i) || AttachmentNameMap.ContainsKey(i)) { continue; } QueryParameterMap[i] = getUrlNameForParameter(parameterList[i]); } }
private static ArgumentAnalysisResult AnalyzeArguments( Symbol symbol, AnalyzedArguments arguments, bool isMethodGroupConversion, bool expanded) { Debug.Assert((object)symbol != null); Debug.Assert(arguments != null); ImmutableArray<ParameterSymbol> parameters = symbol.GetParameters(); // The easy out is that we have no named arguments and are in normal form. if (!expanded && arguments.Names.Count == 0) { return AnalyzeArgumentsForNormalFormNoNamedArguments(parameters, arguments, isMethodGroupConversion, symbol.GetIsVararg()); } // We simulate an additional non-optional parameter for a vararg method. int argumentCount = arguments.Arguments.Count; int[] parametersPositions = null; int? unmatchedArgumentIndex = null; bool? unmatchedArgumentIsNamed = null; // Try to map every argument position to a formal parameter position: for (int argumentPosition = 0; argumentPosition < argumentCount; ++argumentPosition) { // We use -1 as a sentinel to mean that no parameter was found that corresponded to this argument. bool isNamedArgument; int parameterPosition = CorrespondsToAnyParameter(parameters, expanded, arguments, argumentPosition, out isNamedArgument) ?? -1; if (parameterPosition == -1 && unmatchedArgumentIndex == null) { unmatchedArgumentIndex = argumentPosition; unmatchedArgumentIsNamed = isNamedArgument; } if (parameterPosition != argumentPosition && parametersPositions == null) { parametersPositions = new int[argumentCount]; for (int i = 0; i < argumentPosition; ++i) { parametersPositions[i] = i; } } if (parametersPositions != null) { parametersPositions[argumentPosition] = parameterPosition; } } ParameterMap argsToParameters = new ParameterMap(parametersPositions, argumentCount); // We have analyzed every argument and tried to make it correspond to a particular parameter. // There are now three questions we must answer: // // (1) Is there any argument without a corresponding parameter? // (2) was there any named argument that specified a parameter that was already // supplied with a positional parameter? // (3) Is there any non-optional parameter without a corresponding argument? // // If the answer to any of these questions is "yes" then the method is not applicable. // It is possible that the answer to any number of these questions is "yes", and so // we must decide which error condition to prioritize when reporting the error, // should we need to report why a given method is not applicable. We prioritize // them in the given order. // (1) Is there any argument without a corresponding parameter? if (unmatchedArgumentIndex != null) { if (unmatchedArgumentIsNamed.Value) { return ArgumentAnalysisResult.NoCorrespondingNamedParameter(unmatchedArgumentIndex.Value); } else { return ArgumentAnalysisResult.NoCorrespondingParameter(unmatchedArgumentIndex.Value); } } // (2) was there any named argument that specified a parameter that was already // supplied with a positional parameter? int? nameUsedForPositional = NameUsedForPositional(arguments, argsToParameters); if (nameUsedForPositional != null) { return ArgumentAnalysisResult.NameUsedForPositional(nameUsedForPositional.Value); } // (3) Is there any non-optional parameter without a corresponding argument? int? requiredParameterMissing = CheckForMissingRequiredParameter(argsToParameters, parameters, isMethodGroupConversion, expanded); if (requiredParameterMissing != null) { return ArgumentAnalysisResult.RequiredParameterMissing(requiredParameterMissing.Value); } // __arglist cannot be used with named arguments (as it doesn't have a name) if (arguments.Names.Count != 0 && symbol.GetIsVararg()) { return ArgumentAnalysisResult.RequiredParameterMissing(parameters.Length); } // We're good; this one might be applicable in the given form. return expanded ? ArgumentAnalysisResult.ExpandedForm(argsToParameters.ToImmutableArray()) : ArgumentAnalysisResult.NormalForm(argsToParameters.ToImmutableArray()); }
/// <summary>The method to delete related records using external id</summary> /// <param name="externalValue">string</param> /// <param name="paramInstance">Instance of ParameterMap</param> /// <returns>Instance of APIResponse<ActionHandler></returns> public APIResponse <ActionHandler> DeleteRelatedRecordsUsingExternalId(string externalValue, ParameterMap paramInstance) { CommonAPIHandler handlerInstance = new CommonAPIHandler(); string apiPath = ""; apiPath = string.Concat(apiPath, "/crm/v2.1/"); apiPath = string.Concat(apiPath, this.moduleAPIName.ToString()); apiPath = string.Concat(apiPath, "/"); apiPath = string.Concat(apiPath, externalValue.ToString()); apiPath = string.Concat(apiPath, "/"); apiPath = string.Concat(apiPath, this.relatedListAPIName.ToString()); handlerInstance.APIPath = apiPath; handlerInstance.HttpMethod = Constants.REQUEST_METHOD_DELETE; handlerInstance.CategoryMethod = Constants.REQUEST_METHOD_DELETE; handlerInstance.AddHeader(new Header <string>("X-EXTERNAL", "com.zoho.crm.api.RelatedRecords.DeleteRelatedRecordsUsingExternalIDHeader"), this.xExternal); handlerInstance.Param = paramInstance; Utility.GetRelatedLists(this.relatedListAPIName, this.moduleAPIName, handlerInstance); return(handlerInstance.APICall <ActionHandler>(typeof(ActionHandler), "application/json")); }