/// <summary> /// Handler method for SOAP control requests. /// </summary> /// <param name="service">The service whose action was called.</param> /// <param name="messageStream">The stream which contains the HTTP message body with the SOAP envelope.</param> /// <param name="streamEncoding">Encoding of the <paramref name="messageStream"/>.</param> /// <param name="subscriberSupportsUPnP11">Should be set if the requester sent a user agent header which denotes a UPnP /// version of 1.1. If set to <c>false</c>, in- and out-parameters with extended data type will be deserialized/serialized /// using the string-equivalent of the values.</param> /// <param name="context">Context object holding data for the current action call.</param> /// <param name="result">SOAP result - may be an action result, a SOAP fault or <c>null</c> if no body should /// be sent in the HTTP response.</param> /// <returns>HTTP status code to be sent. Should be /// <list> /// <item><see cref="HttpStatusCode.OK"/> If the action could be evaluated correctly and produced a SOAP result.</item> /// <item><see cref="HttpStatusCode.InternalServerError"/> If the result is a SOAP fault.</item> /// <item><see cref="HttpStatusCode.BadRequest"/> If the message stream was malformed.</item> /// </list> /// </returns> public static HttpStatusCode HandleRequest(DvService service, Stream messageStream, Encoding streamEncoding, bool subscriberSupportsUPnP11, CallContext context, out string result) { UPnPError res; try { IList <object> inParameterValues = null; // Default to null if there aren't parameters, will be lazily initialized later DvAction action; using (StreamReader streamReader = new StreamReader(messageStream, streamEncoding)) using (XmlReader reader = XmlReader.Create(streamReader, UPnPConfiguration.DEFAULT_XML_READER_SETTINGS)) { reader.MoveToContent(); // Parse SOAP envelope reader.ReadStartElement("Envelope", UPnPConsts.NS_SOAP_ENVELOPE); reader.ReadStartElement("Body", UPnPConsts.NS_SOAP_ENVELOPE); // Reader is positioned at the action element string serviceTypeVersion_URN = reader.NamespaceURI; string type; int version; // Parse service and action if (!ParserHelper.TryParseTypeVersion_URN(serviceTypeVersion_URN, out type, out version)) { throw new MediaPortal.Utilities.Exceptions.InvalidDataException("Unable to parse service type and version URN '{0}'", serviceTypeVersion_URN); } string actionName = reader.LocalName; if (!service.Actions.TryGetValue(actionName, out action)) { result = CreateFaultDocument(401, "Invalid Action"); return(HttpStatusCode.InternalServerError); } IEnumerator <DvArgument> formalArgumentEnumer = action.InArguments.GetEnumerator(); if (!SoapHelper.ReadEmptyStartElement(reader)) // Action name { while (reader.NodeType != XmlNodeType.EndElement) { string argumentName = reader.Name; // Arguments don't have a namespace, so take full name if (!formalArgumentEnumer.MoveNext() || formalArgumentEnumer.Current.Name != argumentName) { // Too many arguments result = CreateFaultDocument(402, "Invalid Args"); return(HttpStatusCode.InternalServerError); } object value; if (SoapHelper.ReadNull(reader)) { value = null; } else { res = formalArgumentEnumer.Current.SoapParseArgument(reader, !subscriberSupportsUPnP11, out value); if (res != null) { result = CreateFaultDocument(res.ErrorCode, res.ErrorDescription); return(HttpStatusCode.InternalServerError); } } if (inParameterValues == null) { inParameterValues = new List <object>(); } inParameterValues.Add(value); } } if (formalArgumentEnumer.MoveNext()) { // Too few arguments result = CreateFaultDocument(402, "Invalid Args"); return(HttpStatusCode.InternalServerError); } } IList <object> outParameterValues; // Invoke action try { res = action.InvokeAction(inParameterValues, out outParameterValues, false, context); // outParameterValues can be null if the action has no output parameters. Setting it to an empty list makes // it easier to check parameter count later. if (outParameterValues == null) { outParameterValues = EMPTY_OBJECT_LIST; } } catch (Exception e) { UPnPConfiguration.LOGGER.Warn("SOAPHandler: Error invoking UPnP action '{0}'", e, action.Name); result = CreateFaultDocument(501, "Action Failed"); return(HttpStatusCode.InternalServerError); } if (res != null) { result = CreateFaultDocument(res.ErrorCode, res.ErrorDescription); return(HttpStatusCode.InternalServerError); } // Check output parameters IList <DvArgument> formalArguments = action.OutArguments; if (outParameterValues.Count != formalArguments.Count) { result = CreateFaultDocument(501, "Action Failed"); return(HttpStatusCode.InternalServerError); } IList <OutParameter> outParams = formalArguments.Select((t, i) => new OutParameter(t, outParameterValues[i])).ToList(); result = CreateResultDocument(action, outParams, !subscriberSupportsUPnP11); return(HttpStatusCode.OK); } catch (Exception e) { UPnPConfiguration.LOGGER.Warn("Error handling SOAP request: " + e.Message); // Don't log the whole exception; it's only a communication error with a client result = null; return(HttpStatusCode.BadRequest); } }
public static bool Parse(SyntaxContext context, int position) { var list = context.list; var offset = 0; var index = position; var count = 0; var isMissed = false; while (ParenParser.Parse(context, index)) { ; } while (TableIParser.Parse(context, index)) { ; } while (TableSParser.Parse(context, index)) { ; } while (ListParser.Parse(context, index)) { ; } while (PropertyParser.Parse(context, index)) { ; } while (IndexParser.Parse(context, index)) { ; } while (CallParser.Parse(context, index)) { ; } while (NotParser.Parse(context, index)) { ; } while (LengthParser.Parse(context, index)) { ; } while (NegateParser.Parse(context, index)) { ; } while (PowerParser.Parse(context, index)) { ; } while (MultiplyParser.Parse(context, index)) { ; } while (DivisionParser.Parse(context, index)) { ; } while (ModParser.Parse(context, index)) { ; } while (AddParser.Parse(context, index)) { ; } while (SubtractParser.Parse(context, index)) { ; } while (ConcatParser.Parse(context, index)) { ; } while (LessParser.Parse(context, index)) { ; } while (GreaterParser.Parse(context, index)) { ; } while (LessEqualParser.Parse(context, index)) { ; } while (GreaterEqualParser.Parse(context, index)) { ; } while (EqualParser.Parse(context, index)) { ; } while (NotEqualParser.Parse(context, index)) { ; } if (!list[index].isRightValue) { return(false); } else { // ignored } offset += 1; index = position + offset; if (!ParserHelper.IsKeyword(list[index], "and")) { return(false); } else { // ignored } offset += 1; index = position + offset; while (ParenParser.Parse(context, index)) { ; } while (TableIParser.Parse(context, index)) { ; } while (TableSParser.Parse(context, index)) { ; } while (ListParser.Parse(context, index)) { ; } while (PropertyParser.Parse(context, index)) { ; } while (IndexParser.Parse(context, index)) { ; } while (CallParser.Parse(context, index)) { ; } while (NotParser.Parse(context, index)) { ; } while (LengthParser.Parse(context, index)) { ; } while (NegateParser.Parse(context, index)) { ; } while (PowerParser.Parse(context, index)) { ; } while (MultiplyParser.Parse(context, index)) { ; } while (DivisionParser.Parse(context, index)) { ; } while (ModParser.Parse(context, index)) { ; } while (AddParser.Parse(context, index)) { ; } while (SubtractParser.Parse(context, index)) { ; } while (ConcatParser.Parse(context, index)) { ; } while (LessParser.Parse(context, index)) { ; } while (GreaterParser.Parse(context, index)) { ; } while (LessEqualParser.Parse(context, index)) { ; } while (GreaterEqualParser.Parse(context, index)) { ; } while (EqualParser.Parse(context, index)) { ; } while (NotEqualParser.Parse(context, index)) { ; } if (!list[index].isRightValue) { return(false); } else { // ignored } offset += 1; index = position + offset; context.Insert(position, ExpressionCreator.CreateAnd(list, position, offset)); context.Remove(position + 1, offset); return(true); }
internal static VertexData getVertex(FileStream fs, Header header) { VertexData vertex = new VertexData(); vertex.Position = ParserHelper.getFloat3(fs); vertex.Normal = ParserHelper.getFloat3(fs); vertex.UV = ParserHelper.getFloat2(fs); vertex.AdditionalUV = new Vector4[header.AdditionalUVCount]; for (int i = 0; i < header.AdditionalUVCount; i++) { vertex.AdditionalUV[i] = ParserHelper.getFloat4(fs); } switch (ParserHelper.getByte(fs)) { //BDEF1 case 0: vertex.TranslationType = WeightTranslationType.BDEF1; vertex.BoneWeight = new BoneWeight.BDEF1() { boneIndex = ParserHelper.getIndex(fs, header.BoneIndexSize) }; break; case 1: vertex.TranslationType = WeightTranslationType.BDEF2; vertex.BoneWeight = new BoneWeight.BDEF2() { Bone1ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone2ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Weight = ParserHelper.getFloat(fs) }; break; case 2: vertex.TranslationType = WeightTranslationType.BDEF4; vertex.BoneWeight = new BoneWeight.BDEF4() { Bone1ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone2ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone3ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone4ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Weights = ParserHelper.getFloat4(fs) }; break; case 3: vertex.TranslationType = WeightTranslationType.SDEF; vertex.BoneWeight = new BoneWeight.SDEF() { Bone1ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone2ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone1Weight = ParserHelper.getFloat(fs), SDEF_C = ParserHelper.getFloat3(fs), SDEF_R0 = ParserHelper.getFloat3(fs), SDEF_R1 = ParserHelper.getFloat3(fs) }; break; case 4: if (header.Version != 2.1f) { throw new InvalidDataException("QDEFはPMX2.1でのみサポートされます。"); } vertex.TranslationType = WeightTranslationType.QDEF; vertex.BoneWeight = new BoneWeight.QDEF() { Bone1ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone2ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone3ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Bone4ReferenceIndex = ParserHelper.getIndex(fs, header.BoneIndexSize), Weights = ParserHelper.getFloat4(fs) }; break; default: throw new InvalidDataException(); } vertex.EdgeMagnification = ParserHelper.getFloat(fs); return(vertex); }
/// <summary> /// Processes a SPARQL Query sending the results to a RDF/SPARQL Results handler as appropriate /// </summary> /// <param name="rdfHandler">RDF Handler</param> /// <param name="resultsHandler">Results Handler</param> /// <param name="query">SPARQL Query</param> public void ProcessQuery(IRdfHandler rdfHandler, ISparqlResultsHandler resultsHandler, SparqlQuery query) { //Do Handler null checks before evaluating the query if (query == null) { throw new ArgumentNullException("query", "Cannot evaluate a null query"); } if (rdfHandler == null && (query.QueryType == SparqlQueryType.Construct || query.QueryType == SparqlQueryType.Describe || query.QueryType == SparqlQueryType.DescribeAll)) { throw new ArgumentNullException("rdfHandler", "Cannot use a null RDF Handler when the Query is a CONSTRUCT/DESCRIBE"); } if (resultsHandler == null && (query.QueryType == SparqlQueryType.Ask || SparqlSpecsHelper.IsSelectQuery(query.QueryType))) { throw new ArgumentNullException("resultsHandler", "Cannot use a null resultsHandler when the Query is an ASK/SELECT"); } //Handle the Thread Safety of the Query Evaluation #if !NO_RWLOCK ReaderWriterLockSlim currLock = (this._dataset is IThreadSafeDataset) ? ((IThreadSafeDataset)this._dataset).Lock : this._lock; try { currLock.EnterReadLock(); #endif //Reset Query Timers query.QueryExecutionTime = null; query.QueryTime = -1; query.QueryTimeTicks = -1; bool datasetOk = false, defGraphOk = false; try { //Set up the Default and Active Graphs IGraph defGraph; if (query.DefaultGraphs.Any()) { //Default Graph is the Merge of all the Graphs specified by FROM clauses Graph g = new Graph(); foreach (Uri u in query.DefaultGraphs) { if (this._dataset.HasGraph(u)) { g.Merge(this._dataset[u], true); } else { throw new RdfQueryException("A Graph with URI '" + u.ToString() + "' does not exist in this Triple Store, this URI cannot be used in a FROM clause in SPARQL queries to this Triple Store"); } } defGraph = g; this._dataset.SetDefaultGraph(defGraph); } else if (query.NamedGraphs.Any()) { //No FROM Clauses but one/more FROM NAMED means the Default Graph is the empty graph defGraph = new Graph(); this._dataset.SetDefaultGraph(defGraph); } else { defGraph = this._dataset.DefaultGraph; this._dataset.SetDefaultGraph(defGraph); } defGraphOk = true; this._dataset.SetActiveGraph(defGraph); datasetOk = true; //Convert to Algebra and execute the Query SparqlEvaluationContext context = this.GetContext(query); BaseMultiset result; try { context.StartExecution(); ISparqlAlgebra algebra = query.ToAlgebra(); result = context.Evaluate(algebra); //query.Evaluate(context); context.EndExecution(); query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks); query.QueryTime = context.QueryTime; query.QueryTimeTicks = context.QueryTimeTicks; } catch (RdfQueryException) { context.EndExecution(); query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks); query.QueryTime = context.QueryTime; query.QueryTimeTicks = context.QueryTimeTicks; throw; } catch { context.EndExecution(); query.QueryExecutionTime = new TimeSpan(context.QueryTimeTicks); query.QueryTime = context.QueryTime; query.QueryTimeTicks = context.QueryTimeTicks; throw; } //Return the Results switch (query.QueryType) { case SparqlQueryType.Ask: case SparqlQueryType.Select: case SparqlQueryType.SelectAll: case SparqlQueryType.SelectAllDistinct: case SparqlQueryType.SelectAllReduced: case SparqlQueryType.SelectDistinct: case SparqlQueryType.SelectReduced: //For SELECT and ASK can populate a Result Set directly from the Evaluation Context //return new SparqlResultSet(context); resultsHandler.Apply(context); break; case SparqlQueryType.Construct: //Create a new Empty Graph for the Results try { rdfHandler.StartRdf(); foreach (String prefix in query.NamespaceMap.Prefixes) { if (!rdfHandler.HandleNamespace(prefix, query.NamespaceMap.GetNamespaceUri(prefix))) { ParserHelper.Stop(); } } //Construct the Triples for each Solution foreach (ISet s in context.OutputMultiset.Sets) { //List<Triple> constructedTriples = new List<Triple>(); try { ConstructContext constructContext = new ConstructContext(rdfHandler, s, false); foreach (IConstructTriplePattern p in query.ConstructTemplate.TriplePatterns.OfType <IConstructTriplePattern>()) { try { if (!rdfHandler.HandleTriple(p.Construct(constructContext))) { ParserHelper.Stop(); } //constructedTriples.Add(((IConstructTriplePattern)p).Construct(constructContext)); } catch (RdfQueryException) { //If we get an error here then we could not construct a specific triple //so we continue anyway } } } catch (RdfQueryException) { //If we get an error here this means we couldn't construct for this solution so the //entire solution is discarded continue; } //h.Assert(constructedTriples); } rdfHandler.EndRdf(true); } catch (RdfParsingTerminatedException) { rdfHandler.EndRdf(true); } catch { rdfHandler.EndRdf(false); throw; } break; case SparqlQueryType.Describe: case SparqlQueryType.DescribeAll: //For DESCRIBE we retrieve the Describe algorithm and apply it ISparqlDescribe describer = query.Describer; describer.Describe(rdfHandler, context); break; default: throw new RdfQueryException("Unknown query types cannot be processed by Leviathan"); } } finally { if (defGraphOk) { this._dataset.ResetDefaultGraph(); } if (datasetOk) { this._dataset.ResetActiveGraph(); } } #if !NO_RWLOCK } finally { currLock.ExitReadLock(); } #endif }
public void PrintProgram_CommentBomb_ShouldFormatCorrectly() { var programSyntax = ParserHelper.Parse( @" // I can be anywhere /* * I can * be anywhere */ /* I can be any where */ module /* I can be anywhere */ foo /* I can be anywhere */ './myModule' = /* I can be anywhere *//* I can be anywhere */{ name/* I can be any where */ : value // I can be anywhere } var foo = { // I can be any where } param foo bool { default: (true /* I can be anywhere */ ? /* I can be any where */null : false /* I can be anywhere */) /* I can be anywhere */} /* I can be anywhere */ // I can be anywhere // I can be anywhere param foo string // I can be anywhere // I can be anywhere param bar string = { /* I can be anywhere */ /* I can be anywhere */ foo : true bar /* I can be anywhere */ : false /* I can be anywhere */ baz : [ bar az /* I can be anywhere */ .func /* I can be anywhere */ ('foobar', '/', 'bar')[/* I can be anywhere */ 1 /* I can be anywhere */] /* I can be anywhere */ . /* I can be anywhere */ baz // I can be anywhere true { m: [ ] /* I can be any where */ kkk: [ // I can be any where // I can be any where ] x: y p: q /* I can be any where */ // I can be any where // I can be anywhere } null /* I can be anywhere *//* I can be anywhere */] // I can be any where } /* I can be anywhere */ "); var output = PrettyPrinter.PrintProgram(programSyntax, CommonOptions); output.Should().Be( @"// I can be anywhere /* * I can * be anywhere */ /* I can be any where */module /* I can be anywhere */foo /* I can be anywhere */'./myModule' = /* I can be anywhere */ /* I can be anywhere */{ name /* I can be any where */: value // I can be anywhere } var foo = { // I can be any where } param foo bool { default: (true /* I can be anywhere */? /* I can be any where */null : false /* I can be anywhere */) /* I can be anywhere */ } /* I can be anywhere */ // I can be anywhere // I can be anywhere param foo string // I can be anywhere // I can be anywhere param bar string = { /* I can be anywhere */ /* I can be anywhere */ foo: true bar /* I can be anywhere */: false /* I can be anywhere */baz: [ bar az /* I can be anywhere */.func /* I can be anywhere */('foobar', '/', 'bar')[ /* I can be anywhere */1 /* I can be anywhere */] /* I can be anywhere */. /* I can be anywhere */baz // I can be anywhere true { m: [] /* I can be any where */ kkk: [ // I can be any where // I can be any where ] x: y p: q /* I can be any where */ // I can be any where // I can be anywhere } null /* I can be anywhere */ /* I can be anywhere */ ] // I can be any where } /* I can be anywhere */"); }
public static ParserNode Parse(string input, bool strict) { var tree = ParserHelper.Parse <JSONLexer, JSONParser, JSONParser.JsonContext>(input, parser => parser.json(), strict); return(new JSONVisitor().Visit(tree)); }
public void DataSourceAdd(string name, string description, string handler = null, string remotename = null, string copyright = "", string uri = "", List <DataSourceMapping> addMapping = null, List <String> removeMapping = null) { ushort?remoteID = null; string resolvedHandlerAssemblyQualifiedName = null; //if (string.IsNullOrEmpty(remotename) && !String.IsNullOrEmpty(handler)) // ExtractHandlerAssemblyAndTypeName(handler, out toLoad, out handlerType); if (!string.IsNullOrEmpty(remotename) && String.IsNullOrEmpty(handler)) //federated { IFetchConfiguration remoteConfig; try { RemoteFetchClient client = new RemoteFetchClient(new Uri(uri)); remoteConfig = client.GetConfiguration(DateTime.MaxValue); } catch (Exception ex) { throw new ArgumentException("Failed to retrieve configuration of the remote service.\n Exception message: " + ex.Message); } if (!remoteConfig.DataSources.Any(ds => ds.Name == remotename)) { throw new ArgumentException("Data source with given name does not exist on the remote service."); } remoteID = remoteConfig.DataSources.Where(ds => ds.Name == remotename).FirstOrDefault().ID; } else if (string.IsNullOrEmpty(remotename) && !String.IsNullOrEmpty(handler))//local { AssemblyStore gac = null; if (isConnectedToCloud) { gac = astore; } resolvedHandlerAssemblyQualifiedName = ExtractHandlerAssemblyAndTypeName(handler, gac); } else if (!string.IsNullOrEmpty(remotename) && !String.IsNullOrEmpty(handler)) { throw new ArgumentException("Handler and remote name can not be specified simultaneously."); } var localDs = db.GetDataSources(DateTime.MaxValue).ToArray(); if (localDs.All(x => x.Name != name)) { db.AddDataSource(name, description, copyright, resolvedHandlerAssemblyQualifiedName, ParserHelper.AppendDataSetUriWithDimensions(uri), remoteID, remotename); } else { throw new ArgumentException("Data source with given name already exists."); } SetMappings(name, addMapping, null); }
public void PrintProgram_TooManyNewlines_RemovesExtraNewlines() { const string programText = @" param foo int var bar = 1 + mod(foo, 3) var baz = { x: [ 111 222 333 444 555 666 ] y: { mmm: nnn ppp: qqq aaa: bbb ccc: ddd } } "; ProgramSyntax programSyntax = ParserHelper.Parse(programText); var output = PrettyPrinter.PrintProgram(programSyntax, CommonOptions); output.Should().Be( @"param foo int var bar = 1 + mod(foo, 3) var baz = { x: [ 111 222 333 444 555 666 ] y: { mmm: nnn ppp: qqq aaa: bbb ccc: ddd } }"); }
public IFeatureGenerator CreateFeatureGenerator(bool parallelCode, string[] ignoreParallelTags) { var container = GeneratorContainerBuilder.CreateContainer(new SpecFlowConfigurationHolder(ConfigSource.Default, null), new ProjectSettings(), Enumerable.Empty <string>()); var specFlowConfiguration = container.Resolve <SpecFlowConfiguration>(); specFlowConfiguration.MarkFeaturesParallelizable = parallelCode; specFlowConfiguration.SkipParallelizableMarkerForTags = ignoreParallelTags ?? Enumerable.Empty <string>().ToArray(); container.RegisterInstanceAs(CreateTestGeneratorProvider()); var generator = container.Resolve <UnitTestFeatureGeneratorProvider>().CreateGenerator(ParserHelper.CreateAnyDocument()); return(generator); }
private void Application_BeginRequest(Object source, EventArgs e) { var installerPath = "~/Installer/"; var absInstallerUrl = URIHelper.ConvertToAbsUrl(installerPath); var absInstallerPath = URIHelper.ConvertToAbsPath(installerPath); if (Request.CurrentExecutionFilePathExtension == "" && !Request.Url.AbsoluteUri.StartsWith(absInstallerUrl)) { if (Directory.Exists(absInstallerPath) && AppSettings.EnableInstaller) { Response.Redirect(installerPath); } } if (AppSettings.ForceWWWRedirect) { var isSubDomain = (Request.Url.AbsoluteUri.Split('.').Length > 2); if (!AppSettings.IsRunningOnProd && (!Request.Url.Host.StartsWith("www.") && !Request.Url.Host.StartsWith("localhost") && !isSubDomain)) { Response.RedirectPermanent(Request.Url.AbsoluteUri.Replace("://", "://www.")); } } else { if (Request.Url.Host.StartsWith("www.")) { Response.RedirectPermanent(Request.Url.AbsoluteUri.Replace("www.", "")); } } BaseService.AddResponseHeaders(); var virtualPathRequest = HttpContext.Current.Request.Path.EndsWith("/"); if (virtualPathRequest) { Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.Cache.SetNoStore(); } if (isFirstApplicationRequest) { ContextHelper.ClearAllMemoryCache(); FrameworkBaseMedia.InitConnectionSettings(AppSettings.GetConnectionSettings()); isFirstApplicationRequest = false; } if (Request.Url.AbsolutePath.Contains("robots.txt")) { var absPath = URIHelper.ConvertToAbsPath(Request.Url.AbsolutePath); if (File.Exists(absPath)) { var fileContent = File.ReadAllText(absPath); var parsedContent = ParserHelper.ParseData(fileContent, BasePage.GetDefaultTemplateVars("")); BaseService.WriteText(parsedContent); } } }
/// <summary> /// Handles SUBSCRIBE and UNSUBSCRIBE HTTP requests. /// </summary> /// <param name="request">The HTTP request instance to handle</param> /// <param name="context">The HTTP client context of the specified <paramref name="request"/>.</param> /// <param name="config">The UPnP endpoint over that the HTTP request was received.</param> /// <returns><c>true</c> if the request could be handled and a HTTP response was sent, else <c>false</c>.</returns> public bool HandleHTTPRequest(IOwinRequest request, IOwinContext context, EndpointConfiguration config) { var response = context.Response; if (request.Method == "SUBSCRIBE") { // SUBSCRIBE events string pathAndQuery = HttpUtility.UrlDecode(request.Uri.PathAndQuery); DvService service; if (config.EventSubPathsToServices.TryGetValue(pathAndQuery, out service)) { string httpVersion = request.Protocol; string userAgentStr = request.Headers.Get("USER-AGENT"); string callbackURLsStr = request.Headers.Get("CALLBACK"); string nt = request.Headers.Get("NT"); string sid = request.Headers.Get("SID"); string timeoutStr = request.Headers.Get("TIMEOUT"); int timeout = UPnPConsts.GENA_DEFAULT_SUBSCRIPTION_TIMEOUT; ICollection <string> callbackURLs = null; if ((!string.IsNullOrEmpty(timeoutStr) && (!timeoutStr.StartsWith("Second-") || !int.TryParse(timeoutStr.Substring("Second-".Length).Trim(), out timeout))) || (!string.IsNullOrEmpty(callbackURLsStr) && !TryParseCallbackURLs(callbackURLsStr, out callbackURLs))) { response.StatusCode = (int)HttpStatusCode.BadRequest; return(true); } if (!string.IsNullOrEmpty(sid) && (callbackURLs != null || !string.IsNullOrEmpty(nt))) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.ReasonPhrase = "Incompatible Header Fields"; return(true); } if (callbackURLs != null && !string.IsNullOrEmpty(nt)) { // Subscription bool subscriberSupportsUPnP11; try { if (string.IsNullOrEmpty(userAgentStr)) { subscriberSupportsUPnP11 = false; } else { int minorVersion; if (!ParserHelper.ParseUserAgentUPnP1MinorVersion(userAgentStr, out minorVersion)) { response.StatusCode = (int)HttpStatusCode.BadRequest; return(true); } subscriberSupportsUPnP11 = minorVersion >= 1; } } catch (Exception e) { UPnPConfiguration.LOGGER.Warn("GENAServerController: Error in event subscription", e); response.StatusCode = (int)HttpStatusCode.BadRequest; return(true); } if (service.HasComplexStateVariables && !subscriberSupportsUPnP11) { response.StatusCode = (int)HttpStatusCode.ServiceUnavailable; return(true); } bool validURLs = callbackURLs.All(url => url.StartsWith("http://")); if (nt != "upnp:event" || !validURLs) { response.StatusCode = (int)HttpStatusCode.PreconditionFailed; response.ReasonPhrase = "Precondition Failed"; return(true); } DateTime date; if (Subscribe(config, service, callbackURLs, httpVersion, subscriberSupportsUPnP11, ref timeout, out date, out sid)) { response.StatusCode = (int)HttpStatusCode.OK; response.Headers["DATE"] = date.ToUniversalTime().ToString("R"); response.Headers["SERVER"] = UPnPConfiguration.UPnPMachineInfoHeader; response.Headers["SID"] = sid; response.Headers["CONTENT-LENGTH"] = "0"; response.Headers["TIMEOUT"] = "Second-" + timeout; SendInitialEventNotification(sid); return(true); } response.StatusCode = (int)HttpStatusCode.ServiceUnavailable; response.ReasonPhrase = "Unable to accept renewal"; // See (DevArch), table 4-4 return(true); } if (!string.IsNullOrEmpty(sid)) { // Renewal DateTime date; if (RenewSubscription(config, sid, ref timeout, out date)) { response.StatusCode = (int)HttpStatusCode.OK; response.Headers["DATE"] = date.ToUniversalTime().ToString("R"); response.Headers["SERVER"] = UPnPConfiguration.UPnPMachineInfoHeader; response.Headers["SID"] = sid; response.Headers["CONTENT-LENGTH"] = "0"; response.Headers["TIMEOUT"] = "Second-" + timeout; return(true); } response.StatusCode = (int)HttpStatusCode.ServiceUnavailable; response.ReasonPhrase = "Unable to accept renewal"; return(true); } } } else if (request.Method == "UNSUBSCRIBE") { // UNSUBSCRIBE events string pathAndQuery = HttpUtility.UrlDecode(request.Uri.PathAndQuery); DvService service; if (config.EventSubPathsToServices.TryGetValue(pathAndQuery, out service)) { string sid = request.Headers.Get("SID"); string callbackURL = request.Headers.Get("CALLBACK"); string nt = request.Headers.Get("NT"); if (string.IsNullOrEmpty(sid) || !string.IsNullOrEmpty(callbackURL) || !string.IsNullOrEmpty(nt)) { response.StatusCode = (int)HttpStatusCode.BadRequest; response.ReasonPhrase = "Incompatible Header Fields"; return(true); } if (Unsubscribe(config, sid)) { response.StatusCode = (int)HttpStatusCode.OK; return(true); } response.StatusCode = (int)HttpStatusCode.PreconditionFailed; response.ReasonPhrase = "Precondition Failed"; return(true); } } return(false); }
private SqlString ExpandDynamicFilterParameters(SqlString sqlString, ICollection <IParameterSpecification> parameterSpecs, ISessionImplementor session) { var enabledFilters = session.EnabledFilters; if (enabledFilters.Count == 0 || !ParserHelper.HasHqlVariable(sqlString)) { return(sqlString); } Dialect.Dialect dialect = session.Factory.Dialect; string symbols = ParserHelper.HqlSeparators + dialect.OpenQuote + dialect.CloseQuote; var result = new SqlStringBuilder(); foreach (var sqlPart in sqlString) { var parameter = sqlPart as Parameter; if (parameter != null) { result.Add(parameter); continue; } var sqlFragment = sqlPart.ToString(); var tokens = new StringTokenizer(sqlFragment, symbols, true); foreach (string token in tokens) { if (ParserHelper.IsHqlVariable(token)) { string filterParameterName = token.Substring(1); string[] parts = StringHelper.ParseFilterParameterName(filterParameterName); string filterName = parts[0]; string parameterName = parts[1]; var filter = (FilterImpl)enabledFilters[filterName]; var collectionSpan = filter.GetParameterSpan(parameterName); IType type = filter.FilterDefinition.GetParameterType(parameterName); int parameterColumnSpan = type.GetColumnSpan(session.Factory); // Add query chunk string typeBindFragment = string.Join(", ", Enumerable.Repeat("?", parameterColumnSpan)); string bindFragment; if (collectionSpan.HasValue && !type.ReturnedClass.IsArray) { bindFragment = string.Join(", ", Enumerable.Repeat(typeBindFragment, collectionSpan.Value)); } else { bindFragment = typeBindFragment; } // dynamic-filter parameter tracking var filterParameterFragment = SqlString.Parse(bindFragment); var dynamicFilterParameterSpecification = new DynamicFilterParameterSpecification(filterName, parameterName, type, collectionSpan); var parameters = filterParameterFragment.GetParameters().ToArray(); var sqlParameterPos = 0; var paramTrackers = dynamicFilterParameterSpecification.GetIdsForBackTrack(session.Factory); foreach (var paramTracker in paramTrackers) { parameters[sqlParameterPos++].BackTrack = paramTracker; } parameterSpecs.Add(dynamicFilterParameterSpecification); result.Add(filterParameterFragment); } else { result.Add(token); } } } return(result.ToSqlString()); }
/// <summary> /// Parses a series of points. /// </summary> internal static PointStopCollection ParsePoints(string value) { PointStopCollection points = new PointStopCollection(); TokenizerHelper tokenizer = new TokenizerHelper(value); while (tokenizer.NextToken()) { Point point = new Point(ParserHelper.ParseDouble(tokenizer.GetCurrentToken()), ParserHelper.ParseDouble(tokenizer.NextTokenRequired())); points.Add(point); } return(points); }
public string RenderMethod(QueryNode queryNode) { var result = $"_{ParserHelper.GetTokenName(ParserHelper.GetToken(queryNode.MethodType.Value))}(#0)"; switch (queryNode.MethodType) { case QueryMethodType.Set: { // result = $"_{ParserHelper.GetTokenName((int)QueryMethodType.Set)}(#0)"; var arguments = new List <string>(); foreach (var argument in queryNode.Arguments) { var argumentValue = string.Empty; if (argument.ArgumentValueQuery != null) { argumentValue = RenderQuery(argument.ArgumentValueQuery); } else { argumentValue = argument.ArgumentValueConstant.ToQueryLanguageRepresentation(); } arguments.Add($"{RenderQuery(argument.ArgumentSubjectQuery)} = {argumentValue}"); } result = result.Replace("#0", string.Join(", ", arguments)); break; } case QueryMethodType.Add: { // result = $"{ParserHelper.GetTokenName((int)QueryMethodType.Add)}(#0)"; var arguments = new List <string>(); if (queryNode.Arguments.FirstOrDefault()?.ArgumentValueQuery != null) { arguments.Add(RenderQuery(queryNode.Arguments.First().ArgumentValueQuery)); } else { foreach (var argument in queryNode.Arguments) { var argumentValue = string.Empty; if (argument.ArgumentValueQuery != null) { argumentValue = RenderQuery(argument.ArgumentValueQuery); } else { argumentValue = argument.ArgumentValueConstant.ToQueryLanguageRepresentation(); } arguments.Add($"{RenderQuery(argument.ArgumentSubjectQuery)} = {argumentValue}"); } } result = result.Replace("#0", string.Join(", ", arguments)); result = $"{queryNode.GetNodeName()}().{result}"; break; } case QueryMethodType.Get: case QueryMethodType.Delete: result = result.Replace("#0", string.Empty); break; case QueryMethodType.ToMd: break; case QueryMethodType.ToT: break; case QueryMethodType.ToLocal: break; case QueryMethodType.Take: case QueryMethodType.Skip: result = result.Replace("#0", queryNode.Arguments.Single().ArgumentValueConstant.ToQueryLanguageRepresentation()); break; case QueryMethodType.OrderBy: break; case null: break; default: throw new ArgumentOutOfRangeException(); } // TODO: Arguments return(result); }
public void DataSourceSet(string name, string handler = null, string remotename = null, string uri = null, string copyright = null, string description = null, List <DataSourceMapping> addMapping = null, List <String> removeMapping = null) { var localDs = db.GetDataSources(DateTime.MaxValue).ToArray(); if (localDs.All(x => x.Name != name)) { throw new ArgumentException("Specified data source does not exist."); } ushort?remoteID = null; if (!String.IsNullOrEmpty(handler) && String.IsNullOrEmpty(remotename)) { AssemblyStore gac = null; if (isConnectedToCloud) { gac = new AssemblyStore(storageConnectionString); } var resolvedHandlerAssemblyQualifiedName = ExtractHandlerAssemblyAndTypeName(handler, gac); db.SetDataSourceProcessor(name, resolvedHandlerAssemblyQualifiedName, null, null); } else if (String.IsNullOrEmpty(handler) && !String.IsNullOrEmpty(remotename)) { IFetchConfiguration remoteConfig; try { RemoteFetchClient client = new RemoteFetchClient(new Uri(uri)); remoteConfig = client.GetConfiguration(DateTime.MaxValue); } catch (Exception ex) { throw new ArgumentException("Failed to retrieve configuration of the remote service.\n Exception message: " + ex.Message); } if (!remoteConfig.DataSources.Any(ds => ds.Name == remotename)) { throw new ArgumentException("Data source with given name does not exist on the remote service."); } remoteID = remoteConfig.DataSources.Where(ds => ds.Name == remotename).FirstOrDefault().ID; db.SetDataSourceProcessor(name, null, remoteID, remotename); } if (!string.IsNullOrEmpty(remotename) && !String.IsNullOrEmpty(handler)) { throw new ArgumentException("Handler and remote name can not be specified simultaneously."); } if (!String.IsNullOrEmpty(uri)) { db.SetDataSourceUri(name, ParserHelper.AppendDataSetUriWithDimensions(uri)); } //if (isHidden != null) // db.SetDataSourceHidden(name, isHidden); if (copyright != null) { db.SetDataSourceCopyright(name, copyright); } if (description != null) { db.SetDataSourceDescription(name, description); } SetMappings(name, addMapping, removeMapping); }
public void PrintProgram_CommentBeforeCloseSyntax_ShouldMoveOneLineAboveAndIndent() { var programSyntax = ParserHelper.Parse(@" param foo object = { /* I can be anywhere */ } param foo object = { /* I can be anywhere */ } param foo object = { abc: true /* I can be anywhere */} param foo object = { abc: true xyz: false /* I can be anywhere */} param foo object = { abc: true xyz: false /* I can be anywhere */} param bar array = [ /* I can be anywhere */] param bar array = [ /* I can be anywhere */] param bar array = [ true /* I can be anywhere */ ] param bar array = [ true false /* I can be anywhere */ /* I can be anywhere */]"); var output = PrettyPrinter.PrintProgram(programSyntax, CommonOptions); output.Should().Be( @"param foo object = { /* I can be anywhere */ } param foo object = { /* I can be anywhere */ } param foo object = { abc: true /* I can be anywhere */ } param foo object = { abc: true xyz: false /* I can be anywhere */ } param foo object = { abc: true xyz: false /* I can be anywhere */ } param bar array = [ /* I can be anywhere */ ] param bar array = [ /* I can be anywhere */ ] param bar array = [ true /* I can be anywhere */ ] param bar array = [ true false /* I can be anywhere */ /* I can be anywhere */ ]"); }
private void UpdateObjectFromMediaFields() { foreach (var FieldGroupTabContent in FieldGroupTabContents.Items) { var MediaFieldsList = (ListView)FieldGroupTabContent.FindControl("MediaFieldsList"); var index = 0; foreach (var item in MediaFieldsList.Items) { var fieldIdField = (HiddenField)item.FindControl("FieldID"); var dynamicField = (PlaceHolder)item.FindControl("DynamicField"); var fieldId = long.Parse(fieldIdField.Value.ToString()); //var dataItem = MediasMapper.GetDataModel().Fields.SingleOrDefault(i => i.ID == fieldId); var dataItem = (MediaDetailField)((IEnumerable <object>)MediaFieldsList.DataSource).ElementAt(index); index++; if (dynamicField.Controls.Count == 0) { return; } var control = dynamicField.Controls[0]; if (control.Controls.Count > 0) { foreach (Control ctrl in control.Controls) { if (!(ctrl is LiteralControl)) { control = ctrl; } } } var adminPanel = WebFormHelper.FindControlRecursive(dynamicField, "AdminPanel"); if (adminPanel != null) { control = adminPanel.Parent; } if (control is WebApplication.Admin.Controls.Fields.IFieldControl) { var valAsString = ((WebApplication.Admin.Controls.Fields.IFieldControl)control).GetValue().ToString(); if (!string.IsNullOrEmpty(valAsString)) { valAsString = MediaDetailsMapper.ConvertUrlsToShortCodes(valAsString); if (valAsString.Contains(URIHelper.BaseUrl)) { valAsString = valAsString.Replace(URIHelper.BaseUrl, "{BaseUrl}"); } } dataItem.FieldValue = MediaDetailsMapper.ConvertUrlsToShortCodes(valAsString); } else { var fieldValue = ""; if (dataItem.GetAdminControlValue.Contains("@")) { fieldValue = ParserHelper.ParseData(dataItem.GetAdminControlValue, new { Control = control }); } else { fieldValue = ParserHelper.ParseData("{" + dataItem.GetAdminControlValue + "}", control); } if (fieldValue != "{" + dataItem.GetAdminControlValue + "}") { fieldValue = MediaDetailsMapper.ConvertUrlsToShortCodes(fieldValue); dataItem.FieldValue = fieldValue.Replace(URIHelper.BaseUrl, "{BaseUrl}"); } else { dataItem.FieldValue = ""; } } } } /*var returnObj = MediaDetailsMapper.Update(SelectedItem); * * if (returnObj.IsError) * BasePage.DisplayErrorMessage("Error", returnObj.Error);*/ }
public void PrintProgram_SimpleProgram_ShouldFormatCorrectly() { var programSyntax = ParserHelper.Parse(@" param string banana param string apple { allowed : [ 'Static' 'Dynamic' ] metadata: { description : 'no description' } } var num = 1 var call = func1( func2 (1), func3 (true)[0] .a . b.c ) resource myResource1 'myResource' ={ name : 'myName' obj : { x: y m: [ 1 false null { abc: edf } ] } } module myModule 'myModule' = { name : concat('a', 'b', 'c') params : { myParam: call . blah [3] } } resource myResource2 'myResource'={ something: 'foo/${myName}/bar' properties: { emptyObj: { } emptyArr: [ ] } } output myOutput1 int = 1 + num * 3 output myOutput2 string = yes ? 'yes' : 'no' output myOutput3 object = yes ? { value : 42 }:{ } "); var output = PrettyPrinter.PrintProgram(programSyntax, CommonOptions); output.Should().Be( @"param string banana param string apple { allowed: [ 'Static' 'Dynamic' ] metadata: { description: 'no description' } } var num = 1 var call = func1(func2(1), func3(true)[0].a.b.c) resource myResource1 'myResource' = { name: 'myName' obj: { x: y m: [ 1 false null { abc: edf } ] } } module myModule 'myModule' = { name: concat('a', 'b', 'c') params: { myParam: call.blah[3] } } resource myResource2 'myResource' = { something: 'foo/${myName}/bar' properties: { emptyObj: {} emptyArr: [] } } output myOutput1 int = 1 + num * 3 output myOutput2 string = yes ? 'yes' : 'no' output myOutput3 object = yes ? { value: 42 } : {}"); }
private void UpdateMediaFieldsFromObject() { foreach (var FieldGroupTabContent in FieldGroupTabContents.Items) { var MediaFieldsList = (ListView)FieldGroupTabContent.FindControl("MediaFieldsList"); var index = 0; foreach (var item in MediaFieldsList.Items) { var mediaDetailField = (MediaDetailField)((IEnumerable <object>)MediaFieldsList.DataSource).ElementAt(index); index++; var fieldIdField = (HiddenField)item.FindControl("FieldID"); var dynamicField = (PlaceHolder)item.FindControl("DynamicField"); var fieldId = long.Parse(fieldIdField.Value.ToString()); if (dynamicField.Controls.Count == 0) { return; } var control = dynamicField.Controls[0]; if (control.Controls.Count > 0) { foreach (Control ctrl in control.Controls) { if (!(ctrl is LiteralControl)) { control = ctrl; } } } var adminPanel = WebFormHelper.FindControlRecursive(dynamicField, "AdminPanel"); if (adminPanel != null) { control = adminPanel.Parent; } var fieldValue = mediaDetailField.FieldValue.Replace("{BaseUrl}", URIHelper.BaseUrl); if (control is WebApplication.Admin.Controls.Fields.IFieldControl) { var ctrl = ((WebApplication.Admin.Controls.Fields.IFieldControl)control); ctrl.FieldID = fieldId; ctrl.SetValue(fieldValue); } else { if (mediaDetailField.FieldValue != "{" + mediaDetailField.SetAdminControlValue + "}") { if (mediaDetailField.SetAdminControlValue.Contains("@")) { try { var returnData = ParserHelper.ParseData(mediaDetailField.SetAdminControlValue, new { Control = control, Field = mediaDetailField, NewValue = fieldValue }); } catch (Exception ex) { BasePage.DisplayErrorMessage("Error", ErrorHelper.CreateError(ex)); } } else { ParserHelper.SetValue(control, mediaDetailField.SetAdminControlValue, fieldValue); } } } } } }
void IEvaluableMarkupExtension.Initialize(IParserContext context) { _type = ParserHelper.ParseType(context, _typeName); }
public static Program InjectDualityProof(Program program, string DualityProofFile) { Program DualityProof; using (var st = new System.IO.StreamReader(DualityProofFile)) { var s = ParserHelper.Fill(st, new List <string>()); // replace %i by bound_var_i for (int i = 0; i <= 9; i++) { s = s.Replace(string.Format("%{0}", i), string.Format("pm_bv_{0}", i)); } var v = Parser.Parse(s, DualityProofFile, out DualityProof); if (v != 0) { throw new Exception("Failed to parse " + DualityProofFile); } } var implToContracts = new Dictionary <string, List <Expr> >(); foreach (var proc in DualityProof.TopLevelDeclarations.OfType <Procedure>()) { implToContracts.Add(proc.Name, new List <Expr>()); foreach (var ens in proc.Ensures) { implToContracts[proc.Name].AddRange(GetExprConjunctions(ens.Condition)); } } var counter = 0; var GetExistentialConstant = new Func <Constant>(() => { var c = new Constant(Token.NoToken, new TypedIdent(Token.NoToken, "DualityProofConst" + (counter++), Microsoft.Boogie.Type.Bool), false); c.AddAttribute("existential"); return(c); }); var constsToAdd = new List <Declaration>(); foreach (var proc in program.TopLevelDeclarations.OfType <Procedure>()) { if (!implToContracts.ContainsKey(proc.Name)) { continue; } if (QKeyValue.FindBoolAttribute(proc.Attributes, "nohoudini")) { continue; } foreach (var expr in implToContracts[proc.Name]) { var c = GetExistentialConstant(); constsToAdd.Add(c); proc.Ensures.Add(new Ensures(false, Expr.Imp(Expr.Ident(c), expr))); } } program.TopLevelDeclarations.AddRange(constsToAdd); return(program); }
public static bool Parse(SyntaxContext context, int position) { var list = context.list; var offset = 0; var index = position; var count = 0; var isMissed = false; while (ParenParser.Parse(context, index)) { ; } while (TableIParser.Parse(context, index)) { ; } while (TableSParser.Parse(context, index)) { ; } while (ListParser.Parse(context, index)) { ; } while (PropertyParser.Parse(context, index)) { ; } while (IndexParser.Parse(context, index)) { ; } while (CallParser.Parse(context, index)) { ; } while (NotParser.Parse(context, index)) { ; } while (LengthParser.Parse(context, index)) { ; } while (NegateParser.Parse(context, index)) { ; } if (!list[index].isRightValue) { return(false); } else { // ignored } offset += 1; index = position + offset; if (!ParserHelper.IsOperator(list[index], "*")) { return(false); } else { // ignored } offset += 1; index = position + offset; while (ParenParser.Parse(context, index)) { ; } while (TableIParser.Parse(context, index)) { ; } while (TableSParser.Parse(context, index)) { ; } while (ListParser.Parse(context, index)) { ; } while (PropertyParser.Parse(context, index)) { ; } while (IndexParser.Parse(context, index)) { ; } while (CallParser.Parse(context, index)) { ; } while (NotParser.Parse(context, index)) { ; } while (LengthParser.Parse(context, index)) { ; } while (NegateParser.Parse(context, index)) { ; } if (!list[index].isRightValue) { return(false); } else { // ignored } offset += 1; index = position + offset; context.Insert(position, ExpressionCreator.CreateMultiply(list, position, offset)); context.Remove(position + 1, offset); return(true); }
public static ParserNode Parse(string input, bool strict) { var tree = ParserHelper.Parse <XMLLexer, XMLParser, XMLParser.DocumentContext>(input, parser => parser.document(), strict); return(new XMLVisitor(input).Visit(tree)); }
/// <summary> /// Generates the Description for each of the Nodes to be described /// </summary> /// <param name="handler">RDF Handler</param> /// <param name="context">SPARQL Evaluation Context</param> /// <param name="nodes">Nodes to be described</param> protected override void DescribeInternal(IRdfHandler handler, SparqlEvaluationContext context, IEnumerable <INode> nodes) { //Rewrite Blank Node IDs for DESCRIBE Results Dictionary <String, INode> bnodeMapping = new Dictionary <string, INode>(); //Get Triples for this Subject Queue <INode> bnodes = new Queue <INode>(); HashSet <INode> expandedBNodes = new HashSet <INode>(); foreach (INode n in nodes) { //Get Triples where the Node is the Subject foreach (Triple t in context.Data.GetTriplesWithSubject(n).ToList()) { if (t.Object.NodeType == NodeType.Blank) { if (!expandedBNodes.Contains(t.Object)) { bnodes.Enqueue(t.Object); } } if (!handler.HandleTriple(this.RewriteDescribeBNodes(t, bnodeMapping, handler))) { ParserHelper.Stop(); } } //Get Triples where the Node is the Object foreach (Triple t in context.Data.GetTriplesWithObject(n).ToList()) { if (t.Subject.NodeType == NodeType.Blank) { if (!expandedBNodes.Contains(t.Subject)) { bnodes.Enqueue(t.Subject); } } if (!handler.HandleTriple(this.RewriteDescribeBNodes(t, bnodeMapping, handler))) { ParserHelper.Stop(); } } //Compute the Blank Node Closure for this Subject while (bnodes.Count > 0) { INode bsubj = bnodes.Dequeue(); if (expandedBNodes.Contains(bsubj)) { continue; } expandedBNodes.Add(bsubj); foreach (Triple t2 in context.Data.GetTriplesWithSubject(bsubj).ToList()) { if (t2.Object.NodeType == NodeType.Blank) { if (!expandedBNodes.Contains(t2.Object)) { bnodes.Enqueue(t2.Object); } } if (!handler.HandleTriple(this.RewriteDescribeBNodes(t2, bnodeMapping, handler))) { ParserHelper.Stop(); } } foreach (Triple t2 in context.Data.GetTriplesWithObject(bsubj).ToList()) { if (t2.Subject.NodeType == NodeType.Blank) { if (!expandedBNodes.Contains(t2.Subject)) { bnodes.Enqueue(t2.Subject); } } if (!handler.HandleTriple(this.RewriteDescribeBNodes(t2, bnodeMapping, handler))) { ParserHelper.Stop(); } } } } }
public static bool Parse(SyntaxContext context, int position) { var list = context.list; var offset = 0; var index = position; var count = 0; var isMissed = false; if (!ParserHelper.IsKeyword(list[index], "function")) { return(false); } else { // ignored } offset += 1; index = position + offset; if (list[index].type != Expression.Type.Word) { return(false); } else { // ignored } offset += 1; index = position + offset; if (!ParserHelper.IsOperator(list[index], "(")) { return(false); } else { // ignored } offset += 1; index = position + offset; while (WordList1Parser.Parse(context, index)) { ; } if (list[index].type != Expression.Type.WordList1) { return(false); } else { // ignored } offset += 1; index = position + offset; if (!ParserHelper.IsOperator(list[index], ")")) { return(false); } else { // ignored } offset += 1; index = position + offset; while (ModuleParser.Parse(context, index)) { ; } if (list[index].type != Expression.Type.Module) { return(false); } else { // ignored } offset += 1; index = position + offset; if (!ParserHelper.IsKeyword(list[index], "end")) { return(false); } else { // ignored } offset += 1; index = position + offset; context.Insert(position, ExpressionCreator.CreateFunctionN(list, position, offset)); context.Remove(position + 1, offset); return(true); }
public static ParserNode Parse(string input, bool strict) { var tree = ParserHelper.Parse <BalancedLexer, BalancedParser, BalancedParser.BalancedContext>(input, parser => parser.balanced(), strict); return(new BalancedVisitor().Visit(tree)); }
protected override void Render(HtmlTextWriter writer) { System.IO.StringWriter str = new System.IO.StringWriter(); HtmlTextWriter wrt = new HtmlTextWriter(str); // render html base.Render(wrt); //CAPTURE THE CURRENT PAGE HTML SOURCE AS STRING //wrt.Close(); string html = str.ToString(); if (IsAjaxRequest) { writer.Write(html); return; } /*if (CurrentMediaDetail != null && !html.Contains("<html")) * { * var masterPage = CurrentMediaDetail.GetMasterPage(); * * if (masterPage != null) * { * if (masterPage.UseLayout) * { * html = masterPage.Layout.Replace("{PageContent}", html); * html = LoaderHelper.RenderPage(this, html); * } * } * }*/ /*if (!IsInAdminSection) * { * if ((AppSettings.EnableMobileDetection) && (FrontEndBasePage.IsMobile)) * html = HandleMobileLayout(html); * else * html = HandleNonMobileLayout(html); * }*/ if (!IsPostBack) { if (AppSettings.MinifyOutput) { html = StringHelper.StripExtraSpacesBetweenMarkup(html); } } /*if (CurrentMediaDetail != null) * { * if (!IsAjaxRequest && !IsInAdminSection && Request["VisualLayoutEditor"] != "true") * { * html = MediaDetailsMapper.ParseSpecialTags(CurrentMediaDetail, html); * } * }*/ /*if (!IsInAdminSection) * { * HtmlNode.ElementsFlags.Remove("form"); * document = new HtmlAgilityPack.HtmlDocument(); * document.LoadHtml(html); * * var forms = document.DocumentNode.SelectNodes("//form"); * * if (forms != null && forms.Count > 1) * { * forms.RemoveAt(0); * foreach (HtmlNode item in forms) * { * item.ParentNode.InnerHtml = item.ParentNode.InnerHtml.Replace("form", "div data-form"); * } * * html = document.DocumentNode.WriteContentTo(); * } * }*/ /*var settings = SettingsMapper.GetSettings(); * * if (settings.EnableGlossaryTerms && !IsInAdminSection) * { * var document = new HtmlAgilityPack.HtmlDocument(); * document.LoadHtml(html); * * var selectedNodes = document.DocumentNode.SelectNodes("//p/text()|//li/text()"); * var terms = GlossaryTermsMapper.GetAll(); * * if (selectedNodes != null) * { * foreach (HtmlNode node in selectedNodes) * { * foreach (var term in terms) * { * var tempTerm = term.Term.Trim(); * * node.InnerHtml = Regex.Replace(node.InnerHtml, @"\b" + Regex.Escape(tempTerm) + @"\b" + "(?![^<]*</[a-z]+>)", me => * { * var template = "<span data-toggle=\"tooltip\" title=\"" + term.Definition + "\">" + me.Value + "</span>"; * return template; * }, RegexOptions.IgnoreCase); * } * } * } * * html = document.DocumentNode.WriteContentTo(); * }*/ html = ParserHelper.ParseData(html, TemplateVars); if (FrameworkSettings.CurrentUser == null && Request.QueryString.Count == 0) { if (CurrentMediaDetail != null) { if (!IsAjaxRequest) { if (AppSettings.EnableOutputCaching && CurrentMediaDetail.CanCache) { if (AppSettings.EnableLevel1MemoryCaching) { CurrentMediaDetail.SaveToMemoryCache(UserSelectedVersion, html); } if (AppSettings.EnableLevel2FileCaching) { CurrentMediaDetail.SaveToFileCache(UserSelectedVersion, html); } if (AppSettings.EnableLevel3RedisCaching) { CurrentMediaDetail.SaveToRedisCache(UserSelectedVersion, html); } } ContextHelper.SetToSession("CurrentMediaDetail", CurrentMediaDetail); } } } /*if(AppSettings.ForceSSL) * { * html = html.Replace("http:", "https:"); * }*/ html = ParserHelper.ReplaceHrefAndSrcsToAbsoluteUrls(html); writer.Write(html); }
/// <summary> /// Gets the linked entites from the property value /// </summary> /// <param name="propertyValue"> /// The property value. /// </param> /// <returns> /// The <see cref="IEnumerable{T}"/>. /// </returns> public IEnumerable <ILinkedEntity> GetLinkedEntities(object propertyValue) { if (string.IsNullOrEmpty(propertyValue?.ToString())) { return(Enumerable.Empty <ILinkedEntity>()); } var entities = new List <ILinkedEntity>(); try { var jsonValues = JsonConvert.DeserializeObject <JArray>(propertyValue.ToString()); foreach (var item in jsonValues) { if (item["udi"] != null) { var udi = item.Value <string>("udi"); if (ParserHelper.IsDocumentUdi(udi)) { var id = ParserHelper.MapDocumentUdiToId(contentService, cache, udi); if (id > -1) { entities.Add(new LinkedDocumentEntity(id)); } } else if (ParserHelper.IsMediaUdi(udi)) { var id = ParserHelper.MapMediaUdiToId(mediaService, cache, udi); if (id > -1) { entities.Add(new LinkedMediaEntity(id)); } } } else if (item["id"] != null) { var attempId = item["id"].TryConvertTo <int>(); if (attempId.Success) { var isMedia = false; if (item["isMedia"] != null) { var attemptIsMedia = item["isMedia"].TryConvertTo <bool>(); if (attemptIsMedia.Success) { isMedia = attemptIsMedia.Result; } } if (isMedia) { entities.Add(new LinkedMediaEntity(attempId.Result)); } else { entities.Add(new LinkedDocumentEntity(attempId.Result)); } } } } } catch (Exception exception) { ApplicationContext.Current.ProfilingLogger.Logger.Error <RjpMultiUrlPickerParser>("Error parsing multi url picker", exception); } return(entities); }
public void PrintProgram_CommentAfterOpenSyntax_ShouldMoveToNextLineAndIndent() { var programSyntax = ParserHelper.Parse(@" param foo object = { // I can be anywhere } param foo object = { // I can be anywhere abc: true } param foo object = { /* I can be anywhere */ abc: true xyz: false } param foo object = { /* I can be anywhere */ abc: true xyz: false } param bar array = [ // I can be anywhere ] param bar array = [ // I can be anywhere true ] param bar array = [ /*I can be anywhere */ // I can be anywhere true false ]"); var output = PrettyPrinter.PrintProgram(programSyntax, CommonOptions); output.Should().Be( @"param foo object = { // I can be anywhere } param foo object = { // I can be anywhere abc: true } param foo object = { /* I can be anywhere */ abc: true xyz: false } param foo object = { /* I can be anywhere */ abc: true xyz: false } param bar array = [ // I can be anywhere ] param bar array = [ // I can be anywhere true ] param bar array = [ /*I can be anywhere */ // I can be anywhere true false ]"); }
public EntitySSHRepository_old() { _helper = new ParserHelper(); }
public string RenderCriteria(QueryNode queryNode) { var result = String.Empty; var criteriaValue = queryNode.CriteriaValueQuery != null ? RenderQuery(queryNode.CriteriaValueQuery) : queryNode.CriteriaValueConstant.ToQueryLanguageRepresentation(); var comparator = queryNode.Comparator; // "subject = value" type criteria if (comparator.HasValue) { result = $"{RenderQuery(queryNode.CriteriaSubjectQuery)} {ParserHelper.GetTokenName(ParserHelper.GetToken(comparator.Value))} {criteriaValue}"; } // "subject()" type criteria else { result = RenderQuery(queryNode.CriteriaSubjectQuery); } return(result); }