public static bool TryParse(string input, out CookieHeaderValue parsedValue) { var segmentSeparator = new char[] { ';' }; parsedValue = null; if (string.IsNullOrEmpty(input)) { return false; } string[] strArray = input.Split(segmentSeparator); CookieHeaderValue instance = new CookieHeaderValue(); foreach (string str in strArray) { if (!ParseCookieSegment(instance, str)) { return false; } } if (instance.Cookies.Count == 0) { return false; } parsedValue = instance; return true; }
private static bool ParseCookieSegment(CookieHeaderValue instance, string segment) { var nameValueSeparator = new char[] { '=' }; if (string.IsNullOrWhiteSpace(segment)) { return true; } string[] nameValuePair = segment.Split(nameValueSeparator, 2); if ((nameValuePair.Length < 1) || string.IsNullOrWhiteSpace(nameValuePair[0])) { return false; } string a = nameValuePair[0].Trim(); if (string.Equals(a, "expires", StringComparison.OrdinalIgnoreCase)) { DateTimeOffset offset; if (TryParseDate(GetSegmentValue(nameValuePair, null), out offset)) { instance.Expires = new DateTimeOffset?(offset); return true; } return false; } if (string.Equals(a, "max-age", StringComparison.OrdinalIgnoreCase)) { int num; if (TryParseInt32(GetSegmentValue(nameValuePair, null), out num)) { instance.MaxAge = new TimeSpan(0, 0, num); return true; } return false; } if (string.Equals(a, "domain", StringComparison.OrdinalIgnoreCase)) { instance.Domain = GetSegmentValue(nameValuePair, null); return true; } if (string.Equals(a, "path", StringComparison.OrdinalIgnoreCase)) { instance.Path = GetSegmentValue(nameValuePair, "/"); return true; } if (string.Equals(a, "secure", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(GetSegmentValue(nameValuePair, null))) { return false; } instance.Secure = true; return true; } if (string.Equals(a, "httponly", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(GetSegmentValue(nameValuePair, null))) { return false; } instance.HttpOnly = true; return true; } string segmentValue = GetSegmentValue(nameValuePair, null); try { NameValueCollection values = new FormDataCollection(segmentValue).ReadAsNameValueCollection(); CookieState item = new CookieState(a, values); instance.Cookies.Add(item); return true; } catch { return false; } }
public HttpResponseMessage LogIn(LoginApiModel loginObject) { var sessionProvider = ProviderFactory.Instance.CreateSessionServiceProvider(); var transaction = new TransactionalInformation(); transaction.redirectUrl = GlobalProperties.INDEX_PAGE; transaction.IsAuthenicated = true; var response = Request.CreateResponse(HttpStatusCode.OK, transaction); try { if (String.IsNullOrEmpty(loginObject.password)) { transaction.IsException = true; transaction.redirectUrl = GlobalProperties.LOGIN_PAGE; transaction.ReturnMessage.Add("Missing password"); return(Request.CreateResponse(HttpStatusCode.Unauthorized, transaction)); } var sessionToken = sessionProvider.SignIn(new SignInRequest() { Email = loginObject.username, Password = CalculateMD5Hash(loginObject.password), SessionDetails = new SessionDetails() { Timeout = GlobalProperties.SESSION_VALIDITY * 3600 }, UseDefaultTenant = true }).SessionToken; var cookieValue = String.Format("{1}={2}{0}{3}={4}", GlobalProperties.KEY_SEPARATOR, GlobalProperties.KEY_TOKEN, sessionToken, GlobalProperties.KEY_LANGUAGE, "de"); CookieHeaderValue cookie = new CookieHeaderValue("bops", cookieValue); cookie.Expires = DateTime.MaxValue; cookie.Domain = Request.RequestUri.Host; cookie.Path = "/"; response.Headers.AddCookies(new CookieHeaderValue[] { cookie }); } catch (Exception ex) { var sdkException = ex as SDKServiceException; var message = "Irgendwas ist schiefgegangen."; if (sdkException != null) { // Wenn Server nicht erreichbar, dann Fehler bei Zugriff auf Object "sdkException.ServiceError", da sdkException.ServiceError == null if (sdkException.ServiceError.Code == 70204) { message = "Ihre Konto deaktiviert wurden."; // Bruder, ich nicht verstehen, bitte erklären das! } else if (sdkException.ServiceError.Code == 70202 || sdkException.ServiceError.Code == 70103) { message = "Falsche Anmeldungsdaten."; } else { Logger.LogInfo(new LogEntry("code: " + sdkException.ServiceError.Code + "; message: " + sdkException.ServiceError.Message)); Logger.LogInfo(new LogEntry("stack trace: " + sdkException.StackTrace)); } } else { Logger.LogInfo(new LogEntry(ex.Message)); } transaction.IsException = true; transaction.redirectUrl = GlobalProperties.LOGIN_PAGE; transaction.ReturnMessage.Add(message); return(Request.CreateResponse(HttpStatusCode.Unauthorized, transaction)); } return(response); }
public async Task <string> Get(string id) { Trace.TraceInformation("Game Command Received: " + id); string playerId = ""; string playerName = ""; Guid playerGuid = Guid.NewGuid(); CookieHeaderValue cookie = Request.Headers.GetCookies("playerid").FirstOrDefault(); if (cookie != null) { playerId = cookie["playerid"].Value; playerGuid = Guid.Parse(playerId); } else { HttpCookie cook = new HttpCookie("playerid", playerGuid.ToString()); HttpContext.Current.Response.Cookies.Add(cook); } //var player = PlayerGrainFactory.GetGrain(playerGuid); //var player = GrainFactory.GetGrain<IPlayerGrain>(playerGuid.ToString()); var player = GrainFactory.GetGrain <IPlayerGrain>(playerGuid); playerName = await player.Name(); if (id == "begingame" && playerName == Constants.kPlayerSetupName) { //Kick off setup process AdventureSetup setup = new AdventureSetup(); await setup.setup(player); await player.SetInfoGuid(playerGuid); return("What is your name?"); } else if (id == "begingame") { playerName = await player.Name(); return("Welcome back, " + playerName); } if (id == "hubtest") { //PlayerHub hub = new PlayerHub(); var context = GlobalHost.ConnectionManager.GetHubContext <PlayerHub>(); context.Clients.Group("BROWSERS").playerUpdate("This has been a hubtest!"); //hub.PlayerUpdate("BLAH!"); return("Hub should be tested"); } if (id == "hubtest3") { //PlayerHub hub = new PlayerHub(); var context = GlobalHost.ConnectionManager.GetHubContext <PlayerHub>(); List <ClientMessage> messages = new List <ClientMessage>(); messages.Add(new ClientMessage { Message = "Testone" }); messages.Add(new ClientMessage { Message = "Testtwo" }); context.Clients.Group("BROWSERS").objectTest(new ClientMessageBatch { Messages = messages.ToArray() }); //hub.PlayerUpdate("BLAH!"); return("Hub should be tested with ClientMessages"); } if (playerName == Constants.kPlayerSetupName) { playerName = id; await player.SetName(playerName); string response = "Welcome, " + playerName + "\n"; response += await player.Play("start"); return(response); } string result = await player.Play(id); if (result.StartsWith("COMMAND::")) { switch (result) { case "COMMAND::RESTART": await player.ClearGrainAndState(); AdventureSetup setup = new AdventureSetup(); await setup.setup(player); await player.SetInfoGuid(playerGuid); return("What is your name? (restart)"); } } Trace.TraceInformation("GameCommand Result: " + result); return(result); }
/// <summary> /// Process a request message with HttpClient object. /// </summary> public async Task <T> ProcessRequest <T>(T content, SerializationFormat serializationFormat, CancellationToken cancellationToken) { if (this.BaseUri == null) { throw new ArgumentException("BaseUri is not defined"); } HttpResponseMessage response = null; T responseMessage = default(T); try { if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } var requestUri = new StringBuilder(); requestUri.Append(this.BaseUri.ToString()); requestUri.Append(this.BaseUri.ToString().EndsWith("/", StringComparison.CurrentCultureIgnoreCase) ? string.Empty : "/"); // Add params if any if (ScopeParameters != null && ScopeParameters.Count > 0) { string prefix = "?"; foreach (var kvp in ScopeParameters) { requestUri.AppendFormat("{0}{1}={2}", prefix, Uri.EscapeUriString(kvp.Key), Uri.EscapeUriString(kvp.Value)); if (prefix.Equals("?")) { prefix = "&"; } } } // default handler if no one specified HttpClientHandler httpClientHandler = this.Handler ?? new HttpClientHandler(); // serialize dmSet content to bytearraycontent var serializer = BaseConverter <T> .GetConverter(serializationFormat); var binaryData = serializer.Serialize(content); ByteArrayContent arrayContent = new ByteArrayContent(binaryData); // do not dispose HttpClient for performance issue if (client == null) { client = new HttpClient(httpClientHandler); } // add it to the default header if (this.Cookie != null) { client.DefaultRequestHeaders.Add("Cookie", this.Cookie.ToString()); } HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri.ToString()) { Content = arrayContent }; // Adding the serialization format used requestMessage.Headers.Add("dotmim-sync-serialization-format", serializationFormat.ToString()); // Adding others headers if (this.CustomHeaders != null && this.CustomHeaders.Count > 0) { foreach (var kvp in this.CustomHeaders) { requestMessage.Headers.Add(kvp.Key, kvp.Value); } } //request.AddHeader("content-type", "application/json"); if (serializationFormat == SerializationFormat.Json && !requestMessage.Content.Headers.Contains("content-type")) { requestMessage.Content.Headers.Add("content-type", "application/json"); } response = await client.SendAsync(requestMessage, cancellationToken); if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } // get response from server if (!response.IsSuccessStatusCode) { throw new Exception(response.ReasonPhrase); } // try to set the cookie for http session var headers = response?.Headers; if (headers != null) { if (headers.TryGetValues("Set-Cookie", out IEnumerable <string> tmpList)) { var cookieList = tmpList.ToList(); // var cookieList = response.Headers.GetValues("Set-Cookie").ToList(); if (cookieList != null && cookieList.Count > 0) { // Get the first cookie this.Cookie = CookieHeaderValue.ParseList(cookieList).FirstOrDefault(); } } } using (var streamResponse = await response.Content.ReadAsStreamAsync()) if (streamResponse.CanRead && streamResponse.Length > 0) { responseMessage = serializer.Deserialize(streamResponse); } return(responseMessage); } catch (TaskCanceledException ex) { throw ex; } catch (Exception e) { if (response == null || response.Content == null) { throw e; } try { var exrror = await response.Content.ReadAsStringAsync(); WebSyncException webSyncException = JsonConvert.DeserializeObject <WebSyncException>(exrror); if (webSyncException != null) { throw webSyncException; } } catch (WebSyncException) { throw; } catch (Exception) { throw; } throw e; } }