public ToggleButtonHandle(Figure owner, ILocator locator) : base(owner, locator) { FillColor = new Color (1, 1, 0.0, 0.3); Width = 15.0; Height = 15.0; }
public ButtonHandle(IFigure owner, ILocator locator, kindButton type) : base(owner) { _locator = locator; _clicked = false; typeButton = type; }
/// <summary> /// Wrap an existing exception in a SAXParseException. /// <para> /// This constructor is especially useful when an application is /// creating its own exception from within a <see cref="org.xml.sax.ContentHandler" /> callback, /// and needs to wrap an existing exception that is not a /// subclass of <see cref="SAXException" />. /// </para> /// </summary> /// <param name="message"> /// The error or warning message, or null to /// use the message from the embedded exception. /// </param> /// <param name="locator"> /// The locator object for the error or warning (may be null). /// </param> /// <param name="ex">Any exception.</param> /// <seealso cref="ILocator" /> public SAXParseException(string message, ILocator locator, Exception ex) : base(message, ex) { if (locator != null) { Init(locator.PublicId, locator.SystemId, locator.LineNumber, locator.ColumnNumber); } else { Init(null, null, -1, -1); } }
public DetectAndHashJob(JobDescriptor jobDescription, Guid workerId, ILocator locator) : base(jobDescription, workerId, locator) { _codeLocationRepository = _serviceLocator.Locate<ICodeLocationRepository>(); _fileRepository = _serviceLocator.Locate<IFileRepository>(); _repositoryController = _serviceLocator.Locate<IRepositoryController>(); }
public EncodeJobNotification(IJob[] jobsReady, string OriginalAssetName, ILocator[] Locators, string UrlForClientStreaming) { myJobList = jobsReady; myAssetName = OriginalAssetName; myLocators = Locators; myUrlForClientStreaming = UrlForClientStreaming; }
/// <inheritdoc /> public virtual void Prepare(ILocator locator) { if (!this.IsInitialized || this.IsPrepared) throw new InvalidOperationException(); this.Locator = locator; this.IsPrepared = true; }
public ServiceConfiguration(ILocator locator, ICollection<RouteBase> routes, string[] allowedSchemes, Type contractType, Type serviceType) { this.locator = locator; this.routes = routes; this.allowedSchemes = allowedSchemes; this.contractType = contractType; this.serviceType = serviceType; }
public virtual void Inizialize() { locator = CreateServiceLocator(); locator .Singleton<ILogger, SimpleLogger>() .Singleton<ILogger, AdvancedLogger>(); }
//// /// <summary> /// Copy an existing Locator or Locator2 object. /// If the object implements Locator2, values of the /// <em>encoding</em> and <em>version</em>strings are copied, /// otherwise they set to <em>null</em>. /// </summary> /// <param name="locator"> /// The existing Locator object. /// </param> public Locator2(ILocator locator) : base(locator) { if (locator is ILocator2) { var l2 = (ILocator2)locator; _version = l2.XmlVersion; _encoding = l2.Encoding; } }
public TransformHandle(MoonlightController controller, IHandleGroup group, ILocator locator) : base(controller, group) { Locator = locator; rotation = new RotateTransform(); Transforms.Children.Add(rotation); }
private ProjectionGatewayConfigurationBuilder(ILocator locator) { _locator = locator; var stringEqComparer = EqualityComparerFactory.Create<string>( (x, y) => x.ToLower() == y.ToLower(), s => s.GetHashCode()); Subscriptions = new MultiValueDictionary<string, Subscription>(stringEqComparer); }
private IContractBehavior ContractBehavior(ILocator locator, Type serviceType) { var provider = locator.IsRegistered(contractType) ? (IContractBehavior)new LocatorInstanceProvider(locator, contractType) : new ActivatorInstanceProvider(serviceType); return provider; }
public LocatorServiceHostFactory( ServiceHostConfigurator configurator, ILocator locator, string[] allowedSchemes) { this.configurator = configurator; this.locator = locator; this.allowedSchemes = allowedSchemes; }
public static ILocator GetLocator() { if (locator == null) { locator = new DefaultLocator(new DefaultFactoryMethodFactory()); RegisterAbstractions(locator); } return locator; }
public GatewayConfiguration(IReadOnlyCollection<Host> hosts, UserCrenedtial userCredential, ILocator locator, int prefetchCount, int eventSubscriberThreadCount, int commandHandlerThreadCount) { Hosts = hosts; UserCrenedtial = userCredential; Locator = locator; PrefetchCount = prefetchCount; EventSubscriberThreadCount = eventSubscriberThreadCount; CommandHandlerThreadCount = commandHandlerThreadCount; }
public JobPoller(WorkloadPresenter presenter, ILocator locator, WorkerState worker, int? intervalSeconds = null) { _interval = intervalSeconds ?? _interval; _presenter = presenter; _jobRepository = locator.Locate<IJobRepository>(); _worker = worker; _serviceLocator = locator; }
public NewConnectionHandle(IFigure owner, ILocator locator) : base(owner, locator) { if (_icon == null) { // TODO: use icon factory. Pixbuf pixbuf = Pixbuf.LoadFromResource("icons.new_association_handle.png"); _icon = GdkCairoHelper.PixbufToImageSurface(pixbuf); } }
public Job(JobDescriptor jobDescription, Guid workerId, ILocator locator) { _serviceLocator = locator; _jobRepository = locator.Locate<IJobRepository>(); _apiRepository = locator.Locate<IApiDataRepository>(); Id = jobDescription.Id; WorkerId = workerId; JobDescriptor = jobDescription; }
public LocatorServiceHost(ILocator locator, Type contractType, Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses) { this.contractType = contractType; foreach (var contractDescription in ImplementedContracts.Values) { contractDescription.Behaviors.Add(ContractBehavior(locator, serviceType)); } }
public RabbitMqGateway(string connectionString, int eventSubscriberThreadCount, int commandHandlerThreadCount, ILocator locator) { _eventSubscriberThreadCount = eventSubscriberThreadCount; _commandHandlerThreadCount = commandHandlerThreadCount; var adapter = new EasyNetQContainerAdapter(locator); RabbitHutch.SetContainerFactory(() => adapter); _externalMessageBus = RabbitHutch.CreateBus(connectionString, register => register.Register<IConsumerErrorStrategy, MyClass>()); _eventBus = locator.Resolve<Core.IEventBus>(); _commandHandlerFactory = locator.Resolve<ICommandHandlerFactory>(); var a = locator.Resolve<IConsumerErrorStrategy>(); }
public static IJob CreateJob(JobDescriptor description, WorkerState worker, ILocator locator) { var jobType = Type.GetType(description.JobType); if (jobType == null) { throw new TypeAccessException("Could not create a type from " + description.JobType); } var instance = Activator.CreateInstance(jobType, description, worker.Id, locator) as IJob; return instance; }
private void DeleteAccessPolicyAndLocator() { if (this.locator != null) { var accessPolicy = this.locator.AccessPolicy; this.locator.Delete(); this.locator = null; accessPolicy.Delete(); } }
public AnalogClockHandHandle(IFigure owner, ILocator locator) : base(owner, locator) { _default = new Cairo.Color (1, 0, 0, 0.8); _selected = new Cairo.Color (1, 0, 1, 0.8); //We kept the pointer to use it later when requesting cursor //and value to update _hand = (AnalogClockHandLocator) locator; FillColor = _default; LineColor = new Cairo.Color (0.0, 0.0, 0.0, 1.0); }
private string GetUrl(ILocator locator, string fileName) { if (fileName.EndsWith("mp4")) { return locator.Path + fileName; } if (fileName.EndsWith("ism")) { return locator.Path + fileName + "/Manifest"; } return null; }
/// <summary> /// Construct the line with the given start figure and end point /// </summary> /// <param name="canvas">the associated canvas</param> /// <param name="start">the starting figure</param> /// <param name="end">the end point</param> public ConnectingLineFigure(ICanvas canvas, IFigure start, Point end) : base(canvas, start.Location, Size.Empty) { // no handles for a connecting line figure _handles.Clear(); // if an implementation of Translate is provided, the use the following handle // _handles.Add(new Basic.LocatorHandle(new Locator.ProportionalLocator(this), _canvas)); this._startFigure = start; ((IObservable)this._startFigure).AddObserver(this); this._endLocator = new Locator.PointLocator(end); }
public PixButtonHandle(IFigure owner, ILocator locator, Gdk.Pixbuf pixbuf, Action action, int xAnchor, int yAnchor, double valueZoom, double offsetPanX, double offsetPanY) : base (owner, locator, pixbuf) { m_action = action; m_xAnchor = xAnchor; m_yAnchor = yAnchor; m_valueZoom = valueZoom; m_offsetPanX = offsetPanX; m_offsetPanY = offsetPanY; is_resize = true; }
/// <summary> /// Returns a <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>. /// </summary> /// <param name="assets">The <see cref="AssetBaseCollection"/> instance.</param> /// <param name="folderPath">The path to the folder with the files to upload to the new <see cref="IAsset"/>.</param> /// <param name="storageAccountName">The name of the storage account where to store the new <see cref="IAsset"/>.</param> /// <param name="options">The <see cref="AssetCreationOptions"/>.</param> /// <param name="uploadProgressChangedCallback">A callback to report upload progress of the files.</param> /// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> instance used for cancellation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task<IAsset>"/> instance for a new <see cref="IAsset"/> with the files in <paramref name="folderPath"/>.</returns> public static async Task <IAsset> CreateFromFolderAsync(this AssetBaseCollection assets, string folderPath, string storageAccountName, AssetCreationOptions options, Action <IAssetFile, UploadProgressChangedEventArgs> uploadProgressChangedCallback, CancellationToken cancellationToken) { if (assets == null) { throw new ArgumentNullException("assets", "The assets collection cannot be null."); } IEnumerable <string> filePaths = Directory.EnumerateFiles(folderPath); if (!filePaths.Any()) { throw new FileNotFoundException( string.Format(CultureInfo.InvariantCulture, "No files in directory, check the folder path: '{0}'", folderPath)); } MediaContextBase context = assets.MediaContext; if (string.IsNullOrWhiteSpace(storageAccountName)) { storageAccountName = context.DefaultStorageAccount.Name; } string assetName = Path.GetFileName(Path.GetFullPath(folderPath.TrimEnd('\\'))); IAsset asset = await context.Assets.CreateAsync(assetName, storageAccountName, options, cancellationToken).ConfigureAwait(false); ILocator sasLocator = await context.Locators.CreateAsync(LocatorType.Sas, asset, AccessPermissions.Write | AccessPermissions.List, DefaultAccessPolicyDuration).ConfigureAwait(false); EventHandler <UploadProgressChangedEventArgs> uploadProgressChangedHandler = (s, e) => { IAssetFile assetFile = (IAssetFile)s; UploadProgressChangedEventArgs eventArgs = e; if (uploadProgressChangedCallback != null) { uploadProgressChangedCallback(assetFile, eventArgs); } }; IList <Task> uploadTasks = new List <Task>(); foreach (string filePath in filePaths) { uploadTasks.Add(asset.CreateAssetFileFromLocalFileAsync(filePath, sasLocator, uploadProgressChangedHandler, cancellationToken)); } await Task.Factory.ContinueWhenAll(uploadTasks.ToArray(), t => t, TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false); await sasLocator.DeleteAsync().ConfigureAwait(false); return(asset); }
private async Task UpdateStreamingUrl(IAsset asset, ILocator originLocator, ZetronMstIncidents zetronMstIncidents) { try { //Get manifest file to create streaming url IAssetFile manifestFile = asset.AssetFiles.Where(f => f.Name.ToLower().EndsWith(".ism")).FirstOrDefault(); string streamUrl = originLocator.Path + manifestFile.Name + "/manifest(format=m3u8-aapl)"; //var droneDetail = _drone.GetCurrentLocationDetail(); ZetronTrnMediaDetails mediaDetails = new ZetronTrnMediaDetails() { IncidentId = zetronMstIncidents.IncidentId, MediaUrl = streamUrl, Name = asset.Name, MediaType = 1, PostedIon = DateTime.Now.ToUniversalTime(), PostedBy = "Admin", Status = true }; using (var _dbContext = new ZetronContext(options.Options)) { //var mediaId = _dbContext.ZetronTrnMediaDetails.Max(m => m.MediaId) + 1; _dbContext.ZetronTrnMediaDetails.Add(mediaDetails); ZetronMstIncidents recordtoUpdate = null; if (zetronMstIncidents.Status == (int)IncidentStatus.Started) { recordtoUpdate = _dbContext.ZetronMstIncidents.Single(i => i.IncidentId == zetronMstIncidents.IncidentId); recordtoUpdate.Status = (int)IncidentStatus.Processing; } //_dbContext.ZetronTrnDroneLocations.Add(new ZetronTrnDroneLocations() //{ // MediaID = mediaId, // DewPoint = droneDetail.DewPoint, // Humidity = droneDetail.Humidity, // Temperature = droneDetail.Temperature, // WindSpeed = droneDetail.WindSpeed, // Summary = droneDetail.Summary, // WindDirection = droneDetail.WindDirection, // Longitude = droneDetail.Longitude, // Latitude = droneDetail.Latitude //}); await _dbContext.SaveChangesAsync(); } } catch (Exception ex) { Log(ex.Message); throw; } }
/// <summary> /// Uploads a stream asynchronously /// </summary> /// <param name="name">Name for the stream</param> /// <param name="stream">Stream to be uploaded</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to use for canceling upload operation.</param> /// <returns>A function delegate that returns the future result to be available through the Task.</returns> public Task UploadAsync(Stream stream, CancellationToken cancellationToken) { if (stream == null) { throw new ArgumentNullException("stream"); } if (this.IsFragmented()) { throw new NotSupportedException(StringTable.NotSupportedFragblobUpload); } IAccessPolicy accessPolicy = null; ILocator locator = null; var policyName = "SdkUpload" + Guid.NewGuid().ToString(); return(GetMediaContext().AccessPolicies .CreateAsync(policyName, TimeSpan.FromHours(12), AccessPermissions.Write) .ContinueWith <ILocator>( t => { accessPolicy = t.Result; t.ThrowIfFaulted(() => this.Cleanup(null, null, locator, accessPolicy)); cancellationToken.ThrowIfCancellationRequested(() => this.Cleanup(null, null, locator, accessPolicy)); locator = this.GetMediaContext().Locators.CreateSasLocator(this.Asset, accessPolicy); cancellationToken.ThrowIfCancellationRequested(() => this.Cleanup(null, null, locator, accessPolicy)); return locator; }, cancellationToken). ContinueWith( t => { locator = t.Result; t.ThrowIfFaulted(() => this.Cleanup(null, null, locator, accessPolicy)); cancellationToken.ThrowIfCancellationRequested(() => this.Cleanup(null, null, locator, accessPolicy)); var blobTransfer = GetMediaContext().MediaServicesClassFactory.GetBlobTransferClient(); blobTransfer.NumberOfConcurrentTransfers = this.GetMediaContext().NumberOfConcurrentTransfers; blobTransfer.ParallelTransferThreadCount = this.GetMediaContext().ParallelTransferThreadCount; UploadAsync(stream, blobTransfer, locator, cancellationToken).Wait(); locator.Delete(); cancellationToken.ThrowIfCancellationRequested(() => this.Cleanup(null, null, null, accessPolicy)); accessPolicy.Delete(); }, cancellationToken)); }
/// <summary> /// The main functionality to use Intersection Reverse Geocoding /// </summary> /// <param name="X"></param> /// <param name="Y"></param> private static void ReverseGeocodeIntersection(double X, double Y) { // Get a locator from the locator Workspace System.Object obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager")); ILocatorManager2 locatorManager = obj as ILocatorManager2; ILocatorWorkspace locatorWorkspace = locatorManager.GetLocatorWorkspaceFromPath(@"C:\California_fdb.gdb"); ILocator locator = locatorWorkspace.GetLocator("California_streets_10"); IReverseGeocoding reverseGeocoding = locator as IReverseGeocoding; // Get the spatial reference from the locator IAddressGeocoding addressGeocoding = locator as IAddressGeocoding; IFields matchFields = addressGeocoding.MatchFields; IField shapeField = matchFields.get_Field(matchFields.FindField("Shape")); ISpatialReference spatialReference = shapeField.GeometryDef.SpatialReference; // Set up the point from the X and Y values IPoint point = new PointClass(); point.SpatialReference = spatialReference; point.X = X; point.Y = Y; // Set the search tolerance for reverse geocoding IReverseGeocodingProperties reverseGeocodingProperties = reverseGeocoding as IReverseGeocodingProperties; reverseGeocodingProperties.SearchDistance = 2; reverseGeocodingProperties.SearchDistanceUnits = esriUnits.esriKilometers; // Determine if the locator supports intersection geocoding. // intersectionGeocoding will be null if it is not supported. IIntersectionGeocoding intersectionGeocoding = locator as IIntersectionGeocoding; if (intersectionGeocoding == null) { Console.WriteLine("You must use a locator that supports intersections. Use a locator that was built off of one" + "of the US Streets Locator styles."); } else { // Find the intersection that is nearest to the Point IPropertySet addressProperties = reverseGeocoding.ReverseGeocode(point, true); // Print the intersection properties IAddressInputs addressInputs = reverseGeocoding as IAddressInputs; IFields addressFields = addressInputs.AddressFields; for (int i = 0; i < addressFields.FieldCount; i++) { IField addressField = addressFields.get_Field(i); Console.WriteLine(addressField.AliasName + ": " + addressProperties.GetProperty(addressField.Name)); } } }
private static string GetFileUrl(this ILocator locator, string fileName) { if (locator.Type == LocatorType.Sas) { return(string.Concat(locator.BaseUri, locator.BaseUri.EndsWith("/") ? string.Empty : "/", Uri.EscapeDataString(fileName), locator.ContentAccessComponent)); } else if (locator.Type == LocatorType.OnDemandOrigin) { return(string.Concat(locator.Path, locator.Path.EndsWith("/") ? string.Empty : "/", Uri.EscapeDataString(fileName), "/Manifest")); } return(string.Empty); }
string GetStreamingManifestUrl(ILocator locator, IAssetFile assetFile, string cdnStreamingEndpointName) { var manifestUrl = locator.Path + assetFile.Name + "/manifest"; manifestUrl = manifestUrl.Replace("http://", $"https://{cdnStreamingEndpointName}-"); while (manifestUrl.Contains(" ")) { manifestUrl = manifestUrl.Replace(" ", "%20"); } return(manifestUrl); }
public Branch FindLastBranch(ILocator locator, ref FullKey nearFullKey, ref bool hasNearFullKey) { Range range = Optimizator.FindRange(locator); int idx = range.LastIndex; //no matter of range.IsBaseLocator if (idx > 0) { hasNearFullKey = true; nearFullKey = Branches[idx - 1].Key; } return(Branches[idx].Value); }
public HomeModule(ILocator locator, IRootPathProvider rootPathProvider) : base(Constants.BlogBasePath) { _locator = locator; _rootPathProvider = rootPathProvider; Get["/"] = parameters => RenderIndex(parameters); Get["/404"] = parameters => Render404(parameters); Get["/about"] = parameters => RenderAbout(parameters); Get["/{year}/{month}"] = parameters => RenderPosts(parameters); Get["/tag/{tagId}"] = parameters => RenderPostsByTag(parameters); Get["/{post_url}"] = parameters => RenderPost(parameters); }
////////////////////////////////////////////////////////////////////// // Constructors. ////////////////////////////////////////////////////////////////////// /// <summary> /// Create a new <see cref="SAXParseException"/> from a message and a <see cref="ILocator"/>. /// </summary> /// <remarks> /// This constructor is especially useful when an application is /// creating its own exception from within a <see cref="IContentHandler"/> /// callback. /// </remarks> /// <param name="message">The error or warning message.</param> /// <param name="locator">The locator object for the error or warning (may be null).</param> /// <seealso cref="ILocator"/> public SAXParseException(string message, ILocator locator) : base(message) { if (locator != null) { Init(locator.PublicId, locator.SystemId, locator.LineNumber, locator.ColumnNumber); } else { Init(null, null, -1, -1); } }
public Params(WalkMethod walkMethod, WalkAction walkAction, WalkParams walkParams, bool sink, ILocator path) { WalkMethod = walkMethod; WalkAction = walkAction; WalkParams = walkParams; Sink = sink; Path = path; IsPoint = false; IsOverall = true; IsTotal = false; }
private ILocator CreateStreamingLocator(IAsset theAsset, int daysForWhichStreamingUrlIsActive) { ILocator locator = null; var accessPolicy = _MediaServicesContext.AccessPolicies.Create( theAsset.Name , TimeSpan.FromDays(daysForWhichStreamingUrlIsActive) , AccessPermissions.Read); locator = _MediaServicesContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, theAsset, accessPolicy, DateTime.UtcNow.AddMinutes(-5)); return(locator); }
public ParseErrorImpl(string message, ILocator locator, Exception e) { if (locator != null) { Init(message, locator.PublicId, locator.SystemId, locator.LineNumber, locator.ColumnNumber); } else { Init(message, null, null, -1, -1); } baseException = e; }
/// <summary> /// Scans and register Views from the calling assembly. This should be called from all of /// the assemblies containing Views in the initialization. /// </summary> /// <param name="viewLocator">View locator.</param> public static void ScanViews(ILocator <IView> viewLocator) { Assembly assembly = Assembly.GetCallingAssembly(); foreach (Type type in assembly.GetTypes()) { foreach (var attribute in type.GetCustomAttributes(typeof(ViewAttribute), true)) { ViewAttribute viewAttribute = (ViewAttribute)attribute; viewLocator.Register(viewAttribute.ViewName, type, viewAttribute.Priority); } } }
// Create locator and get urls static public string PublishAssetGetURLs(IAsset asset) { // A locator expiry can be set to maximum 100 years, using 99 years below. TimeSpan daysForWhichStreamingUrlIsActive = DateTime.Now.AddYears(99) - DateTime.Now; IAccessPolicy videoWatchPolicy = context.AccessPolicies.Create("videoWatchPolicy", daysForWhichStreamingUrlIsActive, AccessPermissions.Read); ILocator destinationLocator = context.Locators.CreateLocator(LocatorType.OnDemandOrigin, asset, videoWatchPolicy); // Get the asset container URI Uri uploadUri = new Uri(destinationLocator.Path); // Note: You need atleast 1 reserve streaming unit for dynamic packaging of encoded media. If you don't have that, you can't see video file playing return(uploadUri.ToString() + asset.Name + ".ism/manifest"); }
public void ShouldSetLocatorIdWithPrefixWhenCreateOriginLocator() { IAsset asset = AssetTests.CreateAsset(_mediaContext, _smallWmv, AssetCreationOptions.None); IAccessPolicy accessPolicy = _mediaContext.AccessPolicies.Create("Read", TimeSpan.FromMinutes(5), AccessPermissions.Read); string locatorIdWithoutPrefix = Guid.NewGuid().ToString(); string locatorIdWithPrefix = string.Concat(LocatorData.LocatorIdentifierPrefix, locatorIdWithoutPrefix); ILocator locator = _mediaContext.Locators.CreateLocator(locatorIdWithPrefix, LocatorType.OnDemandOrigin, asset, accessPolicy, startTime: null); Assert.IsNotNull(locator); Assert.AreEqual(locator.ContentAccessComponent, locatorIdWithoutPrefix, true); Assert.IsTrue(locator.Path.TrimEnd('/').EndsWith(locatorIdWithoutPrefix, StringComparison.OrdinalIgnoreCase)); }
public ParseErrorImpl(string message, ILocator locator, string id) { if (locator != null) { Init(message, locator.PublicId, locator.SystemId, locator.LineNumber, locator.ColumnNumber); } else { Init(message, null, null, -1, -1); } errorId = id; }
public string GetMp4StreamingOriginLocator(Models.Asset assetToStream) { // Get a reference to the manifest file from the collection // of streaming files in the asset. var theManifest = from f in assetToStream.MediaAsset.AssetFiles where f.Name.EndsWith(".mp4") select f; // Cast the reference to a true IFileInfo type. IAssetFile manifestFile = theManifest.First(); // Create an 1-day readonly access policy. IAccessPolicy streamingPolicy = this.MediaService.MediaContext.AccessPolicies.Create("Readonly 1 hour policy", TimeSpan.FromHours(1), AccessPermissions.Read); // Create the origin locator. Set the start time as 5 minutes // before the present so that the locator can be accessed immediately // if there is clock skew between the client and server. ILocator originLocator = (from l in this.MediaService.MediaContext.Locators where l.AssetId.Equals(assetToStream.MediaAsset.Id) && l.Type == LocatorType.Sas select l).FirstOrDefault(); if (originLocator != null && originLocator.ExpirationDateTime <= DateTime.UtcNow) { originLocator.Delete(); originLocator = null; } if (originLocator == null) { originLocator = this.MediaService.MediaContext .Locators.CreateSasLocator(assetToStream.MediaAsset, streamingPolicy, DateTime.UtcNow.AddMinutes(-5)); } // Create a full URL to the manifest file. Use this for playback // in streaming media clients. UriBuilder bldr = new UriBuilder(originLocator.Path); bldr.Path += "/" + manifestFile.Name; string urlForClientStreaming = bldr.ToString(); // Display the full URL to the streaming manifest file. Console.WriteLine("URL to for progressive download: "); Console.WriteLine(urlForClientStreaming); return(urlForClientStreaming); }
// Create a locator URL to a streaming media asset // on an origin server. static public ILocator GetStreamingOriginLocator(IAsset assetToStream, MediaContentType contentType) { // Get a reference to the streaming manifest file from the // collection of files in the asset. var theManifest = from f in assetToStream.AssetFiles where f.Name.EndsWith(".ism") select f; // Cast the reference to a true IAssetFile type. IAssetFile manifestFile = theManifest.First(); // Create a 30-day readonly access policy. IAccessPolicy policy = _context.AccessPolicies.Create("Streaming policy", TimeSpan.FromDays(30), AccessPermissions.Read); // Create a locator to the streaming content on an origin. ILocator originLocator = _context.Locators.CreateLocator(LocatorType.OnDemandOrigin, assetToStream, policy, DateTime.UtcNow.AddMinutes(-5)); // Display some useful values based on the locator. // Display the base path to the streaming asset on the origin server. Console.WriteLine("Streaming asset base path on origin: "); Console.WriteLine(originLocator.Path); Console.WriteLine(); // Create a full URL to the manifest file. Use this for playback // in streaming media clients. string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest"; if (contentType == MediaContentType.HLS) { urlForClientStreaming = String.Format("{0}{1}", urlForClientStreaming, "(format=m3u8-aapl)"); } Console.WriteLine("URL to manifest for client streaming: "); Console.WriteLine(urlForClientStreaming); Console.WriteLine(); // For convenience, write the URL to a local file. Use the saved // streaming URL to browse directly to the asset in a smooth streaming client. string outFilePath = Path.GetFullPath(_outputFilesFolder + @"\" + "StreamingUrl.txt"); WriteToFile(outFilePath, urlForClientStreaming); // Return the locator. return(originLocator); }
public async Task ShouldTakeScreenshotWithMaskOption() { await Page.SetViewportSizeAsync(500, 500); await Page.GotoAsync(Server.Prefix + "/grid.html"); await Page.EvaluateAsync("() => window.scrollBy(50, 100)"); var element = Page.Locator("body"); await element.ScreenshotAsync(new() { Mask = new ILocator[] { Page.Locator(".box").Nth(3) }, }); }
static void Main(string[] args) { AzureAdTokenCredentials tokenCredentials = new AzureAdTokenCredentials(_AADTenantDomain, new AzureAdClientSymmetricKey(_AMSClientId, _AMSClientSecret), AzureEnvironments.AzureCloudEnvironment); var tokenProvider = new AzureAdTokenProvider(tokenCredentials); _context = new CloudMediaContext(new Uri(_RESTAPIEndpoint), tokenProvider); IChannel channel = CreateAndStartChannel(); // The channel's input endpoint: string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString(); Console.WriteLine("Intest URL: {0}", ingestUrl); // Use the previewEndpoint to preview and verify // that the input from the encoder is actually reaching the Channel. string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString(); Console.WriteLine("Preview URL: {0}", previewEndpoint); // When Live Encoding is enabled, you can now get a preview of the live feed as it reaches the Channel. // This can be a valuable tool to check whether your live feed is actually reaching the Channel. // The thumbnail is exposed via the same end-point as the Channel Preview URL. string thumbnailUri = new UriBuilder { Scheme = Uri.UriSchemeHttps, Host = channel.Preview.Endpoints.FirstOrDefault().Url.Host, Path = "thumbnails/input.jpg" }.Uri.ToString(); Console.WriteLine("Thumbain URL: {0}", thumbnailUri); // Once you previewed your stream and verified that it is flowing into your Channel, // you can create an event by creating an Asset, Program, and Streaming Locator. IAsset asset = CreateAndConfigureAsset(); IProgram program = CreateAndStartProgram(channel, asset); ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength); // You can use slates and ads only if the channel type is Standard. StartStopAdsSlates(channel); // Once you are done streaming, clean up your resources. Cleanup(channel); }
public DistanceMeasurementLines(ILocator locator) { Locator = locator; _mapPoints = new List <MapPoint>(); _lines = new List <Line>(); _distances = new List <TextBlock>(); _ellipses = new List <Ellipse>(); presLine = new Line(); presDistance = new TextBlock(); presEllipse = new Ellipse(); this.Children.Add(presLine); this.Children.Add(presDistance); this.Children.Add(presEllipse); }
public void When_Uploading_Multiple_Files_The_Progress_Event_Should_Only_Be_For_The_Bound_AssetFile() { IAsset asset = _mediaContext.Assets.Create("test", AssetCreationOptions.None); string fileUploaded = _smallWmv; var file = new FileInfo(fileUploaded); IAssetFile fileInfo = asset.AssetFiles.Create(Path.GetFileName(_smallWmv)); IAccessPolicy policy = _mediaContext.AccessPolicies.Create("Write", TimeSpan.FromMinutes(10), AccessPermissions.Write); ILocator locator = _mediaContext.Locators.CreateLocator(LocatorType.Sas, asset, policy); var btc = new BlobTransferClient { NumberOfConcurrentTransfers = 5, ParallelTransferThreadCount = 5 }; int allProgressEventsFiredCount = 0; btc.TransferProgressChanged += (sender, args) => { allProgressEventsFiredCount++; }; bool progressFired = false; bool wrongFileSize = true; int fileProgressEventsCount = 0; fileInfo.UploadProgressChanged += (s, e) => { progressFired = true; wrongFileSize = e.TotalBytes != file.Length; fileProgressEventsCount++; }; Task uploadTask = fileInfo.UploadAsync(fileUploaded, btc, locator, CancellationToken.None); string competingFile = WindowsAzureMediaServicesTestConfiguration.GetVideoSampleFilePath(TestContext, WindowsAzureMediaServicesTestConfiguration.SmallMp41); var retryPolicy = _mediaContext.MediaServicesClassFactory.GetBlobStorageClientRetryPolicy() .AsAzureStorageClientRetryPolicy(); btc.UploadBlob(CreateUrl(locator, Path.GetFileName(competingFile)), competingFile, null, null, CancellationToken.None, retryPolicy).Wait(); uploadTask.Wait(); Assert.IsTrue(progressFired, "No upload progress event fired"); Assert.IsFalse(wrongFileSize, "Received the wrong file size from the upload progress event"); Assert.IsTrue(condition: fileProgressEventsCount < allProgressEventsFiredCount, message: "Unexpected number of fired events, it should be more than the events fired for the uploaded file."); }
/// <summary> /// Uploads the folder to the existing asset. /// </summary> /// <param name="asset">The existing asset.</param> /// <param name="locator">The uploading locator.</param> /// <param name="folderPath">The folder path.</param> /// <param name="blobTransferClient">The blob transfer client.</param> /// <exception cref="System.IO.FileNotFoundException"></exception> private void UploadFolder(IAsset asset, ILocator locator, string folderPath, BlobTransferClient blobTransferClient) { var filePaths = Directory.GetFiles(folderPath); if (!filePaths.Any()) { throw new FileNotFoundException(String.Format("No files in directory, check folderPath: {0}", folderPath)); } Task.WaitAll((from filePath in filePaths let assetFile = asset.AssetFiles.Create(Path.GetFileName(filePath)) select assetFile.UploadAsync(filePath, blobTransferClient, locator, CancellationToken.None)).ToArray()); }
protected string GetQuery(ILocator locator, int?count) { var query = "?"; if (locator != null) { query += $"{locator.GetLocatorQueryString()}"; } if (count.HasValue) { query += $",count:{count}"; } return(query); }
private void GeocodeAddress() { // Get the locator System.Object obj = Activator.CreateInstance(Type.GetTypeFromProgID("esriLocation.LocatorManager")); ILocatorManager2 locatorManager = obj as ILocatorManager2; ILocatorWorkspace locatorWorkspace = locatorManager.GetLocatorWorkspaceFromPath(@"C:\California_fgdb.gdb"); ILocator locator = locatorWorkspace.GetLocator("California_city_state_zip_94_new"); // Set up the address properties IAddressInputs addressInputs = locator as IAddressInputs; IFields addressFields = addressInputs.AddressFields; IPropertySet addressProperties = new PropertySetClass(); addressProperties.SetProperty(addressFields.get_Field(0).Name, this.AddressTextBox.Text); addressProperties.SetProperty(addressFields.get_Field(1).Name, this.CityTextBox.Text); addressProperties.SetProperty(addressFields.get_Field(2).Name, this.StateTextBox.Text); addressProperties.SetProperty(addressFields.get_Field(3).Name, this.ZipTextBox.Text); // Match the Address IAddressGeocoding addressGeocoding = locator as IAddressGeocoding; IPropertySet resultSet = addressGeocoding.MatchAddress(addressProperties); // Print out the results object names, values; resultSet.GetAllProperties(out names, out values); string[] namesArray = names as string[]; object[] valuesArray = values as object[]; int length = namesArray.Length; IPoint point = null; for (int i = 0; i < length; i++) { if (namesArray[i] != "Shape") { this.ResultsTextBox.Text += namesArray[i] + ": " + valuesArray[i].ToString() + "\n"; } else { if (point != null && !point.IsEmpty) { point = valuesArray[i] as IPoint; this.ResultsTextBox.Text += "X: " + point.X + "\n"; this.ResultsTextBox.Text += "Y: " + point.Y + "\n"; } } } this.ResultsTextBox.Text += "\n"; }
public void Commit(CancellationToken cancellationToken, ILocator locator = default(ILocator), bool hasLocator = false, IData fromKey = null, IData toKey = null) { if (disposed) { throw new ObjectDisposedException("WTree"); } Params param; if (!hasLocator) { param = new Params(WalkMethod.CascadeButOnlyLoaded, WalkAction.Store, null, false); } else { if (fromKey == null) { param = new Params(WalkMethod.CascadeButOnlyLoaded, WalkAction.Store, null, false, locator); } else { if (toKey == null) { param = new Params(WalkMethod.CascadeButOnlyLoaded, WalkAction.Store, null, false, locator, fromKey); } else { param = new Params(WalkMethod.CascadeButOnlyLoaded, WalkAction.Store, null, false, locator, fromKey, toKey); } } } lock (RootBranch) { Token token = new Token(CacheSemaphore, cancellationToken); RootBranch.Fall(Depth + 1, token, param); token.CountdownEvent.Signal(); token.CountdownEvent.Wait(); //write settings & root cache (always at handle 0). using (MemoryStream ms = new MemoryStream()) { Settings.Serialize(this, ms); RootBranch.Cache.Store(this, new BinaryWriter(ms)); Heap.Write(0, ms.GetBuffer(), 0, (int)ms.Length); Heap.Commit(); } } }
protected string GetQuery(ILocator locator, BuildField fields = null, int count = 100) { var query = $"?locator=count:{count}"; if (locator != null) { query += $",{locator.GetLocatorQueryString()}"; } if (fields != null) { query += $"&fields={fields.GetFieldsQueryString()}"; } return(query); }
static void Main(string[] args) { // Create and cache the Media Services credentials in a static class variable. _cachedCredentials = new MediaServicesCredentials( _mediaServicesAccountName, _mediaServicesAccountKey); // Used the cached credentials to create CloudMediaContext. _context = new CloudMediaContext(_cachedCredentials); IChannel channel = CreateAndStartChannel(); // The channel's input endpoint: string ingestUrl = channel.Input.Endpoints.FirstOrDefault().Url.ToString(); Console.WriteLine("Intest URL: {0}", ingestUrl); // Use the previewEndpoint to preview and verify // that the input from the encoder is actually reaching the Channel. string previewEndpoint = channel.Preview.Endpoints.FirstOrDefault().Url.ToString(); Console.WriteLine("Preview URL: {0}", previewEndpoint); // When Live Encoding is enabled, you can now get a preview of the live feed as it reaches the Channel. // This can be a valuable tool to check whether your live feed is actually reaching the Channel. // The thumbnail is exposed via the same end-point as the Channel Preview URL. string thumbnailUri = new UriBuilder { Scheme = Uri.UriSchemeHttps, Host = channel.Preview.Endpoints.FirstOrDefault().Url.Host, Path = "thumbnails/input.jpg" }.Uri.ToString(); Console.WriteLine("Thumbain URL: {0}", thumbnailUri); // Once you previewed your stream and verified that it is flowing into your Channel, // you can create an event by creating an Asset, Program, and Streaming Locator. IAsset asset = CreateAndConfigureAsset(); IProgram program = CreateAndStartProgram(channel, asset); ILocator locator = CreateLocatorForAsset(program.Asset, program.ArchiveWindowLength); // You can use slates and ads only if the channel type is Standard. StartStopAdsSlates(channel); // Once you are done streaming, clean up your resources. Cleanup(channel); }
public string GetSmoothStreamingAzureCDNLocator(Models.Asset assetToStream) { // Get a reference to the manifest file from the collection // of streaming files in the asset. var manifestFile = assetToStream.MediaAsset.AssetFiles.Where(x => x.Name.EndsWith(".ism")).FirstOrDefault(); // Cast the reference to a true IFileInfo type. if (null == manifestFile) { return(null); } // Create an 1-day readonly access policy. IAccessPolicy streamingPolicy = this.MediaService.MediaContext.AccessPolicies.Create("CDN Streaming policy", TimeSpan.FromHours(1), AccessPermissions.Read); // Create the origin locator. Set the start time as 5 minutes // before the present so that the locator can be accessed immediately // if there is clock skew between the client and server. ILocator originLocator = (from l in this.MediaService.MediaContext.Locators where l.AssetId.Equals(assetToStream.MediaAsset.Id) && l.Type == LocatorType.None select l).FirstOrDefault(); if (originLocator != null && originLocator.ExpirationDateTime <= DateTime.UtcNow) { originLocator.Delete(); originLocator = null; } if (originLocator == null) { originLocator = this.MediaService.MediaContext .Locators.CreateLocator(LocatorType.None, assetToStream.MediaAsset, streamingPolicy, DateTime.UtcNow.AddMinutes(-5)); } // Create a full URL to the manifest file. Use this for playback // in streaming media clients. string urlForClientStreaming = originLocator.Path + manifestFile.Name + "/manifest"; // Display the full URL to the streaming manifest file. Console.WriteLine("URL to manifest for client streaming: "); Console.WriteLine(urlForClientStreaming); return(urlForClientStreaming); }
public Params(WalkMethod walkMethod, WalkAction walkAction, WalkParams walkParams, bool sink, ILocator path, IData key) { WalkMethod = walkMethod; WalkAction = walkAction; WalkParams = walkParams; Sink = sink; Path = path; FromKey = key; ToKey = key; IsPoint = true; IsOverall = false; IsTotal = false; }
static List<String> GetAssetSasUrlList(IAsset asset, ILocator locator) { // Declare a list to contain all the SAS URLs. List<String> fileSasUrlList = new List<String>(); // If the asset has files, build a list of URLs to // each file in the asset and return. foreach (IAssetFile file in asset.AssetFiles) { string sasUrl = BuildFileSasUrl(file, locator); fileSasUrlList.Add(sasUrl); } // Return the list of SAS URLs. return fileSasUrlList; }
//ロケータの割り当てたURLを取得する static string BuildFileSasUrl(IAssetFile file, ILocator locator) { // ロケータのパスを得るため、SAS URL にファイル名を結合する if (locator.Type == LocatorType.OnDemandOrigin) { return new Uri(locator.Path + file.Name + "/Manifest").ToString(); } else if (locator.Type == LocatorType.None || locator.Type == LocatorType.Sas) { var uriBuilder = new UriBuilder(locator.Path); uriBuilder.Path = uriBuilder.Path + "/" + file.Name; //SAS URL を返す return uriBuilder.Uri.AbsoluteUri; } return string.Empty; }
public async Task Start() { var context = this.createContext.Invoke(); var blobTransferClient = new BlobTransferClient(); blobTransferClient.TransferProgressChanged += this.OnBlobTransferProgressChanged; blobTransferClient.TransferCompleted += this.OnBlobTransferClientOnTransferCompleted; this.asset = await CreateEmptyAsset(context, this.AssetName, AssetCreationOptions.None); this.locator = await CreateSasLocatorAsync(context, this.asset); var fileName = Path.GetFileName(this.FilePath); var assetFile = await this.asset.AssetFiles.CreateAsync(fileName, CancellationToken.None); await assetFile.UploadAsync(this.FilePath, blobTransferClient, this.locator, CancellationToken.None); }