public frmAction(CRM_JURISDICTION_GROUP[] nodes) { InitializeComponent(); JList = nodes; int btnWidth = rect.Width > 880 ? 220:180; int magr = (rect.Width - btnWidth * 4) / 5; //根据权限动态生成按钮并添加事件 for (int i = 0; i < JList[0].CRM_HG_RIGHTList.Length; i++) { Button btn = new Button(); //magr + rect.Width / 4 * (i % 4) factory.configButton(btn, new Size(btnWidth, 90), new Point(magr + (magr + btnWidth) * (i % 4), i / 4 * 100), JList[0].CRM_HG_RIGHTList[i].RIGHTNAME, JList[0].CRM_HG_RIGHTList[i].RIGHTID); btn.FlatStyle = FlatStyle.Popup; btn.Click += new System.EventHandler(this.btn_Click); //this.Controls.Add(btn); panel1.Controls.Add(btn); } // Label xxLabel = new Label(); string ip = new OperationConfig().valueItem("RemoteAddress").Split('/')[2]; factory.configLabel(xxLabel, new Size(rect.Width, 21), new Point(15, 15), new Font(q(Msg_Type.fonttype), 12), string.Format(q(Msg_Type.frmActionTitle), getUserInfo("username"), ip));//"当前帐号:" + getUserInfo("username") + ",服务器地址:" + ip) this.Controls.Add(xxLabel); //Label ipLabel = new Label(); //OperationConfig oCinfig = new OperationConfig(); //factory.configLabel(ipLabel, new Size(300, 21), new Point(15, 35), new Font(q(Msg_Type.fonttype), 12), "当前服务器:" + oCinfig.valueItem("RemoteAddress")); //ipLabel.BringToFront(); //this.Controls.Add(ipLabel); }
void UpdateCardInfo() { try { this.Cursor = Cursors.Wait; if (OperationConfig.GetValue("CardSort") == "USB") { Getuserinfo(backcard); } //else //{ // filterdata.CardId = backcard; // filterdata.resetCard(); // string cardid = filterdata.getcardid(); // if (cardid == "") // return; // Getuserinfo(cardid); // filterdata.resetid(""); //} //this.tb_wrenchbarcode.Focus(); //showjuser(_juser); //showzuser(_zuer); //this.Cursor = Cursors.Arrow; } catch { } }
//void OnTimedEvent(object serder, EventArgs e) //{ // //this.Dispatcher.Invoke(DispatcherPriority.Normal, // // new TimerDispatcherDelegate(UpdateCardInfo)); //} void UpdateCardInfo() { try { if (OperationConfig.GetValue("CardSort") == "USB") { this.tb_cardid.Text = backcard; } else { filterdata.CardId = backcard; filterdata.resetCard(); string cardid = filterdata.getcardid(); if (cardid == "") { return; } filterdata.resetid(""); this.tb_cardid.Text = cardid; } } catch { } }
public void TestContentTypeOverride() { RequestMap requestMap = new RequestMap("{\n\"id\":\"1\"\n}"); RequestMap responseMap = new RequestMap("{\"Account\":{\"Status\":\"true\",\"Listed\":\"true\",\"ReasonCode\":\"S\",\"Reason\":\"STOLEN\"}}"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); // new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081", null, true, "text/json"); RestyRequest request = controller.GetRequest(config, metadata, new TestBaseObject(requestMap)); Assert.AreEqual("http://locahost:8081/test1", request.AbsoluteUrl.ToString()); Assert.AreEqual(true, request.HasBody); Assert.AreEqual("POST", request.Method.ToString()); Assert.AreEqual(true, request.Parameters.Exists(i => i.Name.Equals("Content-Type"))); Assert.AreEqual(true, request.Parameters.Exists(i => i.Name.Equals("Content-Type"))); Assert.AreEqual("text/json; charset=utf-8", request.Parameters.Find(i => i.Name.Equals("Accept")).Value.ToString()); Assert.AreEqual("text/json; charset=utf-8", request.Parameters.Find(i => i.Name.Equals("Content-Type")).Value.ToString()); String authentication = request.Parameters.Find(i => i.Name.Equals("Authorization")).Value.ToString(); Assert.AreEqual(true, authentication.Contains("oauth_body_hash")); }
private void Grid_Load(object sender, RoutedEventArgs e) { try { string PortName = OperationConfig.GetValue("cardcom"); if (OperationConfig.GetValue("CardSort") == "USB") { ruc = new UsbICCard(PortName); } else { ruc = new ComICCard(PortName); } if (ruc.IsOpen()) { thead3 = new Thread(ruc.Read); thead3.Start(); ruc.HandDataBack -= BackCardID; ruc.HandDataBack += BackCardID; } else { idcardError.Visibility = Visibility.Visible; } } catch { idcardError.Visibility = Visibility.Visible; } }
public OperationViewModel(OperationConfig oc) { _operationConfig = oc; UpdateIntervalOfThumbnails = ReactiveProperty.FromObject(oc, w => w.UpdateIntervalOfThumbnails); ReceptionIntervalOfComments = ReactiveProperty.FromObject(oc, w => w.ReceptionIntervalOfComments); SamplingIntervalOfProgramState = ReactiveProperty.FromObject(oc, w => w.SamplingIntervalOfProgramState); NumberOfHoldingComments = ReactiveProperty.FromObject(oc, w => w.NumberOfHoldingComments); PostKey = ReactiveProperty.FromObject(oc, w => w.PostKeyType, x => new EnumWrap <PostKey>(x), w => w.EnumValue); ToastNotificationBeforeMinutes = ReactiveProperty.FromObject(oc, w => w.ToastNotificationBeforeMinutes); Branch = ReactiveProperty.FromObject(oc, w => w.Branch, x => new EnumWrap <Branch>(x), w => w.EnumValue); IsAbsoluteTime = ReactiveProperty.FromObject(oc, w => w.IsAbsoluteTime); IsShowFavoriteOnly = ReactiveProperty.FromObject(oc, w => w.IsShowFavoriteOnly); Delay = ReactiveProperty.FromObject(oc, w => w.Delay); MuteKeywords = oc.MuteKeywords; IsRegex = new ReactiveProperty <bool>(false); Keyword = new ReactiveProperty <string>("") .SetValidateNotifyError(x => IsRegex.Value ? _rgxValidator.Validate(Keyword.Value) : null); Keyword.Subscribe(w => AddMuteKeywordCommand.RaiseCanExecuteChanged()).AddTo(this); IsRegex.Subscribe(w => { Keyword.ForceValidate(); AddMuteKeywordCommand.RaiseCanExecuteChanged(); }).AddTo(this); SelectedKeyword = new ReactiveProperty <MuteKeyword>(); SelectedKeyword.Subscribe(w => { EditMuteKeywordCommand.RaiseCanExecuteChanged(); DeleteMuteKeywordCommand.RaiseCanExecuteChanged(); }).AddTo(this); SelectedIndex = new ReactiveProperty <int>(); }
public override void Run() { base.Run(); Console.WriteLine("Writing configuration"); Console.WriteLine("---------------------"); if (File.Exists(_options.ConfigFile) && _options.Overwrite == false) { Console.WriteLine($"Config file {_options.ConfigFile} exists."); Console.WriteLine($"Overwrite not specified so file will not be overwritten"); return; } var cfg = new OperationConfig(); cfg.Url = _options.Url; cfg.Database = _options.Database; cfg.Token = _options.Token; cfg.Timeout = _options.Timeout; ISitecoreEndpoint endPoint = _endpointFactory.Create(_options.Url); try { Console.Write("Fetching indexes..."); cfg.Indexes = endPoint.FetchIndexes(cfg.Token); Console.WriteLine(); Console.Write("Fetching item data..."); var items = endPoint.FetchItemIds(cfg.Token, _options.Database, _options.Query); cfg.Items = new Queue <ItemEntry>(items); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine(Environment.NewLine + "Exception caught from endpoint while extracting setup data:"); while (ex != null) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); //if(ex is System.Net.WebException) //{ // var s = (ex as System.Net.WebException).Response.GetResponseStream(); // var sr = new StreamReader(s); // Console.WriteLine(sr.ReadToEnd()); //} ex = ex.InnerException; } return; } Console.Write("Saving config to disk..."); _configFileManager.Save(_options.ConfigFile, cfg); Console.WriteLine(); Console.WriteLine($"Config written to {_configFileManager.VerifyFilename(_options.ConfigFile)}"); }
private void PrintItem() { var printDocument = new PrintDocument(); printDocument.PrintPage += printDocument_PrintPage; printDocument.DefaultPageSettings.PaperSize = new PaperSize("票据", 200, 120);//设置纸张的大小 printDocument.PrinterSettings.PrinterName = OperationConfig.GetValue("PrintName"); printDocument.Print(); }
public MyTabitem(users juser, users zuser) { InitializeComponent(); _juser = juser; _zuser = zuser; confarry = Convert.ToInt16(OperationConfig.GetValue("arry")); confcount = Convert.ToInt16(OperationConfig.GetValue("count")); cb_errorrangbinding(); }
/** 选择怪物 */ public void chooseOperation(OperationConfig config) { _chooseElementType = SceneElementType.Operation; _chooseOperationConfig = config; cancelPick(); cancelSelect(); _tempData = createNewElement(SceneElementType.Operation, config.id); selectElement(_tempData); pickUpSelect(); }
public void Test204() { RequestMap responseMap = new RequestMap(" { \"user.name\":\"andrea\", \"user.surname\":\"rizzini\" }"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.NoContent, "")); // new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); IDictionary <String, Object> result = controller.Execute(config, metadata, new TestBaseObject(responseMap)); Assert.IsTrue(result.Count == 0); }
private void readcard() { try { port = new SerialPort(); port.PortName = OperationConfig.GetValue("cardcom"); port.BaudRate = Convert.ToInt32(OperationConfig.GetValue("cardrate")); port.DataBits = 8; port.Open(); _keepreading = true; _thread = new Thread(ReadCard); _thread.Start(); } catch { } }
private void UpdateConfigData(OperationConfig cfg) { var errorItems = cfg.Errors .Where(e => e.FailureType == FailureType.Error) .Select(e => e.Item); foreach (var itm in errorItems) { cfg.Items.Enqueue(itm); } cfg.Errors.Clear(); cfg.Attempts = 0; cfg.Elapsed = TimeSpan.Zero; cfg.Processed.Clear(); }
public frmLogin() { InitializeComponent(); userTextBox.Text = getUserInfo("username"); this.StartPosition = FormStartPosition.CenterScreen; if (getUserInfo("username").Equals("")) { userTextBox.Select(); } else { pwdTextBox.Select(); } //切换服务器地址 if (!string.IsNullOrEmpty(ini.IniReadValue(ini.Section_Remote, "address"))) { OperationConfig o = new OperationConfig(); o.modifyItem("RemoteAddress", ini.IniReadValue(ini.Section_Remote, "address") + o.valueItem("RemoteAddressName")); } List <MES_SY_TYPEMXLIST> languList = new List <MES_SY_TYPEMXLIST>(); MES_SY_TYPEMXLIST langu1 = new MES_SY_TYPEMXLIST { MXNAME = "中文/zh", MAXVALUE = "zh-CN" }; languList.Add(langu1); //MES_SY_TYPEMXLIST langu2 = new MES_SY_TYPEMXLIST(); //langu2.MXNAME = "Tiếng việt/vi"; //langu2.MAXVALUE = "vi-VN"; //languList.Add(langu2); langucomboBox.DisplayMember = "MXNAME"; langucomboBox.ValueMember = "MAXVALUE"; langucomboBox.DataSource = languList; //q(Msg_Type.unamenotempty); //string c = "13.325"; //string c1 = "13.3254"; //string c2 = "13"; //bool d = judge.IsNo_3(c); //bool d1 = judge.IsNo_3(c1); //bool d2 = judge.IsNo_3(c2); }
private void SetOperationToGroupMangerConfig(string groupQQ, bool status, OperationConfig enumCfg) { mangerConfig = GraceGroupMangerConfig.Instance; int index = QQinMangerConfig(groupQQ, mangerConfig); if (index < 0) { GraceGroupConfig cfg = new GraceGroupConfig(); cfg.GroupQQ = groupQQ; switch (enumCfg) { case OperationConfig.Alert: cfg.Alert = status; break; case OperationConfig.IsBanPostLotto: cfg.IsBanPostLotto = status; break; case OperationConfig.JoinRequestMember: cfg.JoinRequestMember = status; break; default: return; } mangerConfig.groupConfigs.Add(cfg); } else { switch (enumCfg) { case OperationConfig.Alert: mangerConfig.groupConfigs[index].Alert = status; break; case OperationConfig.IsBanPostLotto: mangerConfig.groupConfigs[index].IsBanPostLotto = status; break; case OperationConfig.JoinRequestMember: mangerConfig.groupConfigs[index].JoinRequestMember = status; break; default: return; } } mangerConfig.ToJsonString().SaveToFile(GraceGroupMangerConfig.SavePath); return; }
public void Test405_NotAllowedExceptionCaseInsensitive() { RequestMap responseMap = new RequestMap("{\"errors\":{\"error\":{\"source\":\"System\",\"reasonCode\":\"METHOD_NOT_ALLOWED\",\"description\":\"Method not Allowed\",\"Recoverable\":\"false\"}}}"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.MethodNotAllowed, responseMap)); //new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); ApiException ex = Assert.Throws <ApiException>(() => controller.Execute(config, metadata, new TestBaseObject(responseMap))); Assert.That(ex.Message, Is.EqualTo("Method not Allowed")); Assert.That(ex.ReasonCode, Is.EqualTo("METHOD_NOT_ALLOWED")); Assert.That(ex.Source, Is.EqualTo("System")); Assert.That(ex.Recoverable, Is.EqualTo(false)); }
public void Test500_InvalidRequestException() { RequestMap responseMap = new RequestMap("{\"Errors\":{\"Error\":[{\"Source\":\"OAuth.ConsumerKey\",\"ReasonCode\":\"INVALID_CLIENT_ID\",\"Description\":\"Something went wrong\",\"Recoverable\":false,\"Details\":null}]}}"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.InternalServerError, responseMap)); // new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); ApiException ex = Assert.Throws <ApiException> (() => controller.Execute(config, metadata, new TestBaseObject(responseMap))); Assert.That(ex.Message, Is.EqualTo("Something went wrong")); Assert.That(ex.ReasonCode, Is.EqualTo("INVALID_CLIENT_ID")); Assert.That(ex.Source, Is.EqualTo("OAuth.ConsumerKey")); Assert.That(ex.Recoverable, Is.EqualTo(false)); }
private static NamespaceDeclarationSyntax Go(NamespaceDeclarationSyntax ns, Configuration config, Specification spec) { var className = ClassNameNormaliser(spec.Info.Title); var constructorCode = $@"if (!string.IsNullOrWhiteSpace(url)){{ this.url = url;}} else {{ this.url = ""{spec.Schemes[0]}://{spec.Host}""; }}"; if (config.IncludeHTTPClientForCSharp) { constructorCode += Environment.NewLine + " if (httpClient == null){ this.httpClient = new SwaggerHTTPClient();} else { this.httpClient = httpClient; }"; } var baseClass = SyntaxFactory.ClassDeclaration(className) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddMembers(Field("url", "string").AddModifiers(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)), Field("httpClient", "ISwaggerHTTPClient").AddModifiers(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)), Constructor(className, constructorCode, new SimplifiedParameter("url", "string", "null", true), new SimplifiedParameter("httpClient", "ISwaggerHTTPClient", config.IncludeHTTPClientForCSharp ? "null" : null, true))) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); if (spec.Definations != null) { foreach (var defination in spec.Definations) { baseClass = AddDefination(baseClass, defination, config); } } foreach (var path in spec.Paths) { baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Delete, path.Delete, path.Path), config); baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Get, path.Get, path.Path), config); baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Post, path.Post, path.Path), config); baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Put, path.Put, path.Path), config); baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Head, path.Head, path.Path), config); baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Options, path.Options, path.Path), config); baseClass = AddOperation(baseClass, OperationConfig.FromValues(HTTPAction.Patch, path.Patch, path.Path), config); } if (config.IncludeHTTPClientForCSharp) { baseClass = baseClass.WithTrailingTrivia(SyntaxFactory.Comment(httpCode)); } return(ns.AddMembers(baseClass)); }
/** 重新加载配置 */ private void reloadConfig() { long now = Ctrl.getTimer(); BaseC.config.loadSyncForEditorAll(); long now2 = Ctrl.getTimer(); Ctrl.print("editor加载配置All完成,耗时:", now2 - now); int i = 0; _sceneList = new SList <SceneConfig>(); _sceneListStrs = new string[SceneConfig.getDic().size()]; SceneConfig.getDic().getSortedKeyList().forEach(k => { SceneConfig config = SceneConfig.get(k); _sceneList.add(config); _sceneListStrs[i++] = config.id + ":" + config.name; }); i = 0; _monsterList = new SList <MonsterConfig>(); _monsterListStrs = new string[MonsterConfig.getDic().size()]; MonsterConfig.getDic().getSortedKeyList().forEach(k => { MonsterConfig config = MonsterConfig.get(k); _monsterList.add(config); _monsterListStrs[i++] = config.id + ":" + config.name; }); i = 0; _operationList = new SList <OperationConfig>(); _operationListStrs = new string[OperationConfig.getDic().size()]; OperationConfig.getDic().getSortedKeyList().forEach(k => { OperationConfig config = OperationConfig.get(k); _operationList.add(config); _operationListStrs[i++] = config.id + ":" + config.name; }); }
public void Test200ShowById() { RequestMap requestMap = new RequestMap("{\n\"id\":\"1\"\n}"); RequestMap responseMap = new RequestMap("{\"Account\":{\"Status\":\"true\",\"Listed\":\"true\",\"ReasonCode\":\"S\",\"Reason\":\"STOLEN\"}}"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); // new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/test1", "read", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); IDictionary <String, Object> result = controller.Execute(config, metadata, new TestBaseObject(requestMap)); RequestMap responseMapFromResponse = new RequestMap(result); Assert.AreEqual("true", responseMapFromResponse["Account.Status"]); Assert.AreEqual("STOLEN", responseMapFromResponse["Account.Reason"]); }
public void Test400_InvalidRequestExceptionCaseInsensitive_JSONNative() { String response = "[{\"source\":\"validation\",\"reasonCode\":\"INVALID_TYPE\",\"description\":\"The supplied field: 'date' is of an unsupported format\",\"Recoverable\":false,\"Details\":null}]"; TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.BadRequest, response)); // new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); ApiException ex = Assert.Throws <ApiException>(() => controller.Execute(config, metadata, new TestBaseObject())); Assert.That(ex.Message, Is.EqualTo("The supplied field: 'date' is of an unsupported format")); Assert.That(ex.ReasonCode, Is.EqualTo("INVALID_TYPE")); Assert.That(ex.Source, Is.EqualTo("validation")); Assert.That(ex.Recoverable, Is.EqualTo(false)); }
public void Test200WithList() { RequestMap responseMap = new RequestMap("[ { \"name\":\"andrea\", \"surname\":\"rizzini\" } ]"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); //new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); IDictionary <String, Object> result = controller.Execute(config, metadata, new TestBaseObject()); RequestMap responseMapFromResponse = new RequestMap(result); Assert.IsTrue(responseMapFromResponse.ContainsKey("list")); Assert.AreEqual(typeof(List <Dictionary <String, Object> >), responseMapFromResponse ["list"].GetType()); Assert.AreEqual("andrea", responseMapFromResponse["list[0].name"]); Assert.AreEqual("rizzini", responseMapFromResponse["list[0].surname"]); }
public void Test200WithMap() { RequestMap responseMap = new RequestMap(" { \"user.name\":\"andrea\", \"user.surname\":\"rizzini\" }"); TestApiController controller = new TestApiController(); controller.SetRestClient(mockClient(HttpStatusCode.OK, responseMap)); var config = new OperationConfig("/test1", "create", headerList, queryList); var metadata = new OperationMetadata("0.0.1", "http://locahost:8081"); IDictionary <String, Object> result = controller.Execute(config, metadata, new TestBaseObject(responseMap)); RequestMap responseMapFromResponse = new RequestMap(result); Assert.IsTrue(responseMapFromResponse.ContainsKey("user")); Assert.IsTrue(responseMapFromResponse.ContainsKey("user.name")); Assert.IsTrue(responseMapFromResponse.ContainsKey("user.surname")); Assert.AreEqual("andrea", responseMapFromResponse["user.name"]); Assert.AreEqual("rizzini", responseMapFromResponse["user.surname"]); }
void UpdateCardInfo() { try { string cardid; if (OperationConfig.GetValue("CardSort") == "USB") { this.cardid.Text = backcard; cardid = backcard; } else { filterdata.CardId = backcard; filterdata.resetCard(); cardid = filterdata.getcardid(); if (cardid == "") { return; } filterdata.resetid(""); this.cardid.Text = cardid; } borrowuser = getuser.getuserinfo(getuser.getusers(cardid)); if (borrowuser != null && borrowuser.user != null) { this.username.Text = borrowuser.user.username; this.telphone.Text = borrowuser.user.phoneNumber; this.cb_user.IsEnabled = true; _returnwrench = GetBorrowInfo(borrowuser.user.guid); BorrowdgBind(_returnwrench); } else { this.username.Text = ""; this.telphone.Text = ""; } } catch { } }
public void TestEnvironments() { TestApiController controller = new TestApiController(); ResourceConfig instance = ResourceConfig.Instance; ApiConfig.SetEnvironment(Environment.SANDBOX); // new Tuple<string, string, List<string>, List<string>>("/test1", null, headerList, queryList); var config = new OperationConfig("/atms/v1/#env/locations", "read", headerList, queryList); var metadata = new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()); //default Assert.AreEqual("https://sandbox.api.mastercard.com/atms/v1/locations?Format=JSON", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()), new RequestMap()).ToString()); ApiConfig.SetEnvironment(Environment.PRODUCTION_ITF); Assert.AreEqual("https://api.mastercard.com/atms/v1/itf/locations?Format=JSON", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()), new RequestMap()).ToString()); ApiConfig.SetEnvironment(Environment.PRODUCTION_MTF); Assert.AreEqual("https://api.mastercard.com/atms/v1/mtf/locations?Format=JSON", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()), new RequestMap()).ToString()); ApiConfig.SetEnvironment(Environment.SANDBOX); Assert.AreEqual("https://sandbox.api.mastercard.com/atms/v1/locations?Format=JSON", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()), new RequestMap()).ToString()); ApiConfig.SetEnvironment(Environment.PRODUCTION); Assert.AreEqual("https://api.mastercard.com/atms/v1/locations?Format=JSON", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()), new RequestMap()).ToString()); ApiConfig.SetEnvironment(Environment.STAGE); Assert.AreEqual("https://stage.api.mastercard.com/atms/v1/locations?Format=JSON", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext()), new RequestMap()).ToString()); ApiConfig.SetEnvironment(Environment.STAGE); Assert.AreEqual("https://stage.api.mastercard.com/atms/v1/locations", controller.GetURL(config, new OperationMetadata("0.0.1", instance.GetHost(), instance.GetContext(), true), new RequestMap()).ToString()); instance.setHostOverride(); }
private void makeElementModel(SceneElementEditorData data) { switch (data.config.type) { case SceneElementType.Npc: { } break; case SceneElementType.Monster: { MonsterConfig monsterConfig = MonsterConfig.get(data.config.id); data.gameObject = createModel(FightUnitConfig.get(monsterConfig.fightUnitID).modelID, data); } break; case SceneElementType.Operation: { OperationConfig operationConfig = OperationConfig.get(data.config.id); data.gameObject = createModel(operationConfig.modelID, data); } break; case SceneElementType.FieldItem: { ItemConfig itemConfig = ItemConfig.get(data.config.id); data.gameObject = createModel(itemConfig.fieldItemModelID, data); } break; } setPosToGameObject(data); }
private Uri GetURL(OperationConfig config, OperationMetadata metadata, IDictionary <string, object> inputMap) { List <string> queryParams = config.QueryParams; string replacedPath = Util.GetReplacedPath(((metadata.Host == null) ? this.hostUrl : metadata.Host) + config.ResourcePath, inputMap); int num = 0; List <object> list = new List <object>(); StringBuilder stringBuilder = new StringBuilder("{" + num++ + "}"); list.Add(replacedPath); string action = config.Action; if ((action == "read" || action == "delete" || action == "list" || action == "query") && inputMap != null && inputMap.Count > 0) { foreach (KeyValuePair <string, object> current in inputMap) { this.AppendToQueryString(stringBuilder, string.Concat(new object[] { "{", num++, "}={", num++, "}" })); list.Add(this.GetURLEncodedString(current.Key.ToString())); list.Add(this.GetURLEncodedString(current.Value.ToString())); } } if (queryParams.Count > 0) { action = config.Action; if (action == "create" || action == "update") { foreach (KeyValuePair <string, object> current2 in Util.SubMap(inputMap, queryParams)) { this.AppendToQueryString(stringBuilder, string.Concat(new object[] { "{", num++, "}={", num++, "}" })); list.Add(this.GetURLEncodedString(current2.Key.ToString())); list.Add(this.GetURLEncodedString(current2.Value.ToString())); } } } if (config.RepsonseType == DataType.Json) { this.AppendToQueryString(stringBuilder, "Format=JSON"); } else if (config.RepsonseType == DataType.Xml) { this.AppendToQueryString(stringBuilder, "Format=XML"); } Uri result; try { result = new Uri(string.Format(stringBuilder.ToString(), list.ToArray())); } catch (UriFormatException innerException) { throw new InvalidOperationException("Failed to build URI", innerException); } return(result); }
private static ClassDeclarationSyntax AddOperation(ClassDeclarationSyntax @class, OperationConfig config, Configuration swaggerConfig) { if (config.Operation == null) { return @class; } var responseClass = "object"; var authedCall = false; var hasBodyParam = false; var parameters = new List<SimplifiedParameter>(); if (config.Operation.Security?[0].Name?.Equals("oauth", StringComparison.OrdinalIgnoreCase) != null) { authedCall = true; parameters.Add(new SimplifiedParameter { Name = "oauthToken", Type = "string", Required = true }); } var operationName = config.Operation.OperationId; if (string.IsNullOrWhiteSpace(operationName)) { var end = config.Path.IndexOf("/", 2, StringComparison.OrdinalIgnoreCase) - 1; if (end < 0) { end = config.Path.Length - 1; } operationName = config.HTTPAction + config.Path.Substring(1, end); } var methodName = $"{operationName.Replace(" ", "").Trim()}Async"; if (config.Operation.Parameters != null) { foreach (var @param in config.Operation.Parameters) { var name = @param.Name; var type = ""; var typeFormat = ""; var @default = ""; if (@param.GetType() == typeof(BodyParameter)) { hasBodyParam = true; var bodyParam = @param as BodyParameter; if (!string.IsNullOrWhiteSpace(bodyParam.Schema.Ref)) { type = RefToClass(bodyParam.Schema.Ref); } else { type = bodyParam.Schema.Type; typeFormat = bodyParam.Schema.Format; } @default = bodyParam.Schema.Default; } else { var otherParam = @param as OtherParameter; type = otherParam.Type; typeFormat = otherParam.Format; @default = otherParam.Default; } if (!string.IsNullOrWhiteSpace(name)) { parameters.Add(new SimplifiedParameter { Default = @default, Name = name, Type = type.Equals("array", StringComparison.OrdinalIgnoreCase) ? "object[]" : JsonSchemaToDotNetType(type, typeFormat), Location = @param.In, Description = @param.Description, Required = @param.Required }); } } } var successResponse = config.Operation.Responses.Where(_ => _.HttpStatusCode >= 200 && _.HttpStatusCode <= 299).OrderBy(_ => _.HttpStatusCode).FirstOrDefault(); if (successResponse == null) { return @class; } if (successResponse.Schema != null) { if (!string.IsNullOrWhiteSpace(successResponse.Schema.Ref)) { responseClass = RefToClass(successResponse.Schema.Ref); } else { switch (successResponse.Schema.Type.ToUpperInvariant()) { case "OBJECT": { responseClass = ClassNameNormaliser($"{operationName}Out"); @class = AddClass(@class, responseClass, successResponse.Schema.Properties, swaggerConfig); break; } case "ARRAY": { var arrayClass = successResponse.Schema.Items[0]; var resultClass = ""; if (arrayClass.Ref.StartsWith("#/definitions", StringComparison.OrdinalIgnoreCase)) { resultClass = RefToClass(arrayClass.Ref); } else { resultClass = JsonSchemaToDotNetType(operationName, "Out", arrayClass); } responseClass = resultClass + "[]"; break; } default: { responseClass = ClassNameNormaliser(successResponse.Schema.Type); break; } } } } responseClass = ClassNameNormaliser(responseClass); var method = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName($"Task<APIResponse<{responseClass}>>"), methodName) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (parameters.Count > 0) { method = method.AddParameterListParameters(parameters.Select(_ => Parameter(_)).ToArray()); } var httpMethod = "await "; switch (config.HTTPAction) { case HTTPAction.Put: { httpMethod += "httpClient.PutAsync"; break; } case HTTPAction.Get: { httpMethod += "httpClient.GetAsync"; break; } case HTTPAction.Post: { httpMethod += "httpClient.PostAsync"; break; } case HTTPAction.Delete: { httpMethod += "httpClient.DeleteAsync"; break; } case HTTPAction.Head: { httpMethod += "httpClient.HeadAsync"; break; } case HTTPAction.Options: { httpMethod += "httpClient.OptionsAsync"; break; } case HTTPAction.Patch: { httpMethod += "httpClient.PatchAsync"; break; } } var urlPath = config.Path; var queryParameterCode = ""; var addQueryParameterCode = false; if (parameters != null) { var operationParameters = parameters.Where(_ => _.Location != null && (_.Location.Equals("PATH", StringComparison.OrdinalIgnoreCase) || _.Location.Equals("QUERY", StringComparison.OrdinalIgnoreCase))).ToArray(); if (operationParameters.Any()) { queryParameterCode = $"var queryParameters = new Dictionary<string,object>({operationParameters.Length});"; foreach (var urlParam in operationParameters) { var target = $"{{{urlParam.Name}}}"; var value = $"\"+{urlParam.Name}+\""; if (urlPath.Contains(target)) { urlPath = urlPath.Replace(target, value); } else { addQueryParameterCode = true; if (urlParam.Nullable) { queryParameterCode += $"if ({urlParam.Name}.HasValue) {{"; queryParameterCode += $"queryParameters.Add(\"{urlParam.Name}\", {urlParam.Name}.Value);"; queryParameterCode += "}"; } else { queryParameterCode += $"queryParameters.Add(\"{urlParam.Name}\",{urlParam.Name});"; } } } } } var querySuffix = ""; if (addQueryParameterCode) { querySuffix = "+\"?\" + queryParameters.Aggregate(\"\", (curr, next) => (curr.Length > 0 ? \"?\" : \"\") + next.Key + \"=\" + next.Value)"; } httpMethod += $"(new Uri(url + \"{urlPath}\"{querySuffix}, UriKind.Absolute), new SwaggerHTTPClientOptions(TimeSpan.FromSeconds({swaggerConfig.HTTPTimeout.TotalSeconds}))"; if (hasBodyParam) { var bodyParam = parameters.SingleOrDefault(_ => _.Location != null && (_.Location.Equals("body", StringComparison.OrdinalIgnoreCase))); if (bodyParam != null) { httpMethod += $", new StringContent(JsonConvert.SerializeObject({bodyParam.Name}))"; } var formDataParams = parameters.Where(_ => _.Location != null && (_.Location.Equals("formdata", StringComparison.OrdinalIgnoreCase))); if (formDataParams.Any()) { var formDataValue = formDataParams.Aggregate("", (curr, next) => curr + (curr.Length > 0 ? ", " : "") + next.Name); httpMethod += $@", new StringContent(JsonConvert.SerializeObject(new {{{formDataValue}}}))"; } } if (authedCall) { httpMethod += ", token: oauthToken"; } httpMethod += ");"; var methodBody = $@" {{ {(addQueryParameterCode ? queryParameterCode : "")} var response = {httpMethod} if (response == null) {{ return new APIResponse<{responseClass}>(false); }} switch ((int)response.StatusCode) {{"; var successId = config.Operation.Responses.First(_ => _.HttpStatusCode >= 200 && _.HttpStatusCode <= 299).HttpStatusCode; foreach (var response in config.Operation.Responses) { methodBody += $@"case {response.HttpStatusCode}: {{ "; if (response.HttpStatusCode == successId) { if (response.Schema == null || response.Schema.Type == "object") { methodBody += $"return new APIResponse<{responseClass}>(response.StatusCode);"; } else { methodBody += $@"var data = JsonConvert.DeserializeObject<{responseClass}>(await response.Content.ReadAsStringAsync()); return new APIResponse<{responseClass}>(data, response.StatusCode);"; } } else { if (response.Schema == null || response.Schema.Type == "object") { methodBody += $"return new APIResponse<{responseClass}>(response.StatusCode);"; } else { var specialData = string.IsNullOrWhiteSpace(response.Schema.Type) ? RefToClass(response.Schema.Ref) : ClassNameNormaliser(response.Schema.Type); methodBody += $@"var data = JsonConvert.DeserializeObject<{ClassNameNormaliser(specialData)}>(await response.Content.ReadAsStringAsync()); return new APIResponse<{responseClass}>(data, response.StatusCode);"; } } methodBody += "}"; } methodBody += $@"default: {{ return new APIResponse<{responseClass}>(response.StatusCode); }} }} }}"; var xmlComments = new List<SyntaxTrivia>(); if (!string.IsNullOrWhiteSpace(config.Operation.Summary)) { xmlComments.AddRange(AddXmlComment("summary", CleanXMLComment(config.Operation.Summary))); } if (!string.IsNullOrWhiteSpace(config.Operation.Description)) { xmlComments.AddRange(AddXmlComment("remarks", CleanXMLComment(config.Operation.Description))); } if (!string.IsNullOrWhiteSpace(successResponse.Description)) { xmlComments.AddRange(AddXmlComment("returns", CleanXMLComment(successResponse.Description))); } xmlComments.AddRange(parameters.Select(_ => AddXmlParamComment(_.Name, _.Description))); method = method .AddBodyStatements(SyntaxFactory.ParseStatement(methodBody)) .WithLeadingTrivia(SyntaxExtensions.ToSyntaxTriviaList(xmlComments)); return @class.AddMembers(method); }
private RestyRequest GetRequest(OperationConfig config, OperationMetadata metadata, RequestMap requestMap) { RestyRequest restyRequest = null; IDictionary <string, object> dictionary = requestMap.Clone(); IDictionary <string, object> dictionary2 = Util.SubMap(dictionary, config.HeaderParams); Uri uRL = this.GetURL(config, metadata, dictionary); Uri baseUrl = new Uri(string.Concat(new object[] { uRL.Scheme, "://", uRL.Host, ":", uRL.Port })); CryptographyInterceptor cryptographyInterceptor = _apiConfig?.GetCryptographyInterceptor(uRL.AbsolutePath) ?? ApiConfig.GetCryptographyInterceptor(uRL.AbsolutePath); string action = config.Action; if (!(action == "create")) { if (!(action == "delete")) { if (!(action == "update")) { if (action == "read" || action == "list" || action == "query") { restyRequest = new RestyRequest(uRL, Method.GET); } } else { restyRequest = new RestyRequest(uRL, Method.PUT); if (cryptographyInterceptor != null) { dictionary = cryptographyInterceptor.Encrypt(dictionary); } if (config.RequestType == DataType.Json) { restyRequest.AddJsonBody(dictionary); } else if (config.RequestType == DataType.Xml) { restyRequest.AddXmlBody(dictionary); } } } else { restyRequest = new RestyRequest(uRL, Method.DELETE); } } else { restyRequest = new RestyRequest(uRL, Method.POST); if (cryptographyInterceptor != null) { dictionary = cryptographyInterceptor.Encrypt(dictionary); } if (config.RequestType == DataType.Json) { restyRequest.AddJsonBody(dictionary); } else if (config.RequestType == DataType.Xml) { restyRequest.AddXmlBody(dictionary); } } if (config.RepsonseType == DataType.Json) { restyRequest.AddHeader("Accept", "application/json"); } else if (config.RepsonseType == DataType.Xml) { restyRequest.AddHeader("Accept", "application/xml"); } if (config.RequestType == DataType.Json) { restyRequest.AddHeader("Content-Type", "application/json"); } else if (config.RequestType == DataType.Xml) { restyRequest.AddHeader("Content-Type", "application/xml"); } restyRequest.AddHeader("User-Agent", "CSharp-SDK-Unofficial/" + this.apiVersion); foreach (KeyValuePair <string, object> current in dictionary2) { restyRequest.AddHeader(current.Key, current.Value.ToString()); } (_apiConfig?.GetAuthentication() ?? ApiConfig.GetAuthentication()).SignRequest(uRL, restyRequest); restyRequest.AbsoluteUrl = uRL; restyRequest.BaseUrl = baseUrl; restyRequest.interceptor = cryptographyInterceptor; return(restyRequest); }
public virtual IDictionary <string, object> Execute(OperationConfig config, OperationMetadata metadata, BaseObject requestMap) { RestyRequest request; CryptographyInterceptor interceptor; IRestClient restClient; try { request = this.GetRequest(config, metadata, requestMap); interceptor = request.interceptor; if (this.restClient != null) { restClient = this.restClient; restClient.BaseUrl = request.BaseUrl; } else { restClient = new RestClient(request.BaseUrl); } } catch (Exception ex) { throw new ApiException(ex.Message, ex); } IRestResponse restResponse; try { ApiController.log.Debug(string.Concat(new object[] { ">>Execute(action='", config.Action, "', resourcePaht='", config.ResourcePath, "', requestMap='", requestMap, "'" })); ApiController.log.Debug("excute(), request.Method='" + request.Method + "'"); ApiController.log.Debug("excute(), request.URL=" + request.AbsoluteUrl.ToString()); ApiController.log.Debug("excute(), request.Header="); ApiController.log.Debug(request.Parameters.Where(x => x.Type == ParameterType.HttpHeader)); ApiController.log.Debug("excute(), request.Body="); ApiController.log.Debug(request.Parameters.Where(x => x.Type == ParameterType.RequestBody)); restClient.UseSynchronizationContext = true; #if NET461 System.Net.ServicePointManager.Expect100Continue = false; System.Net.ServicePointManager.MaxServicePointIdleTime = 5000; //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11; restResponse = restClient.Execute(request); #elif NETSTANDARD1_6 restResponse = AsyncHelpers.RunSync(async() => { return(await restClient.ExecuteRequestAsync(request)); }, () => { this._apiConfig?.getDoEvents()?.Invoke(); return(Task.FromResult(0)); }); #endif ApiController.log.Debug("Execute(), response.Header="); ApiController.log.Debug(restResponse.Headers); ApiController.log.Debug("Execute(), response.Body="); ApiController.log.Debug(restResponse.Content.ToString()); } catch (Exception ex3) { Exception ex2 = new ApiCommunicationException(ex3.Message, ex3); ApiController.log.Error(ex2.Message, ex2); throw ex2; } if (restResponse.ErrorException != null || restResponse.Content == null) { Exception ex4 = new MasterCard.Core.Exceptions.SystemException(restResponse.ErrorMessage, restResponse.ErrorException); ApiController.log.Error(ex4.Message, ex4); throw ex4; } IDictionary <string, object> dictionary = null; if (restResponse.Content.StartsWith("{") || restResponse.Content.StartsWith("[") || restResponse.ContentType == "application/json") { try { dictionary = RequestMap.AsDictionary(restResponse.Content); if (interceptor != null) { dictionary = interceptor.Encrypt(dictionary); } } catch (Exception) { throw new MasterCard.Core.Exceptions.SystemException("Error: parsing JSON response", restResponse.Content); } } else if (restResponse.Content.StartsWith("<") || restResponse.ContentType == "application/xml") { try { dictionary = RequestMap.AsDictionaryFromXml(restResponse.Content); if (interceptor != null) { dictionary = interceptor.Encrypt(dictionary); } } catch (Exception) { throw new MasterCard.Core.Exceptions.SystemException("Error: parsing XML response", restResponse.Content); } } if (restResponse.StatusCode < HttpStatusCode.MultipleChoices) { ApiController.log.Debug("<<Execute()"); return(dictionary); } try { ApiController.ThrowException(dictionary, restResponse); } catch (Exception ex5) { ApiController.log.Error(ex5.Message, ex5); throw ex5; } return(null); }
private static ClassDeclarationSyntax AddOperation(ClassDeclarationSyntax @class, OperationConfig config, Configuration swaggerConfig) { if (config.Operation == null) { return(@class); } var responseClass = "object"; var authedCall = false; var hasBodyParam = false; var parameters = new List <SimplifiedParameter>(); if (config.Operation.Security?[0].Name?.Equals("oauth", StringComparison.OrdinalIgnoreCase) != null) { authedCall = true; parameters.Add(new SimplifiedParameter { Name = "oauthToken", Type = "string", Required = true }); } var operationName = config.Operation.OperationId; if (string.IsNullOrWhiteSpace(operationName)) { var end = config.Path.IndexOf("/", 2, StringComparison.OrdinalIgnoreCase) - 1; if (end < 0) { end = config.Path.Length - 1; } operationName = config.HTTPAction + config.Path.Substring(1, end); } var methodName = $"{operationName.Replace(" ", "").Trim()}Async"; if (config.Operation.Parameters != null) { foreach (var @param in config.Operation.Parameters) { var name = @param.Name; var type = ""; var typeFormat = ""; var @default = ""; if (@param.GetType() == typeof(BodyParameter)) { hasBodyParam = true; var bodyParam = @param as BodyParameter; if (!string.IsNullOrWhiteSpace(bodyParam.Schema.Ref)) { type = RefToClass(bodyParam.Schema.Ref); } else { type = bodyParam.Schema.Type; typeFormat = bodyParam.Schema.Format; } @default = bodyParam.Schema.Default; } else { var otherParam = @param as OtherParameter; type = otherParam.Type; typeFormat = otherParam.Format; @default = otherParam.Default; } if (!string.IsNullOrWhiteSpace(name)) { parameters.Add(new SimplifiedParameter { Default = @default, Name = name, Type = type.Equals("array", StringComparison.OrdinalIgnoreCase) ? "object[]" : JsonSchemaToDotNetType(type, typeFormat), Location = @param.In, Description = @param.Description, Required = @param.Required }); } } } var successResponse = config.Operation.Responses.Where(_ => _.HttpStatusCode >= 200 && _.HttpStatusCode <= 299).OrderBy(_ => _.HttpStatusCode).FirstOrDefault(); if (successResponse == null) { return(@class); } if (successResponse.Schema != null) { if (!string.IsNullOrWhiteSpace(successResponse.Schema.Ref)) { responseClass = RefToClass(successResponse.Schema.Ref); } else { switch (successResponse.Schema.Type.ToUpperInvariant()) { case "OBJECT": { responseClass = ClassNameNormaliser($"{operationName}Out"); @class = AddClass(@class, responseClass, successResponse.Schema.Properties, swaggerConfig); break; } case "ARRAY": { var arrayClass = successResponse.Schema.Items[0]; var resultClass = ""; if (arrayClass.Ref.StartsWith("#/definitions", StringComparison.OrdinalIgnoreCase)) { resultClass = RefToClass(arrayClass.Ref); } else { resultClass = JsonSchemaToDotNetType(operationName, "Out", arrayClass); } responseClass = resultClass + "[]"; break; } default: { responseClass = ClassNameNormaliser(successResponse.Schema.Type); break; } } } } responseClass = ClassNameNormaliser(responseClass); var method = SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName($"Task<APIResponse<{responseClass}>>"), methodName) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (parameters.Count > 0) { method = method.AddParameterListParameters(parameters.Select(_ => Parameter(_)).ToArray()); } var httpMethod = "await "; switch (config.HTTPAction) { case HTTPAction.Put: { httpMethod += "httpClient.PutAsync"; break; } case HTTPAction.Get: { httpMethod += "httpClient.GetAsync"; break; } case HTTPAction.Post: { httpMethod += "httpClient.PostAsync"; break; } case HTTPAction.Delete: { httpMethod += "httpClient.DeleteAsync"; break; } case HTTPAction.Head: { httpMethod += "httpClient.HeadAsync"; break; } case HTTPAction.Options: { httpMethod += "httpClient.OptionsAsync"; break; } case HTTPAction.Patch: { httpMethod += "httpClient.PatchAsync"; break; } } var urlPath = config.Path; var queryParameterCode = ""; var addQueryParameterCode = false; if (parameters != null) { var operationParameters = parameters.Where(_ => _.Location != null && (_.Location.Equals("PATH", StringComparison.OrdinalIgnoreCase) || _.Location.Equals("QUERY", StringComparison.OrdinalIgnoreCase))).ToArray(); if (operationParameters.Any()) { queryParameterCode = $"var queryParameters = new Dictionary<string,object>({operationParameters.Length});"; foreach (var urlParam in operationParameters) { var target = $"{{{urlParam.Name}}}"; var value = $"\"+{urlParam.Name}+\""; if (urlPath.Contains(target)) { urlPath = urlPath.Replace(target, value); } else { addQueryParameterCode = true; if (urlParam.Nullable) { queryParameterCode += $"if ({urlParam.Name}.HasValue) {{"; queryParameterCode += $"queryParameters.Add(\"{urlParam.Name}\", {urlParam.Name}.Value);"; queryParameterCode += "}"; } else { queryParameterCode += $"queryParameters.Add(\"{urlParam.Name}\",{urlParam.Name});"; } } } } } var querySuffix = ""; if (addQueryParameterCode) { querySuffix = "+\"?\" + queryParameters.Aggregate(\"\", (curr, next) => (curr.Length > 0 ? \"?\" : \"\") + next.Key + \"=\" + next.Value)"; } httpMethod += $"(new Uri(url + \"{urlPath}\"{querySuffix}, UriKind.Absolute), new SwaggerHTTPClientOptions(TimeSpan.FromSeconds({swaggerConfig.HTTPTimeout.TotalSeconds}))"; if (hasBodyParam) { var bodyParam = parameters.SingleOrDefault(_ => _.Location != null && (_.Location.Equals("body", StringComparison.OrdinalIgnoreCase))); if (bodyParam != null) { httpMethod += $", new StringContent(JsonConvert.SerializeObject({bodyParam.Name}))"; } var formDataParams = parameters.Where(_ => _.Location != null && (_.Location.Equals("formdata", StringComparison.OrdinalIgnoreCase))); if (formDataParams.Any()) { var formDataValue = formDataParams.Aggregate("", (curr, next) => curr + (curr.Length > 0 ? ", " : "") + next.Name); httpMethod += $@", new StringContent(JsonConvert.SerializeObject(new {{{formDataValue}}}))"; } } if (authedCall) { httpMethod += ", token: oauthToken"; } httpMethod += ");"; var methodBody = $@" {{ {(addQueryParameterCode ? queryParameterCode : "")} var response = {httpMethod} if (response == null) {{ return new APIResponse<{responseClass}>(false); }} switch ((int)response.StatusCode) {{"; var successId = config.Operation.Responses.First(_ => _.HttpStatusCode >= 200 && _.HttpStatusCode <= 299).HttpStatusCode; foreach (var response in config.Operation.Responses) { methodBody += $@"case {response.HttpStatusCode}: {{ "; if (response.HttpStatusCode == successId) { if (response.Schema == null || response.Schema.Type == "object") { methodBody += $"return new APIResponse<{responseClass}>(response.StatusCode);"; } else { methodBody += $@"var data = JsonConvert.DeserializeObject<{responseClass}>(await response.Content.ReadAsStringAsync()); return new APIResponse<{responseClass}>(data, response.StatusCode);"; } } else { if (response.Schema == null || response.Schema.Type == "object") { methodBody += $"return new APIResponse<{responseClass}>(response.StatusCode);"; } else { var specialData = string.IsNullOrWhiteSpace(response.Schema.Type) ? RefToClass(response.Schema.Ref) : ClassNameNormaliser(response.Schema.Type); methodBody += $@"var data = JsonConvert.DeserializeObject<{ClassNameNormaliser(specialData)}>(await response.Content.ReadAsStringAsync()); return new APIResponse<{responseClass}>(data, response.StatusCode);"; } } methodBody += "}"; } methodBody += $@"default: {{ return new APIResponse<{responseClass}>(response.StatusCode); }} }} }}"; var xmlComments = new List <SyntaxTrivia>(); if (!string.IsNullOrWhiteSpace(config.Operation.Summary)) { xmlComments.AddRange(AddXmlComment("summary", CleanXMLComment(config.Operation.Summary))); } if (!string.IsNullOrWhiteSpace(config.Operation.Description)) { xmlComments.AddRange(AddXmlComment("remarks", CleanXMLComment(config.Operation.Description))); } if (!string.IsNullOrWhiteSpace(successResponse.Description)) { xmlComments.AddRange(AddXmlComment("returns", CleanXMLComment(successResponse.Description))); } xmlComments.AddRange(parameters.Select(_ => AddXmlParamComment(_.Name, _.Description))); method = method .AddBodyStatements(SyntaxFactory.ParseStatement(methodBody)) .WithLeadingTrivia(SyntaxExtensions.ToSyntaxTriviaList(xmlComments)); return(@class.AddMembers(method)); }