public override void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet cleanProperties) { try { m_elementsToClean = GetListOfEnabledElementsToClean(cleanProperties); List<Exclusion> listExclusion = GetListOfExcludedElements(cleanProperties); using (BinaryData bData = new BinaryData(tempFile.GetMemoryStream())) { using (PptxDocumentReader reader = new PptxDocumentReader(bData)) { using (Stream str = GetOutputStream()) { reader.CleanTo(str, m_elementsToClean, listExclusion); File.Copy(InterimTempFileName, tempFile.TempFile, true); } } } } catch (System.Exception ex) { Logger.LogError("PowerpointX cleaning failed"); Logger.LogError(ex); throw; } finally { CleanUp(); } }
public void TestWrite() { FileWriter writer = new FileWriter(); FileReader reader = new FileReader(); List<bool> TestData = new List<bool>(); bool[] genData = { true, true, true, false, true }; TestData.AddRange(genData); BinaryData OriginalData = new BinaryData(TestData); String location = "../../../data/test.bin"; writer.WriteBinFile(OriginalData, location); BinaryData ReadData = reader.ReadBinFile(location); IEnumerator<bool> OrigDataEnum = OriginalData.GetEnumerator(); IEnumerator<bool> ReadDataEnum = ReadData.GetEnumerator(); Assert.AreEqual(OriginalData.Length, ReadData.Length, "Written and read should be of the same length."); for (int i = 0; i < OriginalData.Length; i++) { OrigDataEnum.MoveNext(); ReadDataEnum.MoveNext(); Assert.AreEqual(OrigDataEnum.Current, ReadDataEnum.Current, "The written data must match the read data."); } }
private void ExecuteUsingOfficeOpenXml(TempFileForActions tempFile, CleanActionPropertySet elementsToClean) { try { m_elementsToClean = GetElementsNotRemovedByDomClean(GetListOfEnabledElementsToClean(elementsToClean)); using (BinaryData bData = new BinaryData(tempFile.GetMemoryStream())) { using (XlsxDocumentReader reader = new XlsxDocumentReader(bData)) { using (Stream str = GetOutputStream()) { reader.CleanTo(str, m_elementsToClean); File.Copy(InterimTempFileName, tempFile.TempFile, true); } } } } catch (System.Exception ex) { Logger.LogError(ex); throw; } finally { CleanUp(); } }
public BinarySpectrum(double startRt, double endRt, BinaryData xValues, BinaryData yValues) : base(xValues, yValues) { StartRT = startRt; EndRT = endRt; totalIntensity = yValues.Sum(); }
public void WriteBinFile(BinaryData Data, String Location) { StreamWriter writer = new StreamWriter(Location); foreach (bool i in Data) { writer.Write(i ? '1' : '0'); } writer.Close(); }
public void Send(BinaryData data) { try { TrySendData(data); } catch (SocketException) { Dispose(); } }
private void AddToCache(int timePoint) { BinaryData xValues = new BinaryData(); BinaryData yValues = new BinaryData(); for (int i = 0; i < XYDataHelper.XValueTestSet1.Length; i++) { xValues.Add(XYDataHelper.XValueTestSet1[i]); yValues.Add(XYDataHelper.YValueTestSet1[i]); } cache.Add(timePoint, new BinarySpectrum(1.5, xValues, yValues)); }
public void Dispose() { _xValues.Clear(); _xValues.Dispose(); _xValues = null; _yValues.Clear(); _yValues.Dispose(); _yValues = null; GC.SuppressFinalize(this); }
public Domain.ISpectrum GetSpectrum(int timePoint, TimeUnit timeUnits, double mzLower, double mzUpper) { if (spectrumCache.IsInCache(timePoint)) { Domain.ISpectrum spectrum = spectrumCache.Read(timePoint); if (mzLower == 0 && mzUpper == double.MaxValue) { return spectrum; } else { IList<double> xVals = spectrum.XValues; IList<double> yVals = spectrum.YValues; BinaryData xValues = new BinaryData(); BinaryData yValues = new BinaryData(); for (int i = 0; i < xVals.Count; i++) { if (xVals[i] >= mzLower && xVals[i] <= mzUpper) { xValues.Add(xVals[i]); yValues.Add(yVals[i]); } } return new BinarySpectrum(spectrum.StartRT, xValues, yValues); } } else { pwiz.CLI.msdata.Spectrum spectrumFromFile = run.spectrumList.spectrum(timePoint, true); string level = (string)spectrumFromFile.cvParam(pwiz.CLI.CVID.MS_ms_level).value; if (level == "1") { double rt = RtToTimePointConverter.CalculateRT(spectrumFromFile, timeUnits); BinaryDataArray mzArray = spectrumFromFile.getMZArray(); BinaryDataArray intensityArray = spectrumFromFile.getIntensityArray(); BinaryData mzData = mzArray.data; BinaryData intensityData = intensityArray.data; int totalDataPoints = mzData.Count; AddSpectrumToCacheIfNotPresent(timePoint, new BinarySpectrum(rt, mzData, intensityData)); return FilterMassList(rt, mzData, intensityData, mzLower, mzUpper); } } return new Domain.Spectrum(0, new List<XYPoint>()); }
private IXYData ExtractTicByManuallyLookingAtEachSpectrumInTheFile(TimeUnit timeUnits) { if (ticCache.IsInCache()) { return ticCache.Read(); } else { BinaryData xVals = new BinaryData(); BinaryData yVals = new BinaryData(); pwiz.CLI.msdata.SpectrumList spectrumList = run.spectrumList; int timePoints = spectrumList.size(); for (int i = 0; i < timePoints; i++) { pwiz.CLI.msdata.Spectrum s = spectrumList.spectrum(i); Scan scan = null; if (s.scanList.scans.Count > 0) { scan = s.scanList.scans[0]; } CVParam param; param = s.cvParam(pwiz.CLI.CVID.MS_ms_level); int msLevel = !param.empty() ? (int)param.value : 0; if (msLevel <= 1) { param = scan != null ? scan.cvParam(pwiz.CLI.CVID.MS_scan_start_time) : new CVParam(); double scanTime = !param.empty() ? (double)param.value : 0; // TODO: Duplicated with CalculateRT, reuse RtToTimePointConverter. if (timeUnits == TimeUnit.Seconds) { xVals.Add(scanTime / 60); } param = s.cvParam(pwiz.CLI.CVID.MS_total_ion_current); yVals.Add(!param.empty() ? (double)param.value : 0); } } IXYData tic = new XYBinaryData(xVals, yVals); ticCache.Set(tic); return tic; } }
public void TestEnumerator() { List<bool> data = new List<bool>(); for (int i = 0; i < 10; ++i) { data.Add(i % 2 == 0); } BinaryData bin = new BinaryData(data); IEnumerator<bool> ie = bin.GetEnumerator(); for (int i = 0; i < data.Count; ++i) { ie.MoveNext(); Assert.AreEqual(data[i], ie.Current, "Enumerator values."); } }
public static bool IsDataHTML(BinaryData fileData) { byte[] byteArray = new byte[4]; using (Stream str = fileData.AsStream()) { str.Read(byteArray, 0, 4); Encoding encoding = FindEncoding(ref byteArray); string dataString = fileData.AsString(10240, encoding).ToLowerInvariant(); // Trim off byte order marks from the beginning of the string dataString = dataString.TrimStart(new char[] { '\xFEFF', '\xFFFE' }); return IsStringHTML(dataString); } }
public override bool VerifyFile(TempFileForActions tempFile) { try { using (BinaryData bData = new BinaryData(tempFile.GetMemoryStream())) { PptxDocumentReader reader = new PptxDocumentReader(bData); reader.Read(); } return true; } catch (System.Exception ex) { Logger.LogError("PowerpointX Verification failed"); Logger.LogError(ex); } return false; }
protected async Task <GenericResource> CreateVirtualNetwork() { var vnetName = Recording.GenerateAssetName("testVNet-"); var subnetName = Recording.GenerateAssetName("testSubnet-"); ResourceIdentifier vnetId = new ResourceIdentifier($"{_resourceGroup.Id}/providers/Microsoft.Network/virtualNetworks/{vnetName}"); var addressSpaces = new Dictionary <string, object>() { { "addressPrefixes", new List <string>() { "10.0.0.0/16" } } }; var subnet = new Dictionary <string, object>() { { "name", subnetName }, { "properties", new Dictionary <string, object>() { { "addressPrefix", "10.0.2.0/24" } } } }; var subnets = new List <object>() { subnet }; var input = new GenericResourceData(DefaultLocation) { Properties = BinaryData.FromObjectAsJson(new Dictionary <string, object>() { { "addressSpace", addressSpaces }, { "subnets", subnets } }) }; var operation = await _genericResourceCollection.CreateOrUpdateAsync(WaitUntil.Completed, vnetId, input); return(operation.Value); }
public void BinaryData_EmptyWrite() { // Save binary File file = new File(this.TestRoot); BinaryData target = new BinaryData(); file.Binary = target; file.Save(); int id = file.Id; // Load binary back file = (File)Node.LoadNode(id); Assert.IsTrue(file.GetBinary("Binary").IsEmpty); //Assert.AreNotEqual(0, file.Binary.Id); //Assert.AreEqual(string.Empty, file.Binary.ContentType); //Assert.AreEqual(string.Empty, file.Binary.FileName.FullFileName); //Assert.AreEqual((long)-1, file.Binary.Size); //Assert.AreEqual(null, file.Binary.GetStream()); }
/// <summary> /// Creates BinaryData from filename and stream. /// </summary> /// <param name="fileName">Binary file name.</param> /// <param name="stream">Binary stream or null.</param> /// <param name="contentType">Binary content type. This value is used only if the content type /// could not be computed from the file extension.</param> public static BinaryData CreateBinaryData(string fileName, Stream stream, string contentType = null) { var result = new BinaryData(); // use only the file name var slashIndex = fileName.LastIndexOf("\\", StringComparison.Ordinal); if (slashIndex > -1) { fileName = fileName.Substring(slashIndex + 1); } result.FileName = new BinaryFileName(fileName); // set content type only if we were unable to recognise it if (string.IsNullOrEmpty(result.ContentType) && !string.IsNullOrEmpty(contentType)) { result.ContentType = contentType; } result.SetStream(stream); return(result); }
/// <summary> /// Given JSON-encoded events, parses the event envelope and returns an array of EventGridEvents. /// If the content is not valid JSON, or events are missing required properties, an exception is thrown. /// </summary> /// <param name="json">An instance of <see cref="BinaryData"/> containing the JSON for one or more EventGridEvents.</param> /// <returns> An array of <see cref="EventGridEvent"/> instances.</returns> public static EventGridEvent[] ParseMany(BinaryData json) { Argument.AssertNotNull(json, nameof(json)); EventGridEvent[] egEvents = null; JsonDocument requestDocument = JsonDocument.Parse(json); // Parse JsonElement into separate events, deserialize event envelope properties if (requestDocument.RootElement.ValueKind == JsonValueKind.Object) { egEvents = new EventGridEvent[1]; egEvents[0] = (new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(requestDocument.RootElement))); } else if (requestDocument.RootElement.ValueKind == JsonValueKind.Array) { egEvents = new EventGridEvent[requestDocument.RootElement.GetArrayLength()]; int i = 0; foreach (JsonElement property in requestDocument.RootElement.EnumerateArray()) { egEvents[i++] = new EventGridEvent(EventGridEventInternal.DeserializeEventGridEventInternal(property)); } } return(egEvents ?? Array.Empty <EventGridEvent>()); }
public async Task BatchErrorsAsync() { // Get a connection string to our Azure Storage account. string connectionString = ConnectionString; // Get a reference to a container named "sample-container" and then create it BlobServiceClient service = new BlobServiceClient(connectionString); BlobContainerClient container = service.GetBlobContainerClient(Randomize("sample-container")); await container.CreateAsync(); try { // Create a blob named "valid" BlobClient valid = container.GetBlobClient("valid"); await valid.UploadAsync(BinaryData.FromString("Valid!")); // Get a reference to a blob named "invalid", but never create it BlobClient invalid = container.GetBlobClient("invalid"); // Delete both blobs at the same time BlobBatchClient batch = service.GetBlobBatchClient(); await batch.DeleteBlobsAsync(new Uri[] { valid.Uri, invalid.Uri }); } catch (AggregateException ex) { // An aggregate exception is thrown for all the indivudal failures Assert.AreEqual(1, ex.InnerExceptions.Count); RequestFailedException failure = ex.InnerException as RequestFailedException; Assert.IsTrue(BlobErrorCode.BlobNotFound == failure.ErrorCode); } finally { // Clean up after the test when we're finished await container.DeleteAsync(); } }
public async Task UploadBlobText() { string data = "hello world"; BlobContainerClient containerClient = new BlobContainerClient(ConnectionString, Randomize("sample-container")); try { await containerClient.CreateAsync(); string blobName = Randomize("sample-blob"); string localFilePath = this.CreateTempPath(); FileStream fs = File.OpenWrite(localFilePath); var bytes = Encoding.UTF8.GetBytes(data); await fs.WriteAsync(bytes, 0, bytes.Length); await fs.FlushAsync(); fs.Close(); #region Snippet:SampleSnippetsBlobMigration_UploadBlobText BlobClient blobClient = containerClient.GetBlobClient(blobName); await blobClient.UploadAsync(BinaryData.FromString("hello world"), overwrite : true); #endregion BinaryData downloadedData = (await blobClient.DownloadContentAsync()).Value.Content; Assert.AreEqual(data, downloadedData.ToString()); } finally { await containerClient.DeleteIfExistsAsync(); } }
public async Task RetryPolicy() { string connectionString = this.ConnectionString; string data = "hello world"; //setup blob string containerName = Randomize("sample-container"); string blobName = Randomize("sample-file"); var containerClient = new BlobContainerClient(ConnectionString, containerName); try { await containerClient.CreateIfNotExistsAsync(); await containerClient.GetBlobClient(blobName).UploadAsync(BinaryData.FromString(data)); #region Snippet:SampleSnippetsBlobMigration_RetryPolicy BlobClientOptions blobClientOptions = new BlobClientOptions(); blobClientOptions.Retry.Mode = RetryMode.Exponential; blobClientOptions.Retry.Delay = TimeSpan.FromSeconds(10); blobClientOptions.Retry.MaxRetries = 6; BlobServiceClient service = new BlobServiceClient(connectionString, blobClientOptions); BlobClient blobClient = service.GetBlobContainerClient(containerName).GetBlobClient(blobName); Stream targetStream = new MemoryStream(); await blobClient.DownloadToAsync(targetStream); #endregion } finally { await containerClient.DeleteIfExistsAsync(); } Assert.Pass(); }
private PageState GetPageState(BinaryData binaryData) { if (binaryData == null) { throw new ArgumentNullException("binaryData"); } PageState resultPageState = null; Stream sharedDataBlobStream = binaryData.GetStream(); int streamLength = Convert.ToInt32(sharedDataBlobStream.Length); var byteContent = new byte[streamLength]; //try //{ sharedDataBlobStream.Read(byteContent, 0, streamLength); resultPageState = new PageState(byteContent, PersonalizationScope.Shared); //} //catch (Exception exc) //{ // WriteException(exc); //} return(resultPageState); }
public void EventDataInitializesProperties() { var body = new BinaryData("Hello"); var properties = new Dictionary <string, object> { { "id", 12 } }; var systemProperties = new Dictionary <string, object> { { "custom", "sys-value" } }; var sequenceNumber = long.MaxValue - 512; var offset = long.MaxValue - 1024; var enqueueTime = new DateTimeOffset(2015, 10, 27, 12, 0, 0, TimeSpan.Zero); var partitionKey = "omghai!"; var eventData = EventHubsModelFactory.EventData(body, properties, systemProperties, partitionKey, sequenceNumber, offset, enqueueTime); Assert.That(eventData, Is.Not.Null, "The event should have been created."); Assert.That(eventData.EventBody.ToString(), Is.EqualTo(body.ToString()), "The event body should have been set."); Assert.That(eventData.Properties, Is.EquivalentTo(properties), "The properties should have been set."); Assert.That(eventData.SystemProperties, Is.EquivalentTo(systemProperties), "The system properties should have been set."); Assert.That(eventData.PartitionKey, Is.EqualTo(partitionKey), "The partition key should have been set."); Assert.That(eventData.SequenceNumber, Is.EqualTo(sequenceNumber), "The sequence number should have been set."); Assert.That(eventData.Offset, Is.EqualTo(offset), "The offset should have been set."); Assert.That(eventData.EnqueuedTime, Is.EqualTo(enqueueTime), "The sequence number should have been set."); }
/// <summary> /// Gets the specified from the cache /// </summary> /// <param name="applicationName">The application that owns the resource</param> /// <param name="resourceID">The resource ID</param> /// <returns> /// <see cref="BinaryData"/> if the resource exists in the cache, <c>null</c> otherwise /// </returns> public static BinaryData Get(string applicationName, string resourceID) { BinaryData binaryData = null; if (IsCacheConfigured) { string filename = GetResourceFilename(applicationName, resourceID); if (!String.IsNullOrEmpty(filename)) { byte[] bytes = ReadFile(filename); if (bytes != null) { binaryData = new BinaryData(resourceID, bytes); } } } return(binaryData); }
private void HandleAuthorPutDocument(HttpContext context, string firstLine, System.IO.Stream resultStream) { // firstline: method=put document:14.0.0.6009&service_name=/Root/Sites/Default_Site/workspaces/Project/budapestprojectworkspace/&document=[document_name=Document_Library/Aenean semper.doc;meta_info=[]]&put_option=edit&comment=&keep_checked_out=false var serviceNameIdx = firstLine.IndexOf("&service_name="); var workspacePathIdx = serviceNameIdx + "&service_name=".Length; var documentIdx = firstLine.IndexOf("&document=[document_name="); var documentPathIdx = documentIdx + "&document=[document_name=".Length; var workspacePath = firstLine.Substring(workspacePathIdx, documentIdx - workspacePathIdx); var documentPath = firstLine.Substring(documentPathIdx, firstLine.IndexOf(';') - documentPathIdx); //System.Diagnostics.Trace.Write(" FPP put document workspace: " + workspacePath); //System.Diagnostics.Trace.Write(" FPP put document doc path: " + documentPath); var nodePath = RepositoryPath.Combine(workspacePath, documentPath); var file = Node.LoadNode(nodePath) as File; if (file != null) { var binaryData = new BinaryData(); binaryData.SetStream(resultStream); file.SetBinary("Binary", binaryData); file.Save(SavingMode.KeepVersion); // file is not checked in as of yet. office will try to check it in via lists.asmx } var docinfo = GetDocInfo(file); var responseStr = GetFormattedString(string.Format(PUTDOCUMENTSTR, docinfo)); context.Response.Charset = ""; context.Response.ContentType = "application/x-vermeer-rpc"; context.Response.AddHeader("Content-Length", responseStr.Length.ToString()); context.Response.Write(responseStr); context.Response.Flush(); context.Response.End(); }
public void AnalyzeConversationOrchestrationPredictionQuestionAnswering() { ConversationAnalysisClient client = Client; #region Snippet:ConversationAnalysis_AnalyzeConversationOrchestrationPrediction #if SNIPPET ConversationsProject orchestrationProject = new ConversationsProject("DomainOrchestrator", "production"); Response <AnalyzeConversationResult> response = client.AnalyzeConversation( "How are you?", orchestrationProject); #else Response <AnalyzeConversationTaskResult> response = client.AnalyzeConversation( "How are you?", TestEnvironment.OrchestrationProject); #endif CustomConversationalTaskResult customConversationalTaskResult = response.Value as CustomConversationalTaskResult; var orchestratorPrediction = customConversationalTaskResult.Result.Prediction as OrchestratorPrediction; #endregion #region Snippet:ConversationAnalysis_AnalyzeConversationOrchestrationPredictionQnA string respondingProjectName = orchestratorPrediction.TopIntent; TargetIntentResult targetIntentResult = orchestratorPrediction.Intents[respondingProjectName]; if (targetIntentResult.TargetProjectKind == TargetProjectKind.QuestionAnswering) { Console.WriteLine($"Top intent: {respondingProjectName}"); QuestionAnsweringTargetIntentResult qnaTargetIntentResult = targetIntentResult as QuestionAnsweringTargetIntentResult; BinaryData questionAnsweringResponse = qnaTargetIntentResult.Result; Console.WriteLine($"Qustion Answering Response: {questionAnsweringResponse.ToString()}"); } #endregion Assert.That(targetIntentResult.TargetProjectKind, Is.EqualTo(TargetProjectKind.QuestionAnswering)); Assert.That(orchestratorPrediction.TopIntent, Is.EqualTo("ChitChat-QnA")); }
public async Task AutomaticRouting() { #region Snippet:EventHubs_Sample04_AutomaticRouting var connectionString = "<< CONNECTION STRING FOR THE EVENT HUBS NAMESPACE >>"; var eventHubName = "<< NAME OF THE EVENT HUB >>"; /*@@*/ /*@@*/ connectionString = EventHubsTestEnvironment.Instance.EventHubsConnectionString; /*@@*/ eventHubName = _scope.EventHubName; var producer = new EventHubProducerClient(connectionString, eventHubName); try { using var eventBatch = await producer.CreateBatchAsync(); for (var index = 0; index < 5; ++index) { var eventBody = new BinaryData($"Event #{ index }"); var eventData = new EventData(eventBody); if (!eventBatch.TryAdd(eventData)) { throw new Exception($"The event at { index } could not be added."); } } await producer.SendAsync(eventBatch); } finally { await producer.CloseAsync(); } #endregion }
public async Task SimpleWebSocketClientCanConnectAndReceiveMessage() { WebPubSubServiceClientOptions options = InstrumentClientOptions(new WebPubSubServiceClientOptions()); var serviceClient = new WebPubSubServiceClient(TestEnvironment.ConnectionString, nameof(SimpleWebSocketClientCanConnectAndReceiveMessage), options); var url = await serviceClient.GetClientAccessUriAsync(); // start the connection using var client = new WebSocketClient(url, IsSimpleClientEndSignal); // connected await client.WaitForConnected.OrTimeout(); // broadcast messages var textContent = "Hello"; await serviceClient.SendToAllAsync(textContent, ContentType.TextPlain); var jsonContent = BinaryData.FromObjectAsJson(new { hello = "world" }); await serviceClient.SendToAllAsync(RequestContent.Create(jsonContent), ContentType.ApplicationJson); var binaryContent = BinaryData.FromString("Hello"); await serviceClient.SendToAllAsync(RequestContent.Create(binaryContent), ContentType.ApplicationOctetStream); await serviceClient.SendToAllAsync(RequestContent.Create(GetEndSignalBytes()), ContentType.ApplicationOctetStream); await client.LifetimeTask.OrTimeout(); var frames = client.ReceivedFrames; Assert.AreEqual(3, frames.Count); Assert.AreEqual(textContent, frames[0].MessageAsString); Assert.AreEqual(jsonContent.ToString(), frames[1].MessageAsString); CollectionAssert.AreEquivalent(binaryContent.ToArray(), frames[2].MessageBytes); }
public SubnodeBlock Decode(BinaryData encodedData) { var parser = BinaryDataParser.OfValue(encodedData); var blockType = parser.TakeAndSkip(1).ToInt32(); var blockLevel = parser.TakeAndSkip(1).ToInt32(); var entrySize = blockLevel == 1 ? 16 : 24; var numberOfEntries = parser.TakeAndSkip(2).ToInt32(); var padding = parser.TakeAndSkip(4); var entries = parser.TakeAndSkip(numberOfEntries * entrySize); var entriesPadding = BinaryData.Empty(); var remainingTo64Boundary = Utilities.GetRemainingToNextMultipleOf(numberOfEntries * entrySize + 8, 64); if (remainingTo64Boundary > 0) { entriesPadding = parser.TakeAndSkip(remainingTo64Boundary); } var trailer = parser.TakeAndSkip(16, trailerDecoder); return (new SubnodeBlock( blockType, blockLevel, numberOfEntries, padding, entries, entriesPadding, trailer)); }
public bool ParseBinary(BinaryData binaryData) { if (binaryData == null) { throw new ArgumentNullException("binaryData"); } // TODO: Resolve correct File subtype by the SenseNet.ContentRepository.Storage.MimeTable _nodeType = Providers.Instance.StorageSchema.NodeTypes[typeof(File).Name]; if (_nodeType == null) { // Unknown type _fileNameExtension = null; _contentType = null; return(false); } else { // Fix extension and/or contenttype values by config matching _fileNameExtension = binaryData.FileName.Extension; _contentType = binaryData.ContentType; return(true); } }
private PageTemplate CreatePageTemplate(string zoneName, string parentPath) { var folderpath = parentPath ?? this.TestRoot.Path; PageTemplate pageTemplate = null; pageTemplate = Node.LoadNode(string.Concat(folderpath, "/TestPageTemplate.html")) as PageTemplate; if (pageTemplate == null) { var parent = Node.LoadNode(folderpath); pageTemplate = new PageTemplate(parent); pageTemplate.Name = "TestPageTemplate.html"; } BinaryData binaryData = new BinaryData(); binaryData.FileName = new BinaryFileName("TestPageTemplate.html"); string streamString = string.Concat( "<html>", " <body>", " <snpe-zone name=\"ZoneName_", zoneName, "\"></snpe-zone>", " <snpe-edit name=\"Editor\"></snpe-edit>", " <snpe-catalog name=\"Catalog\"></snpe-catalog>", " <snpe:PortalRemoteControl2 ID=\"RemoteControl1\" runat=\"server\" />", " </body>", "</html>" ); Stream stream = Tools.GetStreamFromString(streamString); binaryData.SetStream(stream); pageTemplate.Binary = binaryData; pageTemplate.Save(); return(pageTemplate); }
protected override void OnClientDataReceived(ClientConnection client, BinaryData message) { LastMessage = message as Info; base.OnClientDataReceived(client, message); }
internal ArmDeploymentExportResult(BinaryData template) { Template = template; }
internal ErrorAdditionalInfo(string errorAdditionalInfoType, BinaryData info) { ErrorAdditionalInfoType = errorAdditionalInfoType; Info = info; }
internal string GetShortName(BinaryData data) { return shortNames[data.GetType()]; }
public static void SendEvent_TestHub(string input, [EventHub(TestHubName, Connection = TestHubName)] out BinaryData evt) { evt = new BinaryData(input); }
internal static ArcExtensionData DeserializeArcExtensionData(JsonElement element) { ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional <ProvisioningState> provisioningState = default; Optional <ExtensionAggregateState> aggregateState = default; Optional <IReadOnlyList <PerNodeExtensionState> > perNodeExtensionDetails = default; Optional <string> forceUpdateTag = default; Optional <string> publisher = default; Optional <string> type0 = default; Optional <string> typeHandlerVersion = default; Optional <bool> autoUpgradeMinorVersion = default; Optional <BinaryData> settings = default; Optional <BinaryData> protectedSettings = default; Optional <string> createdBy = default; Optional <Models.CreatedByType> createdByType = default; Optional <DateTimeOffset> createdAt = default; Optional <string> lastModifiedBy = default; Optional <Models.CreatedByType> lastModifiedByType = default; Optional <DateTimeOffset> lastModifiedAt = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("provisioningState")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } provisioningState = new ProvisioningState(property0.Value.GetString()); continue; } if (property0.NameEquals("aggregateState")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } aggregateState = new ExtensionAggregateState(property0.Value.GetString()); continue; } if (property0.NameEquals("perNodeExtensionDetails")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } List <PerNodeExtensionState> array = new List <PerNodeExtensionState>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(PerNodeExtensionState.DeserializePerNodeExtensionState(item)); } perNodeExtensionDetails = array; continue; } if (property0.NameEquals("extensionParameters")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property1 in property0.Value.EnumerateObject()) { if (property1.NameEquals("forceUpdateTag")) { forceUpdateTag = property1.Value.GetString(); continue; } if (property1.NameEquals("publisher")) { publisher = property1.Value.GetString(); continue; } if (property1.NameEquals("type")) { type0 = property1.Value.GetString(); continue; } if (property1.NameEquals("typeHandlerVersion")) { typeHandlerVersion = property1.Value.GetString(); continue; } if (property1.NameEquals("autoUpgradeMinorVersion")) { if (property1.Value.ValueKind == JsonValueKind.Null) { property1.ThrowNonNullablePropertyIsNull(); continue; } autoUpgradeMinorVersion = property1.Value.GetBoolean(); continue; } if (property1.NameEquals("settings")) { if (property1.Value.ValueKind == JsonValueKind.Null) { property1.ThrowNonNullablePropertyIsNull(); continue; } settings = BinaryData.FromString(property1.Value.GetRawText()); continue; } if (property1.NameEquals("protectedSettings")) { if (property1.Value.ValueKind == JsonValueKind.Null) { property1.ThrowNonNullablePropertyIsNull(); continue; } protectedSettings = BinaryData.FromString(property1.Value.GetRawText()); continue; } } continue; } } continue; } if (property.NameEquals("systemData")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("createdBy")) { createdBy = property0.Value.GetString(); continue; } if (property0.NameEquals("createdByType")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } createdByType = new Models.CreatedByType(property0.Value.GetString()); continue; } if (property0.NameEquals("createdAt")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } createdAt = property0.Value.GetDateTimeOffset("O"); continue; } if (property0.NameEquals("lastModifiedBy")) { lastModifiedBy = property0.Value.GetString(); continue; } if (property0.NameEquals("lastModifiedByType")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } lastModifiedByType = new Models.CreatedByType(property0.Value.GetString()); continue; } if (property0.NameEquals("lastModifiedAt")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } lastModifiedAt = property0.Value.GetDateTimeOffset("O"); continue; } } continue; } } return(new ArcExtensionData(id, name, type, systemData, Optional.ToNullable(provisioningState), Optional.ToNullable(aggregateState), Optional.ToList(perNodeExtensionDetails), forceUpdateTag.Value, publisher.Value, type0.Value, typeHandlerVersion.Value, Optional.ToNullable(autoUpgradeMinorVersion), settings.Value, protectedSettings.Value, createdBy.Value, Optional.ToNullable(createdByType), Optional.ToNullable(createdAt), lastModifiedBy.Value, Optional.ToNullable(lastModifiedByType), Optional.ToNullable(lastModifiedAt))); }
/// <summary> /// Creates a new message from the specified payload. /// </summary> /// <param name="body">The payload of the message represented as bytes.</param> internal ServiceBusReceivedMessage(ReadOnlyMemory <byte> body) : this(new AmqpAnnotatedMessage(new BinaryData[] { BinaryData.FromBytes(body) })) { }
private BinaryData GetBinaryData() { if (Clsid == Guid.Empty) { //If we couldn't get the CLSID, then nothing in the registry will be available return _binaryData; } if (_binaryData == null) { using (RegistryKey reg = Registry.ClassesRoot.OpenSubKey(FilterInstanceRegistryKey)) { if (reg != null) { _binaryDataBlob = (byte[])reg.GetValue(FILTER_DATA_BLOB_VALUE); GCHandle handle = GCHandle.Alloc(_binaryDataBlob, GCHandleType.Pinned); try { _binaryData = new BinaryData(); Marshal.PtrToStructure(handle.AddrOfPinnedObject(), _binaryData); } finally { handle.Free(); } } } } return _binaryData; }
public void Send(BinaryData message) { if (IsConnected) socket.Send(message); }
private void TrySendData(BinaryData data) { int numberOfSendBytes = nativeSocket.Send(data.ToArrayWithLengthHeader()); if (numberOfSendBytes == 0) throw new SocketException(); }
protected virtual void OnReceived(BinaryData message) { if (DataReceived != null) DataReceived(this, message); }
protected virtual void OnDataReceived(ClientConnection sender, BinaryData receivedData) { if (DataReceived != null) DataReceived(sender, receivedData); }
public BinarySpectrum(double startRt, double endRt, BinaryData xValues, BinaryData yValues, double mzLower, double mzUpper) : this(startRt, endRt, xValues, yValues) { this.mzLower = mzLower; this.mzUpper = mzUpper; }
protected virtual void OnClientDataReceived(ClientConnection client, BinaryData message) { if (ClientDataReceived != null) ClientDataReceived(client, message); }
internal static VirtualMachineScaleSetVmExtensionPatch DeserializeVirtualMachineScaleSetVmExtensionPatch(JsonElement element) { Optional <string> name = default; Optional <ResourceType> type = default; Optional <ResourceIdentifier> id = default; Optional <string> forceUpdateTag = default; Optional <string> publisher = default; Optional <string> type0 = default; Optional <string> typeHandlerVersion = default; Optional <bool> autoUpgradeMinorVersion = default; Optional <bool> enableAutomaticUpgrade = default; Optional <BinaryData> settings = default; Optional <BinaryData> protectedSettings = default; Optional <bool> suppressFailures = default; Optional <BinaryData> protectedSettingsFromKeyVault = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } type = new ResourceType(property.Value.GetString()); continue; } if (property.NameEquals("id")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("forceUpdateTag")) { forceUpdateTag = property0.Value.GetString(); continue; } if (property0.NameEquals("publisher")) { publisher = property0.Value.GetString(); continue; } if (property0.NameEquals("type")) { type0 = property0.Value.GetString(); continue; } if (property0.NameEquals("typeHandlerVersion")) { typeHandlerVersion = property0.Value.GetString(); continue; } if (property0.NameEquals("autoUpgradeMinorVersion")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } autoUpgradeMinorVersion = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("enableAutomaticUpgrade")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } enableAutomaticUpgrade = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("settings")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } settings = BinaryData.FromString(property0.Value.GetRawText()); continue; } if (property0.NameEquals("protectedSettings")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } protectedSettings = BinaryData.FromString(property0.Value.GetRawText()); continue; } if (property0.NameEquals("suppressFailures")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } suppressFailures = property0.Value.GetBoolean(); continue; } if (property0.NameEquals("protectedSettingsFromKeyVault")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } protectedSettingsFromKeyVault = BinaryData.FromString(property0.Value.GetRawText()); continue; } } continue; } } return(new VirtualMachineScaleSetVmExtensionPatch(id.Value, name.Value, Optional.ToNullable(type), forceUpdateTag.Value, publisher.Value, type0.Value, typeHandlerVersion.Value, Optional.ToNullable(autoUpgradeMinorVersion), Optional.ToNullable(enableAutomaticUpgrade), settings.Value, protectedSettings.Value, Optional.ToNullable(suppressFailures), protectedSettingsFromKeyVault.Value)); }
public XYBinaryData(BinaryData xValues, BinaryData yValues) { _xValues = xValues; _yValues = yValues; }
/// <summary> /// Предыдущее значение /// </summary> private void timer1_Tick(object sender, EventArgs e) { if (_statusTask == ETaskStatus.Start) { Controller.SendBinaryData(BinaryData.pack_9E(0x05)); Controller.SendBinaryData(BinaryData.pack_BF(GlobalSetting.ControllerSetting.AxleX.MaxSpeed, GlobalSetting.ControllerSetting.AxleY.MaxSpeed, GlobalSetting.ControllerSetting.AxleZ.MaxSpeed, GlobalSetting.ControllerSetting.AxleA.MaxSpeed)); Controller.SendBinaryData(BinaryData.pack_C0()); _statusTask = ETaskStatus.Work; } if (_statusTask == ETaskStatus.Stop) { Controller.SendBinaryData(BinaryData.pack_FF()); Controller.SendBinaryData(BinaryData.pack_9D()); Controller.SendBinaryData(BinaryData.pack_9E(0x02)); Controller.SendBinaryData(BinaryData.pack_FF()); Controller.SendBinaryData(BinaryData.pack_FF()); Controller.SendBinaryData(BinaryData.pack_FF()); Controller.SendBinaryData(BinaryData.pack_FF()); Controller.SendBinaryData(BinaryData.pack_FF()); _statusTask = ETaskStatus.Off; Controller.Locked = false; //разблокируем } if (_statusTask == ETaskStatus.Work) { if (_nowPos >= _endPos) { _statusTask = ETaskStatus.Stop; return; } // сравним наличие изменений в данных, и проанализируем какие команды послать в контроллер DataRow dataRowNow = DataLoader.DataRows[_nowPos]; DataRow dataRowOld = new DataRow(0, ""); if (_nowPos != 0) { dataRowOld = DataLoader.DataRows[_nowPos - 1]; } //TODO: пока не работает if (dataRowNow.Extra.NeedPause) { //MessageBox.Show(@"Выполняется пауза длительностью " + dataRowNow.Extra.timeoutMsec + @" мс.", "", // MessageBoxButtons.OK); //System.Threading.Thread.Sleep(dataRowNow.Extra.timeoutMsec); } //Сравнить, и установить в случае необходимости //1) Шпиндель и скорость работы //2) Выполнить движение с необходимой скоростью //if (dataRowNow.Machine != dataRowOld.Machine) if (dataRowNow.Machine.SpindelON != dataRowOld.Machine.SpindelON || dataRowNow.Machine.SpeedSpindel != dataRowOld.Machine.SpeedSpindel) { Controller.SendBinaryData(BinaryData.pack_B5(dataRowNow.Machine.SpindelON, 2, BinaryData.TypeSignal.Hz, dataRowNow.Machine.SpeedSpindel)); //зафиксируем PlanetCNC_Controller.LastStatus = dataRowNow; } if (dataRowNow.POS.X != dataRowOld.POS.X || dataRowNow.POS.Y != dataRowOld.POS.Y || dataRowNow.POS.Z != dataRowOld.POS.Z || dataRowNow.POS.Z != dataRowOld.POS.Z) { if (Controller.INFO.NuberCompleatedInstruction == 0) { //если нет номера инструкции, то отправляем пока буфер не сильно занят if (GlobalSetting.AppSetting.Controller == ControllerModel.PlanetCNC_MK1 && Controller.INFO.FreebuffSize < 4) { return; } if (GlobalSetting.AppSetting.Controller == ControllerModel.PlanetCNC_MK2 && Controller.INFO.FreebuffSize < 230) { return; } } else { //знаем номер инструкции, и будем отправлять пока не более 10 инструкций if (_nowPos > (Controller.INFO.NuberCompleatedInstruction + GlobalSetting.ControllerSetting.MinBuffSize)) { return; } } int speedToSend = dataRowNow.Machine.SpeedMaсhine; if (checkBoxManualSpeed.Checked) { if (dataRowNow.Machine.NumGkode == 0) { speedToSend = (int)numericUpDown1.Value; } if (dataRowNow.Machine.NumGkode == 1) { speedToSend = (int)numericUpDown2.Value; } } //координаты следующей точки float pointX = (float)dataRowNow.POS.X; float pointY = (float)dataRowNow.POS.Y; float pointZ = (float)dataRowNow.POS.Z; //добавление смещения G-кода if (Controller.CorrectionPos.useCorrection) { //// применение пропорций //pointX *= Setting.koeffSizeX; //pointY *= Setting.koeffSizeY; //применение смещения pointX += (float)Controller.CorrectionPos.deltaX; pointY += (float)Controller.CorrectionPos.deltaY; //применение матрицы поверхности детали if (Controller.CorrectionPos.UseMatrix) { pointZ += ScanSurface.GetPosZ(pointX, pointY); } pointZ += (float)Controller.CorrectionPos.deltaZ; } Controller.SendBinaryData(BinaryData.pack_CA(Controller.INFO.CalcPosPulse("X", (decimal)pointX), Controller.INFO.CalcPosPulse("Y", (decimal)pointY), Controller.INFO.CalcPosPulse("Z", (decimal)pointZ), Controller.INFO.CalcPosPulse("A", dataRowNow.POS.A), speedToSend, dataRowNow.numberRow)); //зафиксируем PlanetCNC_Controller.LastStatus = dataRowNow; } if (_nowPos < _endPos) { _nowPos++; } } }
/// <summary> /// Формирования баркода выбранным алгоритмом /// Кодируемые и декодированные данные передаются через аттрибуты класса /// </summary> public Bitmap Encode() { int count = Marshal.SizeOf(typeof (BinaryData)); var binaryData = new BinaryData { ArchiverIndex = (byte) ArchiverIndex, MixerIndex = (byte) MixerIndex, GammaIndex = (byte) GammaIndex, EccIndex = (byte) EccIndex, ExpandSize = (byte) ExpandSize, EccCodeSize = (byte) EccCodeSize, EccDataSize = (byte) EccDataSize, MaximumGamma = (byte) (MaximumGamma ? 0 : -1), }; byte[] keyBytes = Encoding.Default.GetBytes(Key); var binaryBytes = new byte[count]; IntPtr ptr = Marshal.AllocHGlobal(binaryBytes.Length); Marshal.StructureToPtr(binaryData, ptr, true); Marshal.Copy(ptr, binaryBytes, 0x0, binaryBytes.Length); Marshal.FreeHGlobal(ptr); string text = Convert.ToBase64String(binaryBytes.Concat(keyBytes).ToArray()); switch (_barcodeId) { case 0: throw new ArgumentNullException(); default: var writer = new BarcodeWriter { Format = (BarcodeFormat) _barcodeId, }; Bitmap result = writer.Write(text); using (var image = new Image<Gray, Byte>(result)) return _bitmap = image.Bitmap; } }
/// <summary> /// Выключение шпинделя /// </summary> public static void Spindel_OFF() { Controller.SendBinaryData(BinaryData.pack_B5(false, 2, BinaryData.TypeSignal.Hz, PlanetCNC_Controller.ValueHz)); //зафиксируем PlanetCNC_Controller.LastStatus.Machine.SpindelON = false; }
private IXYData ExtractTicNativelyFromFile() { Chromatogram chromatogram = run.chromatogramList.chromatogram(0, true); IList<double> xVals = chromatogram.binaryDataArrays[0].data; IList<double> yVals = chromatogram.binaryDataArrays[1].data; BinaryData xValues = new BinaryData(); BinaryData yValues = new BinaryData(); for (int i = 0; i < xVals.Count; i++) { xValues.Add(xVals[i]); yValues.Add(yVals[i]); } return new XYBinaryData(xValues, yValues); }
public void Save(BinaryData data, BinaryWriter writer) { writer.Write(GetShortName(data)); data.Save(writer); }
/// <summary> /// Constructor that takes a byte[] as a parameter /// </summary> /// <param name="memoryfile"></param> /// <param name="displayname"></param> public File(BinaryData memoryfile, string displayname) { m_impl = new Workshare.FCS.Lite.Interface.File(memoryfile, displayname); }
internal static ArmDeploymentPropertiesExtended DeserializeArmDeploymentPropertiesExtended(JsonElement element) { Optional <ResourcesProvisioningState> provisioningState = default; Optional <string> correlationId = default; Optional <DateTimeOffset> timestamp = default; Optional <TimeSpan> duration = default; Optional <BinaryData> outputs = default; Optional <IReadOnlyList <ResourceProviderData> > providers = default; Optional <IReadOnlyList <ArmDependency> > dependencies = default; Optional <ArmDeploymentTemplateLink> templateLink = default; Optional <BinaryData> parameters = default; Optional <ArmDeploymentParametersLink> parametersLink = default; Optional <ArmDeploymentMode> mode = default; Optional <DebugSetting> debugSetting = default; Optional <ErrorDeploymentExtended> onErrorDeployment = default; Optional <string> templateHash = default; Optional <IReadOnlyList <SubResource> > outputResources = default; Optional <IReadOnlyList <SubResource> > validatedResources = default; Optional <ResponseError> error = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("provisioningState")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } provisioningState = new ResourcesProvisioningState(property.Value.GetString()); continue; } if (property.NameEquals("correlationId")) { correlationId = property.Value.GetString(); continue; } if (property.NameEquals("timestamp")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } timestamp = property.Value.GetDateTimeOffset("O"); continue; } if (property.NameEquals("duration")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } duration = property.Value.GetTimeSpan("P"); continue; } if (property.NameEquals("outputs")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } outputs = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("providers")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List <ResourceProviderData> array = new List <ResourceProviderData>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(JsonSerializer.Deserialize <ResourceProviderData>(item.ToString())); } providers = array; continue; } if (property.NameEquals("dependencies")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List <ArmDependency> array = new List <ArmDependency>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(ArmDependency.DeserializeArmDependency(item)); } dependencies = array; continue; } if (property.NameEquals("templateLink")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } templateLink = ArmDeploymentTemplateLink.DeserializeArmDeploymentTemplateLink(property.Value); continue; } if (property.NameEquals("parameters")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } parameters = BinaryData.FromString(property.Value.GetRawText()); continue; } if (property.NameEquals("parametersLink")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } parametersLink = ArmDeploymentParametersLink.DeserializeArmDeploymentParametersLink(property.Value); continue; } if (property.NameEquals("mode")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } mode = property.Value.GetString().ToArmDeploymentMode(); continue; } if (property.NameEquals("debugSetting")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } debugSetting = DebugSetting.DeserializeDebugSetting(property.Value); continue; } if (property.NameEquals("onErrorDeployment")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } onErrorDeployment = ErrorDeploymentExtended.DeserializeErrorDeploymentExtended(property.Value); continue; } if (property.NameEquals("templateHash")) { templateHash = property.Value.GetString(); continue; } if (property.NameEquals("outputResources")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List <SubResource> array = new List <SubResource>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(JsonSerializer.Deserialize <SubResource>(item.ToString())); } outputResources = array; continue; } if (property.NameEquals("validatedResources")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List <SubResource> array = new List <SubResource>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(JsonSerializer.Deserialize <SubResource>(item.ToString())); } validatedResources = array; continue; } if (property.NameEquals("error")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } error = JsonSerializer.Deserialize <ResponseError>(property.Value.ToString()); continue; } } return(new ArmDeploymentPropertiesExtended(Optional.ToNullable(provisioningState), correlationId.Value, Optional.ToNullable(timestamp), Optional.ToNullable(duration), outputs.Value, Optional.ToList(providers), Optional.ToList(dependencies), templateLink.Value, parameters.Value, parametersLink.Value, Optional.ToNullable(mode), debugSetting.Value, onErrorDeployment.Value, templateHash.Value, Optional.ToList(outputResources), Optional.ToList(validatedResources), error.Value)); }
private static string DataAsString(BinaryData binaryData, Encoding encoding) { if (null == binaryData) return string.Empty; return binaryData.AsString(16, encoding); }
protected abstract void WriteBinary(BinaryData o);
public static bool LooksLikeXML(BinaryData binaryData) { if (LooksLikeXML(DataAsString(binaryData, Encoding.Default))) return true; if (LooksLikeXML(DataAsString(binaryData, Encoding.Unicode))) return true; return false; }
/* ============================================================================= Methods */ public override object GetData() { if (_data == null) { _data = new SenseNet.ContentRepository.Fields.ImageField.ImageFieldData(this.Field); } var innerControl = _fileUploadControl; var imageIsRefControl = _cbxImageRef; // templates if (IsTemplated) { innerControl = GetInnerControl() as FileUpload; imageIsRefControl = GetImageIsRefControl() as CheckBox; } _binaryData = null; // newly posted filestream bool newStream = false; if (innerControl != null && innerControl.HasFile) { var fileStream = innerControl.PostedFile.InputStream; var contentType = innerControl.PostedFile.ContentType; var fileName = innerControl.PostedFile.FileName; _binaryData = new BinaryData(); _binaryData.ContentType = contentType; _binaryData.FileName = fileName; _binaryData.SetStream(fileStream); newStream = true; } // if there is no new stream and the reference control is not on the page, // it means the data could not be changed, so return the original data if (!newStream && imageIsRefControl == null) { return(_data); } // new image mode var newImageMode = (imageIsRefControl != null && imageIsRefControl.Checked) ? ImageRequestMode.Reference : ImageRequestMode.BinaryData; if (!newStream) { switch (this.ImageField.ImageMode) { case ImageRequestMode.BinaryData: _binaryData = _data.ImgData; break; case ImageRequestMode.Reference: if (_data.ImgRef != null) { _binaryData = _data.ImgRef.Binary; } break; } } // no uploads and no original data, so return with empty data if (_binaryData == null) { return(_data); } // if mode is not changed, proceed only if new uploaded stream is available if ((newImageMode == this.ImageField.ImageMode) && (!newStream)) { return(_data); } // from here either mode is changed or new stream is available // 2 possibilities: new mode is reference or new mode is binary // - reference // - former binarydata is cleared // - the referenced node is created or updated // - binary // - binarydata property is set // - referenced node is deleted if (newImageMode == ImageRequestMode.Reference) { // clear binarydata _data.ImgData = null; if (this.Content.Id != 0) { CreateImageReference(this.ContentHandler); } else { this.ContentHandler.Created += new EventHandler <SenseNet.ContentRepository.Storage.Events.NodeEventArgs>(ContentHandler_Created); } } else { // set binarydata _data.ImgData = new BinaryData(); _data.ImgData.CopyFrom(_binaryData); // if copied from referenced node -> node name should be filename, not node's binary's filename (latter could contain '\'-s) if (!newStream) { _data.ImgData.FileName = new BinaryFileName(_data.ImgRef.Name); } // clear referencedata (also delete the file but only after this node is saved!) this.ContentHandler.Modified += new EventHandler <SenseNet.ContentRepository.Storage.Events.NodeEventArgs>(ContentHandler_Modified); } // reset image url after new image is saved var imageControl = GetImageControl(); if (imageControl != null) { if (!string.IsNullOrEmpty(this.ImageUrl)) { imageControl.ImageUrl = this.ImageUrl; } } return(_data); }
/// <summary> /// Set a custom state on the session which can be later retrieved using <see cref="GetStateAsync"/> /// </summary> /// /// <param name="sessionState">A <see cref="BinaryData"/> of session state</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <remarks>This state is stored on Service Bus forever unless you set an empty state on it.</remarks> /// /// <returns>A task to be resolved on when the operation has completed.</returns> public abstract Task SetStateAsync( BinaryData sessionState, CancellationToken cancellationToken);
public void Indexing_TextExtraction() { Test(() => { // Define a custom filename extension. var ext = "testext"; // Create custom textextractor with log and IsSlow = true. var extractor = new CustomTextExtractor(); // Hack textextractor for filename custom extension. var extractorSettings = @"{TextExtractors: {""" + ext + @""": """ + typeof(CustomTextExtractor).FullName + @"""}}"; var settingsFile = Settings.GetSettingsByName <IndexingSettings>(IndexingSettings.SettingsName, Repository.RootPath); settingsFile.Binary.SetStream(RepositoryTools.GetStreamFromString(extractorSettings)); settingsFile.Save(); try { // Create file with the custom filename extension. var testRoot = new SystemFolder(Repository.Root) { Name = "TestRoot" }; testRoot.Save(); var file = new File(testRoot) { Name = "TestFile." + ext }; // Write some well known words into the file's binary. var text = "tema tis rolod muspi meroL"; var binaryData = new BinaryData() { FileName = file.Name }; binaryData.SetStream(RepositoryTools.GetStreamFromString(text)); file.Binary = binaryData; // Save the file. file.Save(); var fileId = file.Id; // Check and reset the custom extractor's log. var called = CustomTextExtractor.Called; var extraction = CustomTextExtractor.Extraction; CustomTextExtractor.Reset(); Assert.IsTrue(called); Assert.AreEqual(text, extraction); // Check the index with queries by well known words in the default (_Text) and "Binary" field. var words = text.Split(' '); var results = new [] { CreateSafeContentQuery($"+{words[4]} +Name:{file.Name} .AUTOFILTERS:OFF").Execute().Nodes.ToArray(), CreateSafeContentQuery($"+{words[0]} +{words[2]} +Name:{file.Name} .AUTOFILTERS:OFF").Execute().Nodes.ToArray(), CreateSafeContentQuery($"+{words[1]} +{words[3]} +Name:{file.Name} .AUTOFILTERS:OFF").Execute().Nodes.ToArray(), }; Assert.AreEqual(1, results[0].Length); Assert.AreEqual(1, results[1].Length); Assert.AreEqual(1, results[2].Length); var expectedIds = $"{fileId}, {fileId}, {fileId}"; var actualIds = string.Join(", ", results.Select(r => r.First().Id.ToString()).ToArray()); Assert.AreEqual(expectedIds, actualIds); } finally { // Remove the hack. settingsFile.Binary.SetStream(RepositoryTools.GetStreamFromString(null)); settingsFile.Save(); } }); }
public BinarySpectrum(double rt, BinaryData xValues, BinaryData yValues) : this(rt, rt, xValues, yValues) { }