private String BuildSignatureFromJsonAttribute(string authSecret, SessionRequest settings) { var properties = settings.GetType().GetRuntimeProperties(); var navBody = new StringBuilder(); var flag = false; foreach ( var property in properties.Where(pr => pr.GetCustomAttribute <JsonPropertyAttribute>() != null).OrderBy(pr => pr.GetCustomAttribute <JsonPropertyAttribute>().PropertyName)) { var attribute = property.GetCustomAttribute <JsonPropertyAttribute>(); if (property.PropertyType.GetTypeInfo().Namespace.Contains("Quickblox.Sdk")) { var innerClass = property.GetValue(settings); if (innerClass == null) { continue; } var innerProperties = innerClass.GetType().GetRuntimeProperties(); foreach (var innerProperty in innerProperties.Where(pr => pr.GetCustomAttribute <JsonPropertyAttribute>() != null).OrderBy(pr => pr.GetCustomAttribute <JsonPropertyAttribute>().PropertyName)) { var innerAttribute = innerProperty.GetCustomAttribute <JsonPropertyAttribute>(); var value = innerProperty.GetValue(innerClass); if (value == null) { continue; } if (flag) { navBody.Append(String.Format("&{0}[{1}]={2}", attribute.PropertyName, innerAttribute.PropertyName, value)); continue; } navBody.Append(String.Format("{0}[{1}]={2}", attribute.PropertyName, innerAttribute.PropertyName, value)); flag = true; } } else { var value = property.GetValue(settings); if (value == null) { continue; } if (flag) { navBody.Append(String.Format("&{0}={1}", attribute.PropertyName, value)); continue; } navBody.Append(String.Format("{0}={1}", attribute.PropertyName, value)); flag = true; } } return(cryptographicProvider.Encrypt(navBody.ToString(), authSecret)); }
static void DMain(string[] args) { InsuranceWebService insuranceWebService = new InsuranceWebService(); var mta = new AdjustRequest(); var insReq = new InsuranceRequest(); var sess = new SessionRequest(); sess.Username = ""; sess.Password = ""; sess.AuthenticationKey = ""; mta.AccountID = ""; mta.Contact = ""; mta.DealerName = ""; mta.Details = ""; mta.PolicyNumber = ""; mta.MTAReason = ""; mta.Surname = ""; mta.RequestValidation = true; mta.PhoenixMTA = null; insReq.Session = sess; insReq.MTA = mta; var response = insuranceWebService.MTAPolicyByInsuranceRequest(insReq); if (response.Success) { Console.WriteLine("Success"); } else { Console.WriteLine("Fail"); } Console.ReadKey(); }
public async Task <SessionRequest> RejectSessionRequestAsync(SessionRequest entity) { _context.Entry(entity).State = EntityState.Modified; await _context.SaveChangesAsync(); return(entity); }
static void TMain(string[] args) { InsuranceWebService insuranceWebService = new InsuranceWebService(); var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var veh = new VehicleRequest(); sess.Username = ""; sess.Password = ""; sess.DeliveryDate = new DateTime(); sess.AuthenticationKey = ""; sess.GuaranteeWarrantyDate = new DateTime(); sess.LoanProvided = true; veh.Price = 1; sess.Vehicle = veh; insReq.Session = sess; insReq.Vehicle = veh; var response = insuranceWebService.GetProductListRequest(insReq); for (int i = 0; i < response.Plan.Length; i++) { Console.WriteLine(response.Plan[i]); Console.WriteLine(response.Description[i]); } Console.ReadKey(); }
public virtual JsonResult Add(SessionRequest model) { model.RquestDateSh = PersianDateTime.Now.ToString(PersianDateTimeFormat.Date); model.RquestDateMi = DateTime.Now; model.UserId = (User as ICurrentUserPrincipal).UserId; return Json(_sessionRequestService.Add(model)); }
private void SessionRequestHandler(SessionRequest request) { SessionResponse response = new SessionResponse(request); EventArguments.SessionRequestEventArguments args = new EventArguments.SessionRequestEventArguments(() => { //Confirm Session response.IsConfirmed = true; response.ClientName = request.ClientName; response.PublicKey = PublicKey; if (clientPublicKey.ContainsKey(request.ClientName)) { clientPublicKey[request.ClientName] = request.PublicKey; } else { clientPublicKey.Add(request.ClientName, request.PublicKey); } SendMessage(response); }, () => { //Refuse Session response.IsConfirmed = false; response.ClientName = request.ClientName; SendMessage(response); }); args.Request = request; OnSessionRequest(args); }
public RexProSession StartSession() { var request = new SessionRequest(this.settings); var response = this.SendRequest <SessionRequest, SessionResponse>(request, MessageType.SessionRequest); var session = new RexProSession(this, response.Session); var sessionGuid = new Guid(response.Session); SessionStreams.GetOrAdd(sessionGuid, _ => NewTcpClient().GetStream()); session.Kill += (sender, args) => { while (SessionStreams.ContainsKey(sessionGuid)) { NetworkStream stream; if (SessionStreams.TryRemove(sessionGuid, out stream)) { stream.Close(); stream.Dispose(); } else { Thread.SpinWait(10); } } }; return(session); }
public async Task <SessionResponse> Obter(SessionRequest sessionRequest) { string url = UrlEndpoint.URL_WS_DEV_PAGSEGURO + UrlEndpoint.PATH_SESSIONS; var values = new Dictionary <string, string> { { "email", sessionRequest.Email }, { "token", sessionRequest.Token } }; var content = new FormUrlEncodedContent(values); try { var response = await client.PostAsync(url, content); var responseString = await response.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument(); doc.LoadXml(responseString); string json = JsonConvert.SerializeXmlNode(doc); JObject j = JObject.Parse(json); SessionResponse session = JsonConvert.DeserializeObject <SessionResponse>(j.GetValue("session").ToString()); return(session); } catch (Exception e) { throw; } }
/// <summary> /// Asynchronously executes the specified request. /// </summary> public async Task <T> ExecuteAsync <T>(Func <Task <T> > attempt) where T : class { if (_mainSettings.Session == null) { var tokenResponse = await _authenticationService.GetTokenAsync(); if (tokenResponse.Status == AuthenticationStatus.Success && await _authenticator.AuthenticateAsync(_credentials.UserName, _credentials.Password, tokenResponse.Token)) { var sessionRequest = new SessionRequest { TequilaToken = tokenResponse.Token, RememberMe = _mainSettings.SessionStatus == SessionStatus.LoggedIn }; var sessionResponse = await _authenticationService.GetSessionAsync(sessionRequest); if (sessionResponse.Status == AuthenticationStatus.Success) { _mainSettings.Session = sessionResponse.Session; } } else { _mainSettings.SessionStatus = SessionStatus.NotLoggedIn; return(null); } } return(await attempt()); }
private void SessionRequestHandler(SessionRequest request) { SessionResponse response; if (this.Status != StatusEnum.Validated) //Added after a code project user comment. { response = new SessionResponse(request); response.IsConfirmed = false; response.HasError = true; response.Exception = new Exception("Could not request a new session. The current client is already in session, or is not loged in."); SendMessage(response); return; } foreach (var receiver in Server.Receivers.Where(x => x != this)) { if (receiver.Email == request.Email) { if (receiver.Status == StatusEnum.Validated) { request.Email = this.Email; receiver.SendMessage(request); return; } } } response = new SessionResponse(request); response.IsConfirmed = false; response.HasError = true; response.Exception = new Exception(request.Email + " does not exists or not loged in or in session with another user."); SendMessage(response); }
public static object Update(SessionRequest request) { Attachment attachment = (Attachment)request.Session[new Guid(request.Parameters["attachment"])]; UpdateAttachment(attachment, request.Body); return(PersistedObject.GetNoCreate(attachment, request.Session)); }
//[Route("api/GameEngine/LinkClicked")] public HttpResponseMessage LinkClicked(SessionRequest request) { var session = _repository.IncreaseClick(Session); var nextPage = _repository.GetWikiPage(request.WikiLinkId, request.Word, session); return(Request.CreateResponse(HttpStatusCode.OK, new { session = new { session.WikiSessionId, session.TotalClicks, session.PlayerName }, content = new { pageContent = nextPage?.PlainTextContent, pageLinks = nextPage?.Links.Select(lk => new { Word = lk.WordHtmlEncoded, Id = lk.WikiLinksId, lk.Additional }) } })); }
public NetClient(ClientOption clientOption, ILoggerFactory loggerFactory = null) { _clientOption = clientOption; //_clientOptions.PacketFilter = _clientOptions.PacketFilter ?? new XorPacketFilter(); _loggerFactory = loggerFactory ?? DefaultLoggerFactory.Create(builder => { builder.AddConsoleLogger(); }); _logger = _loggerFactory.CreateLogger(nameof(NetClient)); _receivedPacketQueue = new ConcurrentQueue <NetPacket>(); _packetReader = new NetDataReader(); _statistic = new NetStatistic(); _tcpChannel = new TcpChannel( _clientOption, _loggerFactory.CreateLogger(nameof(TcpChannel)), _statistic); if (_clientOption.IsServiceUdp == true) { _udpChannel = new UdpChannel( _clientOption, _loggerFactory.CreateLogger(nameof(UdpChannel)), _statistic, 0); } _request = new SessionRequest(this, _statistic); _rpcHandlers = new List <IRpcInvokable>(); }
static void hMain(string[] args) { InsuranceWebService insuranceWebService = new InsuranceWebService(); var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var doc = new DocumentRequest(); sess.Username = ""; sess.Password = ""; doc.CertificateNumber = ""; doc.PrintCertificate = true; doc.PrintPolicySummary = true; doc.PrintTermsandConditions = true; doc.PrintStatementofPrice = true; doc.PrintDirectDebit = true; insReq.Session = sess; insReq.Documents = doc; var response = insuranceWebService.ReprintPolicyRequest(insReq); if (response.Success) { Console.WriteLine("Success"); } else { Console.WriteLine("Fail"); } Console.ReadKey(); }
public string GetSessionAndRequest(IConnectToDB _Connect, long?_identities_id, string uname) { SessionRequest SR = new SessionRequest(); SR.identities_id = _identities_id > 0 ? _identities_id : 0; SR.username = uname; //TODO: Refactor for .Net Core /* SR.anonymousid = System.Web.HttpContext.Current.Request.AnonymousID != null ? System.Web.HttpContext.Current.Request.AnonymousID : "0"; * SR.sessionid = !Current.Session.Keys.Contains("SessionID") ? "" : Current.Session.GetString("SessionID"); * SR.timeout = !Current.Session.Keys.Contains("Timeout") ? "" : Current.Session.GetString("Timeout"); * SR.useragent = !Current.Request.Headers.Keys.Contains("User-Agent") ? "" : Current.Request.Headers["User-Agent"].ToString(); * SR.userhostaddress = !Current.Request.Headers.Keys.Contains("UserHostAddress") ? "" : Current.Request.Headers["UserAgent"].ToString(); * SR.userhostaddress = System.Web.HttpContext.Current.Request.UserHostAddress == null ? "" : System.Web.HttpContext.Current.Request.UserHostAddress; * SR.userhostname = System.Web.HttpContext.Current.Request.UserHostName == null ? "" : System.Web.HttpContext.Current.Request.UserHostName; * SR.isauthenticated = System.Web.HttpContext.Current.Request.IsAuthenticated.ToString() == null ? "" : System.Web.HttpContext.Current.Request.IsAuthenticated.ToString(); * SR.logonuseridentity = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name.ToString() == null ? "" : System.Web.HttpContext.Current.Request.LogonUserIdentity.Name.ToString(); * SR.browser = System.Web.HttpContext.Current.Request.Browser.Browser.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Browser.Browser.ToString(); * SR.majorversion = System.Web.HttpContext.Current.Request.Browser.MajorVersion.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Browser.MajorVersion.ToString(); * SR.version = System.Web.HttpContext.Current.Request.Browser.Version.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Browser.Version.ToString(); * SR.crawler = System.Web.HttpContext.Current.Request.Browser.Crawler.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Browser.Crawler.ToString(); * SR.clrversion = System.Web.HttpContext.Current.Request.Browser.ClrVersion.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Browser.ClrVersion.ToString(); * SR.cookies = ""; * SR.ismobiledevice = System.Web.HttpContext.Current.Request.Browser.IsMobileDevice.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Browser.IsMobileDevice.ToString(); * SR.platform = System.Web.HttpContext.Current.Request.Browser.Platform == null ? "" : System.Web.HttpContext.Current.Request.Browser.Platform; * SR.url = System.Web.HttpContext.Current.Request.Url.ToString() == null ? "" : System.Web.HttpContext.Current.Request.Url.ToString(); * SR.urlreferrer = (System.Web.HttpContext.Current.Request.UrlReferrer == null) ? "" : System.Web.HttpContext.Current.Request.UrlReferrer.ToString();*/ return(LogRequest(_Connect, SR)); }
public void ApproveReject_Throws_Exception_When_Request_Not_Pending(string currentState, string action) { var request = SessionRequest.Create(Guid.NewGuid(), Guid.NewGuid(), DateTime.Now, DateTime.Now, Guid.NewGuid()); switch (currentState) { case "Approved": request.Approve(); break; case "Rejected": request.Reject("SomeReason"); break; } Assert.Throws <DomainValidationException>(() => { switch (action) { case "Approve": request.Approve(); break; case "Reject": request.Reject("Some reason"); break; } }); }
public Response GetProductListRequest(Dictionary <string, object> parameters) { try { var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var vehicle = new VehicleRequest(); sess.Username = (String)parameters["username"]; sess.Password = ""; sess.AuthenticationKey = (String)parameters["authenticationKey"]; sess.GuaranteeWarrantyDate = (DateTime)parameters["guarenteewarrantydate"]; sess.DeliveryDate = (DateTime)parameters["deliverydate"]; sess.LoanProvided = (bool)parameters["loanprovided"]; vehicle.Price = (decimal)parameters["price"]; insReq.Session = sess; insReq.Vehicle = vehicle; var response = insuranceWebService.GetProductListRequest(insReq); return(MethodRespToObject(response)); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); return(null); } }
public Response ReprintPolicyRequest(Dictionary <string, object> parameters) { try { var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var document = new DocumentRequest(); sess.Username = (String)parameters["username"]; sess.Password = ""; document.CertificateNumber = (String)parameters["certificatenumber"]; document.PrintCertificate = (bool)parameters["printcertificate"]; document.PrintPolicySummary = (bool)parameters["printpolicysummary"]; document.PrintTermsandConditions = (bool)parameters["printtermsandconditions"]; document.PrintStatementofPrice = (bool)parameters["printstatementofprice"]; document.PrintDirectDebit = (bool)parameters["printdirectdebit"]; insReq.Documents = document; insReq.Session = sess; var response = insuranceWebService.ReprintPolicyRequest(insReq); return(MethodRespToObject(response)); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); return(null); } }
public void ApproveReject_SessionRequest_Returns_SessionRequest_With_Updated_Status( string type, string reason, int expectedStatusId) { var userId = Guid.NewGuid(); var roomFunctionId = Guid.NewGuid(); var startTime = DateTime.Now; var endTime = startTime.AddHours(2); var requestedTime = DateRange.Create(startTime, endTime); _sessionScheduleValidator .Setup(v => v.ValidateAsync(It.IsAny <Guid>(), It.IsAny <Guid?>(), It.IsAny <DateRange>())) .Returns(Task.FromResult(SessionScheduleValidatorResult.Success)); var request = Room.RequestSession(userId, requestedTime, roomFunctionId, _sessionScheduleValidator.Object); Assert.Equal((int)SessionRequestStatusId.Pending, request.SessionRequestStatusId); SessionRequest modifiedRequest = null; switch (type) { case "Approve": modifiedRequest = Room.ApproveSessionRequest(request.Id, _sessionScheduleValidator.Object); break; case "Reject": modifiedRequest = Room.RejectSessionRequest(request.Id, reason); break; } Assert.Equal(expectedStatusId, modifiedRequest.SessionRequestStatusId); }
public Response CancelPolicyByInsurance(Dictionary <string, object> parameters) { try { var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var cancel = new CancelRequest(); sess.Username = (String)parameters["username"]; sess.Password = ""; sess.AuthenticationKey = (String)parameters["AuthenticationKey"]; cancel.AccountID = (String)parameters["accountid"]; cancel.CancellationReason = (String)parameters["cancellationreason"]; cancel.CertificateNumber = (String)parameters["certificatenumber"]; cancel.ContactEmail = (String)parameters["contactemail"]; cancel.DealerName = (String)parameters["dealername"]; cancel.Surname = (String)parameters["surname"]; cancel.RequestValidation = (bool)parameters["requestvalidation"]; cancel.RefundCustomer = (String)parameters["refundcustomer"]; cancel.PhoenixCancellation = null; insReq.Session = sess; insReq.Cancellation = cancel; var response = insuranceWebService.CancelPolicyByInsuranceRequest(insReq); return(MethodRespToObject(response)); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); return(null); } }
public async Task <IActionResult> Obter([FromBody] SessionRequest sessionRequest) { try { SessionResponse retorno = await sessionService.Obter(sessionRequest); Response response = new Response { Status = "success", Message = "ID da sessão obtido com sucesso", Error = false, Data = retorno }; return(new ObjectResult(response)); } catch (Exception e) { Response response = new Response { Status = "error", Message = e.Message, Error = true, Data = null }; //return StatusCode(500, response); return(BadRequest(response)); } }
public Response SavePolicyDetailsRequest(Dictionary <string, object> parameters) { try { var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var vehicle = new VehicleRequest(); var client = new ClientRequest(); var policy = new PolicyRequest(); sess.Username = (String)parameters["username"]; sess.AuthenticationKey = (String)parameters["AuthenticationKey"]; sess.Bordereaux = (bool)parameters["bordereaux"]; sess.Account = (String)parameters["account"]; sess.GuaranteeWarrantyDate = (DateTime)parameters["guarenteewarrantydate"]; sess.PaidByCard = (bool)parameters["paidbycard"]; sess.DeliveryDate = (DateTime)parameters["deliverydate"]; sess.LoanProvided = (bool)parameters["loanprovided"]; client.FirstName = (String)parameters["firstname"]; client.Surname = (String)parameters["surname"]; client.Title = (String)parameters["title"]; client.HouseNumber = (String)parameters["housenumber"]; client.Address = (String)parameters["address"]; client.Postcode = (String)parameters["postcode"]; client.Email = (String)parameters["email"]; client.Telephone = (String)parameters["telephone"]; client.IsCompany = (bool)parameters["iscompany"]; policy.Description = (String)parameters["description"]; policy.Plan = (String)parameters["plan"]; policy.GrossPremium = (decimal)parameters["grosspremium"]; policy.Product = (String)parameters["product"]; policy.CoverPeriod = (int)parameters["coverperiod"]; vehicle.Make = (String)parameters["make"]; vehicle.Model = (String)parameters["model"]; vehicle.Registration = (String)parameters["registration"]; vehicle.Price = (decimal)parameters["price"]; vehicle.Mileage = (int)parameters["mileage"]; vehicle.DateRegistered = (DateTime)parameters["dateregistered"]; vehicle.EngineSize = (int)parameters["enginesize"]; vehicle.Fuel = (String)parameters["fuel"]; vehicle.NewVehicle = (bool)parameters["newvehicle"]; vehicle.Motorcycle = (bool)parameters["motorcycle"]; insReq.Session = sess; insReq.Client = client; insReq.Policy = policy; insReq.Vehicle = vehicle; var response = insuranceWebService.SavePolicyDetailsRequest(insReq); return(MethodRespToObject(response)); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); return(null); } }
public async void ApproveSessionRequestAsync_Returns_Approved_SessionRequestDto() { var startTime = DateTime.Now; var endTime = startTime.AddHours(2); var room = Room.Create(Guid.NewGuid(), "Room"); var request = SessionRequest.Create(Guid.NewGuid(), room.Id, startTime, endTime, null); room.SessionRequests.Add(request); var newSession = Session.Create(room.Id, request.RequestedTime, request.Id); _roomRepository .Setup(r => r.GetAsync(It.IsAny <Guid>())) .Returns(Task.FromResult(room)); _roomRepository .Setup(r => r.CreateSessionAsync(It.IsAny <Guid>(), It.IsAny <Session>())) .Returns(Task.FromResult(newSession)); _sessionScheduleValidator .Setup(v => v.ValidateAsync(It.IsAny <Guid>(), It.IsAny <Guid?>(), It.IsAny <DateRange>())) .Returns(Task.FromResult(SessionScheduleValidatorResult.Success)); var result = await _roomService.ApproveSessionRequestAsync(room.Id, request.Id); Assert.Equal((int)SessionRequestStatusId.Approved, result.SessionRequestStatusId); Assert.NotEqual(new Guid(), request.SessionId); }
/// <summary> /// checks for changes in start/end values as well as title (subject) /// </summary> /// <param name="sessionId"></param> /// <param name="request"></param> /// <returns></returns> public async Task UpdateSessionAsync(string sessionId, SessionRequest request) { var @event = await GetMeetingByExternalIdAsync(sessionId); if (@event == null) { throw new SessionNotFoundException($"no session found for session Id: {sessionId}"); } var newBegin = DateTimeTimeZone.FromDateTimeOffset(DateTimeOffset.Parse(request.DateBegin)); var newEnd = DateTimeTimeZone.FromDateTimeOffset(DateTimeOffset.Parse(request.DateEnd)); if (newBegin != @event.Start) { @event.Start = newBegin; } if (newEnd != @event.End) { @event.End = newEnd; } if (@event.Subject != request.Title) { @event.Subject = request.Title; } //ToDo: consider appending new message to top of body if diferent? await confClient.Users[ServiceAccountEmail].Events[@event.Id] .Request().UpdateAsync(@event); return; }
/// <summary> /// Resource /{merchantId}/sessions /// <a href="https://developer.globalcollect.com/documentation/api/server/#__merchantId__sessions_post">Create Session</a> /// </summary> /// <param name="body">SessionRequest</param> /// <param name="context">CallContext</param> /// <returns>SessionResponse</returns> /// <exception cref="ValidationException">if the request was not correct and couldn't be processed (HTTP status code BadRequest)</exception> /// <exception cref="AuthorizationException">if the request was not allowed (HTTP status code Forbidden)</exception> /// <exception cref="IdempotenceException">if an idempotent request caused a conflict (HTTP status code Conflict)</exception> /// <exception cref="ReferenceException">if an object was attempted to be referenced that doesn't exist or has been removed, /// or there was a conflict (HTTP status code NotFound, Conflict or Gone)</exception> /// <exception cref="GlobalCollectException">if something went wrong at the GlobalCollect platform, /// the GlobalCollect platform was unable to process a message from a downstream partner/acquirer, /// or the service that you're trying to reach is temporary unavailable (HTTP status code InternalServerError, BadGateway or ServiceUnavailable)</exception> /// <exception cref="ApiException">if the GlobalCollect platform returned any other error</exception> public async Task <SessionResponse> Create(SessionRequest body, CallContext context = null) { string uri = InstantiateUri("/{apiVersion}/{merchantId}/sessions", null); try { return(await _communicator.Post <SessionResponse>( uri, ClientHeaders, null, body, context)); } catch (ResponseException e) { object errorObject; switch (e.StatusCode) { default: errorObject = _communicator.Marshaller.Unmarshal <ErrorResponse>(e.Body); break; } throw CreateException(e.StatusCode, e.Body, errorObject, context); } }
/// <inheritdoc /> public async Task <string> AuthorizeAsync(CancellationToken cancellationToken = default) { using (RandomNumberGenerator csprng = new RNGCryptoServiceProvider()) { byte[] rawByteArray = new byte[32]; csprng.GetBytes(rawByteArray); var token = BitConverter.ToString(rawByteArray).Replace("-", string.Empty); var content = new SessionRequest { Email = _username, Password = _password, Token = token }; var requestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(new Uri(_beehiveUrl), "sessions"), Content = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json") }; requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(_acceptHeader)); using (var response = await _httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); var responseContent = JsonConvert.DeserializeObject <SessionResponse>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); return(responseContent.AccessToken); } } }
public HandshakeSuccess(Packets.Client client, SessionRequest cka) : base(client) { SetMessageType(20100); Blake.Init(); Blake.Update(Key.Crypto.PrivateKey); _sessionKey = Blake.Finish(); }
private static async Task <string> Authenticate() { Console.WriteLine($"Authenticating as {Environment.UserName}..."); var sessionInfo = new SessionRequest { Application = "TestConsole", ApplicationVersion = new Version(1, 7), DomainName = Environment.UserDomainName, UserName = Environment.UserName, MachineName = Environment.MachineName, Department = "Main" }; using var httpClient = new HttpClient(); var request = new HttpRequestMessage { RequestUri = new Uri($"https://localhost:5001/token"), Method = HttpMethod.Post, Version = new Version(2, 0), Content = new ReadOnlyMemoryContent(JsonSerializer.SerializeToUtf8Bytes(sessionInfo)) }; var tokenResponse = await httpClient.SendAsync(request); tokenResponse.EnsureSuccessStatusCode(); var token = await tokenResponse.Content.ReadAsStringAsync(); Console.WriteLine("Successfully authenticated."); return(token); }
public void createSession() { // Đọc thông tin cấu hình từ Client new ClientInitProcess().docThongTinCauHinhClient(1); // Kiểm tra kết nối, server, service trước khi request Common.Utilities.IsRequestAllow(ApplicationConstant.SystemService.ZAMainAppService.layGiaTri()); LLogging.WriteLog("Process createSession after validation: ", LLogging.LogType.SYS, DateTime.Now.ToLongTimeString()); // Khởi tạo và gán các giá trị cho request SessionRequest request = Common.Utilities.PrepareRequest(new SessionRequest()); request.License = ClientInformation.License; request.Version = ClientInformation.Version; request.Module = DatabaseConstant.Module.QTHT; request.Function = DatabaseConstant.Function.HT_LOGIN; request.Action = DatabaseConstant.Action.DANG_NHAP; // Lấy kết quả trả về SessionResponse response = Client.getSession(request); // Kiểm tra kết quả trả về Common.Utilities.ValidResponse(request, response); // Xử lý dữ liệu trả về string sessionId = response.SessionId; ClientInformation.SessionId = sessionId; }
public SessionResponse Session(SessionRequest request) { var sessionResponse = new SessionResponse { Errors = new List <string>(), Success = true }; var user = _userRepository.GetByUsername(request.Username); if (user == null) { sessionResponse.Success = false; sessionResponse.Errors.Add("User not in DB"); return(sessionResponse); } if (request.Password != user.Password) { sessionResponse.Success = false; sessionResponse.Errors.Add("Incorrect Password"); } if (!sessionResponse.Success) { return(sessionResponse); } var session = _sessionRepository.GenerateSession(request.Username, request.Password); sessionResponse.Success = true; sessionResponse.Key = session.Key; sessionResponse.UserId = session.UserId; return(sessionResponse); }
public Response MTAPolicyByInsuranceRequest(Dictionary <string, object> parameters) { try { var insReq = new InsuranceRequest(); var sess = new SessionRequest(); var mta = new AdjustRequest(); sess.Username = (String)parameters["username"]; sess.Password = ""; sess.AuthenticationKey = (String)parameters["authenticationKey"]; mta.AccountID = (String)parameters["accountid"]; mta.Contact = (String)parameters["contact"]; mta.Details = (String)parameters["details"]; mta.PolicyNumber = (String)parameters["policynumber"]; mta.MTAReason = (String)parameters["mtareason"]; mta.DealerName = (String)parameters["dealername"]; mta.Surname = (String)parameters["surname"]; insReq.MTA = mta; insReq.Session = sess; var response = insuranceWebService.MTAPolicyByInsuranceRequest(insReq); return(MethodRespToObject(response)); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); return(null); } }
protected void Page_Load(object sender, EventArgs e) { sessionRequest = new SessionRequest(this); pagePath = sessionRequest["PagePath"]; dataSourceID = sessionRequest["DataSourceID"]; string Params = sessionRequest["Params"]; string DataTypes = sessionRequest["DataTypes"]; string Conditions = sessionRequest["Conditions"]; if (!string.IsNullOrEmpty(Conditions)) { arrCondition = Conditions.Split(';'); } string IsNvarchars = sessionRequest["IsNvarchars"]; if (!string.IsNullOrEmpty(IsNvarchars)) { arrIsNvarchar = IsNvarchars.Split(';'); } arrParam = Params.Split(';'); arrDataType = DataTypes.Split(';'); colNum = arrParam.Length; dataSetID = sessionRequest["DataSetID"]; dbAlias = sessionRequest["DbAlias"]; commandText = sessionRequest["CommandText"]; if (sessionRequest["MatchControls"] != null && sessionRequest["MatchControls"] != "") matchControls = sessionRequest["MatchControls"]; this.InitializeQueryConditionItem(arrParam); flowFileName = sessionRequest["FLOWFILENAME"]; listId = sessionRequest["LISTID"]; flowPath = sessionRequest["FLOWPATH"]; whereString = sessionRequest["WHERESTRING"]; navMode = sessionRequest["NAVMODE"]; flNavMode = sessionRequest["FLNAVMODE"]; }
public AuthResponseEx Get(SessionRequest sessionRequest) { var authSession = this.GetSession(); if (authSession.UserAuthName == null) { throw new HttpError(HttpStatusCode.NotFound, "No session found. Log in, maybe?"); } else { return new AuthResponseEx() { SessionId = authSession.Id, UserName = authSession.UserAuthName, UserId = authSession.UserName, }; } }
public IServiceResults<Guid> Add(SessionRequest model) { if (IsUnique(model.ClassSessionId, (Guid)model.UserId)) return new ServiceResults<Guid> { IsSuccessfull = false, Message = BusinessMessage.RecordExist, Result = model.SessionRequestId }; model.SessionRequestId = Guid.NewGuid(); _sessionRequest.Add(model); var saveResult = _uow.SaveChanges(); return new ServiceResults<Guid> { IsSuccessfull = saveResult.ToBool(), Message = saveResult.ToBool() ? BusinessMessage.Ok : BusinessMessage.Error, Result = model.SessionRequestId }; }
/// <summary> /// Returns the zero-based index of the first occurrence of the specified value in /// the <b>SessionRequestCollection</b>. /// </summary> /// <param name="value">The value to locate in the <see cref="SessionRequestCollection"/>.</param> /// <returns> /// The zero-based index of <paramref name="value"/>, if <paramref name="value"/> is found in /// the <see cref="SessionRequestCollection"/>; otherwise, -1. /// </returns> /// <remarks> /// <para>The index sequence is based on the sort sequence. When an element is added, /// it is inserted into <see cref="SessionRequestCollection"/> in the correct sort order, and /// the indexing adjusts accordingly. When an element removed, the indexing also adjusts /// accordingly. Therefore, the index of a specific key-and-value pair might change as /// elements are added or removed from the <see cref="SessionRequestCollection"/>.</para> /// <para>The values of the elements of the <see cref="SessionRequestCollection"/> are compared to the /// specified value using the Equals method.</para> /// <para>This method uses a linear search; therefore, the average execution time is /// proportional to <see cref="SessionRequestCollection.Count"/>.</para> /// </remarks> public virtual int IndexOfValue(SessionRequest value) { return Array.IndexOf(values, value, 0, count); }
private void Insert(int index, string key, SessionRequest value) { if (count == keys.Length) EnsureCapacity(count + 1); if (index < count) { Array.Copy(keys, index, keys, index + 1, count - index); Array.Copy(values, index, values, index + 1, count - index); } keys[index] = key; values[index] = value; count++; version++; }
protected void Page_Load(object sender, EventArgs e) { if (!SessionRequest.Enable) { if (this.sessionRequest["Dialog"] != null) { QueryStringEncrypt.Check(this, new string[] { "&Dialog" }); } else { QueryStringEncrypt.Check(this, new string[] { "&Dialog" }, false); } } sessionRequest = new SessionRequest(this); pagePath = sessionRequest["Pagepath"]; dataSourceID = sessionRequest["DataSourceID"]; psyPagePath = sessionRequest["Psypagepath"]; keepcondition = sessionRequest["Keepcondition"]; remotename = sessionRequest["RemoteName"]; clientqueryid = sessionRequest["ClientQueryID"]; string strfont = sessionRequest["Textfont"]; string strforecolor = sessionRequest["Labelcolor"]; string strtextcolor = sessionRequest["Textcolor"]; string strgaphorizontal = sessionRequest["Gaphorizontal"]; string strgapvertical = sessionRequest["Gapvertical"]; string caption = sessionRequest["Caption"]; string column = sessionRequest["Column"]; string condition = sessionRequest["Condition"]; string operators = sessionRequest["Operator"]; string columntype = sessionRequest["Columntype"]; string newline = sessionRequest["NewLine"]; string textwidth = sessionRequest["Textwidth"]; string textAlign = sessionRequest["Textalign"]; string text = sessionRequest["Text"]; string defaultvalue = sessionRequest["Defaultvalue"]; string isnvarchars = sessionRequest["IsNvarchars"]; string refvalcmd = sessionRequest["Refvalselcmd"]; string refvalalias = sessionRequest["Refvalselalias"]; string refvaldstid = sessionRequest["Refvaldstid"]; string refvaldm = sessionRequest["Refvaldm"]; string refvaltf = sessionRequest["Refvaltf"]; string refvalvf = sessionRequest["Refvalvf"]; string refvalcd = sessionRequest["Refvalcd"]; string refvalsize = sessionRequest["RefvalSize"]; string refvalcolumnmatch = sessionRequest["Refvalcolumnmatch"]; string refvalcolumns = sessionRequest["Refvalcolumns"]; string refvalwhereitem = sessionRequest["Refvalwhereitem"]; string refbuttonurl = sessionRequest["RefButtonurl"]; string refbuttonurlsize = sessionRequest["RefButtonurlSize"]; string refbuttoncaption = sessionRequest["RefButtoncaption"]; string datatype = sessionRequest["Datatype"]; arrCaption = caption.Split(';'); arrColumn = column.Split(';'); arrCodition = condition.Split(';'); arrColumnType = columntype.Split(';'); arrOperators = operators.Split(';'); arrDataType = datatype.Split(';'); arrNewLine = newline.Split(';'); arrTextAlign = textAlign.Split(';'); arrTextWidth = textwidth.Split(';'); arrText = text.Split(';'); arrDefaultValue = defaultvalue.Split(';'); arrIsNvarchar = isnvarchars.Split(';'); arrRefValCMD = refvalcmd.Split(';'); arrRefValAlias = refvalalias.Split(';'); arrRefValDSID = refvaldstid.Split(';'); arrRefValDM = refvaldm.Split(';'); arrRefValCD = refvalcd.Split(';'); arrRefValTF = refvaltf.Split(';'); arrRefValVF = refvalvf.Split(';'); arrRefValSize = refvalsize.Split(';'); arrRefValColumnMatch = refvalcolumnmatch.Split(';'); arrRefValColumns = refvalcolumns.Split(';'); arrRefValWhereItem = refvalwhereitem.Split(';'); arrRefButtonURL = refbuttonurl.Split('@'); arrRefButtonURLSize = refbuttonurlsize.Split(';'); arrRefButtonCaption = refbuttoncaption.Split(';'); arrTextFont = strfont.Split(';'); columnNum = arrColumn.Length; forecolor = Color.FromName(strforecolor); textcolor = Color.FromName(strtextcolor); gaphorizontal = int.Parse(strgaphorizontal); gapvertical = int.Parse(strgapvertical); CreatDataSet(arrRefValDSID); InitializeQueryConditionItem(); }
protected void Page_Load(object sender, EventArgs e) { if (allControls == null) { allControls = new DataTable(); allControls.Columns.Add(new DataColumn("AutoSelect", typeof(bool))); allControls.Columns.Add(new DataColumn("Column", typeof(String))); allControls.Columns.Add(new DataColumn("Caption", typeof(String))); allControls.Columns.Add(new DataColumn("Condition", typeof(String))); allControls.Columns.Add(new DataColumn("DataType", typeof(String))); allControls.Columns.Add(new DataColumn("Operators", typeof(String))); allControls.Columns.Add(new DataColumn("ColumnType", typeof(String))); allControls.Columns.Add(new DataColumn("Enabled", typeof(String))); allControls.Columns.Add(new DataColumn("DefaultValue", typeof(String))); allControls.Columns.Add(new DataColumn("TextWidth", typeof(String))); allControls.Columns.Add(new DataColumn("RefValDSID", typeof(String))); allControls.Columns.Add(new DataColumn("RefValWhereItem", typeof(String))); allControls.Columns.Add(new DataColumn("RefValTF", typeof(String))); allControls.Columns.Add(new DataColumn("RefValVF", typeof(String))); allControls.Columns.Add(new DataColumn("RefValAlias", typeof(String))); allControls.Columns.Add(new DataColumn("RefValCMD", typeof(String))); allControls.Columns.Add(new DataColumn("RefValCD", typeof(String))); allControls.Columns.Add(new DataColumn("RefValSize", typeof(String))); allControls.Columns.Add(new DataColumn("RefValColumnMatch", typeof(String))); allControls.Columns.Add(new DataColumn("RefValColumns", typeof(String))); allControls.Columns.Add(new DataColumn("Text", typeof(String))); allControls.Columns.Add(new DataColumn("RefButtonCaption", typeof(String))); allControls.Columns.Add(new DataColumn("RefButtonURL", typeof(String))); allControls.Columns.Add(new DataColumn("RefButtonURLSize", typeof(String))); } this.Panel2.Visible = false; if (!SessionRequest.Enable) { if (sessionRequest["Dialog"] != null) { QueryStringEncrypt.Check(this, new string[] { "&Dialog" }); } else { QueryStringEncrypt.Check(this, new string[] { "&Dialog" }, false); } } sessionRequest = new SessionRequest(this); pagePath = sessionRequest["Pagepath"]; dataSourceID = sessionRequest["DataSourceID"]; psyPagePath = sessionRequest["Psypagepath"]; remotename = sessionRequest["RemoteName"]; webanyqueryid = sessionRequest["WebAnyQueryID"]; keepcondition = sessionRequest["Keepcondition"]; string caption = sessionRequest["Caption"]; string column = sessionRequest["Column"]; string condition = sessionRequest["Condition"]; string operators = sessionRequest["Operator"]; string columntype = sessionRequest["Columntype"]; string textwidth = sessionRequest["Textwidth"]; string text = sessionRequest["Text"]; string defaultvalue = sessionRequest["Defaultvalue"]; string enabled = sessionRequest["Enabled"]; string autoSelect = sessionRequest["AutoSelect"]; string items = sessionRequest["Items"]; String cmd = sessionRequest["Refvalselcmd"].Replace("%2B", "+"); string refvalcmd = cmd; string refvalalias = sessionRequest["Refvalselalias"]; string refvaldstid = sessionRequest["Refvaldstid"]; string refvaldm = sessionRequest["Refvaldm"]; string refvaltf = sessionRequest["Refvaltf"]; string refvalvf = sessionRequest["Refvalvf"]; string refvalcd = sessionRequest["Refvalcd"]; string refvalsize = sessionRequest["RefvalSize"]; string refvalcolumnmatch = sessionRequest["Refvalcolumnmatch"]; string refvalcolumns = sessionRequest["Refvalcolumns"]; string refvalwhereitem = sessionRequest["Refvalwhereitem"]; string refbuttonurl = sessionRequest["RefButtonurl"]; string refbuttonurlsize = sessionRequest["RefButtonurlSize"]; string refbuttoncaption = sessionRequest["RefButtoncaption"]; string datatype = sessionRequest["Datatype"]; webDataSetID = sessionRequest["WebDataSetID"]; queryColumnMode = sessionRequest["QueryColumnMode"]; autoDisableColumns = Convert.ToBoolean(sessionRequest["AutoDisableColumns"]); dataMember = sessionRequest["DataMember"]; maxColumnCount = Convert.ToInt16(sessionRequest["MaxColumnCount"]); anyQueryID = sessionRequest["AnyQueryID"]; displayAllOperator = Convert.ToBoolean(sessionRequest["DisplayAllOperator"]); allowAddQueryField = Convert.ToBoolean(sessionRequest["AllowAddQueryField"]); arrCaption = caption.Split(';'); arrColumn = column.Split(';'); arrCondition = condition.Split(';'); arrColumnType = columntype.Split(';'); arrOperators = operators.Split(';'); arrDataType = datatype.Split(';'); arrTextWidth = textwidth.Split(';'); arrText = text.Split(';'); arrDefaultValue = defaultvalue.Split(';'); arrEnabled = enabled.Split(';'); arrAutoSelect = autoSelect.Split(';'); //arrItems = items.Split(';'); arrRefValCMD = refvalcmd.Split(';'); arrRefValAlias = refvalalias.Split(';'); arrRefValDSID = refvaldstid.Split(';'); arrRefValDM = refvaldm.Split(';'); arrRefValCD = refvalcd.Split(';'); arrRefValTF = refvaltf.Split(';'); arrRefValVF = refvalvf.Split(';'); arrRefValSize = refvalsize.Split(';'); arrRefValColumnMatch = refvalcolumnmatch.Split(';'); arrRefValColumns = refvalcolumns.Split(';'); arrRefValWhereItem = refvalwhereitem.Split(';'); arrRefButtonURL = refbuttonurl.Split('@'); arrRefButtonURLSize = refbuttonurlsize.Split(';'); arrRefButtonCaption = refbuttoncaption.Split(';'); columnNum = arrColumn.Length; CreatDataSet(webDataSetID); CreatDataSet(arrRefValDSID); if (!this.IsPostBack) { allControls.Rows.Clear(); AddAllColumns(); } InitializeQueryConditionItem(); }
public void Execute(bool dialog) { string url = AddParam(); if (dialog) { url += "&Dialog=true"; } if (SessionRequest.Enable) { SessionRequest sessionRequest = new SessionRequest(this.Page); url = "../InnerPages/frmAnyQuery.aspx?" + sessionRequest.SetRequestValue(url); } else { url = "../InnerPages/frmAnyQuery.aspx?" + QueryStringEncrypt.Encrypt(url); } if (dialog) { string script = string.Format("<script>window.open('{0}','query','left=200,top=200,width=700,scrollbars=yes,resizable=yes,toolbar=no,menubar=no,location=no,status=no');</script>", url); Page.ClientScript.RegisterStartupScript(typeof(string), Guid.NewGuid().ToString(), script); } else { Page.Response.Redirect(url); } }
/// <summary> /// Replaces the value at a specific index in the <b>SessionRequestCollection</b>. /// </summary> /// <param name="index">The zero-based index at which to save <paramref name="value"/>.</param> /// <param name="value">The <see cref="SessionRequest"/> to save into the <see cref="SessionRequestCollection"/>.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is outside the range of valid indices for the <see cref="SessionRequestCollection"/>. /// </exception> /// <remarks> /// <para>The index sequence is based on the sort sequence. When an element is added, /// it is inserted into <see cref="SessionRequestCollection"/> in the correct sort order, and /// the indexing adjusts accordingly. When an element removed, the indexing also adjusts /// accordingly. Therefore, the index of a specific key-and-value pair might change as /// elements are added or removed from the <see cref="SessionRequestCollection"/>.</para> /// </remarks> public virtual void SetByIndex(int index, SessionRequest value) { if (index < 0 || index >= count) throw new ArgumentOutOfRangeException("index", index, "The index is outside the range of valid indices."); values[index] = value; version++; }
/// <summary> /// Apply the test requests for a session request. /// </summary> /// <param name="sessionRequest"> The session request.</param> /// <param name="result"> The response buffer result from the safe session.</param> private void ApplyRequestTests(SessionRequest sessionRequest, ResponseBuffer result) { UnitTestItem unitTestItem = sessionRequest.WebUnitTest; unitTestItem.Form = sessionRequest.Form; CookieCollection cookies = null; //int availableTests = this.AvailableTests(); //bool lastItem = false; string requestUrl = sessionRequest.Url.ToString(); #region Run each test in SessionRequest WebUnitTestItem // run each test in Form foreach (DictionaryEntry de in unitTestItem.Tests) { Test test = (Test)de.Value; ArrayList values = new ArrayList(); // get cookies cookies = cookieManager.GetCookies(sessionRequest.Url); // set current test index unitTestItem.SelectedTestIndex = unitTestItem.Tests.IndexOfValue(test); // create SessionCommandProcessEventArgs SessionCommandProcessEventArgs args = new SessionCommandProcessEventArgs("Applying test '" + test.Name + "' to " + sessionRequest.Url.ToString()); args.ProcessType = SessionProcessType.TestRequest; #region Apply Test // -------------------------------------------------------------------------------- // Process data // Html Form Tag if ( test.UnitTestDataType == UnitTestDataContainer.HtmlFormTag ) { // is a form tag // apply test to form HtmlFormTag filledForm = ApplyTestToForm(test, sessionRequest.Form.CloneTag()); values = parser.ConvertToArrayList(filledForm, result.HttpBody, updateElementNames); } // Post Data Hashtable if ( test.UnitTestDataType == UnitTestDataContainer.PostDataHashtable ) { string postdata = ((PostSessionRequest)sessionRequest).PostData; // convert post data to hashtable FormConverter converter = new FormConverter(); Hashtable postDataHash = converter.ConvertPostDataString(postdata); // Applies test to post data hashtable Hashtable filledPostData = ApplyTestToPostData(test, (Hashtable)postDataHash.Clone()); values = converter.ConvertPostDataArrayList(filledPostData); } // Cookies if ( test.UnitTestDataType == UnitTestDataContainer.Cookies ) { cookies = ApplyTestToCookies(test, cookies); } // Url if( test.UnitTestDataType == UnitTestDataContainer.NoPostData ) { // a url test requestUrl = ApplyTestToUrl(test, WebServerUriType.Normal,sessionRequest.Url).ToString(); } // ----------------------------------------------------------------------------------- #endregion if ( (test.UnitTestDataType == UnitTestDataContainer.HtmlFormTag ) || ( test.UnitTestDataType == UnitTestDataContainer.PostDataHashtable ) ) { // Set post data for report test.Arguments.PostData = ConvertToPostDataString(values); args.Detail = "Posted Data:" + test.Arguments.PostData; } if ( test.UnitTestDataType == UnitTestDataContainer.NoPostData ) { args.Detail = "Url query:" + requestUrl; } if ( test.UnitTestDataType == UnitTestDataContainer.Cookies ) { StringBuilder cookieQuery = new StringBuilder(); foreach ( Cookie cky in cookies ) { cookieQuery.Append("Name:" + cky.Name); cookieQuery.Append(", "); cookieQuery.Append("Value:" + cky.Value); cookieQuery.Append(";"); } args.Detail = "Cookie:" + cookieQuery.ToString(); } // // set last item flag // if ( availableTests == 1) // { // lastItem = true; // } // display the current processing this.DisplaySessionProcessEvent(this,args); // clone test item and set last item value HttpState httpRequestState = new HttpState(); httpRequestState.TestItem = unitTestItem.Clone(); //httpRequestState.IsLastItem = lastItem; // http settings HttpProperties httpSettings = null; if ( sessionRequest.RequestHttpSettings == null ) { httpSettings = unitTestGetRequest.ClientSettings; } else { httpSettings = sessionRequest.RequestHttpSettings; } if ( sessionRequest.RequestType == HttpRequestType.GET ) { // get request this.StartGetRequest(unitTestGetRequest, requestUrl, null, cookies, httpSettings, httpRequestState); } else { // post request this.StartPostRequest(unitTestPostRequest, requestUrl, values, cookies, httpSettings, httpRequestState); } //availableTests--; } #endregion }
/// <summary> /// Removes the element at the specified index of the <b>SessionRequestCollection</b>. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="index"/> is outside the range of valid indices for the <see cref="SessionRequestCollection"/>. /// </exception> /// <exception cref="NotSupportedException"> /// <para>The <see cref="SessionRequestCollection"/> is read-only.</para> /// <para>-or-</para> /// <para>The <b>SessionRequestCollection</b> has a fixed size.</para> /// </exception> /// <remarks> /// <para>The index sequence is based on the sort sequence. When an element is added, /// it is inserted into <see cref="SessionRequestCollection"/> in the correct sort order, and /// the indexing adjusts accordingly. When an element removed, the indexing also adjusts /// accordingly. Therefore, the index of a specific key-and-value pair might change as /// elements are added or removed from the <see cref="SessionRequestCollection"/>.</para> /// <para>In collections of contiguous elements, such as lists, the elements that /// follow the removed element move up to occupy the vacated spot. If the collection is /// indexed, the indices of the elements that are moved are also updated.</para> /// </remarks> public virtual void RemoveAt(int index) { if (index < 0 || index >= count) throw new ArgumentOutOfRangeException("index", index, "The index is outside the range of valid indices."); count--; if (index < count) { Array.Copy(keys, index + 1, keys, index, count - index); Array.Copy(values, index + 1, values, index, count - index); } // We can't set the deleted entries equal to null, because they might be value types. // Instead, we'll create empty single-element arrays of the right type and copy them // over the entries we want to erase. string[] tempKey = new string[1]; SessionRequest[] tempVal = new SessionRequest[1]; Array.Copy(tempKey, 0, keys, count, 1); Array.Copy(tempVal, 0, values, count, 1); version++; }
/// <summary> /// Adds an element with the specified key and value to the <b>SessionRequestCollection</b>. /// </summary> /// <param name="key">The key of the element to add.</param> /// <param name="value">The value of the element to add.</param> /// <exception cref="ArgumentNullException">The <paramref name="key"/> is a null reference.</exception> /// <exception cref="ArgumentException"> /// <para>An element with the specified <paramref name="key"/> already exists in the <see cref="SessionRequestCollection"/>.</para> /// <para>-or-</para> /// <para>The <b>SessionRequestCollection</b> is set to use the <see cref="IComparable"/> interface, /// and <paramref name="key"/> does not implement the <b>IComparable</b> interface.</para> /// </exception> /// <exception cref="InvalidOperationException">The comparer throws an exception.</exception> /// <exception cref="NotSupportedException"> /// <para>The <see cref="SessionRequestCollection"/> is read-only.</para> /// <para>-or-</para> /// <para>The <b>SessionRequestCollection</b> has a fixed size.</para> /// </exception> public virtual void Add(string key, SessionRequest value) { if (Object.ReferenceEquals(key, null)) // avoids compiler error for null check on value type throw new ArgumentNullException("key", "The key cannot be null."); int index = Array.BinarySearch(keys, 0, count, key, comparer); if (index >= 0) throw new ArgumentException(String.Format("Item has already been added. Key being added: \"{0}\".", key)); Insert(~index, key, value); }
/// <summary> /// Determines whether the <b>SessionRequestCollection</b> contains a specific value. /// </summary> /// <param name="value">The value to locate in the <see cref="SessionRequestCollection"/>.</param> /// <returns> /// <b>true</b> if the <see cref="SessionRequestCollection"/> contains an element with the specified /// <paramref name="value"/>; otherwise, <b>false</b>. /// </returns> public virtual bool ContainsValue(SessionRequest value) { return (IndexOfValue(value) >= 0); }
public virtual bool Contains(SessionRequest value) { return list.ContainsValue(value); }
public virtual int IndexOf(SessionRequest value) { return list.IndexOfValue(value); }
public override int IndexOfValue(SessionRequest value) { lock (root) return list.IndexOfValue(value); }
public override void SetByIndex(int index, SessionRequest value) { lock (root) list.SetByIndex(index, value); }
public override void Add(string key, SessionRequest value) { lock (root) list.Add(key, value); }
public override bool ContainsValue(SessionRequest value) { lock (root) return list.ContainsValue(value); }
private void DoQuery(WebDataSource ds) { if (this.QueryMode == QueryModeType.Normal) { string param = "MultiLan=" + this.MultiLanguage.ToString() + "&Params="; DataColumnCollection dcc = (ds.CommandTable == null) ? ds.InnerDataSet.Tables[0].Columns : ds.CommandTable.Columns; // 添加要用于查询的字段 StringBuilder Params = new StringBuilder(); StringBuilder DataTypes = new StringBuilder(); StringBuilder Conditions = new StringBuilder(); StringBuilder IsNvarchars = new StringBuilder(); if (this.QueryFields.Count > 0) { foreach (WebQueryField f in this.QueryFields) { if (dcc.Contains(f.FieldName)) { Params.Append(dcc[f.FieldName].ColumnName); Params.Append(";"); DataTypes.Append(dcc[f.FieldName].DataType); DataTypes.Append(";"); Conditions.Append(f.Condition); Conditions.Append(";"); IsNvarchars.Append(f.IsNvarChar); IsNvarchars.Append(";"); } } } else { foreach (DataColumn dc in dcc) { Params.Append(dc.ColumnName); Params.Append(";"); DataTypes.Append(dc.DataType); DataTypes.Append(";"); } } param += Params.Remove(Params.Length - 1, 1).ToString(); param += "&DataTypes="; param += DataTypes.Remove(DataTypes.Length - 1, 1).ToString(); if (Conditions.Length > 0) { param += "&Conditions="; param += Conditions.Remove(Conditions.Length - 1, 1).ToString(); } if (IsNvarchars.Length > 0) { param += "&IsNvarchars="; param += IsNvarchars.Remove(IsNvarchars.Length - 1, 1).ToString(); } // 添加原始page的url param += "&PagePath=" + Page.Request.FilePath; // 添加query的对象(WebDataSource) param += "&DataSourceID=" + ds.ID; // 添加query的dataset对象id, 和DbAlias, CommandText对象 string dsId = "", selAlias = "", cmdText = ""; dsId = ds.WebDataSetID; selAlias = ds.SelectAlias; cmdText = ds.SelectCommand; param += "&DataSetID=" + dsId + "&DbAlias=" + selAlias + "&CommandText=" + cmdText; string itemparam = this.Page.Request.QueryString["ItemParam"] != null ? HttpUtility.UrlEncode(this.Page.Request.QueryString["ItemParam"]) : string.Empty; param += "&ItemParam=" + itemparam; string flowUrl = this.getFlowUrl(); param += flowUrl; if (QueryStyle == QueryStyleType.Dialog) { param += "&Dialog=true"; } string url = @"../InnerPages/frmNavQuery.aspx?"; if (SessionRequest.Enable) { SessionRequest sessionRequest = new SessionRequest(this.Page); url += sessionRequest.SetRequestValue(param); } else { url += param; } if (QueryStyle == QueryStyleType.NewPage) { Page.Response.Redirect(url); } else { string script = string.Format("window.open('{0}','','left=200,top=200,width=600,scrollbars=yes,resizable=yes,toolbar=no,menubar=no,location=no,status=no')" , url, flowUrl); ScriptHelper.RegisterStartupScript(this, script); } } else if (this.QueryMode == QueryModeType.ClientQuery) { WebClientQuery wcq = CopyQueryFileds(1, true); if (QueryStyle == QueryStyleType.NewPage) { wcq.Execute(); } else { wcq.Execute(true); } } else if (this.QueryMode == QueryModeType.AnyQuery) { WebAnyQuery waq = CopyAnyQueryFileds(1, true); if (QueryStyle == QueryStyleType.NewPage) { waq.Execute(); } else { waq.Execute(true); } } }
public virtual void Reset() { if (version != list.version) throw new InvalidOperationException("The collection was modified - enumeration cannot continue."); // We can't set the entries equal to null, because they might be value types. // Instead, we'll create empty single-element arrays of the right type and copy them // over the entries we want to erase. string[] tempKey = new string[1]; SessionRequest[] tempVal = new SessionRequest[1]; key = tempKey[0]; value = tempVal[0]; currentValid = false; index = startIndex; }