public DataResult <int> CreateUriForClient(int clientId, UriModel uri) { var uriTypes = m_uriTypeUoW.GetAllUriTypes(); var newUri = new UriEntity { Uri = uri.Value, UriTypes = new HashSet <UriTypeEntity>(uri.UriTypes.Select(x => uriTypes.FirstOrDefault(y => y.Value == x.UriTypeValue))), }; try { var result = m_uriUoW.CreateUriForClient(clientId, newUri); return(Success(result)); } catch (NoResultException <ClientEntity> e) { m_logger.LogWarning(e); return(Error <int>(m_translator.Translate("invalid-client-id"), DataResultErrorCode.ClientNotExistId)); } catch (DatabaseException e) { m_logger.LogWarning(e); return(Error <int>(e.Message)); } }
public string GetBuildUri(string uri) { Regex regx = new Regex(@"\b(?<=(http|https)://)[\w- ./?%&=]*$"); string encode = regx.Replace(uri, new MatchEvaluator(ReplaceURl)); string ReplaceURl(Match m) { string x = m.ToString(); x = Uri.EscapeUriString(x); return(x); } var uriModel = new UriModel() { Id = Guid.NewGuid().ToString(), Uri = encode }; _context.UriModel.Add(uriModel); _context.SaveChanges(); var request = this.HttpContext.Request; var path = $"{request.Host.ToUriComponent()}/api/UriModels/redirect?id={uriModel.Id}"; return($"{request.Scheme}://{path}"); }
public OperationMetadata(UriModel uri, IMember returnType) { Uri = uri; DesiredReturnType = returnType; ResponseCodes = new List <ResponseCode>(); UriParser = new UriParameterParser(Uri.Uri); }
public async Task <IActionResult> PutUriModel([FromRoute] string id, [FromBody] UriModel uriModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != uriModel.Id) { return(BadRequest()); } _context.Entry(uriModel).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UriModelExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public UriModel Assemble(string inputUri) { if (!_matchingRules.IsValid(inputUri)) { return new UriModel { Uri = inputUri, IsValid = false } } ; var model = new UriModel { Uri = inputUri, IsValid = true, Scheme = _matchingRules.GetScheme(inputUri), Host = _matchingRules.GetHost(inputUri), Port = _matchingRules.GetPort(inputUri), Authority = _matchingRules.GetAuthority(inputUri), PathParams = _matchingRules.GetPathParams(inputUri), QueryParams = _matchingRules.GetQueryParams(inputUri), Fragment = _matchingRules.GetFragment(inputUri) }; return(model); } }
public OperationGroup Group(ResourceModel resourceModel, UriModel uriModel, OperationMetadata operation) { if (IsUnknownReturnType(operation.ReturnType)) { return(new OperationGroup { Name = "Unknown", Path = "unknown" }); } if (IsEnumerableButNotAString(operation)) { var collectionType = operation.ReturnType.GetElementType(); if (operation.ReturnType.IsGenericType) { collectionType = operation.ReturnType.GetGenericArguments()[0]; } return(new OperationGroup { Name = "Collection of " + collectionType.Name, Path = collectionType.Name.ToLower() + "[]" }); } return(new OperationGroup { Name = operation.ReturnType.Name, Path = operation.ReturnType.Name.ToLower() }); }
public CustomizedProxyHandler(string remoteApiBasePath, UriModel model, string propertyNamePrefix, bool hyperlinkWithDebugInformation, int headRetryCounter) { _remoteApiBasePath = remoteApiBasePath; _uriModel = model; _propertyNamePrefix = propertyNamePrefix; _hyperlinkWithDebugInformation = hyperlinkWithDebugInformation; HeadRetryCounter = headRetryCounter; }
public void Instantiation_with_Utility_and_URI_confirmation_token_not_null() { var uri = "https://www.google.com"; var util = new Utility(); var url = new UriModel(util, uri); Assert.IsNotNull(url.ConfirmationCode, "Confirmation code should be auto-populated when not provided"); }
public UriDefinition(ResourceDefinition resourceDefinition, string uri) { _resourceDefinition = resourceDefinition; _uriModel = new UriModel { Uri = uri }; _resourceDefinition.Registration.Uris.Add(_uriModel); }
public UriModel Create(string uri, string shortUri) { UriModel dto = new UriModel(); dto.Uri = uri; dto.ShortUri = shortUri; _uris.InsertOne(dto); return(dto); }
public async Task <IActionResult> PostUriModel([FromBody] UriModel uriModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.UriModel.Add(uriModel); await _context.SaveChangesAsync(); return(CreatedAtAction("GetUriModel", new { id = uriModel.Id }, uriModel)); }
public void Instantiation_with_Utility_throws_no_Exception() { try { var util = new Utility(); var url = new UriModel(util); } catch (Exception ex) { Assert.Fail($"Expected no exception but got: {ex.ToString()}"); } }
public IUriDefinition <T> AtUri(Expression <Func <T, string> > uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } var uriModel = new UriModel { Uri = new UriExpressionVisitor().GenerateUri(typeof(T), uri) }; Resource.Uris.Add(uriModel); return(new UriDefinition <T>(this, uriModel)); }
public void Instantiation_with_Utility_and_URI_throws_no_Exception() { try { var uri = "https://www.google.com"; var util = new Utility(); var url = new UriModel(util, uri); } catch (Exception ex) { Assert.Fail($"Expected no exception but got: {ex.ToString()}"); } }
/// <summary> /// Returns true, if the passed <see cref="UriModel"/> contains variable path segments that have more than one path parameter. /// </summary> /// <param name="uriModel"></param> /// <returns></returns> private bool HasUriModelVariablePathSegmentsWithMoreThanOnePathParameter(UriModel uriModel) { IList <PathSegment> variablePathSegments = uriModel.Root.QuerySubTree.IsVariable().Results; foreach (PathSegment variablePathSegment in variablePathSegments) { if (variablePathSegment.PathParameters.Count > 1) { return(true); } } return(false); }
public new IUriDefinition <T> AtUri(string uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } var uriModel = new UriModel { Uri = uri, ResourceModel = Resource }; Resource.Uris.Add(uriModel); return(new UriDefinition <T>(this, uriModel)); }
public UriRegistration(string uri, object resourceKey, string uriName = null, CultureInfo ci = null) { UriModel = new UriModel { Language = ci, Name = uriName, Uri = uri ?? throw new ArgumentNullException(nameof(uri)) }; ResourceModel = new ResourceModel { ResourceKey = resourceKey ?? throw new ArgumentNullException(nameof(resourceKey)), Uris = { UriModel } }; }
public IActionResult Post([FromBody] FormDTO formDto) { try { Uri uri = new Uri(formDto.Uri); formDto.Uri = uri.AbsoluteUri; } catch (UriFormatException ex) { var res = new Dictionary <string, string>(); res.Add("Uri", "Invalid Uri."); return(BadRequest(res)); } var uriModel = _uriRepository.FindByField(FIELD_ORIGINAL, formDto.Uri); if (uriModel != null) { formDto.Alias = GetBaseUrl(Request, uriModel.Alias); return(Ok(formDto)); } else { string token = null; uriModel = null; for (var count = 0; count < 20; count++) { token = Token.Generate(); uriModel = _uriRepository.FindByField(FIELD_ALIAS, token); if (uriModel == null) { break; } } uriModel = new UriModel { Original = formDto.Uri, Alias = token }; _uriRepository.Add(uriModel); formDto.Alias = GetBaseUrl(Request, token); return(Created("", formDto)); } }
public static HasTheUri TheUri(this IHas anchor, string uri) { var target = (IFluentTarget)anchor; var uriModel = new UriModel { Uri = uri }; var resourceModel = new ResourceModel { Uris = { uriModel }, Handlers = { new ReflectionBasedTypeSystem().FromClr <WebFormsDefaultHandler>() } }; target.Repository.ResourceRegistrations.Add(resourceModel); return(new HasTheUri(resourceModel, uriModel)); }
public ActionResult Shortened(LocationModel location) { var repo = (UriRepository)Session["repo"]; if (repo == null) { repo = new UriRepository(); } var uri = new UriModel(new Helpers.Utility(), location.FullURI, location.ConfirmationCode); repo.Add(uri); uri = repo.Get(uri.ShortURI); // if uri already exists, use original confirmation token, etc. Session["repo"] = repo; return(View(nameof(Shortened), uri.Location)); }
public OperationGroup Group(ResourceModel resourceModel, UriModel uriModel, OperationMetadata operation) { var operationCanBeGroupedByUri = _groupRegex.Match(uriModel.Uri); if (!operationCanBeGroupedByUri.Success) { return(new OperationGroup { Name = "everything else", Path = "misc" }); } return(new OperationGroup { Name = operationCanBeGroupedByUri.Groups[1].Value.ToLower(), Path = operationCanBeGroupedByUri.Groups[1].Value }); }
public void Print(UriModel uriModel) { if (!uriModel.IsValid) { Console.WriteLine($"Not a valid URI - {uriModel.Uri}"); Console.WriteLine(); return; } Console.WriteLine($"URI - {CheckForEmpty(uriModel.Uri)}"); Console.WriteLine($"Scheme - {CheckForEmpty(uriModel.Scheme)}"); Console.WriteLine($"Authority - {CheckForEmpty(uriModel.Authority)}"); Console.WriteLine($"Host - {CheckForEmpty(uriModel.Host)}"); Console.WriteLine($"Port - {CheckForEmpty(uriModel.Port)}"); Console.WriteLine($"Path - {CheckForEmpty(string.Join(", ", uriModel.PathParams))}"); Console.WriteLine($"Query - {CheckForEmpty(string.Join(", ", uriModel.QueryParams))}"); Console.WriteLine($"Fragment - {CheckForEmpty(uriModel.Fragment)}"); Console.WriteLine(); }
private void AddOneToOneReachabilityAssociations(JObject data, IList <KeyValuePair <PathSegment, string> > pathSegmentsRepresentingStableUriPath) { //extract path segment representing the queried or manipulated resource (a check whether it exists has been already done before) PathSegment pathSegmentRepresentingQueriedOrManipulatedResource = pathSegmentsRepresentingStableUriPath[pathSegmentsRepresentingStableUriPath.Count - 1].Key; foreach (ReachabilityPath reachabilityAssociation in ((CustomizedPathSegment)pathSegmentRepresentingQueriedOrManipulatedResource).ReachabilityPaths) { //filter for one-to-one reachability associations if (reachabilityAssociation.Type == ReachabilityPathType.oneToOne) { //create stable URI path pointing on target IList <KeyValuePair <PathSegment, string> > pathSegmentsToTarget = _uriModel.GetPathSegmentsByStablePathSegments(reachabilityAssociation.Target, ConvertListToDictionary(pathSegmentsRepresentingStableUriPath)); string pathToTarget = UriModel.BuildFullPath(pathSegmentsToTarget); //send pre-flight request: PreflightResult preflightResult = SendPreflight(pathToTarget); if (preflightResult.StatusCode < 200 || preflightResult.StatusCode >= 300) { if (_hyperlinkWithDebugInformation) { Hyperlink hyperlink = new Hyperlink() { Href = pathToTarget, Rel = pathSegmentRepresentingQueriedOrManipulatedResource.IsAncestorOf(reachabilityAssociation.Target) ? DESCENDANT_REL : ANCESTOR_REL, Debug_statusCode = preflightResult.StatusCode, Debug_msg = preflightResult.Message }; this.AddObjectToLinksArray(data, hyperlink); } } else { Hyperlink hyperlink = new Hyperlink() { Href = pathToTarget, Rel = pathSegmentRepresentingQueriedOrManipulatedResource.IsAncestorOf(reachabilityAssociation.Target) ? DESCENDANT_REL : ANCESTOR_REL }; this.AddObjectToLinksArray(data, hyperlink); } } } }
/// <summary>Modelses this instance.</summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public virtual IEnumerable <T> Models <T>() { if (UriModel != null) { if (UriModel.GetType() == typeof(T) || UriModel.GetType().IsSubclassOf(typeof(T))) { yield return((T)UriModel); } } if (BodyModel != null) { if (BodyModel.GetType() == typeof(T) || BodyModel.GetType().IsSubclassOf(typeof(T))) { yield return((T)BodyModel); } } yield break; }
public ActionResult Index() { ViewBag.Title = "UrlShortener"; // TODO: instantiate a repository // add something to it for testing // store the repository in a Session variable // UGH SESSION VARS var repo = new UriRepository(); var uri = new UriModel(new Helpers.Utility(), "http://www.michaelpaulukonis.com"); // TODO: controller's dependencies should be mocked! repo.Add(uri); Session["repo"] = repo; var location = new LocationModel(); return(View(location)); }
public IUriDefinition <T> AtUri(Expression <Func <T, string> > uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } var compiled = uri.Compile(); string compiledUntyped(object resource) => compiled((T)resource); var uriModel = new UriModel { Uri = new UriExpressionVisitor().GenerateUri(typeof(T), uri), ResourceModel = Resource, Properties = { ["compiled"] = (Func <object, string>)compiledUntyped } }; Resource.Uris.Add(uriModel); return(new UriDefinition <T>(this, uriModel)); }
public string Get(string uriName) { Uri uriResult; UriResultModel result = new UriResultModel(); bool isValidUri = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult); result.IsValid = isValidUri; if (result.IsValid) { UriModel model = _uriService.GetByUri(uriResult.AbsoluteUri); if (model == null) { string tempId = Helper.Generator.GetNextId(); while (_uriService.GetByShortUri(tempId) != null) { tempId = Helper.Generator.GetNextId(); } model = _uriService.Create(uriResult.AbsoluteUri, tempId); } result.Url = model.ShortUri; } return(JsonConvert.SerializeObject(result)); }
public TemplatedUriMatch(ResourceModel resourceModel, UriModel uriModel, UriTemplateMatch match) { ResourceModel = resourceModel; UriModel = uriModel; Match = match; }
public UriDefinition(ResourceDefinition <TResource> resourceDefinition, UriModel uriModel) : base(resourceDefinition, uriModel) { _resourceDefinition = resourceDefinition; }
public UriRegistration(ResourceModel resourceModel, UriModel uriModel) { ResourceModel = resourceModel; UriModel = uriModel; }