public FhirResponse GetResponse(ResourceFormat? acceptFormat) { bool needsFormatParam = UseFormatParameter && acceptFormat.HasValue; var location = new RestUrl(_location); if(needsFormatParam) location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(acceptFormat.Value)); var request = createRequest(location.ToString(), _method); if(acceptFormat != null && !UseFormatParameter) request.Accept = ContentType.BuildContentType(acceptFormat.Value, forBundle: false); if (_body != null) { request.WriteBody(_body); request.ContentType = _contentType; if(_contentLocation != null) request.Headers[HttpRequestHeader.ContentLocation] = _contentLocation; } if(_categoryHeader != null) request.Headers[HttpUtil.CATEGORY] = _categoryHeader; FhirResponse result = null; // Make sure the HttpResponse gets disposed! using (HttpWebResponse response = (HttpWebResponse)request.GetResponseNoEx()) { result = FhirResponse.FromHttpWebResponse(response); } return result; }
public static string GetContentType(Type type, ResourceFormat format) { if (typeof(Resource).IsAssignableFrom(type) || type == typeof(ResourceEntry)) { switch (format) { case ResourceFormat.Json: return JsonResource; case ResourceFormat.Xml: return XmlResource; default: return XmlResource; } } else if (type == typeof(Bundle)) { switch (format) { case ResourceFormat.Json: return JsonBundle; case ResourceFormat.Xml: return XmlBundle; default: return XmlBundle; } } else if (type == typeof(TagList)) { switch (format) { case ResourceFormat.Json: return JsonTagList; case ResourceFormat.Xml: return XmlTagList; default: return XmlTagList; } } else return "application/octet-stream"; }
public void SetBody(TagList tagList, ResourceFormat format) { if (tagList == null) throw Error.ArgumentNull("tagList"); _body = format == ResourceFormat.Xml ? FhirSerializer.SerializeTagListToXmlBytes(tagList) : FhirSerializer.SerializeTagListToJsonBytes(tagList); _contentType = ContentType.BuildContentType(format, forBundle: false); }
public void SetBody(Bundle bundle, ResourceFormat format) { if (bundle == null) throw Error.ArgumentNull("bundle"); _body = format == ResourceFormat.Xml ? FhirSerializer.SerializeBundleToXmlBytes(bundle, summary: false) : FhirSerializer.SerializeBundleToJsonBytes(bundle, summary: false); _contentType = ContentType.BuildContentType(format, forBundle: true); }
public static string BuildContentType(ResourceFormat format, bool forBundle) { string contentType; if (format == ResourceFormat.Json) contentType = JSON_CONTENT_HEADER; else if (format == ResourceFormat.Xml) contentType = XML_CONTENT_HEADER; else throw new ArgumentException("Cannot determine content type for data format " + format); return contentType + ";charset=" + Encoding.UTF8.WebName; }
public static HttpResponseMessage ToHttpResponseMessage(this OperationOutcome outcome, ResourceFormat target, HttpRequestMessage request) { byte[] data = null; if (target == ResourceFormat.Xml) data = FhirSerializer.SerializeResourceToXmlBytes((OperationOutcome)outcome); else if (target == ResourceFormat.Json) data = FhirSerializer.SerializeResourceToJsonBytes((OperationOutcome)outcome); HttpResponseMessage response = new HttpResponseMessage(); //setResponseHeaders(response, target); response.Content = new ByteArrayContent(data); setContentHeaders(response, target); return response; }
public void SetBody(Resource resource, ResourceFormat format) { if (resource == null) throw Error.ArgumentNull("resource"); if (resource is Binary) { var bin = (Binary)resource; _body = bin.Content; _contentType = bin.ContentType; } else { _body = format == ResourceFormat.Xml ? FhirSerializer.SerializeResourceToXmlBytes(resource, summary: false) : FhirSerializer.SerializeResourceToJsonBytes(resource, summary: false); _contentType = ContentType.BuildContentType(format, forBundle: false); } }
public static HttpWebRequest ToHttpRequest(this Bundle.BundleEntryComponent entry, Prefer bodyPreference, ResourceFormat format, bool useFormatParameter, out byte[] body) { System.Diagnostics.Debug.WriteLine("{0}: {1}", entry.Request.Method, entry.Request.Url); var interaction = entry.Request; body = null; if (entry.Resource != null && !(interaction.Method == Bundle.HTTPVerb.POST || interaction.Method == Bundle.HTTPVerb.PUT)) throw Error.InvalidOperation("Cannot have a body on an Http " + interaction.Method.ToString()); var location = new RestUrl(interaction.Url); if (useFormatParameter) location.AddParam(HttpUtil.RESTPARAM_FORMAT, Hl7.Fhir.Rest.ContentType.BuildFormatParam(format)); var request = (HttpWebRequest)HttpWebRequest.Create(location.Uri); request.Method = interaction.Method.ToString(); setAgent(request, ".NET FhirClient for FHIR " + Model.ModelInfo.Version); if (!useFormatParameter) request.Accept = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); if (interaction.IfMatch != null) request.Headers["If-Match"] = interaction.IfMatch; if (interaction.IfNoneMatch != null) request.Headers["If-None-Match"] = interaction.IfNoneMatch; #if PORTABLE45 if (interaction.IfModifiedSince != null) request.Headers["If-Modified-Since"] = interaction.IfModifiedSince.Value.UtcDateTime.ToString(); #else if (interaction.IfModifiedSince != null) request.IfModifiedSince = interaction.IfModifiedSince.Value.UtcDateTime; #endif if (interaction.IfNoneExist != null) request.Headers["If-None-Exist"] = interaction.IfNoneExist; if (interaction.Method == Bundle.HTTPVerb.POST || interaction.Method == Bundle.HTTPVerb.PUT) { if (bodyPreference == Prefer.ReturnMinimal) request.Headers["Prefer"] = bodyPreference == Prefer.ReturnMinimal ? "return=minimal" : "return=representation"; } if (entry.Resource != null) setBodyAndContentType(request, entry.Resource, format, out body); return request; }
protected void cmdSave_Click(object sender, EventArgs e) { ResourceFormat newFormat = new ResourceFormat(); newFormat.formatId = String.IsNullOrEmpty(hidFormatId.Value) ? 0 : int.Parse(hidFormatId.Value); newFormat.name = txtFormatName.Text; newFormat.active = chkActive.Checked; HttpWebRequest request = WebRequest.Create(dashboardUrlBase + "resourceformat/") as HttpWebRequest; request.ContentType = "text/json"; request.Method = "PUT"; try { using (var streamWriter = new StreamWriter(request.GetRequestStream())) { string json = JsonConvert.SerializeObject(newFormat); streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)request.GetResponse(); } catch (Exception ex) { throw new ApplicationException(ex.ToString()); } divFormats.Visible = true; divAddEdit.Visible = false; string url = dashboardUrlBase + "resourceformat"; WebClient client = new WebClient(); List<ResourceFormat> result = JsonConvert.DeserializeObject<List<ResourceFormat>>(client.DownloadString(url)); gvResourceFormat.DataSource = result; gvResourceFormat.DataBind(); }
private DepthStencilView DoCreateDepthStencilView(uint mipIndex, ResourceFormat format) { Assure.True( (PermittedBindings & GPUBindings.DepthStencilTarget) == GPUBindings.DepthStencilTarget, "Can not create a depth stencil view to a texture that wasn't created with the " + GPUBindings.DepthStencilTarget + " binding." ); DepthStencilViewHandle outViewHandle; if (IsArrayTexture) { InteropUtils.CallNative( NativeMethods.ResourceFactory_CreateDSVToTexArr, RenderingModule.Device, (Texture2DResourceHandle)ResourceHandle, mipIndex, ArrayIndex, format, (InteropBool)IsMultisampled, (IntPtr)(&outViewHandle) ).ThrowOnFailure(); } else { InteropUtils.CallNative( NativeMethods.ResourceFactory_CreateDSV, RenderingModule.Device, (Texture2DResourceHandle)ResourceHandle, mipIndex, format, (InteropBool)IsMultisampled, (IntPtr)(&outViewHandle) ).ThrowOnFailure(); } return(new DepthStencilView(outViewHandle, this, mipIndex)); }
private static Bundle tryParseBundle(ResourceFormat format, string data) { Bundle importedBundle = null; //ErrorList errors = new ErrorList(); if (format == ResourceFormat.Xml) importedBundle = FhirParser.ParseBundleFromXml(data); if (format == ResourceFormat.Json) importedBundle = FhirParser.ParseBundleFromJson(data); //if (errors.Count == 0) return importedBundle; //else // return null; }
public static bool LoadFromResource(DivinityLocaleFile fileData, Resource resource, ResourceFormat resourceFormat, bool sort = true) { try { if (resourceFormat == ResourceFormat.LSB) { var rootNode = resource.Regions.First().Value; foreach (var entry in rootNode.Children) { foreach (var node in entry.Value) { DivinityLocaleEntry localeEntry = LoadFromNode(node, resourceFormat); localeEntry.Parent = fileData; fileData.Entries.Add(localeEntry); } } } if (resourceFormat == ResourceFormat.LSJ || resourceFormat == ResourceFormat.LSX) { var rootNode = resource.Regions.First().Value; var stringNodes = new List <Node>(); foreach (var nodeList in rootNode.Children) { var nodes = FindTranslatedStringsInNodeList(nodeList); stringNodes.AddRange(nodes); } foreach (var node in stringNodes) { DivinityLocaleEntry localeEntry = LoadFromNode(node, resourceFormat); localeEntry.Parent = fileData; fileData.Entries.Add(localeEntry); } } if (sort) { fileData.Entries = fileData.Entries.OrderBy(e => e.Key).ToList(); } return(true); } catch (Exception ex) { Log.Here().Error($"Error loading from resource: {ex.ToString()}"); return(false); } }
private Uri tryCreatePatient(FhirClient client, ResourceFormat formatIn, string id = null) { client.PreferredFormat = formatIn; ResourceEntry<Patient> created = null; Patient demopat = DemoData.GetDemoPatient(); if (id == null) { HttpTests.AssertSuccess(client, () => created = client.Create<Patient>(demopat)); } else { HttpTests.AssertSuccess(client, () => created = client.Create<Patient>(demopat, id)); var ep = new RestUrl(client.Endpoint); if (!ep.IsEndpointFor(created.Id)) TestResult.Fail("Location of created resource is not located within server endpoint"); var rl = new ResourceIdentity(created.Id); if (rl.Id != id) TestResult.Fail("Server refused to honor client-assigned id"); } HttpTests.AssertLocationPresentAndValid(client); // Create bevat geen response content meer. Terecht verwijderd?: // EK: Niet helemaal, er is weliswaar geen data meer gereturned, maar de headers (id, versie, modified) worden // nog wel geupdate HttpTests.AssertContentLocationValidIfPresent(client); return created.SelfLink; }
/// <summary> /// Initializes a new instance of the <see cref="FhirClient"/> class. /// </summary> /// <param name="baseAddress">The address of the FHIR server to communicate with.</param> /// <param name="format">The format to communicate with the FHIR server.</param> /// <exception cref="InvalidOperationException">Returned if the format specified is invalid.</exception> public FhirClient(Uri baseAddress, ResourceFormat format) : this(new HttpClient { BaseAddress = baseAddress }, format) { }
public FormatAttribute(ResourceFormat format) { this.format = format; }
/// <summary> /// Builds the <see cref="GeometryCache"/> with all the models that have previously been added with <see cref="AddModel"/>. /// This method may only be called once per GeometryCacheBuilder. /// </summary> /// <returns>A new <see cref="GeometryCache"/> containing 'baked' resource data for all the loaded models and an /// "instance pool", allowing model instances to be created and loaded in to the <see cref="Scene"/>.</returns> public unsafe GeometryCache Build() { lock (instanceMutationLock) { if (isBuilt) { throw new InvalidOperationException("Cache has already been built!"); } FieldInfo[] vertexComponents = typeof(TVertex).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (vertexComponents.Length > VertexShader.MAX_VS_INPUT_BINDINGS) { throw new InvalidOperationException("Vertex type '" + typeof(TVertex).Name + "' has too many components. Maximum " + "permissible is " + VertexShader.MAX_VS_INPUT_BINDINGS + ", but the vertex type has " + vertexComponents.Length + " fields."); } else if (vertexComponents.Length == 0) { throw new InvalidOperationException("Vertex type '" + typeof(TVertex).Name + "' has no components. Please choose a type with " + "at least one field."); } if (vertexCounts.Count == 0) { throw new InvalidOperationException("Can not build empty geometry cache: Please add at least one model first!"); } if (modelNames.AnyDuplicates()) { throw new InvalidOperationException("No two models should have the same name."); } if (GeometryCache.CheckForModelNameClashes(modelNames)) { throw new InvalidOperationException("One or more model names added to this builder have already been used in other active geometry caches."); } IVertexBuffer[] vertexComponentBuffers = new IVertexBuffer[vertexComponents.Length]; string[] vertexComponentSemantics = new string[vertexComponents.Length]; ResourceFormat[] vertexComponentFormats = new ResourceFormat[vertexComponents.Length]; for (int i = 0; i < vertexComponents.Length; ++i) { FieldInfo component = vertexComponents[i]; if (!component.FieldType.IsBlittable()) { throw new InvalidOperationException("Invalid vertex component type: '" + component.FieldType.Name + "'."); } if (!component.HasCustomAttribute <VertexComponentAttribute>()) { throw new InvalidOperationException("Every field on given vertex type (" + typeof(TVertex).Name + ") must be annoted with " + "a " + typeof(VertexComponentAttribute).Name + "!"); } typeof(GeometryCacheBuilder <TVertex>) .GetMethod("FillComponentBuffer", BindingFlags.NonPublic | BindingFlags.Instance) // TODO replace with nameof() operator when C#6 is released .MakeGenericMethod(component.FieldType) .Invoke(this, new object[] { component, i, vertexComponentBuffers, vertexComponentSemantics, vertexComponentFormats }); } IndexBuffer indexBuffer = BufferFactory.NewIndexBuffer().WithInitialData(indices.ToArray()).WithUsage(ResourceUsage.Immutable); Assure.Equal(vertexCounts.Count, indexCounts.Count); AlignedAllocation <uint> componentStartPointsAlloc = AlignedAllocation <uint> .AllocArray( START_POINT_ARRAY_ALIGNMENT, (uint)vertexCounts.Count + 1U // Extra one so we can set the last value to one-past-the-end (performance improvement later on) ); AlignedAllocation <uint> indexStartPointsAlloc = AlignedAllocation <uint> .AllocArray( START_POINT_ARRAY_ALIGNMENT, (uint)vertexCounts.Count + 1U // Extra one so we can set the last value to one-past-the-end (performance improvement later on) ); uint *componentStartPtr = (uint *)componentStartPointsAlloc.AlignedPointer; uint *indexStartPtr = (uint *)indexStartPointsAlloc.AlignedPointer; uint vbCounter = 0U; uint ibCounter = 0U; for (int i = 0; i < vertexCounts.Count; ++i) { componentStartPtr[i] = vbCounter; indexStartPtr[i] = ibCounter; vbCounter += vertexCounts[i]; ibCounter += indexCounts[i]; } // Set the last two elements of each start-point array to one-past-the-last, so we don't have to test // for being the 'last' count later on componentStartPtr[vertexCounts.Count] = (uint)vertices.Count; indexStartPtr[vertexCounts.Count] = (uint)indices.Count; Dictionary <string, ModelHandle> modelNameToHandleMap = new Dictionary <string, ModelHandle>(); for (uint i = 0U; i < modelNames.Count; ++i) { modelNameToHandleMap.Add(modelNames[(int)i], new ModelHandle(cacheID, i)); } isBuilt = true; return(new GeometryCache( vertexComponentBuffers, vertexComponentSemantics, vertexComponentFormats, indexBuffer, componentStartPointsAlloc, indexStartPointsAlloc, (uint)vertexCounts.Count, typeof(TVertex), cacheID, modelNameToHandleMap, orderFirst )); } }
public void ConvertResources(string inputDir, string outputDir, ResourceFormat inputFormat, ResourceFormat outputFormat, int outputVersion = -1) { this.progressUpdate("Enumerating files ...", 0, 1); var paths = new List <string>(); EnumerateFiles(paths, inputDir, inputDir, "." + inputFormat.ToString().ToLower()); this.progressUpdate("Converting resources ...", 0, 1); for (var i = 0; i < paths.Count; i++) { var path = paths[i]; var inPath = inputDir + "/" + path; var outPath = outputDir + "/" + Path.ChangeExtension(path, outputFormat.ToString().ToLower()); var dirName = Path.GetDirectoryName(outPath); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } this.progressUpdate("Converting: " + inPath, i, paths.Count); var resource = LoadResource(inPath, inputFormat); SaveResource(resource, outPath, outputFormat, outputVersion); } }
private TreelistView.Node MakeFragmentNode(PixelModification mod) { bool uintTex = (texture.format.compType == FormatComponentType.UInt); bool sintTex = (texture.format.compType == FormatComponentType.SInt); bool floatTex = (!uintTex && !sintTex); bool depth = false; if (texture.format.compType == FormatComponentType.Depth || (texture.format.special && texture.format.specialFormat == SpecialFormat.D24S8) || (texture.format.special && texture.format.specialFormat == SpecialFormat.D32S8) || (texture.format.special && texture.format.specialFormat == SpecialFormat.S8)) { depth = true; } TreelistView.Node node = null; if (mod.uavWrite) { string name = "Potential UAV/Copy write"; string preModVal = "Tex Before\n\n" + ModificationValueString(mod.preMod, texture.format, depth); string postModVal = "Tex After\n\n" + ModificationValueString(mod.postMod, texture.format, depth); if (mod.preMod.col.value.u[0] == mod.postMod.col.value.u[0] && mod.preMod.col.value.u[1] == mod.postMod.col.value.u[1] && mod.preMod.col.value.u[2] == mod.postMod.col.value.u[2] && mod.preMod.col.value.u[3] == mod.postMod.col.value.u[3]) { name += "\nNo change in tex value"; } node = new TreelistView.Node(new object[] { name, preModVal, "", postModVal, "" }); } else { string name = String.Format("Primitive {0}\n", mod.primitiveID); if (mod.shaderDiscarded) { name += FailureString(mod); } ResourceFormat fmt = new ResourceFormat(floatTex ? FormatComponentType.Float : texture.format.compType, 4, 4); string shadOutVal = "Shader Out\n\n" + ModificationValueString(mod.shaderOut, fmt, depth); string postModVal = "Tex After\n\n" + ModificationValueString(mod.postMod, texture.format, depth); if (!mod.EventPassed() && hideFailedEventsToolStripMenuItem.Checked) { return(null); } node = new TreelistView.Node(new object[] { name, shadOutVal, "", postModVal, "" }); if (mod.shaderDiscarded) { node.DefaultBackColor = Color.FromArgb(255, 235, 235); } } node.Tag = new EventTag(mod.eventID, mod.uavWrite ? uint.MaxValue : mod.primitiveID); if (floatTex || depth) { node.IndexedBackColor[2] = ModificationValueColor(mod.shaderOut, depth); node.IndexedBackColor[4] = ModificationValueColor(mod.postMod, depth); } return(node); }
private void resourceBulkConvertBtn_Click(object sender, EventArgs e) { ResourceFormat inputFormat = ResourceFormat.LSX; switch (resourceInputFormatCb.SelectedIndex) { case 0: inputFormat = ResourceFormat.LSX; break; case 1: inputFormat = ResourceFormat.LSB; break; case 2: inputFormat = ResourceFormat.LSF; break; } ResourceFormat outputFormat = ResourceFormat.LSF; int outputVersion = -1; switch (resourceOutputFormatCb.SelectedIndex) { case 0: outputFormat = ResourceFormat.LSX; break; case 1: outputFormat = ResourceFormat.LSB; break; case 2: outputFormat = ResourceFormat.LSF; if (GetGame() == DivGame.DOS2) { outputVersion = (int)FileVersion.VerExtendedNodes; } else { outputVersion = (int)FileVersion.VerChunkedCompress; } break; } try { resourceConvertBtn.Enabled = false; var utils = new ResourceUtils(); utils.progressUpdate += this.ResourceProgressUpdate; utils.ConvertResources(resourceInputDir.Text, resourceOutputDir.Text, inputFormat, outputFormat, outputVersion); MessageBox.Show("Resources converted successfully."); } catch (Exception exc) { MessageBox.Show("Internal error!\r\n\r\n" + exc.ToString(), "Conversion Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { resourceProgressLabel.Text = ""; resourceConversionProgress.Value = 0; resourceConvertBtn.Enabled = true; } }
public static HttpWebRequest ToHttpRequest(this Bundle.EntryComponent entry, Uri baseUrl, Prefer bodyPreference, ResourceFormat format, bool useFormatParameter, bool CompressRequestBody, out byte[] body) { System.Diagnostics.Debug.WriteLine("{0}: {1}", entry.Request.Method, entry.Request.Url); var interaction = entry.Request; body = null; if (entry.Resource != null && !(interaction.Method == Bundle.HTTPVerb.POST || interaction.Method == Bundle.HTTPVerb.PUT)) { throw Error.InvalidOperation("Cannot have a body on an Http " + interaction.Method.ToString()); } // Create an absolute uri when the interaction.Url is relative. var uri = new Uri(interaction.Url, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = HttpUtil.MakeAbsoluteToBase(uri, baseUrl); } var location = new RestUrl(uri); if (useFormatParameter) { location.AddParam(HttpUtil.RESTPARAM_FORMAT, Hl7.Fhir.Rest.ContentType.BuildFormatParam(format)); } var request = (HttpWebRequest)HttpWebRequest.Create(location.Uri); request.Method = interaction.Method.ToString(); setAgent(request, ".NET FhirClient for FHIR " + Model.ModelInfo.Version); if (!useFormatParameter) { request.Accept = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); } if (interaction.IfMatch != null) { request.Headers["If-Match"] = interaction.IfMatch; } if (interaction.IfNoneMatch != null) { request.Headers["If-None-Match"] = interaction.IfNoneMatch; } #if NETSTANDARD1_1 if (interaction.IfModifiedSince != null) { request.Headers["If-Modified-Since"] = interaction.IfModifiedSince.Value.UtcDateTime.ToString(); } #else if (interaction.IfModifiedSince != null) { request.IfModifiedSince = interaction.IfModifiedSince.Value.UtcDateTime; } #endif if (interaction.IfNoneExist != null) { request.Headers["If-None-Exist"] = interaction.IfNoneExist; } if (interaction.Method == Bundle.HTTPVerb.POST || interaction.Method == Bundle.HTTPVerb.PUT) { request.Headers["Prefer"] = bodyPreference == Prefer.ReturnMinimal ? "return=minimal" : "return=representation"; } if (entry.Resource != null) { bool searchUsingPost = interaction.Method == Bundle.HTTPVerb.POST && (entry.HasAnnotation <TransactionBuilder.InteractionType>() && entry.Annotation <TransactionBuilder.InteractionType>() == TransactionBuilder.InteractionType.Search) && entry.Resource is Parameters; setBodyAndContentType(request, entry.Resource, format, CompressRequestBody, searchUsingPost, out body); } // PCL doesn't support setting the length (and in this case will be empty anyway) #if !NETSTANDARD1_1 else { request.ContentLength = 0; } #endif return(request); }
private string ModificationValueString(ModificationValue val, ResourceFormat fmt, bool depth) { string s = ""; bool uintTex = (fmt.compType == FormatComponentType.UInt); bool sintTex = (fmt.compType == FormatComponentType.SInt); int numComps = (int)(fmt.compCount); if (!depth) { if (uintTex) { for (int i = 0; i < numComps; i++) { s += colourLetterPrefix[i] + val.col.value.u[i].ToString() + "\n"; } } else if (sintTex) { for (int i = 0; i < numComps; i++) { s += colourLetterPrefix[i] + val.col.value.i[i].ToString() + "\n"; } } else { for (int i = 0; i < numComps; i++) { s += colourLetterPrefix[i] + Formatter.Format(val.col.value.f[i]) + "\n"; } } } if (val.depth >= 0.0f) { s += "\nD: " + Formatter.Format(val.depth); } else if (val.depth < -1.5f) { s += "\nD: ?"; } else { s += "\nD: -"; } if (val.stencil >= 0) { s += String.Format("\nS: 0x{0:X2}", val.stencil); } else if (val.stencil == -2) { s += "\nS: ?"; } else { s += "\nS: -"; } return(s); }
private static void setBodyAndContentType(HttpWebRequest request, Resource data, ResourceFormat format, bool CompressRequestBody, bool searchUsingPost, out byte[] body) { if (data == null) { throw Error.ArgumentNull(nameof(data)); } if (data is Binary) { var bin = (Binary)data; body = bin.Content; // This is done by the caller after the OnBeforeRequest is called so that other properties // can be set before the content is committed // request.WriteBody(CompressRequestBody, bin.Content); request.ContentType = bin.ContentType; } else if (searchUsingPost) { IDictionary <string, string> bodyParameters = new Dictionary <string, string>(); foreach (Parameters.ParameterComponent parameter in ((Parameters)data).Parameter) { bodyParameters.Add(parameter.Name, parameter.Value.ToString()); } if (bodyParameters.Count > 0) { FormUrlEncodedContent content = new FormUrlEncodedContent(bodyParameters); body = content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); } else { body = null; } request.ContentType = "application/x-www-form-urlencoded"; } else { body = format == ResourceFormat.Xml ? new FhirXmlSerializer().SerializeToBytes(data, summary: Fhir.Rest.SummaryType.False) : new FhirJsonSerializer().SerializeToBytes(data, summary: Fhir.Rest.SummaryType.False); // This is done by the caller after the OnBeforeRequest is called so that other properties // can be set before the content is committed // request.WriteBody(CompressRequestBody, body); request.ContentType = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); } }
private void ImportResourceData() { string file_name = cmd.InputPath(); ResourceFormat format = cmd.GetEnum("format", ResourceFormat.resx); string schema_name = cmd.GetValue("schema-name") ?? SchemaName.dbo; string table_name = cmd.GetValue("table-name"); string name_column = cmd.GetValue("name-column") ?? "name"; string value_column = cmd.GetValue("value-column") ?? name_column; string order_column = cmd.GetValue("order-column"); bool trim_name = cmd.Has("trim-name"); bool trim_value = cmd.Has("trim-value"); bool deleteRowNotInResource = cmd.Has("delete-rows-not-in-resource-file"); if (file_name == null) { cerr.WriteLine($"file name is not defined, use option /in:file_name"); return; } if (!File.Exists(file_name)) { cerr.WriteLine($"file doesn't exist: \"{file_name}\""); return; } if (tname == null) { if (table_name == null) { cerr.WriteLine($"/table-name is not defined"); return; } if (dname == null) { cerr.WriteLine($"required to select a database"); return; } tname = new TableName(dname, schema_name, table_name); if (!tname.Exists()) { cerr.WriteLine($"table-name doesn't exist: {tname}"); return; } } DataTable dt = new TableReader(tname) { CaseSensitive = true, }.Table; if (!ValidateColumn <string>(dt, name_column, "name-column", required: true)) { return; } if (!ValidateColumn <string>(dt, value_column, "value-column", required: true)) { return; } if (!ValidateColumn <int>(dt, order_column, "order-column", required: false)) { return; } cout.WriteLine($"{dt.Rows.Count} of entries on \"{file_name}\""); ResourceTableWriter writer = new ResourceTableWriter(file_name, tname, name_column, value_column, order_column); List <ResourceEntry> entries = writer.Differ(format, dt, trim_name, trim_value); foreach (var entry in entries) { switch (entry.Action) { case DataRowAction.Add: cout.WriteLine($"new entry: \"{entry.Name}\", \"{entry.NewValue}\""); break; case DataRowAction.Change: cout.WriteLine($"update entry: \"{entry.Name}\", \"{entry.OldValue}\" -> \"{entry.NewValue}\""); break; case DataRowAction.Delete: cout.WriteLine($"delete entry: \"{entry.Name}\""); break; } } if (entries.Count > 0) { cout.WriteLine($"{entries.Count} of entries were changed"); } else { cout.WriteLine($"no entry is changed"); } if (entries.Count == 0) { return; } bool commit = cmd.Has("submit-changes"); if (!commit) { return; } cout.WriteLine($"starting to save changes into table \"{tname}\""); try { writer.SubmitChanges(entries, deleteRowNotInResource); cout.WriteLine($"completed to save on table \"{tname}\" from \"{file_name}\""); } catch (Exception ex) { cerr.WriteLine($"failed to save in \"{tname}\" , {ex.AllMessages()}"); } }
private static void SetUpAndValidate(CommandLineArguments args) { string[] batchActions = { "extract-packages", "convert-models", "convert-resources" }; string[] packageActions = { "create-package", "extract-package", "extract-packages" }; string[] graphicsActions = { "convert-model", "convert-models" }; LogLevel = CommandLineArguments.GetLogLevelByString(args.LogLevel); CommandLineLogger.LogDebug($"Using log level: {LogLevel}"); Game = CommandLineArguments.GetGameByString(args.Game); CommandLineLogger.LogDebug($"Using game: {Game}"); if (batchActions.Any(args.Action.Contains)) { if (args.InputFormat == null || args.OutputFormat == null) { if (args.InputFormat == null && args.Action != "extract-packages") { CommandLineLogger.LogFatal("Cannot perform batch action without --input-format and --output-format arguments", 1); } } InputFormat = CommandLineArguments.GetResourceFormatByString(args.InputFormat); CommandLineLogger.LogDebug($"Using input format: {InputFormat}"); if (args.Action != "extract-packages") { OutputFormat = CommandLineArguments.GetResourceFormatByString(args.OutputFormat); CommandLineLogger.LogDebug($"Using output format: {OutputFormat}"); } } if (packageActions.Any(args.Action.Contains)) { PackageVersion = CommandLineArguments.GetPackageVersion(args.PackageVersion); CommandLineLogger.LogDebug($"Using package version: {PackageVersion}"); } if (graphicsActions.Any(args.Action.Contains)) { GR2Options = CommandLineArguments.GetGR2Options(args.Options); CommandLineLogger.LogDebug($"Using graphics options: {GR2Options}"); if (GR2Options["conform"]) { ConformPath = TryToValidatePath(args.ConformPath); } } SourcePath = TryToValidatePath(args.Source); DestinationPath = TryToValidatePath(args.Destination); }
public async Task <bool> IsFormatSupportedAsync(string contentType) { ResourceFormat resourceFormat = ContentType.GetResourceFormatFromContentType(contentType); return(await IsFormatSupportedAsync(resourceFormat)); }
public static HttpResponseMessage ToHttpResponseMessage(this OperationOutcome outcome, ResourceFormat target, HttpRequestMessage request) { byte[] data = null; if (target == ResourceFormat.Xml) { FhirXmlSerializer serializer = new FhirXmlSerializer(); data = serializer.SerializeToBytes(outcome); } else if (target == ResourceFormat.Json) { FhirJsonSerializer serializer = new FhirJsonSerializer(); data = serializer.SerializeToBytes(outcome); } HttpResponseMessage response = new HttpResponseMessage { Content = new ByteArrayContent(data) }; setContentHeaders(response, target); return(response); }
public static string BuildFormatParam(ResourceFormat format) { if (format == ResourceFormat.Json) return FORMAT_PARAM_JSON; else if (format == ResourceFormat.Xml) return FORMAT_PARAM_XML; else throw new ArgumentException("Cannot determine content type for data format " + format); }
private static void setBodyAndContentType(HttpWebRequest request, Resource data, ResourceFormat format, bool CompressRequestBody, out byte[] body) { if (data == null) { throw Error.ArgumentNull(nameof(data)); } if (data is Binary) { var bin = (Binary)data; body = bin.Content; // This is done by the caller after the OnBeforeRequest is called so that other properties // can be set before the content is committed // request.WriteBody(CompressRequestBody, bin.Content); request.ContentType = bin.ContentType; } else { body = format == ResourceFormat.Xml ? new FhirXmlSerializer().SerializeToBytes(data, summary: Fhir.Rest.SummaryType.False) : new FhirJsonSerializer().SerializeToBytes(data, summary: Fhir.Rest.SummaryType.False); // This is done by the caller after the OnBeforeRequest is called so that other properties // can be set before the content is committed // request.WriteBody(CompressRequestBody, body); request.ContentType = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); } }
public static HttpResponseMessage ToHttpResponseMessage(this OperationOutcome outcome, ResourceFormat target, HttpRequestMessage request) { byte[] data = null; if (target == ResourceFormat.Xml) { data = FhirSerializer.SerializeResourceToXmlBytes((OperationOutcome)outcome); } else if (target == ResourceFormat.Json) { data = FhirSerializer.SerializeResourceToJsonBytes((OperationOutcome)outcome); } HttpResponseMessage response = new HttpResponseMessage(); //setResponseHeaders(response, target); response.Content = new ByteArrayContent(data); setContentHeaders(response, target); return(response); }
public FhirResponse GetResponse(ResourceFormat? acceptFormat) { bool needsFormatParam = UseFormatParameter && acceptFormat.HasValue; var location = new RestUrl(_location); if(needsFormatParam) location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(acceptFormat.Value)); System.Diagnostics.Debug.WriteLine("{0}: {1}", _method, location.Uri.OriginalString); var request = createRequest(location.Uri, _method); if(acceptFormat != null && !UseFormatParameter) request.Accept = ContentType.BuildContentType(acceptFormat.Value, forBundle: false); if (_body != null) { request.WriteBody(_body); request.ContentType = _contentType; if(_contentLocation != null) request.Headers[HttpRequestHeader.ContentLocation] = _contentLocation; } if(_categoryHeader != null) request.Headers[HttpUtil.CATEGORY] = _categoryHeader; FhirResponse fhirResponse = null; #if !PORTABLE45 request.Timeout = Timeout; #endif // Make sure the HttpResponse gets disposed! if (_beforeRequest != null) _beforeRequest(request, _body); using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponseNoEx()) { fhirResponse = FhirResponse.FromHttpWebResponse(webResponse); if (_afterRequest != null) _afterRequest(webResponse, fhirResponse); } return fhirResponse; }
public static void AssertResourceResponseConformsTo(FhirClient client, ResourceFormat format) { AssertValidResourceContentTypePresent(client); var type = client.LastResponseDetails.ContentType; if (ContentType.GetResourceFormatFromContentType(type) != format) TestResult.Fail(String.Format("{0} is not acceptable when expecting {1}", type, format.ToString())); }
private static void setContentHeaders(HttpResponseMessage response, ResourceFormat format) { response.Content.Headers.ContentType = FhirMediaType.GetMediaTypeHeaderValue(typeof(Resource), format); }
public static HttpResponseMessage ToHttpResponseMessage(this OperationOutcome outcome, ResourceFormat target, HttpRequestMessage request) { return(ToHttpResponseMessage(outcome, target)); }
internal static void LoadFromResource(string locale, string assemblyPrefix, Type typeFromAssembly, string resourceFileName, ResourceFormat resourceFormat, out Dictionary <string, string> strings, out Dictionary <string, ErrorResource> errorResources) { var assembly = typeFromAssembly.Assembly; // This is being done because the filename of the manifest is case sensitive e.g. given zh-CN it was returning English if (locale.Equals("zh-CN")) { locale = "zh-cn"; } else if (locale.Equals("zh-TW")) { locale = "zh-tw"; } else if (locale.Equals("ko-KR")) { locale = "ko-kr"; } using (var res = assembly.GetManifestResourceStream(assemblyPrefix + locale.Replace("-", "_") + "." + resourceFileName)) { if (res == null) { if (locale == FallbackLocale) { throw new InvalidProgramException(string.Format("[StringResources] Resources not found for locale '{0}' and failed to find fallback", locale)); } // Load the default ones (recursive, but not infinite due to check above) LoadFromResource(FallbackLocale, assemblyPrefix, typeFromAssembly, resourceFileName, resourceFormat, out strings, out errorResources); } else { var loadedStrings = XDocument.Load(res).Descendants(XName.Get("data")); strings = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); errorResources = new Dictionary <string, ErrorResource>(StringComparer.OrdinalIgnoreCase); if (resourceFormat == ResourceFormat.Pares) { foreach (var item in loadedStrings) { string type; if (item.TryGetNonEmptyAttributeValue("type", out type) && type == ErrorResource.XmlType) { errorResources[item.Attribute("name").Value] = ErrorResource.Parse(item); } else { strings[item.Attribute("name").Value] = item.Element("value").Value; } } } else if (resourceFormat == ResourceFormat.Resw) { var separatedResourceKeys = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); foreach (var item in loadedStrings) { var itemName = item.Attribute("name").Value; if (itemName.StartsWith(ErrorResource.ReswErrorResourcePrefix, StringComparison.OrdinalIgnoreCase)) { separatedResourceKeys[itemName] = item.Element("value").Value; } else { strings[itemName] = item.Element("value").Value; } } errorResources = PostProcessErrorResources(separatedResourceKeys); } else { Contracts.Assert(false, "Unknown Resource Format"); } } } }
public static HttpWebRequest ToHttpRequest(this Bundle.EntryComponent entry, Prefer bodyPreference, ResourceFormat format, bool useFormatParameter, bool CompressRequestBody, out byte[] body) { System.Diagnostics.Debug.WriteLine("{0}: {1}", entry.Request.Method, entry.Request.Url); var interaction = entry.Request; body = null; if (entry.Resource != null && !(interaction.Method == Bundle.HTTPVerb.POST || interaction.Method == Bundle.HTTPVerb.PUT)) { throw Error.InvalidOperation("Cannot have a body on an Http " + interaction.Method.ToString()); } var location = new RestUrl(interaction.Url); if (useFormatParameter) { location.AddParam(HttpUtil.RESTPARAM_FORMAT, Hl7.Fhir.Rest.ContentType.BuildFormatParam(format)); } var request = (HttpWebRequest)HttpWebRequest.Create(location.Uri); request.Method = interaction.Method.ToString(); setAgent(request, ".NET FhirClient for FHIR " + Model.ModelInfo.Version); if (!useFormatParameter) { request.Accept = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); } if (interaction.IfMatch != null) { request.Headers["If-Match"] = interaction.IfMatch; } if (interaction.IfNoneMatch != null) { request.Headers["If-None-Match"] = interaction.IfNoneMatch; } #if DOTNETFW if (interaction.IfModifiedSince != null) { request.IfModifiedSince = interaction.IfModifiedSince.Value.UtcDateTime; } #else if (interaction.IfModifiedSince != null) { request.Headers["If-Modified-Since"] = interaction.IfModifiedSince.Value.UtcDateTime.ToString(); } #endif if (interaction.IfNoneExist != null) { request.Headers["If-None-Exist"] = interaction.IfNoneExist; } if (interaction.Method == Bundle.HTTPVerb.POST || interaction.Method == Bundle.HTTPVerb.PUT) { request.Headers["Prefer"] = bodyPreference == Prefer.ReturnMinimal ? "return=minimal" : "return=representation"; } if (entry.Resource != null) { setBodyAndContentType(request, entry.Resource, format, CompressRequestBody, out body); } // PCL doesn't support setting the length (and in this case will be empty anyway) #if DOTNETFW else { request.ContentLength = 0; } #endif return(request); }
private static void SetContentHeaders(HttpResponseMessage response, ResourceFormat format) { response.Content.Headers.ContentType = FhirMediaType.GetMediaTypeHeaderValue(typeof(Resource), format); }
public async Task<WebResponse> GetResponseAsync(ResourceFormat? acceptFormat) { bool needsFormatParam = UseFormatParameter && acceptFormat.HasValue; var location = new RestUrl(_location); if (needsFormatParam) location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(acceptFormat.Value)); System.Diagnostics.Debug.WriteLine("(async) {0}: {1}", _method, location.ToString()); HttpWebRequest request = createRequest(location.Uri, _method); if (acceptFormat != null && !UseFormatParameter) request.Accept = ContentType.BuildContentType(acceptFormat.Value, forBundle: false); if (_categoryHeader != null) request.Headers[HttpUtil.CATEGORY] = _categoryHeader; if (_body != null) { request.ContentType = _contentType; if (_contentLocation != null) request.Headers[HttpRequestHeader.ContentLocation] = _contentLocation; await request.WriteBodyAsync(_body); } // Make sure the caller disposes the HttpResponse gets disposed... if (_beforeRequest != null) _beforeRequest(request); var webResponse = await request.GetResponseAsync(TimeSpan.FromMilliseconds(Timeout)); if (_afterRequest != null) _afterRequest(webResponse, null); return response; }
private static void setContentAndContentType(HttpRequestMessage request, byte[] data, string contentType, ResourceFormat format) { if (data == null) { throw Error.ArgumentNull(nameof(data)); } request.Content = new ByteArrayContent(data); if (contentType == null) { contentType = ContentType.BuildContentType(format, forBundle: false); } request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); }
private static void setBodyAndContentType(HttpWebRequest request, Resource data, ResourceFormat format, bool CompressRequestBody, out byte[] body) { if (data == null) { throw Error.ArgumentNull("data"); } if (data is Binary) { var bin = (Binary)data; body = bin.Content; request.WriteBody(CompressRequestBody, bin.Content); request.ContentType = bin.ContentType; } else { body = format == ResourceFormat.Xml ? FhirSerializer.SerializeToXmlBytes(data, summary: Fhir.Rest.SummaryType.False) : FhirSerializer.SerializeToJsonBytes(data, summary: Fhir.Rest.SummaryType.False); request.WriteBody(CompressRequestBody, body); request.ContentType = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); } }
public Resource(ResourceFormat format, string path) { Format = format; TargetPath = path; }
private static void BatchConvertResource(string sourcePath, string destinationPath, ResourceFormat inputFormat, ResourceFormat outputFormat, FileVersion fileVersion) { try { CommandLineLogger.LogDebug($"Using destination extension: {outputFormat}"); ResourceUtils resourceUtils = new ResourceUtils(); resourceUtils.ConvertResources(sourcePath, destinationPath, inputFormat, outputFormat, fileVersion); CommandLineLogger.LogInfo($"Wrote resources to: {destinationPath}"); } catch (Exception e) { CommandLineLogger.LogFatal($"Failed to batch convert resources: {e.Message}", 2); CommandLineLogger.LogTrace($"{e.StackTrace}"); } }
static public FormatElement[] ParseFormatString(string formatString, UInt64 maxLen, bool tightPacking, out string errors) { var elems = new List <FormatElement>(); var formatReader = new StringReader(formatString); // regex doesn't account for trailing or preceeding whitespace, or comments var regExpr = @"^(row_major\s+)?" + // row_major matrix @"(" + @"uintten|unormten" + @"|unormh|unormb" + @"|snormh|snormb" + @"|bool" + // bool is stored as 4-byte int @"|byte|short|int" + // signed ints @"|ubyte|ushort|uint" + // unsigned ints @"|xbyte|xshort|xint" + // hex ints @"|half|float|double" + // float types @"|vec|uvec|ivec" + // OpenGL vector types @"|mat|umat|imat" + // OpenGL matrix types @")" + @"([1-9])?" + // might be a vector @"(x[1-9])?" + // or a matrix @"(\s+[A-Za-z_][A-Za-z0-9_]*)?" + // get identifier name @"(\[[0-9]+\])?" + // optional array dimension @"(\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?" + // optional semantic @"$"; Regex regParser = new Regex(regExpr, RegexOptions.Compiled); bool success = true; errors = ""; var text = formatReader.ReadToEnd(); text = text.Replace("{", "").Replace("}", ""); Regex c_comments = new Regex(@"/\*[^*]*\*+(?:[^*/][^*]*\*+)*/", RegexOptions.Compiled); text = c_comments.Replace(text, ""); Regex cpp_comments = new Regex(@"//.*", RegexOptions.Compiled); text = cpp_comments.Replace(text, ""); uint offset = 0; // get each line and parse it to determine the format the user wanted foreach (var l in text.Split(';')) { var line = l; line = line.Trim(); if (line.Length == 0) { continue; } var match = regParser.Match(line); if (!match.Success) { errors = "Couldn't parse line:\n" + line; success = false; break; } var basetype = match.Groups[2].Value; bool row_major = match.Groups[1].Success; var vectorDim = match.Groups[3].Success ? match.Groups[3].Value : "1"; var matrixDim = match.Groups[4].Success ? match.Groups[4].Value.Substring(1) : "1"; var name = match.Groups[5].Success ? match.Groups[5].Value.Trim() : "data"; var arrayDim = match.Groups[6].Success ? match.Groups[6].Value.Trim() : "[1]"; arrayDim = arrayDim.Substring(1, arrayDim.Length - 2); if (match.Groups[4].Success) { var a = vectorDim; vectorDim = matrixDim; matrixDim = a; } ResourceFormat fmt = new ResourceFormat(FormatComponentType.None, 0, 0); bool hex = false; FormatComponentType type = FormatComponentType.Float; uint count = 0; uint arrayCount = 1; uint matrixCount = 0; uint width = 0; // check for square matrix declarations like 'mat4' and 'mat3' if (basetype == "mat" && !match.Groups[4].Success) { matrixDim = vectorDim; } // calculate format { if (!uint.TryParse(vectorDim, out count)) { errors = "Invalid vector dimension on line:\n" + line; success = false; break; } if (!uint.TryParse(arrayDim, out arrayCount)) { arrayCount = 1; } arrayCount = Math.Max(0, arrayCount); if (!uint.TryParse(matrixDim, out matrixCount)) { errors = "Invalid matrix second dimension on line:\n" + line; success = false; break; } if (basetype == "bool") { type = FormatComponentType.UInt; width = 4; } else if (basetype == "byte") { type = FormatComponentType.SInt; width = 1; } else if (basetype == "ubyte" || basetype == "xbyte") { type = FormatComponentType.UInt; width = 1; } else if (basetype == "short") { type = FormatComponentType.SInt; width = 2; } else if (basetype == "ushort" || basetype == "xshort") { type = FormatComponentType.UInt; width = 2; } else if (basetype == "int" || basetype == "ivec" || basetype == "imat") { type = FormatComponentType.SInt; width = 4; } else if (basetype == "uint" || basetype == "xint" || basetype == "uvec" || basetype == "umat") { type = FormatComponentType.UInt; width = 4; } else if (basetype == "half") { type = FormatComponentType.Float; width = 2; } else if (basetype == "float" || basetype == "vec" || basetype == "mat") { type = FormatComponentType.Float; width = 4; } else if (basetype == "double") { type = FormatComponentType.Double; width = 8; } else if (basetype == "unormh") { type = FormatComponentType.UNorm; width = 2; } else if (basetype == "unormb") { type = FormatComponentType.UNorm; width = 1; } else if (basetype == "snormh") { type = FormatComponentType.SNorm; width = 2; } else if (basetype == "snormb") { type = FormatComponentType.SNorm; width = 1; } else if (basetype == "uintten") { fmt = new ResourceFormat(FormatComponentType.UInt, 4 * count, 1); fmt.special = true; fmt.specialFormat = SpecialFormat.R10G10B10A2; } else if (basetype == "unormten") { fmt = new ResourceFormat(FormatComponentType.UNorm, 4 * count, 1); fmt.special = true; fmt.specialFormat = SpecialFormat.R10G10B10A2; } else { errors = "Unrecognised basic type on line:\n" + line; success = false; break; } } if (basetype == "xint" || basetype == "xshort" || basetype == "xbyte") { hex = true; } if (fmt.compType == FormatComponentType.None) { fmt = new ResourceFormat(type, count, width); } if (arrayCount == 1) { FormatElement elem = new FormatElement(name, 0, offset, false, 1, row_major, matrixCount, fmt, hex); uint advance = elem.ByteSize; if (!tightPacking) { // cbuffer packing always works in floats advance = (advance + 3U) & (~3U); // cbuffer packing doesn't allow elements to cross float4 boundaries, nudge up if this was the case if (offset / 16 != (offset + elem.ByteSize - 1) / 16) { elem.offset = offset = (offset + 0xFU) & (~0xFU); } } elems.Add(elem); offset += advance; } else { // when cbuffer packing, arrays are always aligned at float4 boundary if (!tightPacking) { if (offset % 16 != 0) { offset = (offset + 0xFU) & (~0xFU); } } for (uint a = 0; a < arrayCount; a++) { FormatElement elem = new FormatElement(String.Format("{0}[{1}]", name, a), 0, offset, false, 1, row_major, matrixCount, fmt, hex); elems.Add(elem); uint advance = elem.ByteSize; // cbuffer packing each array element is always float4 aligned if (!tightPacking) { advance = (advance + 0xFU) & (~0xFU); } offset += advance; } } } if (!success || elems.Count == 0) { elems.Clear(); var fmt = new ResourceFormat(FormatComponentType.UInt, 4, 4); if (maxLen > 0 && maxLen < 16) { fmt.compCount = 1; } if (maxLen > 0 && maxLen < 4) { fmt.compByteWidth = 1; } elems.Add(new FormatElement("data", 0, 0, false, 1, false, 1, fmt, true)); } return(elems.ToArray()); }
public static HttpResponseMessage ToHttpResponseMessage(this OperationOutcome outcome, ResourceFormat target) { // TODO: Remove this method is seems to not be in use. byte[] data = null; if (target == ResourceFormat.Xml) { FhirXmlSerializer serializer = new FhirXmlSerializer(); data = serializer.SerializeToBytes(outcome); } else if (target == ResourceFormat.Json) { FhirJsonSerializer serializer = new FhirJsonSerializer(); data = serializer.SerializeToBytes(outcome); } HttpResponseMessage response = new HttpResponseMessage { Content = new ByteArrayContent(data) }; SetContentHeaders(response, target); return(response); }
public FormatElement(string Name, int buf, uint offs, bool pi, int ir, bool rowMat, uint matDim, ResourceFormat f, bool h) { name = Name; buffer = buf; offset = offs; format = f; perinstance = pi; instancerate = ir; rowmajor = rowMat; matrixdim = matDim; hex = h; systemValue = SystemAttribute.None; }
public void ConvertResources(string inputDir, string outputDir, ResourceFormat inputFormat, ResourceFormat outputFormat, FileVersion outputVersion = 0x0) { this.progressUpdate("Enumerating files ...", 0, 1); var paths = new List <string>(); EnumerateFiles(paths, inputDir, inputDir, "." + inputFormat.ToString().ToLower()); this.progressUpdate("Converting resources ...", 0, 1); for (var i = 0; i < paths.Count; i++) { var path = paths[i]; var inPath = inputDir + "/" + path; var outPath = outputDir + "/" + Path.ChangeExtension(path, outputFormat.ToString().ToLower()); FileManager.TryToCreateDirectory(outPath); this.progressUpdate("Converting: " + inPath, i, paths.Count); var resource = LoadResource(inPath, inputFormat); SaveResource(resource, outPath, outputFormat, outputVersion); } }
private static void setBodyAndContentType(HttpWebRequest request, Resource data, ResourceFormat format, out byte[] body) { if (data == null) throw Error.ArgumentNull("data"); if (data is Binary) { var bin = (Binary)data; body = bin.Content; request.WriteBody(bin.Content); request.ContentType = bin.ContentType; } else { body = format == ResourceFormat.Xml ? FhirSerializer.SerializeToXmlBytes(data, summary: false) : FhirSerializer.SerializeToJsonBytes(data, summary: false); request.WriteBody(body); request.ContentType = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false); } }
private GeometryInputLayout CreateInputLayout(VertexShader shader) { uint numInputBindings = (uint)shader.InputBindings.Length; List <KeyValuePair <VertexInputBinding, IVertexBuffer> > inputLayoutComponentBuffers = new List <KeyValuePair <VertexInputBinding, IVertexBuffer> >(); // +3 because the instance matrix is split in to four row vectors InputElementDesc[] inputElements = new InputElementDesc[numInputBindings + 3]; for (int i = 0; i < numInputBindings; ++i) { VertexInputBinding curVIB = shader.InputBindings[i]; if (curVIB == shader.InstanceDataBinding) { continue; } string semantic = curVIB.Identifier; int componentBufferIndex = Array.IndexOf(vertexComponentSemantics, semantic); if (componentBufferIndex < 0) { throw new InvalidOperationException("Can not bind " + this + " to vertex shader with semantics " + shader.InputBindings.Select(srb => srb.Identifier).ToStringOfContents() + ", " + "semantic '" + semantic + "' is not provided in this cache!"); } IVertexBuffer bufferForCurSemantic = vertexComponentBuffers[componentBufferIndex]; ResourceFormat formatForCurSemantic = vertexComponentFormats[componentBufferIndex]; inputLayoutComponentBuffers.Add(new KeyValuePair <VertexInputBinding, IVertexBuffer>(curVIB, bufferForCurSemantic)); inputElements[i] = new InputElementDesc( semantic, 0U, formatForCurSemantic, curVIB.SlotIndex, true ); } // Add the instance data slot uint semanticIndex = 0U; for (uint i = numInputBindings - 1U; i < numInputBindings + 3U; ++i) { inputElements[i] = new InputElementDesc( shader.InstanceDataBinding.Identifier, semanticIndex++, VertexShader.INSTANCE_DATA_FORMAT, shader.InstanceDataBinding.SlotIndex, false ); } InputLayoutHandle outInputLayoutPtr; NativeCallResult createInputLayoutResult = InteropUtils.CallNative(NativeMethods.ShaderManager_CreateInputLayout, RenderingModule.Device, shader.Handle, inputElements, (uint)inputElements.Length, (IntPtr)(&outInputLayoutPtr) ); if (!createInputLayoutResult.Success) { throw new InvalidOperationException("Given shader could not be bound to this cache, " + "this is likely because one or more semantics/bindings are incorrect. Details: " + createInputLayoutResult.FailureMessage); } Logger.Debug("Successfully created input layout for " + shader + " and " + this + ": " + inputElements.ToStringOfContents()); return(new GeometryInputLayout(outInputLayoutPtr, inputLayoutComponentBuffers.ToArray(), shader, this)); }
public static MediaTypeHeaderValue GetMediaTypeHeaderValue(Type type, ResourceFormat format) { string mediatype = FhirMediaType.GetContentType(type, format); MediaTypeHeaderValue header = new MediaTypeHeaderValue(mediatype); header.CharSet = Encoding.UTF8.WebName; return header; }